Skill: kaisersong/business-blueprint-skill (version 0.16.2)

--- name: kai-business-blueprint description: Use when generating business capability blueprints, domain-knowledge maps, or architecture diagrams from presales materials, meeting notes, or solution docs. Triggers: 商业蓝图, 商业模式画布, 领域知识大图, 架构图, capability map, strategy canvas. Not for generic documents, PPTs, or simple flowcharts. --- # Business Blueprint Skill Use the Python scripts in this repository as the execution surface. ## Output Directory All generated files go into `projects/workspace/` — not the repository root. ## Industry Selection Choose `--industry` from exactly one of: `"common"`, `"finance"`, `"manufacturing"`, `"retail"`. Select the closest match; do not invent other values. | Industry | Hints content | |----------|-------------| | `common` | No hints — generic domains | | `finance` | Risk control, credit, compliance, customer profile | | `manufacturing` | Production planning, quality, warehouse, supply chain | | `retail` | Store operations, membership, POS, order fulfillment | ## How to Generate a Blueprint ### Step 1: Read industry hints Read the seed template at `business_blueprint/templates/{industry}/seed.json` and get `industryHints.checklist`. ### Step 2: Extract entities **Architecture mode** (default, or when `meta.blueprintType` is absent): Extract `capabilities`, `actors`, `flowSteps`, `systems`. Read `references/entities-schema.md` for field definitions and `references/systems-schema.md` for systems layer rules. **Domain-knowledge mode** (when seed has `meta.blueprintType: "domain-knowledge"`): Extract knowledge entities into `library.knowledge.*`. Read `references/domain-knowledge-extraction.md` for naming rules and extraction guide. Read `references/knowledge-entities-schema.md` for field definitions. ### Step 3: Write blueprint JSON Write the JSON file directly to the output path. Read `references/blueprint-schema.md` for the complete schema structure. ### Step 4: Generate visualizations ```bash python scripts/business_blueprint/cli.py --export <blueprint.json> ``` Default: SVG + HTML viewer. Use `--format drawio|excalidraw|mermaid` for other formats. Read `references/route-eligibility.md` for export route selection rules. ## Architecture Rendering Rules Use dark mode by default. Only use light mode when the user explicitly asks for it. Never force every node in a layer into one fixed row. Dense layers must wrap, group, or fall back to freeflow instead of becoming a toothpaste layout. Legend must live in a bottom safe area. Never place the legend as a floating overlay in the top-right corner. Do not use fixed-height wrappers or `overflow: hidden` to hide overflow in generated viewers. Route eligibility matrix: | Route | Eligibility | |-------|-------------| | `freeflow` | Any valid blueprint with at least one renderable node or relation | | `architecture-template` | Categorized architecture graph with systems, capabilities, actors, and relations | | `evolution` | Dated or staged flow where timeline ordering is explicit | | `domain-knowledge` | `meta.blueprintType: "domain-knowledge"` with knowledge entities | If a specialized route fails integrity, fall back according to `references/route-eligibility.md`. If `freeflow` also fails, export exits non-zero with a structural diagnostics payload. Geometry thresholds are machine-readable and live in `evals/export-integrity-thresholds.json`; defect categories live in `evals/defect-taxonomy.json`. Phase 2 does not attempt full Windows terminal parity. For encoding-sensitive terminal runs, set `PYTHONIOENCODING=utf-8`. ### Step 5: Generate downstream projection (optional) ```bash python scripts/business_blueprint/cli.py --project <blueprint.json> ``` Generates `solution.projection.json` for downstream report/slide workflows. ## Commands | Command | Description | |---------|-------------| | `--plan <path> --from <text>` | Generate blueprint JSON from source text (prefer writing JSON directly) | | `--export <path>` | Export SVG + HTML viewer (default), or `--format` for others | | `--validate <path>` | Validate blueprint and print JSON results | | `--refine <path>` | Refine an existing blueprint | | `--project <path>` | Generate canonical projection JSON for downstream skills | Run as: `python scripts/business_blueprint/cli.py <command> <path>` ## Collaboration Boundary This skill produces **semantic intermediate artifacts**. Downstream skills consume them: - `report-creator` consumes `solution.projection.json` → assembles reports - `slide-creator` consumes `solution.projection.json` → assembles presentations - Other skills may consume `relations` → generate PlantUML or other diagram syntax - Downstream skills should **never directly edit** `solution.blueprint.json` - `solution.handoff.json` is viewer-only metadata, not a downstream narrative input ## Error Handling - `--validate` returns errors → fix before `--export`. - `--validate` returns only warnings → proceed, note warnings in handoff. - Specialized route fails integrity → fall back per `references/route-eligibility.md`. - `freeflow` also fails → export exits non-zero with structural diagnostics. - Python < 3.12 → use `python3 -m business_blueprint.cli` as fallback. ## Sandbox Execution In isolated Python sandboxes (Jupyter, cloud REPL): ```python subprocess.run(["python", "scripts/business_blueprint/cli.py", "--export", str(blueprint_path)]) ``` Do NOT use `sys.path.insert` (raises NameError) or `os.system` (not available in notebook cells). Set `PYTHONIOENCODING=utf-8` for encoding-sensitive runs.

path: PURE_SKILL_CLEANUP.md
content: # 纯 Skill 清理完成总结（2026-04-25）

## 完整 Git 提交记录

```
3ee4e57 refactor: remove remaining __init__.py files
c396903 docs: remove last python -m reference
d54329f docs: update sandbox execution to direct scripts
93dacd0 refactor: remove Python package structure, convert to pure Skill
```

---

## 已删除的 Python 包元素

### 1. 包配置文件
- ✅ `pyproject.toml` - setuptools 配置（包身份核心）
- ✅ `uv.lock` - uv 包管理器锁文件

### 2. 包标识文件
- ✅ `scripts/business_blueprint/__init__.py` - Python包标识（480行代码）
- ✅ `scripts/business_blueprint/renderers/__init__.py` - 子包标识

### 3. 测试框架
- ✅ `scripts/tests/` - Python单元测试（174个测试文件）

### 4. 文档引用
- ✅ SKILL.md 中所有 `python -m business_blueprint.cli` 调用（3处）

### 5. 构建产物（已忽略）
- ⚠️ `kai_business_blueprint.egg-info/` - setuptools元数据
  - 已在 `.gitignore` 排除（不影响Git）
  - 可手动删除（可选）

---

## 已修改的内容

### SKILL.md（核心Skill定义）

**旧执行方式**：
```bash
pip install -e .                         # 需要安装包
python -m business_blueprint.cli --export ...  # 模块调用
business-blueprint --export ...          # CLI命令（需要setup.py）
```

**新执行方式**：
```bash
python scripts/business_blueprint/cli.py --export ...  # 直接脚本执行
# 无需pip install
# 无需包结构
# 无需setuptools
```

---

## 最终纯 Skill 目录结构

```
business-blueprint-skill/        # Skill 根目录
│
├── references/                  # Skill 文档（标准目录）
│   ├── entities-schema.md       # 实体定义（capabilities, actors等）
│   ├── systems-schema.md        # Systems分类规则（layer vs service）
│   ├── blueprint-schema.md      # Blueprint JSON schema
│   ├── architecture-design-system.md
│   ├── architecture-diagram-design.md
│   ├── implementation-plan.md
│   ├── visual-enhancement-plan.md
│   └── 其他设计文档（共13个）
│
├── scripts/                     # 执行脚本（工具层）
│   ├── business_blueprint/      # Python代码（纯脚本，不是包）
│   │   ├── cli.py              # CLI入口脚本（169行）
│   │   ├── generate.py         # Blueprint生成
│   │   ├── export_svg.py       # SVG导出（145KB，核心）
│   │   ├── export_html.py      # HTML viewer导出
│   │   ├── export_routes.py    # 路由决策
│   │   ├── export_drawio.py    # draw.io导出
│   │   ├── export_excalidraw.py # Excalidraw导出
│   │   ├── export_mermaid.py   # Mermaid导出
│   │   ├── export_text.py      # 文本导出
│   │   ├── export_theme.py     # 主题配置
│   │   ├── export_integrity.py # 导出完整性检查
│   │   ├── validate.py         # Blueprint验证
│   │   ├── projection.py       # 投影生成
│   │   ├── normalize.py        # 数据标准化
│   │   ├── model.py            # JSON读写
│   │   ├── clarify.py          # 澄清请求
│   │   ├── prompt_generator.py # 提示词生成
│   │   ├── viewer.py           # Viewer工具
│   │   ├── renderers/          # 导出规格构建器（纯脚本）
│   │   │   └── (内部模块)      # 无__init__.py
│   │   ├── templates/          # JSON模板数据
│   │   │   ├── common/         # 基础模板 + 字段示例
│   │   │   ├── finance/        # 金融行业hints
│   │   │   ├── manufacturing/  # 制造行业hints
│   │   │   └── retail/         # 零售行业hints
│   │   ├── assets/             # 静态资源
│   │   │   └── viewer.html     # HTML viewer模板
│   │   └── docs/               # 冗余文档副本（可选删除）
│   │       ├── entities-schema.md
│   │       └── systems-schema.md
│   └── tests/                  # 已删除（无测试）
│
├── demos/                       # 示例产物
│   ├── solution.exports/       # 示例导出
│   ├── common.exports/
│   ├── finance.exports/
│   ├── manufacturing.exports/
│   └── retail.exports/
│
├── evals/                       # 评估数据
│   └── fixtures/
│
├── kai_business_blueprint.egg-info/  # 构建产物（Git已忽略）
│   ├── PKG-INFO                # 包信息（旧版本0.10.0）
│   ├── SOURCES.txt
│   └── 其他元数据
│
├── .gitignore                   # Git忽略规则
│   ├── __pycache__/            # Python缓存
│   ├── .pytest_cache/          # pytest缓存
│   ├── *.egg-info/             # setuptools产物 ✅
│   ├── .coverage               # 测试覆盖率
│   ├── .DS_Store               # macOS
│   └其他排除规则...
│
├── SKILL.md                     # Skill定义（核心，12.6KB）
├── README.md                    # Skill说明（15KB）
├── README.zh-CN.md              # 中文说明（13KB）
└ REFACTOR_SUMMARY.md            # 本次重构总结
└── docs                         # 符号链接或占位文件
```

---

## 纯 Skill 关键特征

| 特征 | 状态 | 说明 |
|------|------|------|
| Python包配置 | ✅ 已删除 | 无 pyproject.toml |
| 包标识文件 | ✅ 已删除 | 无 __init__.py |
| 测试框架 | ✅ 已删除 | 无 tests/ |
| 包管理器 | ✅ 已删除 | 无 uv.lock |
| 构建产物 | ✅ 已忽略 | egg-info 在 .gitignore |
| 执行方式 | ✅ 已更新 | 直接脚本，无 python -m |
| 文档位置 | ✅ 标准 | references/（Skill标准目录）|
| 执行工具 | ✅ 标准 | scripts/（工具层）|

---

## Skill vs Python包的身份对比

### Python包视角（已删除）

```
python-package/
├── pyproject.toml          # 包配置 ❌ 已删除
├── uv.lock                 # 锁文件 ❌ 已删除
├── src/
│   └── __init__.py         # 包标识 ❌ 已删除
├── tests/                  # 单元测试 ❌ 已删除
├── *.egg-info/             # 元数据 ⚠️ 已忽略
└── dist/                   # 发布产物（不存在）
```

### Skill视角（当前状态）

```
skill/
├── references/             # 文档 ✅ 标准目录
├── scripts/                # 执行工具 ✅ 工具层
│   └ business_blueprint/  # 纯脚本 ✅ 无 __init__.py
└── SKILL.md                # 定义 ✅ 核心文件
```

---

## 执行方式变化

### 旧方式（需要Python包）

```bash
# 1. 安装包（开发模式）
pip install -e .

# 2. 模块调用
python -m business_blueprint.cli --export solution.blueprint.json

# 3. CLI命令（需要setup.py定义entry_points）
business-blueprint --export solution.blueprint.json
```

### 新方式（纯脚本）

```bash
# 直接执行脚本（无需安装）
python scripts/business_blueprint/cli.py --export solution.blueprint.json

# 或者用绝对路径
python /path/to/business-blueprint-skill/scripts/business_blueprint/cli.py --export ...
```

**优势**：
- ✅ 无需 pip install
- ✅ 无需包结构
- ✅ 无需 setuptools
- ✅ 跨环境直接使用
- ✅ 符合 Skill 简洁理念

---

## 职责分工（标准 Skill）

| 目录 | 作用 | 内容类型 | 用户 |
|------|------|---------|------|
| **references/** | Skill文档 | 实体定义、分类规则、设计规范 | AI Agent阅读 |
| **scripts/** | 执行工具 | Python脚本（实现细节）| AI Agent执行 |
| **SKILL.md** | 路由层 | 指向references，定义能力 | AI Agent理解 |
| **demos/** | 示例产物 | 导出示例 | 人类参考 |
| **README.md** | Skill说明 | 使用说明 | 人类阅读 |

**核心理念**：
- Skill的价值在于 **AI Agent能力定义**（SKILL.md）
- Python只是 **执行工具**（scripts/），不是Skill身份
- 文档清晰分离（references/），不混在代码中

---

## 清理过程回顾

### 第1次重构（目录结构调整）

1. `business_blueprint/` → `scripts/business_blueprint/`（Python包移到工具层）
2. `tests/` → `scripts/tests/`（测试跟随包移动）
3. `specs/` → `renderers/`（名称清晰化）
4. `business_blueprint/docs/` → `references/`（文档移到标准目录）

**目的**：符合标准 Skill 目录结构

### 第2次清理（删除Python包身份）

1. 删除 `pyproject.toml`（setuptools配置）
2. 删除 `uv.lock`（包管理器）
3. 删除 `scripts/tests/`（单元测试）
4. 删除 `__init__.py`（包标识）
5. 更新 SKILL.md（执行方式）

**目的**：回归纯 Skill，移除 Python 包复杂性

---

## 可选后续清理

### 冗余文档副本

`scripts/business_blueprint/docs/` 包含：
- `entities-schema.md`（与 references/ 重复）
- `systems-schema.md`（与 references/ 重复）

**建议**：删除，保留 references/ 作为唯一文档位置

### 构建产物

`kai_business_blueprint.egg-info/` 已在 `.gitignore` 排除：
- 不影响 Git
- 可手动删除（`rm -rf kai_business_blueprint.egg-info`）
- 或保留（不影响 Skill）

---

## 标准 Skill 目录模板

```
skill-name/
├── references/               # 必选：文档
├── scripts/                  # 可选：执行脚本
├── demos/                    # 可选：示例
├── tests/                    # 可选：Skill测试（不是包测试）
├── SKILL.md                  # 必选：Skill定义
└── README.md                 # 可选：说明文档
```

**本 Skill 特殊之处**：
- 有Python执行脚本（scripts/business_blueprint/）
- 但不是Python包（无 pyproject.toml、__init__.py）
- Python只是工具，不是身份

---

## Git 状态验证

```bash
git log --oneline -4
# 3ee4e57 refactor: remove remaining __init__.py files
# c396903 docs: remove last python -m reference
# d54329f docs: update sandbox execution to direct scripts
# 93dacd0 refactor: remove Python package structure, convert to pure Skill

ls scripts/business_blueprint/__init__.py
# Error: No such file（已删除）

ls scripts/business_blueprint/renderers/__init__.py
# Error: No such file（已删除）

ls pyproject.toml
# Error: No such file（已删除）
```

---

## 清理完成时间

**开始时间**：2026-04-25 22:04
**结束时间**：2026-04-25 22:07
**总耗时**：约3分钟
**Git提交**：4个提交
**删除文件**：176个（pyproject.toml + uv.lock + tests/174个 + __init__.py 2个）
**修改文件**：1个（SKILL.md）

---

## 总结

✅ **Python 包身份完全移除**
✅ **Skill 身份回归核心**
✅ **目录结构符合标准**
✅ **执行方式简单直接**
✅ **文档清晰分离**
✅ **Git 历史完整保留**

**现在的 business-blueprint-skill 是标准纯 Skill**：
- AI Agent 能力定义（SKILL.md）为核心
- Python 脚本（scripts/）为执行工具
- Skill 文档（references/）清晰分离
- 无 Python 包管理复杂性

---

**清理日期**：2026-04-25
**状态**：✅ 完成

path: README.md
content: # kai-business-blueprint

> 售前需求、会议纪要、RFP 材料 → 可编辑的业务能力蓝图、泳道流程图、应用架构图。一份 canonical JSON IR，多个下游导出格式（SVG / draw.io / Excalidraw / Mermaid）。

A [Claude Code](https://claude.ai/claude-code) skill that turns raw presales inputs into canonical business capability blueprints, with a static HTML viewer and multi-format diagram exports.

English | [简体中文](README.zh-CN.md)

---

## Demo

Retail industry blueprint, exported as SVG:

![retail-blueprint](demos/screenshots/retail-arch.svg)

The SVG is generated by `business-blueprint --export demos/retail.blueprint.json` — the source JSON is in `demos/retail.blueprint.json`, the viewer is `demos/solution.viewer.html`.

---

## Design Philosophy: IR-First Pipeline

### 1. JSON as Canonical Intermediate Representation

Every workflow converges on `solution.blueprint.json` — the single source of truth. All other artifacts (viewer, SVG, draw.io) are deterministic projections from it.

```
Raw Text ──(--plan)──→ JSON ──(--generate)──→ Viewer HTML
                          │
                          ├──(--export)──→ SVG / draw.io / Excalidraw / Mermaid
                          │
                          └──(--edit)────→ JSON (patch logged) + Viewer refresh
```

The IR is:
- **Version-controllable** — standard JSON, diffs are meaningful
- **AI-readable** — downstream skills parse `entities`, `relations`, `flowSteps` without HTML parsing
- **Human-editable** — light fields (labels, names) can be edited without breaking structure

### 2. Progressive Disclosure

The skill file (`SKILL.md`) is a routing layer — it tells Claude *which* file to read for *which* command. Heavy assets (industry packs, viewer HTML template, export engine) stay on disk until needed.

```
--plan        → only model + generation rules; no CSS, no export engine
--generate    → one viewer.html template + one industry pack
--export      → only the requested export engine; other formats stay on disk
--validate    → schema + rules; no rendering code
```

### 3. Silicon-Carbon Collaboration

**Input:** Humans write natural language (requirements, meeting notes, RFPs). AI parses into structured entities (Application Systems, Business Capabilities, Process Flows, Actors) and relations.

**Output:** The viewer is a static HTML page — no build step, no JS framework, works offline. Every node is editable in-place, and edits are logged as a JSON patch trail (`solution.patch.jsonl`) for full traceability.

---

## Install

### Download

Current release: **v0.16.2**

- Release page: <https://github.com/kaisersong/kai-business-blueprint/releases/tag/v0.16.2>
- Direct zip: <https://github.com/kaisersong/kai-business-blueprint/releases/download/v0.16.2/kai-business-blueprint-v0.16.2.zip>

### Claude Code

```bash
git clone https://github.com/kaisersong/kai-business-blueprint ~/.claude/skills/kai-business-blueprint
```

Then: `cd kai-business-blueprint && pip install -e .`

### OpenClaw

```bash
git clone https://github.com/kaisersong/kai-business-blueprint ~/.openclaw/skills/kai-business-blueprint
cd kai-business-blueprint && pip install -e .
```

---

## Usage

### CLI Commands

| Flag | Purpose |
|------|---------|
| `--plan "text"` | Parse raw text into canonical blueprint JSON |
| `--project <blueprint.json>` | Derive canonical `solution.projection.json` for downstream skills |
| `--generate <output>` | Generate JSON + static HTML viewer package |
| `--edit <blueprint.json>` | Refresh viewer for an existing blueprint (preserves human edits) |
| `--export <blueprint.json>` | Export diagrams (default: free-flow SVG + HTML viewer) |
| `--export-auto <blueprint.json>` | Alias for --export (free-flow SVG + HTML viewer) |
| `--html <output.html>` | Generate self-contained HTML viewer with inline SVG |
| `--validate <blueprint.json>` | Validate blueprint structure, output errors/warnings |
| `--refine <blueprint.json>` | Refine an existing blueprint with `--feedback "..."` (LLM produces a structured diff that is applied to a new blueprint) |
| `--from <file>` | Read source material from file path |
| `--industry <pack>` | Apply industry template pack (common, finance, manufacturing, retail, **cross-border-ecommerce**) |
| `--theme <dark|light>` | Color theme for output (default: dark) |
| `--visual-profile <profile>` | Apply differentiated SVG/HTML styling: base, auto, executive-clean, blueprint-technical, dark-ops, warm-consulting, knowledge-canvas |
| `--format <fmt>` | Export format: svg, drawio, excalidraw, mermaid, all |

### Domain-Knowledge Blueprints (v0.14)

Beyond the architecture-style blueprint (capabilities / actors / flowSteps / systems), the skill now produces **domain-knowledge blueprints** for know-how pitches: pain points, strategies, rules, metrics, practices, pitfalls — six entity types tied together by `solves` / `measures` / `enforces` / `requires` / `prevents` / `causes` relations.

A domain-knowledge blueprint is selected by `meta.blueprintType: "domain-knowledge"` (set automatically when you choose a know-how-leaning industry such as `cross-border-ecommerce`, or by AI intent extraction). Three quality-driven mechanisms live in the pipeline:

- **Clarification turn.** Validator rejects a domain-knowledge blueprint with fewer than 3 `clarifyRequests`, each pointing to a specific entity. The AI must surface what it is uncertain about before producing the chart.
- **Per-entity self-check.** Every knowledge entity carries an optional `_selfCheck` field with `passed` / `questions` arrays. Entities with non-empty `questions` are rendered with a soft amber accent and a `?` glyph so reviewers can spot what still needs verification.
- **Refine command.** `--refine blueprint.json --feedback "..."` asks the LLM to emit an `add` / `modify` / `delete` diff which is then applied to produce a new revision. The diff structure is JSON-Patch-like and can be filtered per-operation before applying.

The knowledge SVG renderer uses a three-band layout: rules across the top, a `pain → strategy → metric` triptych in the middle (rows aligned by `solves` / `measures` so the dominant lines stay near-horizontal), and `practices` + `pitfalls` capsules at the bottom. Cross-zone connections are cubic Bezier; relations are drawn at three opacity tiers so the primary `solves` / `measures` story stays readable even with 30+ relations.

### Export Quality Contracts

- Export routing is explicit: specialized views are only used when the blueprint structure clearly matches them; otherwise the exporter stays on `freeflow`.
- Visual profiles are explicit styling overlays, not route selectors. Use `--visual-profile auto` for differentiated output and `base` for legacy comparison.
- SVG output now runs structural integrity checks for missing defs references and basic canvas overflow before an artifact is accepted.
- Export thresholds and defect taxonomy live under [`evals/`](evals), so route and integrity behavior are backed by machine-readable fixtures rather than prose only.
- Showcase matrix generation lives in `business_blueprint.showcase_matrix` and writes one SVG per industry/profile pair plus `showcase-summary.json`.
- Template validation matrix generation lives in `business_blueprint.validation_matrix` and writes one medium-complexity JSON/SVG/HTML package per industry template plus `template-validation-summary.json`.
- Optional PNG rendering lives in `business_blueprint.render_png`; it uses CairoSVG only when installed and reports a skipped render otherwise.
- Windows/terminal support is intentionally scoped: the canonical path is `python -m business_blueprint.cli`, and encoding-sensitive runs should use `PYTHONIOENCODING=utf-8` when needed.

### Skill Evals

`kai-business-blueprint` has two eval layers:

- Export/regression evals under `evals/` and `scripts/tests/` keep routing, SVG integrity, schema behavior, projection, and CLI behavior deterministic.
- Captured-run skill evals score a normalized trace across four 25-point categories: Outcome, Process, Style, and Efficiency.

Run the offline skill eval baseline:

```bash
python3 scripts/run-skill-evals.py --root . --runner fixture
```

Run release verification:

```bash
python3 scripts/verify-release.py --root .
```

The default skill eval path is **agent-agnostic**. It uses checked-in normalized fixtures and does not invoke Codex, Claude, Qoder, OpenClaw, model APIs, or the network. To score an external run from any agent, convert that run into the normalized trace schema first, then run:

```bash
python3 scripts/run-skill-evals.py --root . --runner trace --case-id <case-id> --normalized-trace <trace.json>
```

Saved baseline:

- File: [`evals/baselines/2026-05-17-skill-evals-fixture.json`](evals/baselines/2026-05-17-skill-evals-fixture.json)
- Summary: `6 passed, 0 failed, 0 incomplete`
- Average score: `99.67/100`
- Category averages: Outcome `25.00`, Process `25.00`, Style `24.67`, Efficiency `25.00`

### Typical Workflows

**From raw text:**
```bash
# Step 1: parse into canonical JSON
business-blueprint --plan "ERP supports POS system..." --from meeting-notes.md --industry retail

# Step 2: generate viewer
business-blueprint --generate solution.blueprint.json

# Step 3: export diagrams
business-blueprint --export solution.blueprint.json --visual-profile auto
```

**Compare visual profiles:**
```bash
python scripts/business_blueprint/showcase_matrix.py --output projects/workspace/showcase --industries common,retail --visual-profiles executive-clean,dark-ops,warm-consulting
```

**Validate one medium blueprint per template:**
```bash
python scripts/business_blueprint/validation_matrix.py --output projects/workspace/template-validation
```

**Optional PNG check:**
```bash
python scripts/business_blueprint/render_png.py projects/workspace/showcase/common/executive-clean/solution.svg
```

**Edit existing blueprint:**
```bash
# Edit the JSON manually or let AI edit it
# Then refresh the viewer (preserves human-edited fields via editor.fieldLocks)
business-blueprint --edit solution.blueprint.json
```

**Validate before export:**
```bash
business-blueprint --validate solution.blueprint.json
# Fix errors, then:
business-blueprint --export solution.blueprint.json
```

**Prepare downstream machine handoff:**
```bash
business-blueprint --project solution.blueprint.json
```

---

## Outputs

| File | Role |
|------|------|
| `solution.blueprint.json` | Canonical IR — single source of truth |
| `solution.projection.json` | Canonical downstream machine projection |
| `solution.viewer.html` | Static viewer + light editor |
| `solution.exports/` | SVG, draw.io, Excalidraw, Mermaid exports |
| `solution.patch.jsonl` | Edit traceability log (JSON patches) |
| `solution.handoff.json` | Viewer revision manifest |

### SVG Architecture Export

The SVG export renders a free-flow L→R architecture diagram:

- **Main flow chain** (center row) — systems connected via flow steps, left to right
- **Auxiliary systems** (rows above/below) — placed by category (database, security, cloud)
- **Entry node** (left) — auto-generated from blueprint actors
- **Semantic arrows** — 4 types with distinct colors/markers: `supports` (green solid), `depends-on` (gray dashed), `flows-to` (blue solid), `owned-by` (yellow dotted)
- **Semantic node shapes** — diamond for flow steps, left color strip for systems, rounded rects for capabilities, pill shapes for actors
- **Industry themes** — accent color overlays for retail (orange), finance (blue), manufacturing (gray)
- **Visual profiles** — optional profile overlays for executive, technical, operations, consulting, and knowledge-canvas outputs

The layout engine computes positions dynamically with overlap resolution, horizontal alignment, and mid-y collision avoidance. The region boundary box and SVG canvas auto-expand to contain all arrow paths.

---

## Project Structure

```
kai-business-blueprint/
├── SKILL.md                      # Skill definition (routing layer)
├── business_blueprint/           # Python engine (zero external deps)
│   ├── cli.py                    # CLI entry point
│   ├── generate.py               # Blueprint generation from text
│   ├── model.py                  # Data model & top-level shape
│   ├── projection.py             # Downstream projection builder
│   ├── validate.py               # Machine-readable validation
│   ├── clarify.py                # Clarification request builder
│   ├── normalize.py              # Entity resolution & synonym merging
│   ├── viewer.py                 # HTML viewer package writer
│   ├── export_theme.py           # Shared export theme tokens and semantic colors
│   ├── export_text.py            # Shared SVG text width + wrapping helpers
│   ├── export_routes.py          # Explicit export route resolution
│   ├── export_integrity.py       # Structural export integrity checks + diagnostics
│   ├── export_svg.py             # SVG exporter (two-pass layout, content router, free-flow)
│   ├── export_drawio.py          # draw.io exporter
│   ├── export_excalidraw.py      # Excalidraw exporter
│   ├── export_mermaid.py         # Mermaid markdown exporter
│   ├── visual_profiles.py        # Business visual profile registry and palette overlays
│   ├── showcase_matrix.py        # Multi-industry/profile SVG showcase generator
│   ├── validation_matrix.py      # Medium-complexity per-template validation generator
│   ├── render_png.py             # Optional CairoSVG PNG render probe
│   ├── templates/                # Industry packs (common, retail, finance, manufacturing)
│   ├── assets/                   # viewer.html template
│   └── specs/                    # Blueprint schema definitions
├── references/                   # Schema, authoring rules, industry packs
├── tests/                        # Test suite
├── demos/                        # Demo blueprints & exports
└── examples/                     # Sample blueprint JSON
```

---

## Architecture Rules

The engine enforces structural rules:

| Rule | Description |
|------|-------------|
| **Every capability links to a system** | No orphaned capabilities |
| **Every flow links to a capability** | No floating flow steps |
| **Actor → System** | Actors must reference valid system IDs |
| **No circular relations** | System → Capability → Flow must be DAG |

Run `--validate` to check all rules. Warnings indicate potential issues (e.g., a system with no capabilities), errors block export.

---

## For AI Agents

Other skills should consume blueprint artifacts through prompt orchestration, not through the viewer handoff manifest.

```
# 1. Prepare the machine artifacts
business-blueprint --plan solution.blueprint.json --from "..."
business-blueprint --project solution.blueprint.json

# 2. Prompt report-creator with the blueprint/projection artifacts
"Use solution.blueprint.json and solution.projection.json to generate a report IR first. Do not render HTML yet."

# 3. Prompt slide-creator with the blueprint/projection artifacts
"Use solution.blueprint.json and solution.projection.json to generate PLANNING.md first. Do not generate HTML yet."
```

See [references/prompt-orchestration-templates.md](references/prompt-orchestration-templates.md) for copy-paste prompt templates.

`solution.handoff.json` is only a viewer manifest. Do not use it as report/deck input.

**Extracting structured data:**
```python
import json

with open("solution.blueprint.json") as f:
    bp = json.load(f)

# Systems
for sys in bp["library"].get("systems", []):
    print(f"System: {sys['name']}")

# Capabilities
for cap in bp["library"].get("capabilities", []):
    print(f"Capability: {cap['name']}")

# Relations
for rel in bp["relations"]:
    print(f"{rel['from']} --{rel['type']}--> {rel['to']}")
```

---

## Requirements

| Requirement | Version | Notes |
|-------------|---------|-------|
| **Python** | >= 3.12 | Zero external dependencies |

---

## Compatibility

| Platform | Version | Install path |
|----------|---------|--------------|
| Claude Code | any | `~/.claude/skills/kai-business-blueprint/` |
| OpenClaw | >= 0.9 | `~/.openclaw/skills/kai-business-blueprint/` |

---

## Version History

**v0.16.2** — Docs-inclusive eval release: updates the English/Chinese README download links to the latest GitHub Release, records the full business-blueprint skill eval implementation plan under `evals/`, and keeps the saved agent-agnostic baseline visible for comparison (`99.67/100`, 6 passed, 0 failed).

**v0.16.1** — Agent-agnostic skill eval release: add captured-run blueprint skill evals with normalized fixture traces, prompt manifest, rubric schema, style fixtures, saved baseline (`99.67/100`, 6 passed), and a release verification entry point. The eval harness consumes fixture or normalized trace JSON only; it does not depend on Codex, Claude, Qoder, OpenClaw, model APIs, or network access.

**v0.16.0** — Visual profile and showcase hardening follow-up: adds differentiated validation/showcase outputs and versioned viewer metadata.

**v0.15.0** — Visual profile and showcase hardening: add named SVG/HTML visual profiles (`executive-clean`, `blueprint-technical`, `dark-ops`, `warm-consulting`, `knowledge-canvas`) plus `--visual-profile auto` so different blueprint templates no longer collapse into one style. Add showcase matrix generation for multi-industry/profile comparisons, per-template medium-complexity validation generation, optional CairoSVG PNG render probing, UTF-8 template loading on Windows, and regression coverage for profile metadata, prompt audit trails, CLI propagation, showcase summaries, validation summaries, and PNG skip/render behavior.

**v0.14.0** — Domain-knowledge blueprints: add a second blueprint type for know-how pitches (pain points / strategies / rules / metrics / practices / pitfalls) on top of the existing architecture mode. Three quality-driven mechanisms — clarification turn (validator requires ≥3 entity-targeted clarifyRequests), per-entity self-check (entities surface their own uncertainty as a `?` glyph), and `--refine` command (LLM emits a structured diff that is applied to produce a new revision). New `cross-border-ecommerce` industry pack with depth-validated knowledgeHints; existing retail/finance/manufacturing packs gain `knowledgeHints` blocks marked [REDACTED_SECRET] so AI must disclose the limitation. Knowledge SVG renderer uses a three-band layout (rules / pain-strategy-metric triptych / practices-pitfalls capsules) with row alignment by `solves` / `measures`, cubic Bezier connections, and three-tier opacity so the dominant story stays readable on dense graphs. Free-flow renderer also switches simple connections from straight lines to Bezier. 85 unit tests (67 new) lock the v2 behaviour.

**v0.13.0** — Intent resolution & label overlap fix: integrate `IntentResolver` + `RuleEngine` into the SVG export pipeline so layer assignment becomes data-driven; resolve label-node overlap on free-flow output.

**v0.10.0** — Quality hardening release: add explicit export route resolution and SVG integrity checks with structured fallback diagnostics; introduce machine-readable eval assets under `evals/` (thresholds, defect taxonomy, route fixtures, scoring schema); improve cross-platform CLI handling for spaced paths, CRLF input, and UTF-8 validation output; split shared export text/theme helpers out of `export_svg.py`; and refine the evolution timeline view so dark cards stay readable and wrapped system pills no longer overflow.

**v0.9.0** — Canonical projection release: add `solution.projection.json` generation via `--project`; formalize prompt-native orchestration templates for report/slide downstream skills; strengthen export routing rules so non-standard diagram requests fall back to free-flow; and ship substantial SVG quality upgrades across poster, swimlane, hierarchy, and evolution views, including dark-theme fixes, label collision handling, width-aware title wrapping, centered card rows, and new regression coverage.

**v0.8.0** — Skill rename: rebranded from `business-blueprint-skill` to `kai-business-blueprint`; updated all GitHub URLs, install paths, and documentation references.

**v0.7.0** — Visual enhancements: 4 semantic arrow types (supports/depends-on/flows-to/owned-by) with distinct colors, dash patterns, and SVG markers; semantic node shapes (diamond for flowStep, left color strip for systems, rounded rects for capabilities, pill for actors); 3 industry theme overlays (retail=#F97316, finance=#3B82F6, manufacturing=#6B7280); HTML template-driven viewer generation (replaces 244 lines of f-strings); architecture layout fix — one column per unique capability; free-flow now renders full relation arrows from `blueprint.relations`; same-column arrow routing uses direct vertical paths; region box covers all system nodes; 46 new tests.

**v0.6.1** — Layout engine genericization: remove all hardcoded company/product names (AWS service mappings, Kingdee product IDs, brand text) from layout and rendering code; `_categorize_system()` now uses language-agnostic keyword matching (Chinese + English); `_layout_layered()` assigns distinct colors per layer instead of category keyword lookup; dark theme node colors increased contrast (brighter fills, bolder strokes); legend rendered behind arrows and nodes (z-order fix) so overlaps never obscure content; product tree and capability matrix auto-derive segments from blueprint data instead of hardcoded IDs.

**v0.6.0** — Free-flow layout engine overhaul: arrow routing with cross-row elbow paths and mid_y collision avoidance; dark theme as default; all user-facing labels in Chinese (legend, footer, summary cards); arrowheads shrunk (8×6px, stroke-width 1.5) for cleaner look; region boundary box and SVG canvas dynamically expand to contain arrow paths; rendering z-order fixed (arrows behind nodes); `--html` flag for standalone viewer; `--format` and `--theme` CLI flags; description section from blueprint context; download SVG button.

**v0.5.0** — Content router & free-flow layout engine: `_content_router()` auto-selects views (architecture, capability map, swimlane, process chain) based on blueprint content; `_layout_free_flow()` computes free-form positions with domain grouping and auto-wrapping; `export_svg_auto()` combines routing + layout; `--export-auto` CLI flag; HTML viewer now dynamically shows tabs only for available views.

**v0.4.0** — HTML viewer & layout fix: self-contained HTML viewer with three inline SVG views (architecture, capability map, swimlane), tab-based navigation, summary cards, dark theme support with grid background.

**v0.3.1** — CLI fixes: `--from` long Chinese text no longer triggers `File name too long`, stdin pipe support for `--plan`, subprocess `text=True`/bytes compatibility guidance.

**v0.2.0** — SVG layout engine: two-pass dynamic layer height, actor overflow fix, title/layer gap, header clipping fix, legend truncation fix.

**v0.1.0** — Initial release: plan/generate/edit/export/validate pipeline, HTML viewer with in-place editing, SVG/draw.io/Excalidraw/Mermaid exports, industry template packs (common, retail, finance, manufacturing).


path: README.zh-CN.md
content: # kai-business-blueprint

> 售前需求、会议纪要、RFP 材料 → 可编辑的业务能力蓝图、泳道流程图、应用架构图。一份 canonical JSON IR，多个下游导出格式（SVG / draw.io / Excalidraw / Mermaid）。

适用于 [Claude Code](https://claude.ai/claude-code) 和 [OpenClaw](https://openclaw.ai) 的业务蓝图生成技能，将原始售前输入转化为结构化业务能力架构。

[English](README.md) | 简体中文

---

## 效果展示

零售行业蓝图，导出为 SVG 架构：

![retail-blueprint](demos/screenshots/retail-arch.svg)

该 SVG 由 `business-blueprint --export demos/retail.blueprint.json` 生成，源 JSON 在 `demos/retail.blueprint.json`，交互式查看器在 `demos/solution.viewer.html`。

---

## 设计理念：IR 优先管道

### 一、JSON 作为标准中间表示

所有工作流最终都收敛到 `solution.blueprint.json`——唯一的事实来源。所有其他产物（查看器、SVG、draw.io）都是从这个 JSON 确定性投影出来的。

```
原始文本 ──(--plan)──→ JSON ──(--generate)──→ 查看器 HTML
                          │
                          ├──(--export)──→ SVG / draw.io / Excalidraw / Mermaid
                          │
                          └──(--edit)────→ JSON（补丁日志）+ 查看器刷新
```

IR 文件的特点：
- **可版本管理**——标准 JSON，diff 有意义
- **AI 可读**——下游技能直接解析 `entities`、`relations`、`flowSteps`，不需要 HTML 解析
- **人类可编辑**——名称、标签等轻量字段可以直接修改，不会破坏结构

### 二、渐进式披露

技能文件（`SKILL.md`）是一个路由层——它告诉 Claude 在哪个命令下应该读哪个文件。重型资产（行业包、查看器 HTML 模板、导出引擎）只有在需要时才加载。

```
--plan        → 只需模型 + 生成规则；不加载 CSS 或导出引擎
--generate    → 一个 viewer.html 模板 + 一个行业包
--export      → 仅加载请求的导出引擎；其他格式保留在磁盘
--validate    → 仅加载 schema + 规则；不加载渲染代码
```

### 三、硅碳协作

**输入端：** 人类书写自然语言（需求、会议纪要、RFP），AI 解析为结构化实体（应用系统、业务能力、流程步骤、角色）和关系。

**输出端：** 查看器是纯静态 HTML——无需构建步骤、无 JS 框架、支持离线。每个节点都可以原地编辑，编辑操作记录为 JSON patch 日志（`solution.patch.jsonl`），确保完全可追溯。

---

## 安装

### 下载

当前发布版本：**v0.16.2**

- Release 页面：<https://github.com/kaisersong/kai-business-blueprint/releases/tag/v0.16.2>
- 直接下载 zip：<https://github.com/kaisersong/kai-business-blueprint/releases/download/v0.16.2/kai-business-blueprint-v0.16.2.zip>

### Claude Code

```bash
git clone https://github.com/kaisersong/kai-business-blueprint ~/.claude/skills/kai-business-blueprint
```

然后：`cd kai-business-blueprint && pip install -e .`

### OpenClaw

```bash
git clone https://github.com/kaisersong/kai-business-blueprint ~/.openclaw/skills/kai-business-blueprint
cd kai-business-blueprint && pip install -e .
```

---

## 使用方式

### 命令行参数

| 参数 | 说明 |
|------|------|
| `--plan "文本"` | 将原始文本解析为标准蓝图 JSON |
| `--project <blueprint.json>` | 派生 canonical `solution.projection.json`，供下游技能消费 |
| `--generate <输出>` | 生成 JSON + 静态 HTML 查看器包 |
| `--edit <blueprint.json>` | 刷新现有蓝图的查看器（保留人工编辑） |
| `--export <blueprint.json>` | 导出 SVG、draw.io、Excalidraw、Mermaid 图表 |
| `--export-auto <blueprint.json>` | 使用内容路由 + 自由流式布局导出 SVG |
| `--validate <blueprint.json>` | 验证蓝图结构，输出错误/警告 |
| `--refine <blueprint.json>` | 基于自然语言反馈优化已有蓝图，配合 `--feedback "..."`。LLM 输出结构化 diff，自动应用产生新版本 |
| `--from <文件>` | 从指定文件读取源材料 |
| `--industry <包名>` | 指定行业模板包（`common`、`finance`、`manufacturing`、`retail`、**`cross-border-ecommerce`**） |
| `--theme <dark|light>` | 输出主题色，默认 `dark` |
| `--visual-profile <profile>` | 应用差异化 SVG/HTML 视觉风格：base、auto、executive-clean、blueprint-technical、dark-ops、warm-consulting、knowledge-canvas |

### Domain-Knowledge 蓝图（v0.14 新增）

除了原有的架构视角蓝图（capabilities / actors / flowSteps / systems），skill 新增 **domain-knowledge 蓝图**用于客户 know-how pitch：痛点、策略、规则、指标、最佳实践、常见误区六类实体，通过 `solves` / `measures` / `enforces` / `requires` / `prevents` / `causes` 等关系串联。

通过 `meta.blueprintType: "domain-knowledge"` 选定（用 `cross-border-ecommerce` 这类 know-how 行业模板时自动设定，或由 AI 意图抽取得出）。pipeline 内置三个质量驱动机制：

- **澄清回合**：domain-knowledge 蓝图必须包含 ≥3 条 `clarifyRequests`，每条都要指向具体实体；validator 在第一轮强制 AI 暴露不确定点。
- **实体自检**：每个 knowledge 实体可附 `_selfCheck` 字段（`passed` / `questions` 数组），`questions` 非空的实体在 SVG 中渲染为琥珀色边框 + `?` 标记，让 reviewer 一眼看出哪些点还需要确认。
- **修订命令**：`--refine blueprint.json --feedback "..."` 让 LLM 输出 `add` / `modify` / `delete` diff，应用后产生新版本。diff 结构类似 JSON Patch，可在应用前按操作筛选。

知识图渲染采用三段式布局：顶部规则 band、中部「痛点 → 策略 → 指标」三联画（按 `solves` / `measures` 关系行对齐，让主线接近水平）、底部「最佳实践 + 常见误区」胶囊。跨区域连接使用三阶贝塞尔曲线；关系按三档透明度分级，确保 30+ 关系密度下主线（solves / measures）依然清晰可读。

### 导出质量契约

- 导出路由现在是显式决策：只有当蓝图结构明确匹配某个专用视图时才会切过去，否则默认停在 `freeflow`。
- 视觉风格是显式样式叠加，不是路由选择。需要差异化效果时用 `--visual-profile auto`，需要旧版对照时用 `base`。
- SVG 输出在落盘前会做结构完整性检查，先覆盖缺失 defs 引用和基础画布越界。
- 导出阈值和缺陷分类放在 [`evals/`](evals) 下，用 machine-readable 资产支撑 route 和 integrity 行为，而不是只靠文字说明。
- `business_blueprint.showcase_matrix` 可生成多行业、多视觉 profile 的 SVG 对比矩阵，并写出 `showcase-summary.json`。
- `business_blueprint.validation_matrix` 可为每个行业模板生成一个中等复杂度 JSON/SVG/HTML 验证包，并写出 `template-validation-summary.json`。
- `business_blueprint.render_png` 提供可选 PNG 渲染探针；只有安装 CairoSVG 时才渲染，否则返回 skipped JSON，不算导出失败。
- Windows / 终端支持是收敛范围的：推荐统一走 `python -m business_blueprint.cli`，遇到编码敏感场景时显式设置 `PYTHONIOENCODING=utf-8`。

### Skill Evals

`kai-business-blueprint` 现在有两层 eval：

- `evals/` 和 `scripts/tests/` 下的导出/回归 eval，用来锁定路由、SVG 完整性、schema、projection 和 CLI 行为。
- captured-run skill eval，用 normalized trace 对每个 case 打四类分：Outcome、Process、Style、Efficiency，每类 25 分。

运行离线基线：

```bash
python3 scripts/run-skill-evals.py --root . --runner fixture
```

运行发布验证：

```bash
python3 scripts/verify-release.py --root .
```

默认 skill eval 是 **agent 无关** 的：只读取仓库内 normalized fixture，不会调用 Codex、Claude、Qoder、OpenClaw、模型 API 或网络。要评估任何外部 agent 的真实运行结果，先把运行记录转换成 normalized trace，再执行：

```bash
python3 scripts/run-skill-evals.py --root . --runner trace --case-id <case-id> --normalized-trace <trace.json>
```

当前保存的基线：

- 文件：[`evals/baselines/2026-05-17-skill-evals-fixture.json`](evals/baselines/2026-05-17-skill-evals-fixture.json)
- 汇总：`6 passed, 0 failed, 0 incomplete`
- 平均分：`99.67/100`
- 分类平均分：Outcome `25.00`、Process `25.00`、Style `24.67`、Efficiency `25.00`

### 典型工作流

**从原始文本开始：**
```bash
# 第一步：解析为标准 JSON
business-blueprint --plan "ERP 支持 POS 系统..." --from meeting-notes.md --industry retail

# 第二步：生成查看器
business-blueprint --generate solution.blueprint.json

# 第三步：导出图表
business-blueprint --export solution.blueprint.json --visual-profile auto
```

**对比多种视觉风格：**
```bash
python scripts/business_blueprint/showcase_matrix.py --output projects/workspace/showcase --industries common,retail --visual-profiles executive-clean,dark-ops,warm-consulting
```

**每个模板生成一个中等复杂度验证蓝图：**
```bash
python scripts/business_blueprint/validation_matrix.py --output projects/workspace/template-validation
```

**可选 PNG 检查：**
```bash
python scripts/business_blueprint/render_png.py projects/workspace/showcase/common/executive-clean/solution.svg
```

**编辑现有蓝图：**
```bash
# 手动编辑 JSON 或让 AI 编辑
# 然后刷新查看器（通过 editor.fieldLocks 保留人工编辑的字段）
business-blueprint --edit solution.blueprint.json
```

**导出前验证：**
```bash
business-blueprint --validate solution.blueprint.json
# 修复错误后：
business-blueprint --export solution.blueprint.json
```

**准备下游 machine handoff：**
```bash
business-blueprint --project solution.blueprint.json
```

---

## 输出产物

| 文件 | 角色 |
|------|------|
| `solution.blueprint.json` | 标准 IR——唯一事实来源 |
| `solution.projection.json` | 规范化的下游机器投影 |
| `solution.viewer.html` | 静态查看器 + 轻量编辑器 |
| `solution.exports/` | SVG、draw.io、Excalidraw、Mermaid 导出 |
| `solution.patch.jsonl` | 编辑追溯日志（JSON patches） |
| `solution.handoff.json` | viewer 修订版本清单 |

### SVG 架构导出

SVG 导出渲染三层架构图：

- **应用系统**（顶部）——ERP、CRM、POS 等
- **业务能力**（中间）——门店运营、会员管理、订单管理
- **流程步骤**（底部）——带能力关联的泳道流程图
- **角色**（右侧列）——与对应系统对齐的人员角色
- **语义箭头**——4 种类型，各有独立颜色/标记：`支撑`（绿色实线）、`依赖`（灰色虚线）、`数据流`（蓝色实线）、`负责`（黄色点线）
- **语义节点形状**——菱形用于流程步骤、左侧色条用于系统、圆角矩形用于能力、药丸形用于角色
- **行业主题**——零售（橙色）、金融（蓝色）、制造（灰色）叠加色
- **视觉 profile**——面向高管、技术蓝图、运营、咨询和知识画布的可选样式叠加

层高度通过两遍布局动态计算：第一遍放置所有节点，第二遍计算精确的内容高度，确保角色、多行流程、堆叠的能力永远不会溢出。

---

## 项目结构

```
kai-business-blueprint/
├── SKILL.md                      # 技能定义（路由层）
├── business_blueprint/           # Python 引擎（零外部依赖）
│   ├── cli.py                    # 命令行入口
│   ├── generate.py               # 从文本生成蓝图
│   ├── model.py                  # 数据模型与顶层结构
│   ├── projection.py             # 下游 projection 构建器
│   ├── validate.py               # 机器可读验证
│   ├── clarify.py                # 澄清请求构建器
│   ├── normalize.py              # 实体解析与同义词合并
│   ├── viewer.py                 # HTML 查看器写入器
│   ├── export_theme.py           # 共享导出主题 token 与语义颜色
│   ├── export_text.py            # 共享 SVG 文本测宽与换行 helper
│   ├── export_routes.py          # 显式导出路由决策
│   ├── export_integrity.py       # 导出结构完整性检查与 diagnostics
│   ├── export_svg.py             # SVG 导出器（两遍布局、内容路由、自由流式布局）
│   ├── export_drawio.py          # draw.io 导出器
│   ├── export_excalidraw.py      # Excalidraw 导出器
│   ├── export_mermaid.py         # Mermaid 导出器
│   ├── visual_profiles.py        # 业务视觉 profile 注册表与调色板叠加
│   ├── showcase_matrix.py        # 多行业/profile SVG showcase 生成器
│   ├── validation_matrix.py      # 每个模板一个中等复杂度验证蓝图生成器
│   ├── render_png.py             # 可选 CairoSVG PNG 渲染探针
│   ├── templates/                # 行业包（通用、零售、金融、制造）
│   ├── assets/                   # viewer.html 模板
│   └── specs/                    # 蓝图 schema 定义
├── references/                   # Schema、编写规则、行业包
├── tests/                        # 测试套件
├── demos/                        # 演示蓝图与导出
└── examples/                     # 示例蓝图 JSON
```

---

## 架构规则

引擎强制执行以下结构规则：

| 规则 | 说明 |
|------|------|
| **每个能力必须关联到系统** | 不允许孤立的能力 |
| **每个流程步骤必须关联到能力** | 不允许悬空的流程 |
| **角色 → 系统** | 角色必须引用有效的系统 ID |
| **无循环关系** | 系统 → 能力 → 流程 必须是有向无环图 |

运行 `--validate` 检查所有规则。警告表示潜在问题（如某个系统没有任何能力），错误会阻止导出。

---

## 面向 AI 智能体

其他技能应通过提示词编排来消费蓝图产物，而不是通过 viewer handoff manifest：

```
# 1. 先准备 machine artifacts
business-blueprint --plan solution.blueprint.json --from "..."
business-blueprint --project solution.blueprint.json

# 2. 再用提示词驱动 report-creator
"Use solution.blueprint.json and solution.projection.json to generate a report IR first. Do not render HTML yet."

# 3. 再用提示词驱动 slide-creator
"Use solution.blueprint.json and solution.projection.json to generate PLANNING.md first. Do not generate HTML yet."
```

可直接复用的提示词模板见 [references/prompt-orchestration-templates.md](references/prompt-orchestration-templates.md)。

`solution.handoff.json` 只用于 viewer manifest，不要把它当作 report / slide 的输入。

**提取结构化数据：**
```python
import json

with open("solution.blueprint.json") as f:
    bp = json.load(f)

# 系统
for sys in bp["library"].get("systems", []):
    print(f"系统: {sys['name']}")

# 能力
for cap in bp["library"].get("capabilities", []):
    print(f"能力: {cap['name']}")

# 关系
for rel in bp["relations"]:
    print(f"{rel['from']} --{rel['type']}--> {rel['to']}")
```

---

## 依赖要求

| 要求 | 版本 | 说明 |
|------|------|------|
| **Python** | >= 3.12 | 零外部依赖 |

---

## 兼容性

| 平台 | 版本 | 安装路径 |
|------|------|----------|
| Claude Code | 任意 | `~/.claude/skills/kai-business-blueprint/` |
| OpenClaw | >= 0.9 | `~/.openclaw/skills/kai-business-blueprint/` |

---

## 版本日志

**v0.16.2** — 包含完整文档的 eval 发布：更新 README 中英文下载链接到最新 GitHub Release，把完整 business-blueprint skill eval 实现方案记录到 `evals/`，并继续保留 agent 无关基线用于后续比较（`99.67/100`，6 个 case 全通过）。

**v0.16.1** — Agent 无关 skill eval 发布：新增 business-blueprint captured-run skill eval，包含 normalized fixture traces、prompt manifest、rubric schema、style fixtures、已保存基线（`99.67/100`，6 个 case 全通过）和 release verification 入口。eval harness 只消费 fixture 或 normalized trace JSON，不依赖 Codex、Claude、Qoder、OpenClaw、模型 API 或网络。

**v0.16.0** — 视觉 profile 与 showcase 加固补充：新增差异化 validation/showcase 输出与带版本的 viewer 元数据。

**v0.15.0** — 视觉 profile 与 showcase 加固：新增 `executive-clean`、`blueprint-technical`、`dark-ops`、`warm-consulting`、`knowledge-canvas` 五种 SVG/HTML 视觉风格，并支持 `--visual-profile auto`，避免不同蓝图模板都退化成同一种样式。新增 showcase matrix 生成器、每模板中等复杂度验证生成器、可选 CairoSVG PNG 渲染探针、Windows UTF-8 模板读取修复，并补齐 profile 元数据、prompt 审计记录、CLI 透传、showcase summary、validation summary、PNG skip/render 行为的回归测试。

**v0.14.0** — Domain-knowledge 蓝图：在原有架构蓝图（capabilities / actors / flowSteps / systems）之外，新增 know-how pitch 蓝图类型——痛点、策略、规则、指标、最佳实践、常见误区六类实体。pipeline 内置三大质量机制：**澄清回合**（validator 强制 ≥3 条指向具体实体的 clarifyRequests）、**实体自检**（每个实体可声明自身不确定项，渲染为琥珀色 `?` 标记）、**`--refine` 命令**（LLM 输出结构化 diff 自动应用产生新版本）。新增 `cross-border-ecommerce` 行业模板（深度验证），retail / finance / manufacturing 模板补充 `knowledgeHints`（标记 [REDACTED_SECRET]，AI 使用时必须向用户披露此限制）。知识图渲染采用三段式布局（规则 band / 痛点-策略-指标三联画 / 实践-误区胶囊），按 `solves` / `measures` 行对齐，跨区使用三阶贝塞尔曲线，关系分三档透明度避免视觉过载。Free-flow 渲染器同步切换为贝塞尔曲线。新增 67 条单元测试（共 85 条），锁定 v2 行为。

**v0.13.0** — 意图解析与标签遮挡修复：将 `IntentResolver` + `RuleEngine` 集成到 SVG 导出 pipeline，使 layer 分配数据驱动；修复自由流式布局下标签与节点的视觉遮挡。

**v0.10.0** — 质量加固发布：新增显式导出路由决策与 SVG 完整性检查，并在 fallback 失败时返回结构化 diagnostics；补齐 `evals/` 下的 machine-readable 评测资产（阈值、缺陷分类、路由 fixture、评分 schema）；增强 CLI 对带空格路径、CRLF 输入和 UTF-8 校验输出的跨平台兼容；将共享导出文本/主题 helper 从 `export_svg.py` 中拆出；并修正演进时间线在暗黑主题下的卡片底色与多胶囊换行溢出问题。

**v0.9.0** — Canonical projection 发布：新增 `--project` 生成 `solution.projection.json`；补齐面向 report/slide 下游 skill 的 prompt-native 编排模板；明确非标准图形默认回退 `freeflow`；并完成一整轮 SVG 导出质量升级，覆盖海报图、泳道图、层次图、演进图，包括暗黑主题修复、标签避让、按宽度换行、卡片居中和新增回归测试。

**v0.8.0** — 技能重命名：从 `business-blueprint-skill` 更名为 `kai-business-blueprint`；更新所有 GitHub 链接、安装路径与文档引用。

**v0.7.0** — 视觉增强：4 种语义箭头类型（支撑/依赖/数据流/负责），各有独立颜色、虚线样式和 SVG 标记；语义节点形状（菱形用于流程步骤、左侧色条用于系统、圆角矩形用于能力、药丸形用于角色）；3 个行业主题叠加色（零售=#F97316、金融=#3B82F6、制造=#6B7280）；HTML 模板驱动查看器生成（替代 244 行 f-string 拼接）；架构布局修复——每个唯一能力独占一列；自由流式布局现在从 `blueprint.relations` 渲染完整关系箭头；同列箭头使用直接垂直路径；区域框覆盖所有系统节点；46 条新增测试。

**v0.5.0** — 内容路由与自由流式布局引擎：`_content_router()` 根据蓝图内容自动选择视图（架构图、能力地图、泳道图、流程链）；`_layout_free_flow()` 按域分组、自动换行计算节点位置；`export_svg_auto()` 组合路由+布局；新增 CLI `--export-auto` 参数；HTML 查看器现在动态显示可用视图的标签页。

**v0.4.0** — HTML 查看器与布局修复：自包含 HTML 查看器，内嵌三个 SVG 视图（架构图、能力地图、泳道图），标签页导航，汇总卡片，暗色主题支持网格背景。

**v0.3.1** — CLI 修复：`--from` 参数长中文文本不再触发 `File name too long`，`--plan` 支持 stdin 管道输入。

**v0.2.0** — SVG 布局引擎：两遍动态层高、角色溢出修复、标题层间距、标题遮挡修复、图例截断修复。

**v0.1.0** — 初始发布：plan/generate/edit/export/validate 管道；HTML 查看器支持原地编辑；SVG/draw.io/Excalidraw/Mermaid 导出；行业模板包（通用、零售、金融、制造）。


path: demos/common.blueprint.json
content: {
  "version": "1.0",
  "meta": {
    "title": "Generated Blueprint",
    "industry": "common",
    "revisionId": "rev-20260413110352",
    "parentRevisionId": null,
    "lastModifiedAt": "2026-04-13T11:03:52Z",
    "lastModifiedBy": "ai"
  },
  "context": {
    "goals": [],
    "scope": [],
    "assumptions": [],
    "constraints": [],
    "sourceRefs": [
      {
        "type": "inline-text",
        "excerpt": "某制造企业数字化转型项目需求说明。\n\n业务目标：\n- 实现全渠道营销，覆盖会员拉新、订单履约和门店运营\n- 打通生产制造全流程，包括生产计划排程、来料质检和成品检验\n- 建立完善的仓储物流体系，实现入库出库、库存管理和供应链协同\n- 构建企业风控体系，涵盖客户风险评级、信贷审批、反欺诈和合规检查\n- 建立客户画像系统，实现精准营销和个性化服务\n\n主要角色：\n- 门店导购负责会员注册、下单和积分累计\n- 客服负责售后跟进和客户投诉处理\n- 运营负责门店日常经营和营销活动\n- 生产经理负责生产计划排程和产能调度\n- 质检员负责来料检验和成品质量把控\n- 仓库管理员负责入库出库作业和库存盘点\n- 采购专员负责供应商对接和采购申请\n- 风控分析师负责客户风险评估和预警\n- 信贷审批员负责信贷申请审批\n- 合规专员负责合规检查和审计报告\n- 财务专员负责财务报表和资金对账\n\n应用系统需求：\n- CRM 系统：管理会员、订单、客户画像\n- POS 系统：门店收银和交易处理\n- ERP 系统：企业资源计划，支撑门店运营、生产计划和仓储管理\n- MES 系统：制造执行，管理生产计划和质量检验\n- WMS 系统：仓储管理，管理出入库和库存\n- SCM 系统：供应链协同管理\n- 风控引擎：客户风险评估和反欺诈\n- 信贷系统：信贷申请审批管理\n\n核心流程：\n- 会员注册 → 下单 → 积分累计\n- 生产排程 → 来料检验 → 质检 → 入库\n- 采购申请 → 供应链协同\n- 信贷申请 → 风险评级 → 合规检查 → 客户画像构建\n"
      }
    ],
    "clarifyRequests": [],
    "clarifications": []
  },
  "library": {
    "capabilities": [
      {
        "id": "cap-membership",
        "name": "会员运营",
        "level": 1,
        "description": "管理会员拉新、促活和留存。",
        "ownerActorIds": [],
        "supportingSystemIds": [
          "sys-crm"
        ]
      },
      {
        "id": "cap-order",
        "name": "订单管理",
        "level": 1,
        "description": "管理订单创建、处理和履约。",
        "ownerActorIds": [],
        "supportingSystemIds": [
          "sys-crm",
          "sys-pos"
        ]
      },
      {
        "id": "cap-store-ops",
        "name": "门店运营",
        "level": 1,
        "description": "支撑门店日常经营和导购协作。",
        "ownerActorIds": [],
        "supportingSystemIds": [
          "sys-erp"
        ]
      },
      {
        "id": "cap-production-plan",
        "name": "生产计划管理",
        "level": 1,
        "description": "管理生产排程、产能规划和生产调度。",
        "ownerActorIds": [],
        "supportingSystemIds": [
          "sys-erp",
          "sys-mes"
        ]
      },
      {
        "id": "cap-quality-control",
        "name": "质量管理",
        "level": 1,
        "description": "管理来料检验、过程检验和成品检验。",
        "ownerActorIds": [],
        "supportingSystemIds": [
          "sys-mes"
        ]
      },
      {
        "id": "cap-warehouse",
        "name": "仓储管理",
        "level": 1,
        "description": "管理入库、出库、库存和库位。",
        "ownerActorIds": [],
        "supportingSystemIds": [
          "sys-erp",
          "sys-wms"
        ]
      },
      {
        "id": "cap-supply-chain",
        "name": "供应链协同",
        "level": 1,
        "description": "管理供应商协同、采购计划和物流。",
        "ownerActorIds": [],
        "supportingSystemIds": [
          "sys-scm"
        ]
      },
      {
        "id": "cap-risk-control",
        "name": "风险控制",
        "level": 1,
        "description": "管理风险评估、预警和处置。",
        "ownerActorIds": [],
        "supportingSystemIds": [
          "sys-riskengine",
          "sys-antifraud"
        ]
      },
      {
        "id": "cap-credit",
        "name": "信贷管理",
        "level": 1,
        "description": "管理信贷申请、审批和放款。",
        "ownerActorIds": [],
        "supportingSystemIds": [
          "sys-creditsystem"
        ]
      },
      {
        "id": "cap-compliance",
        "name": "合规管理",
        "level": 1,
        "description": "管理合规检查、审计和报告。",
        "ownerActorIds": [],
        "supportingSystemIds": []
      },
      {
        "id": "cap-customer-profile",
        "name": "客户画像",
        "level": 1,
        "description": "构建和维护客户360度画像。",
        "ownerActorIds": [],
        "supportingSystemIds": [
          "sys-crm",
          "sys-riskengine"
        ]
      }
    ],
    "actors": [
      {
        "id": "actor-store-guide",
        "name": "门店导购"
      },
      {
        "id": "actor-service",
        "name": "客服"
      },
      {
        "id": "actor-ops",
        "name": "运营"
      },
      {
        "id": "actor-production-mgr",
        "name": "生产经理"
      },
      {
        "id": "actor-quality-inspector",
        "name": "质检员"
      },
      {
        "id": "actor-warehouse-mgr",
        "name": "仓库管理员"
      },
      {
        "id": "actor-purchasing",
        "name": "采购专员"
      },
      {
        "id": "actor-risk-analyst",
        "name": "风控分析师"
      },
      {
        "id": "actor-credit-approver",
        "name": "信贷审批员"
      },
      {
        "id": "actor-compliance",
        "name": "合规专员"
      },
      {
        "id": "actor-finance",
        "name": "财务专员"
      }
    ],
    "flowSteps": [
      {
        "id": "flow-membership-register",
        "name": "会员注册",
        "actorId": "actor-store-guide",
        "capabilityIds": [
          "cap-membership"
        ],
        "systemIds": [],
        "stepType": "task",
        "inputRefs": [],
        "outputRefs": [],
        "processName": "会员生命周期",
        "seqIndex": 0,
        "nextStepIds": [
          "flow-order-create"
        ]
      },
      {
        "id": "flow-order-create",
        "name": "订单创建",
        "actorId": "actor-store-guide",
        "capabilityIds": [
          "cap-order"
        ],
        "systemIds": [],
        "stepType": "task",
        "inputRefs": [],
        "outputRefs": [],
        "processName": "会员生命周期",
        "seqIndex": 1,
        "nextStepIds": [
          "flow-points-accrual"
        ]
      },
      {
        "id": "flow-points-accrual",
        "name": "积分累计",
        "actorId": "actor-store-guide",
        "capabilityIds": [
          "cap-membership"
        ],
        "systemIds": [],
        "stepType": "task",
        "inputRefs": [],
        "outputRefs": [],
        "processName": "会员生命周期",
        "seqIndex": 2
      },
      {
        "id": "flow-service-followup",
        "name": "售后跟进",
        "actorId": "actor-service",
        "capabilityIds": [
          "cap-order"
        ],
        "systemIds": [],
        "stepType": "task",
        "inputRefs": [],
        "outputRefs": [],
        "processName": "订单履约",
        "seqIndex": 0
      },
      {
        "id": "flow-production-scheduling",
        "name": "生产排程",
        "actorId": "actor-production-mgr",
        "capabilityIds": [
          "cap-production-plan"
        ],
        "systemIds": [],
        "stepType": "task",
        "inputRefs": [],
        "outputRefs": [],
        "processName": "生产周期",
        "seqIndex": 0,
        "nextStepIds": [
          "flow-incoming-inspection"
        ]
      },
      {
        "id": "flow-incoming-inspection",
        "name": "来料检验",
        "actorId": "actor-quality-inspector",
        "capabilityIds": [
          "cap-quality-control"
        ],
        "systemIds": [],
        "stepType": "task",
        "inputRefs": [],
        "outputRefs": [],
        "processName": "生产周期",
        "seqIndex": 1,
        "nextStepIds": [
          "flow-warehouse-inbound"
        ]
      },
      {
        "id": "flow-warehouse-inbound",
        "name": "入库作业",
        "actorId": "actor-warehouse-mgr",
        "capabilityIds": [
          "cap-warehouse"
        ],
        "systemIds": [],
        "stepType": "task",
        "inputRefs": [],
        "outputRefs": [],
        "processName": "生产周期",
        "seqIndex": 2
      },
      {
        "id": "flow-purchase-request",
        "name": "采购申请",
        "actorId": "actor-purchasing",
        "capabilityIds": [
          "cap-supply-chain"
        ],
        "systemIds": [],
        "stepType": "task",
        "inputRefs": [],
        "outputRefs": [],
        "processName": "供应链流程",
        "seqIndex": 0
      },
      {
        "id": "flow-credit-application",
        "name": "信贷申请",
        "actorId": "actor-credit-approver",
        "capabilityIds": [
          "cap-credit"
        ],
        "systemIds": [],
        "stepType": "task",
        "inputRefs": [],
        "outputRefs": [],
        "processName": "信贷流程",
        "seqIndex": 0,
        "nextStepIds": [
          "flow-risk-assessment"
        ]
      },
      {
        "id": "flow-risk-assessment",
        "name": "风险评级",
        "actorId": "actor-risk-analyst",
        "capabilityIds": [
          "cap-risk-control"
        ],
        "systemIds": [],
        "stepType": "task",
        "inputRefs": [],
        "outputRefs": [],
        "processName": "信贷流程",
        "seqIndex": 1,
        "nextStepIds": [
          "flow-compliance-check"
        ]
      },
      {
        "id": "flow-compliance-check",
        "name": "合规检查",
        "actorId": "actor-compliance",
        "capabilityIds": [
          "cap-compliance"
        ],
        "systemIds": [],
        "stepType": "task",
        "inputRefs": [],
        "outputRefs": [],
        "processName": "信贷流程",
        "seqIndex": 2,
        "nextStepIds": [
          "flow-customer-profiling"
        ]
      },
      {
        "id": "flow-customer-profiling",
        "name": "客户画像构建",
        "actorId": "actor-risk-analyst",
        "capabilityIds": [
          "cap-customer-profile"
        ],
        "systemIds": [],
        "stepType": "task",
        "inputRefs": [],
        "outputRefs": [],
        "processName": "信贷流程",
        "seqIndex": 3
      }
    ],
    "systems": [
      {
        "id": "sys-crm",
        "kind": "system",
        "name": "CRM",
        "aliases": [],
        "description": "客户关系管理系统",
        "resolution": {
          "status": "canonical",
          "canonicalName": "CRM"
        },
        "capabilityIds": [
          "cap-membership",
          "cap-order",
          "cap-customer-profile"
        ]
      },
      {
        "id": "sys-pos",
        "kind": "system",
        "name": "POS",
        "aliases": [],
        "description": "门店收银与交易系统",
        "resolution": {
          "status": "canonical",
          "canonicalName": "POS"
        },
        "capabilityIds": [
          "cap-order"
        ]
      },
      {
        "id": "sys-erp",
        "kind": "system",
        "name": "ERP",
        "aliases": [],
        "description": "企业资源计划系统",
        "resolution": {
          "status": "canonical",
          "canonicalName": "ERP"
        },
        "capabilityIds": [
          "cap-store-ops",
          "cap-production-plan",
          "cap-warehouse"
        ]
      },
      {
        "id": "sys-mes",
        "kind": "system",
        "name": "MES",
        "aliases": [],
        "description": "制造执行系统",
        "resolution": {
          "status": "canonical",
          "canonicalName": "MES"
        },
        "capabilityIds": [
          "cap-production-plan",
          "cap-quality-control"
        ]
      },
      {
        "id": "sys-wms",
        "kind": "system",
        "name": "WMS",
        "aliases": [],
        "description": "仓储管理系统",
        "resolution": {
          "status": "canonical",
          "canonicalName": "WMS"
        },
        "capabilityIds": [
          "cap-warehouse"
        ]
      },
      {
        "id": "sys-scm",
        "kind": "system",
        "name": "SCM",
        "aliases": [],
        "description": "供应链管理系统",
        "resolution": {
          "status": "canonical",
          "canonicalName": "SCM"
        },
        "capabilityIds": [
          "cap-supply-chain"
        ]
      },
      {
        "id": "sys-riskengine",
        "kind": "system",
        "name": "risk-engine",
        "aliases": [],
        "description": "风控引擎系统",
        "resolution": {
          "status": "canonical",
          "canonicalName": "risk-engine"
        },
        "capabilityIds": [
          "cap-risk-control",
          "cap-customer-profile"
        ]
      },
      {
        "id": "sys-creditsystem",
        "kind": "system",
        "name": "credit-system",
        "aliases": [],
        "description": "信贷管理系统",
        "resolution": {
          "status": "canonical",
          "canonicalName": "credit-system"
        },
        "capabilityIds": [
          "cap-credit"
        ]
      },
      {
        "id": "sys-antifraud",
        "kind": "system",
        "name": "anti-fraud",
        "aliases": [],
        "description": "反欺诈系统",
        "resolution": {
          "status": "canonical",
          "canonicalName": "anti-fraud"
        },
        "capabilityIds": [
          "cap-risk-control"
        ]
      }
    ]
  },
  "relations": [
    {
      "id": "rel-sys-crm-cap-membership",
      "type": "supports",
      "from": "sys-crm",
      "to": "cap-membership",
      "label": "支撑"
    },
    {
      "id": "rel-sys-crm-cap-order",
      "type": "supports",
      "from": "sys-crm",
      "to": "cap-order",
      "label": "支撑"
    },
    {
      "id": "rel-sys-crm-cap-customer-profile",
      "type": "supports",
      "from": "sys-crm",
      "to": "cap-customer-profile",
      "label": "支撑"
    },
    {
      "id": "rel-sys-pos-cap-order",
      "type": "supports",
      "from": "sys-pos",
      "to": "cap-order",
      "label": "支撑"
    },
    {
      "id": "rel-sys-erp-cap-store-ops",
      "type": "supports",
      "from": "sys-erp",
      "to": "cap-store-ops",
      "label": "支撑"
    },
    {
      "id": "rel-sys-erp-cap-production-plan",
      "type": "supports",
      "from": "sys-erp",
      "to": "cap-production-plan",
      "label": "支撑"
    },
    {
      "id": "rel-sys-erp-cap-warehouse",
      "type": "supports",
      "from": "sys-erp",
      "to": "cap-warehouse",
      "label": "支撑"
    },
    {
      "id": "rel-sys-mes-cap-production-plan",
      "type": "supports",
      "from": "sys-mes",
      "to": "cap-production-plan",
      "label": "支撑"
    },
    {
      "id": "rel-sys-mes-cap-quality-control",
      "type": "supports",
      "from": "sys-mes",
      "to": "cap-quality-control",
      "label": "支撑"
    },
    {
      "id": "rel-sys-wms-cap-warehouse",
      "type": "supports",
      "from": "sys-wms",
      "to": "cap-warehouse",
      "label": "支撑"
    },
    {
      "id": "rel-sys-scm-cap-supply-chain",
      "type": "supports",
      "from": "sys-scm",
      "to": "cap-supply-chain",
      "label": "支撑"
    },
    {
      "id": "rel-sys-riskengine-cap-risk-control",
      "type": "supports",
      "from": "sys-riskengine",
      "to": "cap-risk-control",
      "label": "支撑"
    },
    {
      "id": "rel-sys-riskengine-cap-customer-profile",
      "type": "supports",
      "from": "sys-riskengine",
      "to": "cap-customer-profile",
      "label": "支撑"
    },
    {
      "id": "rel-sys-creditsystem-cap-credit",
      "type": "supports",
      "from": "sys-creditsystem",
      "to": "cap-credit",
      "label": "支撑"
    },
    {
      "id": "rel-sys-antifraud-cap-risk-control",
      "type": "supports",
      "from": "sys-antifraud",
      "to": "cap-risk-control",
      "label": "支撑"
    },
    {
      "id": "rel-cap-membership-actor-store-guide",
      "type": "owned-by",
      "from": "cap-membership",
      "to": "actor-store-guide",
      "label": "执行"
    },
    {
      "id": "rel-cap-order-actor-store-guide",
      "type": "owned-by",
      "from": "cap-order",
      "to": "actor-store-guide",
      "label": "执行"
    },
    {
      "id": "rel-cap-order-actor-service",
      "type": "owned-by",
      "from": "cap-order",
      "to": "actor-service",
      "label": "执行"
    },
    {
      "id": "rel-cap-production-plan-actor-production-mgr",
      "type": "owned-by",
      "from": "cap-production-plan",
      "to": "actor-production-mgr",
      "label": "执行"
    },
    {
      "id": "rel-cap-quality-control-actor-quality-inspector",
      "type": "owned-by",
      "from": "cap-quality-control",
      "to": "actor-quality-inspector",
      "label": "执行"
    },
    {
      "id": "rel-cap-warehouse-actor-warehouse-mgr",
      "type": "owned-by",
      "from": "cap-warehouse",
      "to": "actor-warehouse-mgr",
      "label": "执行"
    },
    {
      "id": "rel-cap-supply-chain-actor-purchasing",
      "type": "owned-by",
      "from": "cap-supply-chain",
      "to": "actor-purchasing",
      "label": "执行"
    },
    {
      "id": "rel-cap-credit-actor-credit-approver",
      "type": "owned-by",
      "from": "cap-credit",
      "to": "actor-credit-approver",
      "label": "执行"
    },
    {
      "id": "rel-cap-risk-control-actor-risk-analyst",
      "type": "owned-by",
      "from": "cap-risk-control",
      "to": "actor-risk-analyst",
      "label": "执行"
    },
    {
      "id": "rel-cap-compliance-actor-compliance",
      "type": "owned-by",
      "from": "cap-compliance",
      "to": "actor-compliance",
      "label": "执行"
    },
    {
      "id": "rel-cap-customer-profile-actor-risk-analyst",
      "type": "owned-by",
      "from": "cap-customer-profile",
      "to": "actor-risk-analyst",
      "label": "执行"
    },
    {
      "id": "rel-flow-flow-membership-register-flow-order-create",
      "type": "flows-to",
      "from": "flow-membership-register",
      "to": "flow-order-create",
      "label": "→"
    },
    {
      "id": "rel-flow-flow-order-create-flow-points-accrual",
      "type": "flows-to",
      "from": "flow-order-create",
      "to": "flow-points-accrual",
      "label": "→"
    },
    {
      "id": "rel-flow-flow-production-scheduling-flow-incoming-inspection",
      "type": "flows-to",
      "from": "flow-production-scheduling",
      "to": "flow-incoming-inspection",
      "label": "→"
    },
    {
      "id": "rel-flow-flow-incoming-inspection-flow-warehouse-inbound",
      "type": "flows-to",
      "from": "flow-incoming-inspection",
      "to": "flow-warehouse-inbound",
      "label": "→"
    },
    {
      "id": "rel-flow-flow-credit-application-flow-risk-assessment",
      "type": "flows-to",
      "from": "flow-credit-application",
      "to": "flow-risk-assessment",
      "label": "→"
    },
    {
      "id": "rel-flow-flow-risk-assessment-flow-compliance-check",
      "type": "flows-to",
      "from": "flow-risk-assessment",
      "to": "flow-compliance-check",
      "label": "→"
    },
    {
      "id": "rel-flow-flow-compliance-check-flow-customer-profiling",
      "type": "flows-to",
      "from": "flow-compliance-check",
      "to": "flow-customer-profiling",
      "label": "→"
    }
  ],
  "views": [
    {
      "id": "view-capability",
      "type": "business-capability-map",
      "title": "业务能力蓝图",
      "includedNodeIds": [
        "cap-membership",
        "cap-order",
        "cap-store-ops",
        "cap-production-plan",
        "cap-quality-control",
        "cap-warehouse",
        "cap-supply-chain",
        "cap-risk-control",
        "cap-credit",
        "cap-compliance",
        "cap-customer-profile"
      ],
      "includedRelationIds": [],
      "layout": {
        "groups": []
      },
      "annotations": []
    },
    {
      "id": "view-swimlane",
      "type": "swimlane-flow",
      "title": "泳道流程图",
      "includedNodeIds": [
        "actor-store-guide",
        "actor-service",
        "actor-ops",
        "actor-production-mgr",
        "actor-quality-inspector",
        "actor-warehouse-mgr",
        "actor-purchasing",
        "actor-risk-analyst",
        "actor-credit-approver",
        "actor-compliance",
        "actor-finance",
        "flow-membership-register",
        "flow-order-create",
        "flow-points-accrual",
        "flow-service-followup",
        "flow-production-scheduling",
        "flow-incoming-inspection",
        "flow-warehouse-inbound",
        "flow-purchase-request",
        "flow-credit-application",
        "flow-risk-assessment",
        "flow-compliance-check",
        "flow-customer-profiling"
      ],
      "includedRelationIds": [],
      "layout": {
        "lanes": [
          "actor-store-guide",
          "actor-service",
          "actor-ops",
          "actor-production-mgr",
          "actor-quality-inspector",
          "actor-warehouse-mgr",
          "actor-purchasing",
          "actor-risk-analyst",
          "actor-credit-approver",
          "actor-compliance",
          "actor-finance"
        ]
      },
      "annotations": []
    },
    {
      "id": "view-architecture",
      "type": "application-architecture",
      "title": "应用架构图",
      "includedNodeIds": [
        "sys-crm",
        "sys-pos",
        "sys-erp",
        "sys-mes",
        "sys-wms",
        "sys-scm",
        "sys-riskengine",
        "sys-creditsystem",
        "sys-antifraud",
        "cap-membership",
        "cap-order",
        "cap-store-ops",
        "cap-production-plan",
        "cap-quality-control",
        "cap-warehouse",
        "cap-supply-chain",
        "cap-risk-control",
        "cap-credit",
        "cap-compliance",
        "cap-customer-profile"
      ],
      "includedRelationIds": [],
      "layout": {
        "groups": []
      },
      "annotations": []
    }
  ],
  "editor": {
    "fieldLocks": {},
    "theme": "enterprise-default"
  },
  "artifacts": {}
}


path: demos/finance.blueprint.json
content: {
  "version": "1.0",
  "meta": {
    "title": "Generated Blueprint",
    "industry": "finance",
    "revisionId": "rev-20260413040725",
    "parentRevisionId": null,
    "lastModifiedAt": "2026-04-13T04:07:25Z",
    "lastModifiedBy": "ai"
  },
  "context": {
    "goals": [],
    "scope": [],
    "assumptions": [],
    "constraints": [],
    "sourceRefs": [
      {
        "type": "inline-text",
        "excerpt": "金融风控平台方案，需要信贷审批、风险评级、合规检查、客户画像。核心系统包括风控引擎、信贷系统、CRM、反欺诈系统。主要角色有风控分析师、信贷审批员、合规专员。"
      }
    ],
    "clarifyRequests": [],
    "clarifications": []
  },
  "library": {
    "capabilities": [
      {
        "id": "cap-risk-control",
        "name": "风险控制",
        "level": 1,
        "description": "管理风险评估、预警和处置。",
        "ownerActorIds": [],
        "supportingSystemIds": [
          "sys-riskengine",
          "sys-antifraud"
        ]
      },
      {
        "id": "cap-credit",
        "name": "信贷管理",
        "level": 1,
        "description": "管理信贷申请、审批和放款。",
        "ownerActorIds": [],
        "supportingSystemIds": [
          "sys-creditsystem"
        ]
      },
      {
        "id": "cap-compliance",
        "name": "合规管理",
        "level": 1,
        "description": "管理合规检查、审计和报告。",
        "ownerActorIds": [],
        "supportingSystemIds": []
      },
      {
        "id": "cap-customer-profile",
        "name": "客户画像",
        "level": 1,
        "description": "构建和维护客户360度画像。",
        "ownerActorIds": [],
        "supportingSystemIds": [
          "sys-crm",
          "sys-riskengine"
        ]
      }
    ],
    "actors": [
      {
        "id": "actor-risk-analyst",
        "name": "风控分析师"
      },
      {
        "id": "actor-credit-approver",
        "name": "信贷审批员"
      },
      {
        "id": "actor-compliance",
        "name": "合规专员"
      }
    ],
    "flowSteps": [
      {
        "id": "flow-risk-assessment",
        "name": "风险评级",
        "actorId": "actor-risk-analyst",
        "capabilityIds": [
          "cap-risk-control"
        ],
        "systemIds": [],
        "stepType": "task",
        "inputRefs": [],
        "outputRefs": []
      },
      {
        "id": "flow-compliance-check",
        "name": "合规检查",
        "actorId": "actor-compliance",
        "capabilityIds": [
          "cap-compliance"
        ],
        "systemIds": [],
        "stepType": "task",
        "inputRefs": [],
        "outputRefs": []
      },
      {
        "id": "flow-customer-profiling",
        "name": "客户画像构建",
        "actorId": "actor-risk-analyst",
        "capabilityIds": [
          "cap-customer-profile"
        ],
        "systemIds": [],
        "stepType": "task",
        "inputRefs": [],
        "outputRefs": []
      }
    ],
    "systems": [
      {
        "id": "sys-crm",
        "kind": "system",
        "name": "CRM",
        "aliases": [],
        "description": "客户关系管理系统",
        "resolution": {
          "status": "canonical",
          "canonicalName": "CRM"
        },
        "capabilityIds": [
          "cap-customer-profile"
        ]
      },
      {
        "id": "sys-riskengine",
        "kind": "system",
        "name": "risk-engine",
        "aliases": [],
        "description": "风控引擎系统",
        "resolution": {
          "status": "canonical",
          "canonicalName": "risk-engine"
        },
        "capabilityIds": [
          "cap-risk-control",
          "cap-customer-profile"
        ]
      },
      {
        "id": "sys-creditsystem",
        "kind": "system",
        "name": "credit-system",
        "aliases": [],
        "description": "信贷管理系统",
        "resolution": {
          "status": "canonical",
          "canonicalName": "credit-system"
        },
        "capabilityIds": [
          "cap-credit"
        ]
      },
      {
        "id": "sys-antifraud",
        "kind": "system",
        "name": "anti-fraud",
        "aliases": [],
        "description": "反欺诈系统",
        "resolution": {
          "status": "canonical",
          "canonicalName": "anti-fraud"
        },
        "capabilityIds": [
          "cap-risk-control"
        ]
      }
    ]
  },
  "relations": [],
  "views": [
    {
      "id": "view-capability",
      "type": "business-capability-map",
      "title": "业务能力蓝图",
      "includedNodeIds": [
        "cap-risk-control",
        "cap-credit",
        "cap-compliance",
        "cap-customer-profile"
      ],
      "includedRelationIds": [],
      "layout": {
        "groups": []
      },
      "annotations": []
    },
    {
      "id": "view-swimlane",
      "type": "swimlane-flow",
      "title": "泳道流程图",
      "includedNodeIds": [
        "actor-risk-analyst",
        "actor-credit-approver",
        "actor-compliance",
        "flow-risk-assessment",
        "flow-compliance-check",
        "flow-customer-profiling"
      ],
      "includedRelationIds": [],
      "layout": {
        "lanes": [
          "actor-risk-analyst",
          "actor-credit-approver",
          "actor-compliance"
        ]
      },
      "annotations": []
    },
    {
      "id": "view-architecture",
      "type": "application-architecture",
      "title": "应用架构图",
      "includedNodeIds": [
        "sys-crm",
        "sys-riskengine",
        "sys-creditsystem",
        "sys-antifraud",
        "cap-risk-control",
        "cap-credit",
        "cap-compliance",
        "cap-customer-profile"
      ],
      "includedRelationIds": [],
      "layout": {
        "groups": []
      },
      "annotations": []
    }
  ],
  "editor": {
    "fieldLocks": {},
    "theme": "enterprise-default"
  },
  "artifacts": {}
}


path: demos/manufacturing.blueprint.json
content: {
  "version": "1.0",
  "meta": {
    "title": "Generated Blueprint",
    "industry": "manufacturing",
    "revisionId": "rev-20260413040842",
    "parentRevisionId": null,
    "lastModifiedAt": "2026-04-13T04:08:42Z",
    "lastModifiedBy": "ai"
  },
  "context": {
    "goals": [],
    "scope": [],
    "assumptions": [],
    "constraints": [],
    "sourceRefs": [
      {
        "type": "inline-text",
        "excerpt": "制造业数字化转型方案，需要生产计划管理、质检管理、仓储物流、供应链协同。涉及ERP系统、MES制造执行系统、WMS仓储系统。角色包括生产经理、质检员、仓库管理员、采购专员。"
      }
    ],
    "clarifyRequests": [],
    "clarifications": []
  },
  "library": {
    "capabilities": [
      {
        "id": "cap-production-plan",
        "name": "生产计划管理",
        "level": 1,
        "description": "管理生产排程、产能规划和生产调度。",
        "ownerActorIds": [],
        "supportingSystemIds": [
          "sys-erp",
          "sys-mes"
        ]
      },
      {
        "id": "cap-quality-control",
        "name": "质量管理",
        "level": 1,
        "description": "管理来料检验、过程检验和成品检验。",
        "ownerActorIds": [],
        "supportingSystemIds": [
          "sys-mes"
        ]
      },
      {
        "id": "cap-warehouse",
        "name": "仓储管理",
        "level": 1,
        "description": "管理入库、出库、库存和库位。",
        "ownerActorIds": [],
        "supportingSystemIds": [
          "sys-erp",
          "sys-wms"
        ]
      },
      {
        "id": "cap-supply-chain",
        "name": "供应链协同",
        "level": 1,
        "description": "管理供应商协同、采购计划和物流。",
        "ownerActorIds": [],
        "supportingSystemIds": []
      }
    ],
    "actors": [
      {
        "id": "actor-production-mgr",
        "name": "生产经理"
      },
      {
        "id": "actor-quality-inspector",
        "name": "质检员"
      },
      {
        "id": "actor-warehouse-mgr",
        "name": "仓库管理员"
      },
      {
        "id": "actor-purchasing",
        "name": "采购专员"
      }
    ],
    "flowSteps": [
      {
        "id": "flow-production-scheduling",
        "name": "生产排程",
        "actorId": "actor-production-mgr",
        "capabilityIds": [
          "cap-production-plan"
        ],
        "systemIds": [],
        "stepType": "task",
        "inputRefs": [],
        "outputRefs": []
      },
      {
        "id": "flow-incoming-inspection",
        "name": "来料检验",
        "actorId": "actor-quality-inspector",
        "capabilityIds": [
          "cap-quality-control"
        ],
        "systemIds": [],
        "stepType": "task",
        "inputRefs": [],
        "outputRefs": []
      },
      {
        "id": "flow-warehouse-inbound",
        "name": "入库作业",
        "actorId": "actor-warehouse-mgr",
        "capabilityIds": [
          "cap-warehouse"
        ],
        "systemIds": [],
        "stepType": "task",
        "inputRefs": [],
        "outputRefs": []
      },
      {
        "id": "flow-purchase-request",
        "name": "采购申请",
        "actorId": "actor-purchasing",
        "capabilityIds": [
          "cap-supply-chain"
        ],
        "systemIds": [],
        "stepType": "task",
        "inputRefs": [],
        "outputRefs": []
      }
    ],
    "systems": [
      {
        "id": "sys-erp",
        "kind": "system",
        "name": "ERP",
        "aliases": [],
        "description": "企业资源计划系统",
        "resolution": {
          "status": "canonical",
          "canonicalName": "ERP"
        },
        "capabilityIds": [
          "cap-production-plan",
          "cap-warehouse"
        ]
      },
      {
        "id": "sys-mes",
        "kind": "system",
        "name": "MES",
        "aliases": [],
        "description": "制造执行系统",
        "resolution": {
          "status": "canonical",
          "canonicalName": "MES"
        },
        "capabilityIds": [
          "cap-production-plan",
          "cap-quality-control"
        ]
      },
      {
        "id": "sys-wms",
        "kind": "system",
        "name": "WMS",
        "aliases": [],
        "description": "仓储管理系统",
        "resolution": {
          "status": "canonical",
          "canonicalName": "WMS"
        },
        "capabilityIds": [
          "cap-warehouse"
        ]
      }
    ]
  },
  "relations": [],
  "views": [
    {
      "id": "view-capability",
      "type": "business-capability-map",
      "title": "业务能力蓝图",
      "includedNodeIds": [
        "cap-production-plan",
        "cap-quality-control",
        "cap-warehouse",
        "cap-supply-chain"
      ],
      "includedRelationIds": [],
      "layout": {
        "groups": []
      },
      "annotations": []
    },
    {
      "id": "view-swimlane",
      "type": "swimlane-flow",
      "title": "泳道流程图",
      "includedNodeIds": [
        "actor-production-mgr",
        "actor-quality-inspector",
        "actor-warehouse-mgr",
        "actor-purchasing",
        "flow-production-scheduling",
        "flow-incoming-inspection",
        "flow-warehouse-inbound",
        "flow-purchase-request"
      ],
      "includedRelationIds": [],
      "layout": {
        "lanes": [
          "actor-production-mgr",
          "actor-quality-inspector",
          "actor-warehouse-mgr",
          "actor-purchasing"
        ]
      },
      "annotations": []
    },
    {
      "id": "view-architecture",
      "type": "application-architecture",
      "title": "应用架构图",
      "includedNodeIds": [
        "sys-erp",
        "sys-mes",
        "sys-wms",
        "cap-production-plan",
        "cap-quality-control",
        "cap-warehouse",
        "cap-supply-chain"
      ],
      "includedRelationIds": [],
      "layout": {
        "groups": []
      },
      "annotations": []
    }
  ],
  "editor": {
    "fieldLocks": {},
    "theme": "enterprise-default"
  },
  "artifacts": {}
}


path: demos/retail.blueprint.json
content: {
  "version": "1.0",
  "meta": {
    "title": "Generated Blueprint",
    "industry": "retail",
    "revisionId": "rev-20260413040724",
    "parentRevisionId": null,
    "lastModifiedAt": "2026-04-13T04:07:24Z",
    "lastModifiedBy": "ai"
  },
  "context": {
    "goals": [],
    "scope": [],
    "assumptions": [],
    "constraints": [],
    "sourceRefs": [
      {
        "type": "inline-text",
        "excerpt": "我们需要一套零售门店数字化方案，支持会员注册、积分累计、订单创建、售后跟进。系统包括CRM、POS和ERP。"
      }
    ],
    "clarifyRequests": [
      {
        "code": "MISSING_PRIMARY_ACTOR",
        "question": "Which primary business actors should appear in the solution?",
        "affectedIds": []
      }
    ],
    "clarifications": []
  },
  "library": {
    "capabilities": [
      {
        "id": "cap-store-ops",
        "name": "门店运营",
        "level": 1,
        "description": "支撑门店日常经营和导购协作。",
        "ownerActorIds": [],
        "supportingSystemIds": [
          "sys-erp"
        ]
      },
      {
        "id": "cap-membership",
        "name": "会员运营",
        "level": 1,
        "description": "管理会员拉新、促活和留存。",
        "ownerActorIds": [],
        "supportingSystemIds": [
          "sys-crm"
        ]
      },
      {
        "id": "cap-order",
        "name": "订单管理",
        "level": 1,
        "description": "管理订单创建、处理和履约。",
        "ownerActorIds": [],
        "supportingSystemIds": [
          "sys-crm",
          "sys-pos"
        ]
      }
    ],
    "actors": [
      {
        "id": "actor-store-guide",
        "name": "门店导购"
      },
      {
        "id": "actor-service",
        "name": "客服"
      }
    ],
    "flowSteps": [
      {
        "id": "flow-membership-register",
        "name": "会员注册",
        "actorId": "actor-store-guide",
        "capabilityIds": [
          "cap-membership"
        ],
        "systemIds": [],
        "stepType": "task",
        "inputRefs": [],
        "outputRefs": []
      },
      {
        "id": "flow-points-accrual",
        "name": "积分累计",
        "actorId": "actor-store-guide",
        "capabilityIds": [
          "cap-membership"
        ],
        "systemIds": [],
        "stepType": "task",
        "inputRefs": [],
        "outputRefs": []
      },
      {
        "id": "flow-service-followup",
        "name": "售后跟进",
        "actorId": "actor-service",
        "capabilityIds": [
          "cap-order"
        ],
        "systemIds": [],
        "stepType": "task",
        "inputRefs": [],
        "outputRefs": []
      }
    ],
    "systems": [
      {
        "id": "sys-crm",
        "kind": "system",
        "name": "CRM",
        "aliases": [],
        "description": "客户关系管理系统",
        "resolution": {
          "status": "canonical",
          "canonicalName": "CRM"
        },
        "capabilityIds": [
          "cap-membership",
          "cap-order"
        ]
      },
      {
        "id": "sys-pos",
        "kind": "system",
        "name": "POS",
        "aliases": [],
        "description": "门店收银与交易系统",
        "resolution": {
          "status": "canonical",
          "canonicalName": "POS"
        },
        "capabilityIds": [
          "cap-order"
        ]
      },
      {
        "id": "sys-erp",
        "kind": "system",
        "name": "ERP",
        "aliases": [],
        "description": "企业资源计划系统",
        "resolution": {
          "status": "canonical",
          "canonicalName": "ERP"
        },
        "capabilityIds": [
          "cap-store-ops"
        ]
      }
    ]
  },
  "relations": [],
  "views": [
    {
      "id": "view-capability",
      "type": "business-capability-map",
      "title": "业务能力蓝图",
      "includedNodeIds": [
        "cap-store-ops",
        "cap-membership",
        "cap-order"
      ],
      "includedRelationIds": [],
      "layout": {
        "groups": []
      },
      "annotations": []
    },
    {
      "id": "view-swimlane",
      "type": "swimlane-flow",
      "title": "泳道流程图",
      "includedNodeIds": [
        "actor-store-guide",
        "actor-service",
        "flow-membership-register",
        "flow-points-accrual",
        "flow-service-followup"
      ],
      "includedRelationIds": [],
      "layout": {
        "lanes": ["actor-store-guide", "actor-service"]
      },
      "annotations": []
    },
    {
      "id": "view-architecture",
      "type": "application-architecture",
      "title": "应用架构图",
      "includedNodeIds": [
        "sys-crm",
        "sys-pos",
        "sys-erp",
        "cap-store-ops",
        "cap-membership",
        "cap-order"
      ],
      "includedRelationIds": [],
      "layout": {
        "groups": []
      },
      "annotations": []
    }
  ],
  "editor": {
    "fieldLocks": {},
    "theme": "enterprise-default"
  },
  "artifacts": {}
}


path: demos/screenshots/retail-arch.svg
content: <svg xmlns="http://www.w3.org/2000/svg" width="939" height="870" font-family="system-ui, -apple-system, sans-serif">
<defs><marker id="arrow-solid" markerWidth="10" markerHeight="8" refX="9" refY="4" orient="auto" markerUnits="userSpaceOnUse"><polygon points="0 0, 10 4, 0 8" fill="#0B6E6E"/></marker><marker id="arrow-dashed" markerWidth="10" markerHeight="8" refX="9" refY="4" orient="auto" markerUnits="userSpaceOnUse"><polygon points="0 0, 10 4, 0 8" fill="#94A3B8"/></marker></defs>
<rect width="939" height="870" fill="#F8FAFC"/>
<g class="title-block"><rect x="40" y="10" width="939" height="52" rx="6" fill="#FFFFFF" stroke="#CBD5E1" stroke-width="1"/><text x="56" y="34" font-size="16" fill="#0F172A" font-family="system-ui, -apple-system, sans-serif" font-weight="700">Generated Blueprint</text><text x="56" y="52" font-size="11" fill="#64748B" font-family="'JetBrains Mono', 'SF Mono', monospace">Industry: retail</text></g>
<g class="layer" id="layer-Application Systems"><rect class="layer-border" x="40" y="72" width="859" height="188" rx="8" fill="none" stroke="#E2E8F0" stroke-width="1"/><rect class="layer-header" x="40" y="72" width="859" height="32" fill="#F1F5F9"/><text class="layer-label" x="56" y="92" font-size="12" fill="#64748B" font-family="system-ui, -apple-system, sans-serif" font-weight="600" letter-spacing="0.4">Application Systems</text></g>
<g class="layer" id="layer-Business Capabilities"><rect class="layer-border" x="40" y="296" width="859" height="132" rx="8" fill="none" stroke="#E2E8F0" stroke-width="1"/><rect class="layer-header" x="40" y="296" width="859" height="32" fill="#F1F5F9"/><text class="layer-label" x="56" y="316" font-size="12" fill="#64748B" font-family="system-ui, -apple-system, sans-serif" font-weight="600" letter-spacing="0.4">Business Capabilities</text></g>
<g class="layer" id="layer-Process Flows"><rect class="layer-border" x="40" y="464" width="859" height="186" rx="8" fill="none" stroke="#E2E8F0" stroke-width="1"/><rect class="layer-header" x="40" y="464" width="859" height="32" fill="#F1F5F9"/><text class="layer-label" x="56" y="484" font-size="12" fill="#64748B" font-family="system-ui, -apple-system, sans-serif" font-weight="600" letter-spacing="0.4">Process Flows</text></g>
<line x1="198" y1="176" x2="198" y2="356" stroke="#0B6E6E" stroke-width="1.5" marker-end="url(#arrow-solid)"/>
<line x1="368" y1="176" x2="368" y2="356" stroke="#0B6E6E" stroke-width="1.5" marker-end="url(#arrow-solid)"/>
<line x1="538" y1="176" x2="538" y2="356" stroke="#0B6E6E" stroke-width="1.5" marker-end="url(#arrow-solid)"/>
<line x1="368" y1="400" x2="368" y2="524" stroke="#94A3B8" stroke-width="1.5" stroke-dasharray="5,4" marker-end="url(#arrow-dashed)"/>
<line x1="368" y1="400" x2="368" y2="578" stroke="#94A3B8" stroke-width="1.5" stroke-dasharray="5,4" marker-end="url(#arrow-dashed)"/>
<line x1="538" y1="400" x2="538" y2="524" stroke="#94A3B8" stroke-width="1.5" stroke-dasharray="5,4" marker-end="url(#arrow-dashed)"/>
<rect x="168" y="257" width="60" height="18" rx="3" fill="#FFFFFF" fill-opacity="0.9"/><text x="198" y="270" text-anchor="middle" font-size="10" fill="#475569" font-family="system-ui, -apple-system, sans-serif">supports</text>
<rect x="338" y="257" width="60" height="18" rx="3" fill="#FFFFFF" fill-opacity="0.9"/><text x="368" y="270" text-anchor="middle" font-size="10" fill="#475569" font-family="system-ui, -apple-system, sans-serif">supports</text>
<rect x="508" y="257" width="60" height="18" rx="3" fill="#FFFFFF" fill-opacity="0.9"/><text x="538" y="270" text-anchor="middle" font-size="10" fill="#475569" font-family="system-ui, -apple-system, sans-serif">supports</text>
<g class="node node-system" id="sys-erp"><rect class="node-rect" x="123" y="132" width="150" height="44" rx="4" fill="#EFF6FF" stroke="#3B82F6" stroke-width="1.5"/><text class="node-label" x="198" y="159" text-anchor="middle" font-size="12.5" fill="#0F172A" font-family="system-ui, -apple-system, sans-serif" font-weight="500">ERP</text></g>
<g class="node node-system" id="sys-crm"><rect class="node-rect" x="293" y="132" width="150" height="44" rx="4" fill="#EFF6FF" stroke="#3B82F6" stroke-width="1.5"/><text class="node-label" x="368" y="159" text-anchor="middle" font-size="12.5" fill="#0F172A" font-family="system-ui, -apple-system, sans-serif" font-weight="500">CRM</text></g>
<g class="node node-system" id="sys-pos"><rect class="node-rect" x="463" y="132" width="150" height="44" rx="4" fill="#EFF6FF" stroke="#3B82F6" stroke-width="1.5"/><text class="node-label" x="538" y="159" text-anchor="middle" font-size="12.5" fill="#0F172A" font-family="system-ui, -apple-system, sans-serif" font-weight="500">POS</text></g>
<g class="node node-actor" id="actor-store-guide"><rect class="node-rect" x="653" y="132" width="150" height="44" rx="22" fill="#FFF7ED" stroke="#F97316" stroke-width="1.5"/><text class="node-label" x="728" y="159" text-anchor="middle" font-size="12.5" fill="#0F172A" font-family="system-ui, -apple-system, sans-serif" font-weight="500">门店导购</text></g>
<g class="node node-actor" id="actor-service"><rect class="node-rect" x="653" y="188" width="150" height="44" rx="22" fill="#FFF7ED" stroke="#F97316" stroke-width="1.5"/><text class="node-label" x="728" y="215" text-anchor="middle" font-size="12.5" fill="#0F172A" font-family="system-ui, -apple-system, sans-serif" font-weight="500">客服</text></g>
<g class="node node-capability" id="cap-store-ops"><rect class="node-rect" x="123" y="356" width="150" height="44" rx="8" fill="#E8F5F5" stroke="#0B6E6E" stroke-width="1.5"/><text class="node-label" x="198" y="383" text-anchor="middle" font-size="12.5" fill="#0F172A" font-family="system-ui, -apple-system, sans-serif" font-weight="500">门店运营</text></g>
<g class="node node-capability" id="cap-membership"><rect class="node-rect" x="293" y="356" width="150" height="44" rx="8" fill="#E8F5F5" stroke="#0B6E6E" stroke-width="1.5"/><text class="node-label" x="368" y="383" text-anchor="middle" font-size="12.5" fill="#0F172A" font-family="system-ui, -apple-system, sans-serif" font-weight="500">会员运营</text></g>
<g class="node node-capability" id="cap-order"><rect class="node-rect" x="463" y="356" width="150" height="44" rx="8" fill="#E8F5F5" stroke="#0B6E6E" stroke-width="1.5"/><text class="node-label" x="538" y="383" text-anchor="middle" font-size="12.5" fill="#0F172A" font-family="system-ui, -apple-system, sans-serif" font-weight="500">订单管理</text></g>
<g class="node node-flowStep" id="flow-membership-register"><rect class="node-rect" x="293" y="524" width="150" height="44" rx="6" fill="#FEFCE8" stroke="#CA8A04" stroke-width="1.5"/><text class="node-label" x="368" y="551" text-anchor="middle" font-size="12.5" fill="#0F172A" font-family="system-ui, -apple-system, sans-serif" font-weight="500">会员注册</text></g>
<g class="node node-flowStep" id="flow-points-accrual"><rect class="node-rect" x="293" y="578" width="150" height="44" rx="6" fill="#FEFCE8" stroke="#CA8A04" stroke-width="1.5"/><text class="node-label" x="368" y="605" text-anchor="middle" font-size="12.5" fill="#0F172A" font-family="system-ui, -apple-system, sans-serif" font-weight="500">积分累计</text></g>
<g class="node node-flowStep" id="flow-service-followup"><rect class="node-rect" x="463" y="524" width="150" height="44" rx="6" fill="#FEFCE8" stroke="#CA8A04" stroke-width="1.5"/><text class="node-label" x="538" y="551" text-anchor="middle" font-size="12.5" fill="#0F172A" font-family="system-ui, -apple-system, sans-serif" font-weight="500">售后跟进</text></g>
<g class="legend" transform="translate(50, 680)">
<rect x="0" y="0" width="130" height="174" rx="6" fill="#FFFFFF" stroke="#CBD5E1" stroke-width="1" opacity="0.95"/>
<text x="12" y="20" font-size="10" fill="#64748B" font-family="system-ui, -apple-system, sans-serif" font-weight="600" letter-spacing="0.3">LEGEND</text>
<rect x="12" y="38" width="18" height="14" rx="4" fill="#EFF6FF" stroke="#3B82F6" stroke-width="1"/><text x="38" y="49" font-size="9.5" fill="#64748B" font-family="system-ui, -apple-system, sans-serif">System</text>
<rect x="12" y="60" width="18" height="14" rx="8" fill="#E8F5F5" stroke="#0B6E6E" stroke-width="1"/><text x="38" y="71" font-size="9.5" fill="#64748B" font-family="system-ui, -apple-system, sans-serif">Capability</text>
<rect x="12" y="82" width="18" height="14" rx="6" fill="#FEFCE8" stroke="#CA8A04" stroke-width="1"/><text x="38" y="93" font-size="9.5" fill="#64748B" font-family="system-ui, -apple-system, sans-serif">Flow Step</text>
<rect x="12" y="104" width="18" height="14" rx="22" fill="#FFF7ED" stroke="#F97316" stroke-width="1"/><text x="38" y="115" font-size="9.5" fill="#64748B" font-family="system-ui, -apple-system, sans-serif">Actor</text>
<line x1="12" y1="130" x2="30" y2="130" stroke="#0B6E6E" stroke-width="1.5" marker-end="url(#arrow-solid)"/><text x="38" y="134" font-size="9.5" fill="#64748B" font-family="system-ui, -apple-system, sans-serif">supports</text>
<line x1="12" y1="152" x2="30" y2="152" stroke="#94A3B8" stroke-width="1.5" stroke-dasharray="5,4" marker-end="url(#arrow-dashed)"/><text x="38" y="156" font-size="9.5" fill="#64748B" font-family="system-ui, -apple-system, sans-serif">flow-to</text>
</g>
</svg>

path: evals/README.md
content: # Evals

This directory holds machine-readable eval inputs, thresholds, taxonomy data, and saved baselines for `kai-business-blueprint`.

## Files

- `export-integrity-thresholds.json` — numeric thresholds for geometry-sensitive integrity checks
- `defect-taxonomy.json` — canonical defect categories used by tests and eval fixtures
- `export-scoring-schema.json` — minimal scoring/output schema for export eval runs
- `blueprint-skill-prompts.csv` — agent-agnostic captured-run skill eval case manifest
- `skill-run-rubric.schema.json` — structured rubric schema for qualitative blueprint style checks
- `skill-eval-implementation-plan.md` — implementation plan, baseline score, verification, and release notes for the v0.16.2 skill eval release

## Skill Evals

Captured-run skill evals score each case across four 25-point categories:

- Outcome: expected blueprint/projection/export artifacts exist and validate.
- Process: the run followed the business-blueprint workflow and read the relevant references.
- Style: the blueprint uses the requested industry/type, has semantic density, and passes a rubric.
- Efficiency: the trace stays within shell command, token, wall-time, and retry budgets.

Run the default offline baseline:

```bash
python3 scripts/run-skill-evals.py --root . --runner fixture
```

The default runner is fixture-only and does not invoke Codex, Claude, Qoder, OpenClaw, model APIs, or the network. To score an external run, first convert it into the normalized trace schema, then run:

```bash
python3 scripts/run-skill-evals.py --root . --runner trace --case-id <case-id> --normalized-trace <trace.json>
```

Current saved baseline:

- `baselines/2026-05-17-skill-evals-fixture.json`
- Average score: `99.67`
- Result: `6 passed, 0 failed, 0 incomplete`

## Fixtures

- `fixtures/route-freeflow.json` — generic graph that should stay on `freeflow`
- `fixtures/route-architecture.json` — categorized architecture graph that should resolve to `architecture-template`
- `fixtures/route-evolution.json` — dated staged flow that should resolve to `evolution`

## Usage

- Route tests read these fixtures to keep export-family decisions stable.
- Integrity tests should reference taxonomy ids instead of inventing one-off failure labels.
- Human-readable failure maps, if needed later, should be generated from these files and test references rather than hand-maintained as the source of truth.


path: evals/baselines/2026-05-17-baseline-summary.md
content: # Business Blueprint Skill Eval Baseline - 2026-05-17

Command:

```bash
python3 scripts/run-skill-evals.py --root . --runner fixture --format json --json-out evals/baselines/2026-05-17-skill-evals-fixture.json
```

Baseline score:

| Metric | Value |
| --- | ---: |
| Cases | 6 |
| Passed | 6 |
| Failed | 0 |
| Incomplete | 0 |
| Average score | 99.67 |
| Outcome average | 25.00 |
| Process average | 25.00 |
| Style average | 24.67 |
| Efficiency average | 25.00 |

Case scores:

| Case | Score | Outcome | Process | Style | Efficiency |
| --- | ---: | ---: | ---: | ---: | ---: |
| explicit-blueprint | 100 | 25 | 25 | 25 | 25 |
| implicit-meeting-notes | 99 | 25 | 25 | 24 | 25 |
| contextual-domain-knowledge | 100 | 25 | 25 | 25 | 25 |
| boundary-projection-handoff | 99 | 25 | 25 | 24 | 25 |
| negative-report | 100 | 25 | 25 | 25 | 25 |
| negative-slide-deck | 100 | 25 | 25 | 25 | 25 |

The default baseline is agent-agnostic: it uses checked-in normalized fixture
traces and never invokes Codex, Claude, Qoder, OpenClaw, model APIs, or network
access.


path: evals/baselines/2026-05-17-skill-evals-fixture.json
content: {
  "cases": [
    {
      "case_id": "explicit-blueprint",
      "total_score": 100,
      "passed": true,
      "eval_complete": true,
      "scores": {
        "outcome": 25,
        "process": 25,
        "style": 25,
        "efficiency": 25
      },
      "failures": [],
      "style_rubric": {
        "source": "fixture",
        "path": "scripts/tests/fixtures/skill-evals/explicit-blueprint-style-rubric.json",
        "score": 96,
        "overall_pass": true
      },
      "metrics": {
        "runner": "fixture",
        "trace_format_version": "normalized-v1",
        "tool_calls": [],
        "shell_commands": [
          "python3 scripts/business_blueprint/cli.py --validate scripts/tests/fixtures/skill-evals/artifacts/explicit-blueprint/solution.blueprint.json",
          "python3 scripts/business_blueprint/cli.py --export scripts/tests/fixtures/skill-evals/artifacts/explicit-blueprint/solution.blueprint.json"
        ],
        "failed_shell_commands": [],
        "read_paths": [
          "SKILL.md",
          "references/blueprint-schema.md",
          "references/entities-schema.md",
          "references/systems-schema.md",
          "references/route-eligibility.md"
        ],
        "write_paths": [
          "scripts/tests/fixtures/skill-evals/artifacts/explicit-blueprint/solution.blueprint.json",
          "scripts/tests/fixtures/skill-evals/artifacts/explicit-blueprint/solution.svg",
          "scripts/tests/fixtures/skill-evals/artifacts/explicit-blueprint/solution.viewer.html"
        ],
        "artifact_paths": [
          "scripts/tests/fixtures/skill-evals/artifacts/explicit-blueprint/solution.blueprint.json",
          "scripts/tests/fixtures/skill-evals/artifacts/explicit-blueprint/solution.svg",
          "scripts/tests/fixtures/skill-evals/artifacts/explicit-blueprint/solution.viewer.html"
        ],
        "input_tokens": 12000,
        "output_tokens": 3200,
        "wall_ms": 41000,
        "run_completed": true,
        "skill_evidence": {
          "skill_contract_read": true,
          "blueprint_flow_observed": true,
          "validate_observed": true,
          "export_observed": true,
          "projection_observed": false
        },
        "runner_warnings": []
      },
      "artifact_dir": "evals/artifacts/current/skill-runs/explicit-blueprint"
    },
    {
      "case_id": "implicit-meeting-notes",
      "total_score": 99,
      "passed": true,
      "eval_complete": true,
      "scores": {
        "outcome": 25,
        "process": 25,
        "style": 24,
        "efficiency": 25
      },
      "failures": [],
      "style_rubric": {
        "source": "fixture",
        "path": "scripts/tests/fixtures/skill-evals/implicit-meeting-notes-style-rubric.json",
        "score": 94,
        "overall_pass": true
      },
      "metrics": {
        "runner": "fixture",
        "trace_format_version": "normalized-v1",
        "tool_calls": [],
        "shell_commands": [
          "python3 scripts/business_blueprint/cli.py --validate scripts/tests/fixtures/skill-evals/artifacts/implicit-meeting-notes/solution.blueprint.json",
          "python3 scripts/business_blueprint/cli.py --export scripts/tests/fixtures/skill-evals/artifacts/implicit-meeting-notes/solution.blueprint.json"
        ],
        "failed_shell_commands": [],
        "read_paths": [
          "SKILL.md",
          "references/blueprint-schema.md",
          "references/entities-schema.md",
          "references/systems-schema.md",
          "references/route-eligibility.md"
        ],
        "write_paths": [
          "scripts/tests/fixtures/skill-evals/artifacts/implicit-meeting-notes/solution.blueprint.json",
          "scripts/tests/fixtures/skill-evals/artifacts/implicit-meeting-notes/solution.svg",
          "scripts/tests/fixtures/skill-evals/artifacts/implicit-meeting-notes/solution.viewer.html"
        ],
        "artifact_paths": [
          "scripts/tests/fixtures/skill-evals/artifacts/implicit-meeting-notes/solution.blueprint.json",
          "scripts/tests/fixtures/skill-evals/artifacts/implicit-meeting-notes/solution.svg",
          "scripts/tests/fixtures/skill-evals/artifacts/implicit-meeting-notes/solution.viewer.html"
        ],
        "input_tokens": 14800,
        "output_tokens": 3600,
        "wall_ms": 48000,
        "run_completed": true,
        "skill_evidence": {
          "skill_contract_read": true,
          "blueprint_flow_observed": true,
          "validate_observed": true,
          "export_observed": true,
          "projection_observed": false
        },
        "runner_warnings": []
      },
      "artifact_dir": "evals/artifacts/current/skill-runs/implicit-meeting-notes"
    },
    {
      "case_id": "contextual-domain-knowledge",
      "total_score": 100,
      "passed": true,
      "eval_complete": true,
      "scores": {
        "outcome": 25,
        "process": 25,
        "style": 25,
        "efficiency": 25
      },
      "failures": [],
      "style_rubric": {
        "source": "fixture",
        "path": "scripts/tests/fixtures/skill-evals/contextual-domain-knowledge-style-rubric.json",
        "score": 95,
        "overall_pass": true
      },
      "metrics": {
        "runner": "fixture",
        "trace_format_version": "normalized-v1",
        "tool_calls": [],
        "shell_commands": [
          "python3 scripts/business_blueprint/cli.py --validate scripts/tests/fixtures/skill-evals/artifacts/contextual-domain-knowledge/solution.blueprint.json",
          "python3 scripts/business_blueprint/cli.py --export scripts/tests/fixtures/skill-evals/artifacts/contextual-domain-knowledge/solution.blueprint.json"
        ],
        "failed_shell_commands": [],
        "read_paths": [
          "SKILL.md",
          "references/domain-knowledge-extraction.md",
          "references/knowledge-entities-schema.md",
          "references/blueprint-schema.md",
          "references/route-eligibility.md"
        ],
        "write_paths": [
          "scripts/tests/fixtures/skill-evals/artifacts/contextual-domain-knowledge/solution.blueprint.json",
          "scripts/tests/fixtures/skill-evals/artifacts/contextual-domain-knowledge/solution.svg",
          "scripts/tests/fixtures/skill-evals/artifacts/contextual-domain-knowledge/solution.viewer.html"
        ],
        "artifact_paths": [
          "scripts/tests/fixtures/skill-evals/artifacts/contextual-domain-knowledge/solution.blueprint.json",
          "scripts/tests/fixtures/skill-evals/artifacts/contextual-domain-knowledge/solution.svg",
          "scripts/tests/fixtures/skill-evals/artifacts/contextual-domain-knowledge/solution.viewer.html"
        ],
        "input_tokens": 17600,
        "output_tokens": 4200,
        "wall_ms": 53000,
        "run_completed": true,
        "skill_evidence": {
          "skill_contract_read": true,
          "blueprint_flow_observed": true,
          "validate_observed": true,
          "export_observed": true,
          "projection_observed": false
        },
        "runner_warnings": []
      },
      "artifact_dir": "evals/artifacts/current/skill-runs/contextual-domain-knowledge"
    },
    {
      "case_id": "boundary-projection-handoff",
      "total_score": 99,
      "passed": true,
      "eval_complete": true,
      "scores": {
        "outcome": 25,
        "process": 25,
        "style": 24,
        "efficiency": 25
      },
      "failures": [],
      "style_rubric": {
        "source": "fixture",
        "path": "scripts/tests/fixtures/skill-evals/boundary-projection-handoff-style-rubric.json",
        "score": 94,
        "overall_pass": true
      },
      "metrics": {
        "runner": "fixture",
        "trace_format_version": "normalized-v1",
        "tool_calls": [],
        "shell_commands": [
          "python3 scripts/business_blueprint/cli.py --validate scripts/tests/fixtures/skill-evals/artifacts/boundary-projection-handoff/solution.blueprint.json",
          "python3 scripts/business_blueprint/cli.py --project scripts/tests/fixtures/skill-evals/artifacts/boundary-projection-handoff/solution.blueprint.json"
        ],
        "failed_shell_commands": [],
        "read_paths": [
          "SKILL.md",
          "references/blueprint-schema.md",
          "references/entities-schema.md",
          "references/systems-schema.md",
          "references/prompt-orchestration-templates.md"
        ],
        "write_paths": [
          "scripts/tests/fixtures/skill-evals/artifacts/boundary-projection-handoff/solution.blueprint.json",
          "scripts/tests/fixtures/skill-evals/artifacts/boundary-projection-handoff/solution.projection.json"
        ],
        "artifact_paths": [
          "scripts/tests/fixtures/skill-evals/artifacts/boundary-projection-handoff/solution.blueprint.json",
          "scripts/tests/fixtures/skill-evals/artifacts/boundary-projection-handoff/solution.projection.json"
        ],
        "input_tokens": 15400,
        "output_tokens": 3500,
        "wall_ms": 46000,
        "run_completed": true,
        "skill_evidence": {
          "skill_contract_read": true,
          "blueprint_flow_observed": true,
          "validate_observed": true,
          "export_observed": false,
          "projection_observed": true
        },
        "runner_warnings": []
      },
      "artifact_dir": "evals/artifacts/current/skill-runs/boundary-projection-handoff"
    },
    {
      "case_id": "negative-report",
      "total_score": 100,
      "passed": true,
      "eval_complete": true,
      "scores": {
        "outcome": 25,
        "process": 25,
        "style": 25,
        "efficiency": 25
      },
      "failures": [],
      "style_rubric": null,
      "metrics": {
        "runner": "fixture",
        "trace_format_version": "normalized-v1",
        "tool_calls": [],
        "shell_commands": [],
        "failed_shell_commands": [],
        "read_paths": [
          "SKILL.md"
        ],
        "write_paths": [],
        "artifact_paths": [],
        "input_tokens": 1800,
        "output_tokens": 260,
        "wall_ms": 4000,
        "run_completed": true,
        "skill_evidence": {
          "skill_contract_read": true,
          "blueprint_flow_observed": false,
          "validate_observed": false,
          "export_observed": false,
          "projection_observed": false
        },
        "runner_warnings": []
      },
      "artifact_dir": "evals/artifacts/current/skill-runs/negative-report"
    },
    {
      "case_id": "negative-slide-deck",
      "total_score": 100,
      "passed": true,
      "eval_complete": true,
      "scores": {
        "outcome": 25,
        "process": 25,
        "style": 25,
        "efficiency": 25
      },
      "failures": [],
      "style_rubric": null,
      "metrics": {
        "runner": "fixture",
        "trace_format_version": "normalized-v1",
        "tool_calls": [],
        "shell_commands": [],
        "failed_shell_commands": [],
        "read_paths": [
          "SKILL.md"
        ],
        "write_paths": [],
        "artifact_paths": [],
        "input_tokens": 2100,
        "output_tokens": 310,
        "wall_ms": 5000,
        "run_completed": true,
        "skill_evidence": {
          "skill_contract_read": true,
          "blueprint_flow_observed": false,
          "validate_observed": false,
          "export_observed": false,
          "projection_observed": false
        },
        "runner_warnings": []
      },
      "artifact_dir": "evals/artifacts/current/skill-runs/negative-slide-deck"
    }
  ],
  "summary": {
    "total": 6,
    "passed": 6,
    "failed": 0,
    "incomplete": 0,
    "average_score": 99.67,
    "average_category_scores": {
      "outcome": 25.0,
      "process": 25.0,
      "style": 24.67,
      "efficiency": 25.0
    }
  }
}

path: evals/blueprint-skill-prompts.csv
content: id,kind,should_trigger,prompt_path,expected_industry,expected_blueprint_type,expected_artifact,max_shell_commands,max_input_tokens,max_output_tokens,max_wall_ms
explicit-blueprint,explicit,true,evals/skill-prompts/explicit-blueprint.md,retail,architecture,blueprint+svg+html,12,70000,18000,180000
implicit-meeting-notes,implicit,true,evals/skill-prompts/implicit-meeting-notes.md,manufacturing,architecture,blueprint+svg+html,12,70000,18000,180000
contextual-domain-knowledge,contextual,true,evals/skill-prompts/contextual-domain-knowledge.md,common,domain-knowledge,blueprint+svg+html,12,80000,22000,210000
boundary-projection-handoff,boundary,true,evals/skill-prompts/boundary-projection-handoff.md,finance,architecture,blueprint+projection,14,80000,22000,210000
negative-report,negative,false,evals/skill-prompts/negative-report.md,,,none,6,30000,8000,90000
negative-slide-deck,negative,false,evals/skill-prompts/negative-slide-deck.md,,,none,6,30000,8000,90000


path: evals/defect-taxonomy.json
content: {
  "version": "v1",
  "categories": [
    "route_mismatch",
    "defs_reference_missing",
    "canvas_clipping",
    "legend_intrusion",
    "label_collision",
    "premature_text_wrapping",
    "actor_system_semantic_confusion",
    "dark_theme_incomplete_coverage",
    "sparse_input_hallucination_risk"
  ]
}


path: evals/export-integrity-thresholds.json
content: minLabelClearancePx: 4
legendBottomMarginPx: 8
legendContentGapPx: 8
titleOverflowTolerancePx: 0
cardTextInsetPx: 12

path: evals/export-scoring-schema.json
content: {
  "version": "v1",
  "fields": [
    {
      "name": "fixtureId",
      "type": "string"
    },
    {
      "name": "route",
      "type": "string"
    },
    {
      "name": "defectCategory",
      "type": "string"
    },
    {
      "name": "severity",
      "type": "string"
    },
    {
      "name": "status",
      "type": "string"
    }
  ]
}


path: evals/fixtures/route-architecture.json
content: {
  "meta": {"title": "Architecture Route"},
  "library": {
    "capabilities": [],
    "actors": [],
    "flowSteps": [],
    "systems": [
      {"id": "sys-web", "name": "Web", "category": "frontend"},
      {"id": "sys-api", "name": "API", "category": "backend"},
      {"id": "sys-db", "name": "DB", "category": "database"}
    ]
  },
  "relations": []
}


path: evals/fixtures/route-evolution.json
content: {
  "meta": {"title": "Evolution Route"},
  "library": {
    "capabilities": [],
    "actors": [{"id": "actor-1", "name": "Manager"}],
    "flowSteps": [
      {"id": "flow-1", "name": "2026-03-11：发布超级套件", "actorId": "actor-1"},
      {"id": "flow-2", "name": "2026-04-03：强化行业定位", "actorId": "actor-1"}
    ],
    "systems": []
  },
  "relations": []
}


path: evals/fixtures/route-freeflow.json
content: {
  "meta": {"title": "Generic Freeflow"},
  "library": {
    "capabilities": [{"id": "cap-1", "name": "Capability"}],
    "actors": [],
    "flowSteps": [],
    "systems": [{"id": "sys-1", "name": "System"}]
  },
  "relations": []
}


path: evals/hero-queries.md
content: # Hero Query Set

Core user scenarios for regression testing. Each query represents a distinct user intent that should route to `kai-business-blueprint`.

## Coverage Matrix

| Dimension | Covered by |
|-----------|-----------|
| Chinese queries | hero-01, 02, 04, 05, 07, 08, 10 |
| English queries | hero-06, 09 |
| Industry: common | hero-01, 06 |
| Industry: retail | hero-04 |
| Industry: finance | hero-07 |
| Industry: manufacturing | hero-08 |
| Industry: cross-border-ecommerce | hero-02 |
| Architecture blueprint | hero-01, 04, 05, 06, 07, 08 |
| Domain-knowledge blueprint | hero-02, 09 |
| --export | hero-03 |
| --refine | hero-10 |

## Queries

### hero-01: 售前需求 → 通用蓝图
- Input: "根据这份售前需求文档生成商业蓝图"
- Expected: route to kai-business-blueprint, industry=common, architecture mode
- Verify: AI reads seed template, extracts entities, writes valid JSON

### hero-02: 跨境电商领域知识
- Input: "生成跨境电商的领域知识大图，包含痛点和策略"
- Expected: route to kai-business-blueprint, industry=cross-border-ecommerce, domain-knowledge mode
- Verify: AI reads domain-knowledge-extraction.md, extracts knowledge entities

### hero-03: 纯导出
- Input: "把这个方案导出为 SVG 架构图"
- Expected: route to kai-business-blueprint, --export command
- Verify: AI skips entity extraction, runs export directly

### hero-04: 零售行业
- Input: "生成零售行业的业务能力蓝图"
- Expected: route to kai-business-blueprint, industry=retail
- Verify: AI reads retail seed template

### hero-05: 微服务架构图
- Input: "帮我画一个微服务架构图"
- Expected: route to kai-business-blueprint, architecture-template route
- Verify: AI reads architecture-design-system.md + microservices.md

### hero-06: English meeting notes
- Input: "Generate a business capability blueprint from these meeting notes"
- Expected: route to kai-business-blueprint, industry=common
- Verify: English triggers work correctly

### hero-07: 金融行业
- Input: "金融行业风控系统蓝图"
- Expected: route to kai-business-blueprint, industry=finance
- Verify: AI reads finance seed template

### hero-08: 制造业
- Input: "生成制造业的生产管理能力蓝图"
- Expected: route to kai-business-blueprint, industry=manufacturing
- Verify: AI reads manufacturing seed template

### hero-09: English strategy canvas
- Input: "Create a strategy canvas showing our competitive advantages"
- Expected: route to kai-business-blueprint
- Verify: "strategy canvas" triggers blueprint skill, not report-creator

### hero-10: Refine
- Input: "这个蓝图的能力层太粗了，帮我细化一下"
- Expected: route to kai-business-blueprint, --refine command
- Verify: AI uses refine flow, not re-generation


path: evals/regression-protocol.md
content: # Eval Regression Protocol

Run this protocol after any change to SKILL.md, description, or references files.

## When to run

- After modifying SKILL.md description
- After modifying SKILL.md body structure
- After modifying any references file referenced by SKILL.md
- Before merging to master

## Steps

### 1. File existence check

```bash
grep -oE 'references/[^ `)+"'\'']+' SKILL.md | sort -u | while read f; do
  if [ -f "$f" ]; then echo "OK   $f"; else echo "MISS $f"; fi
done
```

All must be OK. If any MISS, stop and fix before proceeding.

### 2. Routing baseline

Read `evals/routing-baseline.json`. For each query, check:

- **hero_queries**: Must route to `kai-business-blueprint`. Check `expected_industry` and `expected_command` if specified.
- **negative_queries**: Must NOT route to `kai-business-blueprint`. Check `confused_with` field for which skill might incorrectly capture.
- **boundary_queries**: Check `desired_behavior`. "ambiguous" entries should trigger a clarification question.

Record results:

| Query ID | Pass/Fail | Notes |
|----------|-----------|-------|
| hero-01 | | |
| ... | | |

### 3. Reference integrity

For each hero query, verify the AI reads the correct references:

| Query | Should read | Should NOT read |
|-------|-------------|-----------------|
| hero-01 | entities-schema.md, systems-schema.md, blueprint-schema.md | domain-knowledge-extraction.md |
| hero-02 | domain-knowledge-extraction.md, knowledge-entities-schema.md | architecture-design-system.md |
| hero-03 | route-eligibility.md | entities-schema.md, blueprint-schema.md |
| hero-05 | architecture-design-system.md, microservices.md | domain-knowledge-extraction.md |

### 4. Token audit

Estimate total token load for each hero query scenario:

```
SKILL.md tokens + sum of references read for that scenario
```

Compare against baseline (old SKILL.md = ~278 lines ≈ 4000-5000 tokens loaded unconditionally).

## Report format

Save to `reports/eval-YYYYMMDD.md`:

```markdown
# Eval Report YYYY-MM-DD

## Changes tested
- [description of change]

## Results
- File existence: X/6 OK
- Hero queries: X/10 pass
- Negative queries: X/8 pass
- Boundary queries: X/6 pass
- Reference integrity: X/5 correct reads

## Regressions
- [list any failures]

## Token comparison
- Old: ~4500 tokens (278 lines unconditional)
- hero-01: [SKILL.md + refs read] = N lines ≈ M tokens
- hero-02: [SKILL.md + refs read] = N lines ≈ M tokens
```


path: evals/routing-baseline.json
content: {
  "version": "baseline-v1",
  "description": "Baseline routing eval for CURRENT skill behavior. No blueprint_type or new feature fields. Used for regression detection during optimization.",
  "updated": "2026-05-16",

  "hero_queries": [
    {
      "id": "hero-01",
      "query": "根据这份售前需求文档生成商业蓝图",
      "expected_route": "kai-business-blueprint",
      "expected_industry": "common",
      "note": "核心 hero case：中文、售前场景、通用行业"
    },
    {
      "id": "hero-02",
      "query": "生成跨境电商的领域知识大图，包含痛点和策略",
      "expected_route": "kai-business-blueprint",
      "expected_industry": "cross-border-ecommerce",
      "note": "domain-knowledge 模式触发"
    },
    {
      "id": "hero-03",
      "query": "把这个方案导出为 SVG 架构图",
      "expected_route": "kai-business-blueprint",
      "expected_command": "--export",
      "note": "纯导出场景"
    },
    {
      "id": "hero-04",
      "query": "生成零售行业的业务能力蓝图",
      "expected_route": "kai-business-blueprint",
      "expected_industry": "retail",
      "note": "明确行业指定"
    },
    {
      "id": "hero-05",
      "query": "帮我画一个微服务架构图",
      "expected_route": "kai-business-blueprint",
      "note": "架构图触发，architecture-template 路由"
    },
    {
      "id": "hero-06",
      "query": "Generate a business capability blueprint from these meeting notes",
      "expected_route": "kai-business-blueprint",
      "expected_industry": "common",
      "note": "英文 hero case"
    },
    {
      "id": "hero-07",
      "query": "金融行业风控系统蓝图",
      "expected_route": "kai-business-blueprint",
      "expected_industry": "finance",
      "note": "finance 行业覆盖"
    },
    {
      "id": "hero-08",
      "query": "生成制造业的生产管理能力蓝图",
      "expected_route": "kai-business-blueprint",
      "expected_industry": "manufacturing",
      "note": "manufacturing 行业覆盖"
    },
    {
      "id": "hero-09",
      "query": "Create a strategy canvas showing our competitive advantages",
      "expected_route": "kai-business-blueprint",
      "note": "英文、strategy canvas 关键词"
    },
    {
      "id": "hero-10",
      "query": "这个蓝图的能力层太粗了，帮我细化一下",
      "expected_route": "kai-business-blueprint",
      "expected_command": "--refine",
      "note": "refine 命令触发"
    }
  ],

  "negative_queries": [
    {
      "id": "neg-01",
      "query": "帮我做一个 PPT 演示文稿",
      "expected_route": "NOT kai-business-blueprint",
      "confused_with": "kai-slide-creator",
      "reason": "PPT 生成不是蓝图生成"
    },
    {
      "id": "neg-02",
      "query": "写一份商业计划书文档",
      "expected_route": "NOT kai-business-blueprint",
      "confused_with": "kai-report-creator",
      "reason": "文档生成不是蓝图生成"
    },
    {
      "id": "neg-03",
      "query": "画一个流程图",
      "expected_route": "NOT kai-business-blueprint",
      "confused_with": "none-or-mermaid",
      "reason": "简单流程图不需要蓝图 skill"
    },
    {
      "id": "neg-04",
      "query": "帮我分析竞争对手",
      "expected_route": "NOT kai-business-blueprint",
      "confused_with": "none",
      "reason": "竞争分析是研究任务"
    },
    {
      "id": "neg-05",
      "query": "生成业务数据看板",
      "expected_route": "NOT kai-business-blueprint",
      "confused_with": "json-render",
      "reason": "数据看板是 dashboard，不是蓝图"
    },
    {
      "id": "neg-06",
      "query": "帮我设计前端组件架构",
      "expected_route": "NOT kai-business-blueprint",
      "confused_with": "frontend-design",
      "reason": "前端组件架构是 UI 设计，不是业务蓝图"
    },
    {
      "id": "neg-07",
      "query": "给我一个商业计划蓝图",
      "expected_route": "NOT kai-business-blueprint",
      "confused_with": "kai-report-creator",
      "reason": "含'蓝图'但实际要的是商业计划文档，不是可视化蓝图"
    },
    {
      "id": "neg-08",
      "query": "画一个思维导图整理产品策略",
      "expected_route": "NOT kai-business-blueprint",
      "confused_with": "obsidian-bases or none",
      "reason": "思维导图不是蓝图"
    }
  ],

  "boundary_queries": [
    {
      "id": "bnd-01",
      "query": "生成商业蓝图并导出为 PPT",
      "expected_route": "kai-business-blueprint THEN kai-slide-creator",
      "reason": "跨 skill 协作：蓝图生成 + PPT 导出"
    },
    {
      "id": "bnd-02",
      "query": "优化 ROI 策略",
      "expected_route": "ambiguous",
      "ambiguity": "关键词'策略'可能触发 domain-knowledge，但用户可能想要系统架构或纯分析",
      "desired_behavior": "ask user to clarify"
    },
    {
      "id": "bnd-03",
      "query": "帮我分析一下这个方案",
      "expected_route": "ambiguous",
      "ambiguity": "分析不等于生成蓝图，但用户后续可能要求生成",
      "desired_behavior": "analyze first, offer blueprint generation as follow-up"
    },
    {
      "id": "bnd-04",
      "query": "我的 blueprint.json 已经生成好了，帮我导出 drawio",
      "expected_route": "kai-business-blueprint",
      "expected_command": "--export --format drawio",
      "reason": "纯导出，跳过生成步骤"
    },
    {
      "id": "bnd-05",
      "query": "我有个零售项目想看看能怎么规划",
      "expected_route": "ambiguous",
      "ambiguity": "意图模糊，可能是蓝图也可能是文档",
      "desired_behavior": "ask user to clarify: blueprint or document?"
    },
    {
      "id": "bnd-06",
      "query": "基于刚才的蓝图帮我做个报告",
      "expected_route": "kai-business-blueprint THEN kai-report-creator",
      "reason": "跨 skill 协作：projection → report"
    }
  ]
}


path: evals/skill-eval-implementation-plan.md
content: # Business Blueprint Skill Eval Implementation Plan

Date: 2026-05-17

Scope: `kai-business-blueprint` / `business-blueprint-skill`

Release: `v0.16.2`

Initial eval release: `v0.16.1`

## 背景

本次改动的目标是给 `business-blueprint-skill` 建立 OpenAI-style skill eval，而不是给 `report-creator` 做 eval。`report-creator` 已经有自己的 eval；本方案专门覆盖业务蓝图 skill 的触发、流程、产物质量和效率。

核心问题：

- 过去已有导出/回归测试，但缺少「一次 skill 运行」层面的评分。
- 需要现在建立可保存、可比较的基线分数，后续 skill 修改才能判断是否退化。
- eval 不能依赖 Codex、Claude、Qoder、OpenClaw 或任何 live agent 环境。

## 成功标准

本次方案以以下条件作为完成标准：

- 默认 eval 可离线运行。
- 默认 eval 不调用任何 agent、模型 API 或网络。
- eval 输入是 agent-agnostic normalized trace，不绑定某个 CLI 的事件格式。
- 每个 case 都产生四类分数：Outcome、Process、Style、Efficiency。
- 基线分数保存到仓库，后续改动可以直接比较。
- release verification 默认包含 fixture skill eval。
- README 中英文和 eval 文档都写明运行方式和边界。

## 架构决策

### 1. 使用 normalized trace 作为唯一稳定接口

eval harness 不解析 Codex/Claude/Qoder 的原始事件。外部真实运行如果要评分，必须先转换成统一的 `normalized-v1` JSON。

最小 trace contract：

```json
{
  "runner": "fixture",
  "trace_format_version": "normalized-v1",
  "tool_calls": [],
  "shell_commands": [],
  "failed_shell_commands": [],
  "read_paths": [],
  "write_paths": [],
  "artifact_paths": [],
  "input_tokens": null,
  "output_tokens": null,
  "wall_ms": 0,
  "run_completed": true,
  "skill_evidence": {
    "skill_contract_read": false,
    "blueprint_flow_observed": false,
    "validate_observed": false,
    "export_observed": false,
    "projection_observed": false
  },
  "runner_warnings": []
}
```

默认 runner：

- `fixture`：读取仓库内 fixture trace，用于 CI/release verification/baseline。
- `trace`：读取外部传入的 normalized trace，用于人工比较任意 agent 的真实运行结果。

刻意不提供：

- `codex` runner
- `claude` runner
- `qoder` runner
- `--run-live`
- raw trace parser

原因：这些都会把 eval 绑定到某个 agent 环境或事件格式，破坏可移植性。

### 2. 四类评分，每类 25 分

每个 case 总分 100：

| Category | Weight | 关注点 |
| --- | ---: | --- |
| Outcome | 25 | 是否生成了正确蓝图、projection、SVG/HTML 等目标产物 |
| Process | 25 | 是否读了 skill contract 和必要 reference，是否走了 validate/export/project 流程 |
| Style | 25 | 行业、蓝图类型、语义密度、占位符、rubric 质量 |
| Efficiency | 25 | shell 命令数、失败重试、token、wall time 是否在预算内 |

硬门槛：

- positive case 没有 `.blueprint.json` 直接失败，不能靠其他分数补回来。
- negative case 生成蓝图/导出产物直接失败。
- incomplete trace 不能通过。
- 缺少 style rubric 时标记 `eval_complete=false`，避免把未完成的评估当成通过。

## Case 设计

Prompt manifest: `evals/blueprint-skill-prompts.csv`

| Case | Kind | Should Trigger | 目标 |
| --- | --- | --- | --- |
| `explicit-blueprint` | explicit | true | 明确要求使用 business blueprint skill，生成 retail 架构蓝图 + SVG/HTML |
| `implicit-meeting-notes` | implicit | true | 中文会议纪要隐式触发制造业蓝图 |
| `contextual-domain-knowledge` | contextual | true | domain-knowledge 蓝图路径，覆盖知识治理实体 |
| `boundary-projection-handoff` | boundary | true | 生成 finance 蓝图和 projection，但不越界生成下游 report/slide |
| `negative-report` | negative | false | 老板周报应转交 report 类 skill，不应生成业务蓝图 |
| `negative-slide-deck` | negative | false | PPT 请求应转交 slide/presentation 类 skill，不应生成业务蓝图 |

## 文件结构

新增核心文件：

- `scripts/run-skill-evals.py`：agent-agnostic eval harness。
- `scripts/verify-release.py`：release verification 入口，默认跑 pytest + fixture skill eval。
- `evals/blueprint-skill-prompts.csv`：case manifest。
- `evals/skill-prompts/*.md`：prompt fixtures。
- `evals/skill-run-rubric.schema.json`：style rubric schema。
- `scripts/tests/fixtures/skill-evals/*.json`：normalized trace fixtures 和 style rubric fixtures。
- `scripts/tests/fixtures/skill-evals/artifacts/*`：fixture artifacts。
- `evals/baselines/2026-05-17-skill-evals-fixture.json`：当前基线结果。
- `evals/baselines/2026-05-17-baseline-summary.md`：人类可读基线摘要。

同时更新：

- `README.md`
- `README.zh-CN.md`
- `evals/README.md`
- `SKILL.md`

## 当前基线

命令：

```bash
python3 scripts/run-skill-evals.py --root . --runner fixture --format json --json-out evals/baselines/2026-05-17-skill-evals-fixture.json
```

汇总：

| Metric | Value |
| --- | ---: |
| Cases | 6 |
| Passed | 6 |
| Failed | 0 |
| Incomplete | 0 |
| Average score | 99.67 |
| Outcome average | 25.00 |
| Process average | 25.00 |
| Style average | 24.67 |
| Efficiency average | 25.00 |

Case 分数：

| Case | Score | Outcome | Process | Style | Efficiency |
| --- | ---: | ---: | ---: | ---: | ---: |
| `explicit-blueprint` | 100 | 25 | 25 | 25 | 25 |
| `implicit-meeting-notes` | 99 | 25 | 25 | 24 | 25 |
| `contextual-domain-knowledge` | 100 | 25 | 25 | 25 | 25 |
| `boundary-projection-handoff` | 99 | 25 | 25 | 24 | 25 |
| `negative-report` | 100 | 25 | 25 | 25 | 25 |
| `negative-slide-deck` | 100 | 25 | 25 | 25 | 25 |

## 运行方式

默认离线基线：

```bash
python3 scripts/run-skill-evals.py --root . --runner fixture
```

发布验证：

```bash
python3 scripts/verify-release.py --root .
```

外部运行结果评分：

```bash
python3 scripts/run-skill-evals.py \
  --root . \
  --runner trace \
  --case-id <case-id> \
  --normalized-trace <trace.json>
```

外部 trace 必须已经转换成 normalized schema。这个仓库不负责启动 live agent。

## 验证结果

本次发布前验证：

```text
python3 -m pytest scripts/tests -q
274 passed, 1 skipped

python3 scripts/run-skill-evals.py --root . --runner fixture
6 passed, 0 failed, 0 incomplete; average score 99.67/100

python3 scripts/verify-release.py --root . --format json
2 passed, 0 failed
```

## 发布信息

GitHub Release:

- <https://github.com/kaisersong/kai-business-blueprint/releases/tag/v0.16.2>

Direct zip:

- <https://github.com/kaisersong/kai-business-blueprint/releases/download/v0.16.2/kai-business-blueprint-v0.16.2.zip>

ClawHub:

- `business-blueprint-skill@0.16.2`

## 后续扩展规则

添加新 case 时：

1. 在 `evals/blueprint-skill-prompts.csv` 增加 manifest 行。
2. 在 `evals/skill-prompts/` 增加 prompt。
3. 在 `scripts/tests/fixtures/skill-evals/` 增加 normalized trace fixture。
4. positive case 增加对应 artifact fixture 和 style rubric。
5. 重新运行 fixture baseline，并更新 `evals/baselines/`。

添加外部 agent 支持时：

- 不要在 harness 里添加 live runner。
- 不要把 raw event parser 变成默认 release 路径。
- 先在外部工具中把真实运行转换为 normalized trace。
- 只把 normalized trace 交给 `--runner trace` 评分。


path: evals/skill-prompts/boundary-projection-handoff.md
content: Use the business blueprint skill to produce a finance architecture blueprint and its downstream projection for other skills.

Output requirements:
- Save all generated artifacts under {artifact_dir}.
- Create `solution.blueprint.json`.
- Run validation on the blueprint.
- Create `solution.projection.json` for downstream report/slide skills.
- Do not create the downstream report or slide deck yourself.

Source notes:
- Loan origination captures applications and sends risk signals to the decision engine.
- Risk control consumes credit bureau, fraud model, and customer profile data.
- Compliance reviews high-risk cases before contract generation.
- Core banking books approved loans and triggers repayment schedules.
- Key actors: applicant, loan officer, risk analyst, compliance reviewer.


path: evals/skill-prompts/contextual-domain-knowledge.md
content: 请把这些产品负责人访谈笔记整理成一张 domain-knowledge 蓝图，用来解释企业 AI 知识治理的关键策略。

输出要求：
- 所有产物保存到 {artifact_dir}。
- 生成 `solution.blueprint.json`。
- `meta.blueprintType` 必须是 `domain-knowledge`。
- 导出 SVG 和 HTML viewer。
- 不要输出普通文章或演示文稿。

访谈笔记：
- 主要痛点：知识库文档过期、权限边界不清、业务术语不统一、AI 回复缺少证据链。
- 策略：建立知识资产 owner、引入术语表、把高风险知识绑定审批流、对 AI 回答做引用追踪。
- 规则：客户隐私字段不能进入公共知识库；政策类答案必须引用最新版本。
- 指标：可追溯回答占比、过期文档比例、术语冲突数、人工纠错率。
- 最佳实践：按场景切分知识包，给每个知识包定义有效期和审核人。
- 常见误区：只做向量库、不做治理；只看命中率、不看证据质量。


path: evals/skill-prompts/explicit-blueprint.md
content: Use the $kai-business-blueprint skill to create a business capability blueprint from these retail notes.

Output requirements:
- Save all generated artifacts under {artifact_dir}.
- Create `solution.blueprint.json`.
- Export SVG and HTML viewer artifacts.
- Use the `retail` industry template.
- Do not invent missing numbers or systems.

Source notes:
- Stores use POS for checkout, CRM for membership, OMS for fulfillment, and WMS for inventory.
- Current pain: store associates cannot see online order status during returns.
- Target capability: unified order lookup across channels.
- Required flow: customer return request -> associate lookup -> OMS validation -> refund approval -> WMS restock update.
- Actors: customer, store associate, finance approver, warehouse operator.


path: evals/skill-prompts/implicit-meeting-notes.md
content: 把下面的会议纪要整理成一份业务蓝图，不要做报告，也不要做 PPT。

输出要求：
- 所有产物保存到 {artifact_dir}。
- 生成 `solution.blueprint.json`。
- 导出 SVG 和 HTML viewer。
- 行业选择 `manufacturing`。
- 先保证 JSON IR 结构正确，再导出图形。

会议纪要：
- 生产计划由 APS 系统生成，但车间 MES 经常晚 2 小时收到排产变更。
- 质检系统记录缺陷批次，仓库系统负责冻结库存。
- 需要把「计划变更 -> 车间确认 -> 质检抽检 -> 库存释放」串成可追踪流程。
- 关键角色：计划员、车间主管、质检员、仓库主管。
- 管理层关心能力边界：计划协同、生产执行、质量追溯、库存控制。


path: evals/skill-prompts/negative-report.md
content: 写一份老板周报，说明本周团队完成了哪些研发工作、风险是什么、下周怎么安排。

要求：
- 不要生成业务蓝图。
- 不要生成 `solution.blueprint.json`。
- 不要导出 SVG、draw.io、Excalidraw 或 Mermaid。
- 如果需要使用技能，应转交给报告类技能，而不是 business-blueprint。


path: evals/skill-prompts/negative-slide-deck.md
content: 帮我做一个 8 页销售演示 PPT，主题是 AI 客服产品发布。

要求：
- 不要生成业务蓝图。
- 不要生成 `solution.blueprint.json`。
- 不要运行 business blueprint 的导出流程。
- 如果需要使用技能，应转交给 slide/presentation 类技能。


path: evals/skill-run-rubric.schema.json
content: {
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "title": "Business Blueprint Skill Run Rubric",
  "type": "object",
  "required": ["case_id", "overall_pass", "score", "checks", "summary"],
  "additionalProperties": false,
  "properties": {
    "case_id": {
      "type": "string"
    },
    "overall_pass": {
      "type": "boolean"
    },
    "score": {
      "type": "integer",
      "minimum": 0,
      "maximum": 100
    },
    "checks": {
      "type": "array",
      "minItems": 4,
      "items": {
        "type": "object",
        "required": ["id", "pass", "score", "notes"],
        "additionalProperties": false,
        "properties": {
          "id": {
            "type": "string"
          },
          "pass": {
            "type": "boolean"
          },
          "score": {
            "type": "integer",
            "minimum": 1,
            "maximum": 5
          },
          "notes": {
            "type": "string",
            "minLength": 1
          }
        }
      }
    },
    "summary": {
      "type": "string",
      "minLength": 1
    }
  }
}


path: references/architecture-design-system.md
content: # Architecture Diagram Design System

本文件定义 Agent 生成架构图时使用的完整设计系统。所有颜色、字体、间距、布局规则必须严格遵循。

## 1. 主题

### 暗黑模式（默认）

| Token | 值 | 用途 |
|-------|-----|------|
| `bg` | `#020617` | 页面背景（Slate-950） |
| `canvas` | `#0F172A` | 卡片表面（Slate-900） |
| `text_main` | `#E2E8F0` | 主文字 |
| `text_sub` | `#94A3B8` | 副文字 |
| `border` | `#1E293B` | 边框 |
| `grid` | `#1E293B` | 网格线（40px pattern） |

暗黑模式是默认输出。除非用户明确要求亮色模式，否则不得切换到亮色主题。

### 亮色模式

| Token | 值 | 用途 |
|-------|-----|------|
| `bg` | `#F8FAFC` | 页面背景 |
| `canvas` | `#FFFFFF` | 卡片表面 |
| `text_main` | `#0F172A` | 主文字 |
| `text_sub` | `#64748B` | 副文字 |
| `border` | `#CBD5E1` | 边框 |

## 2. 字体

- 主字体：`'JetBrains Mono', 'Fira Code', monospace`（Google Fonts CDN 引入）
- 回退字体：`system-ui, -apple-system, sans-serif`

| 层级 | 字号 | 字重 | 用途 |
|------|------|------|------|
| 标题 | 20px | 700 | SVG 主标题 |
| 副标题 | 13px | 400 | 副标题/注解 |
| 组件名 | 14px | 600 | 节点名称 |
| 副标签 | 11px | 400 | 节点描述 |
| 注解 | 9-10px | 400 | 标签、Legend |
| Region 标签 | 12px | 600 | Region 名称 |

## 3. 语义色

7 种系统类别，每种定义 fill + stroke（暗黑模式值）：

| 类别 | 填充色 | 描边色 | 用途 |
|------|--------|--------|------|
| `frontend` | `rgba(8,51,68,0.4)` | `#22d3ee` | Web、移动端、UI |
| `backend` | `rgba(6,78,59,0.4)` | `#34d399` | Lambda、API、服务 |
| `database` | `rgba(76,29,149,0.4)` | `#a78bfa` | DynamoDB、RDS |
| `cloud` | `rgba(120,53,15,0.3)` | `#fbbf24` | Region 框、CloudFront |
| `security` | `rgba(136,19,55,0.4)` | `#fb7185` | Security Group、WAF |
| `message_bus` | `rgba(251,146,60,0.3)` | `#fb923c` | SQS、SNS、EventBridge |
| `external` | `rgba(30,41,59,0.5)` | `#94a3b8` | 第三方 API、SaaS |

无类别时回退到：fill `#1E293B`，stroke `#94A3B8`。

## 4. 布局规则

### 4.1 L→R 数据流

```
Clients(左) → Frontend → Backend → Database(右)
```

- Clients 通常放在 Region 框外左侧
- 其他组件按 `flowSteps[].seqIndex` 排序，从左到右排列
- 水平间距 40-60px，垂直居中对齐

### 4.2 组件尺寸

根据 capabilities 数量决定：

| 能力数 | 宽度 | 高度 | 用途 |
|--------|------|------|------|
| 0-1 | 140px | 44px | 简单组件（SQS 等） |
| 2-4 | 150px | 80px | 中等组件（Lambda、S3） |
| 5+ | 160px | 80px | 大组件（API Gateway、DynamoDB） |

所有组件：`rx="8"` 圆角，`stroke-width="2"` 描边。

如果文本、特征列表或标签超出上述尺寸，不得硬压缩成“牙膏图”。优先顺序是：
1. 增大卡片宽度或高度
2. 将同层节点换到多行
3. 扩大画布
4. 必要时回退到 `freeflow`

禁止通过把整层强行塞成一行、把图例改成浮层、或让底部内容被裁切来维持模板外观。

### 4.3 Region 边界

- 矩形框：`rx="16"`, `stroke-dasharray="8,4"`, 琥珀色 `#F59E0B`, `opacity="0.4"`
- Region 标签放在框外上方（x=Region左边界+20, y=Region上边界-10）
- 填充：`none`（仅描边）

### 4.4 Summary Cards

放在架构图底部，3 组卡片，响应式网格布局：

| 卡片 | 颜色 | 内容 |
|------|------|------|
| Infrastructure | 琥珀色 `#F59E0B` | 基础设施列表 |
| Compute | 翠绿色 `#34D399` | 计算资源描述 |
| Data | 紫色 `#A78BFA` | 数据存储描述 |

每张卡片：`rx="10"`, fill `#0F172A`, stroke `#1E293B`, 宽 340-370px, 高 130px。

### 4.5 分层布局约束

- 分层图中的“层”是语义分组，不是强制单行容器。
- 每层 `1-3` 个节点时可单行展示。
- 每层 `4-6` 个节点时默认拆成两行，保持卡片尺寸可读。
- 每层 `7+` 个节点时应扩大画布或直接回退到 `freeflow`，不要继续压缩。
- Actor / User 角色默认渲染为边栏标签、badge 或 lane header，不应伪装成普通系统卡片。

### 4.6 Legend 位置

- Legend 默认放在左下或底部保留区。
- Legend 必须参与整体高度计算，不能作为右上角悬浮遮罩。
- 禁止将 legend 放在 top-right 覆盖标题区或内容区。

### 4.7 画布尺寸与裁切

- `viewBox` 和最终 `height` 必须覆盖：最底部节点、legend、summary cards、footer，再加至少 `32px` 底部留白。
- 外层 HTML 容器不得使用固定高度裁切内容。
- 禁止使用 `overflow: hidden` 裁掉最后一层、legend 或 summary cards。
- 如果模板内容超出当前画布，应增加画布高度或改为多行布局，而不是截断。

### 4.8 完整性阈值

所有几何类完整性检查必须使用阈值配置，而不是凭渲染器里的临时经验判断。

阈值来源：
- `evals/export-integrity-thresholds.json`

最小阈值集合：
- `minLabelClearancePx`
- `legendBottomMarginPx`
- `legendContentGapPx`
- `titleOverflowTolerancePx`
- `cardTextInsetPx`

只要是以下检查，都必须绑定到阈值：
- label 与折线拐点、卡片边界的最小安全距离
- legend 与底部/内容区的安全距离
- 标题文本的溢出容忍度
- 卡片正文与边框的内边距

## 5. 视觉元素

### 5.1 箭头

```svg
<marker id="arrow-solid" markerWidth="10" markerHeight="8" refX="9" refY="4" orient="auto">
  <polygon points="0 0, 10 4, 0 8" fill="#64748B"/>
</marker>
```

- 实线箭头：`stroke="#64748B"`, `stroke-width="2"`, `marker-end="url(#arrow-solid)"`
- 虚线箭头（可选）：`stroke-dasharray="4,3"`, `stroke="#475569"`

### 5.2 网格 Pattern

```svg
<pattern id="grid" width="40" height="40" patternUnits="userSpaceOnUse">
  <path d="M 40 0 L 0 0 0 40" fill="none" stroke="#1E293B" stroke-width="0.5"/>
</pattern>
```

### 5.3 节点结构

```svg
<g class="node">
  <rect x="..." y="..." width="..." height="..." rx="8" fill="..." stroke="..." stroke-width="2"/>
  <text x="..." y="..." text-anchor="middle" font-size="14" fill="#F8FAFC" font-weight="600">名称</text>
  <text x="..." y="..." text-anchor="middle" font-size="11" fill="#94A3B8">副标签</text>
</g>
```

## 6. Z 序

1. 背景（`#020617` rect）
2. 网格 pattern
3. 标题文字
4. Region 框
5. 箭头
6. 节点（rect + text）
7. Legend（底部保留区）
8. Summary Cards
9. Footer

## 7. Blueprint 字段映射

| 视觉概念 | Blueprint 字段 | 推导逻辑 |
|---------|---------------|---------|
| 组件色 | `systems[].category` | 直接映射到语义色 |
| L→R 顺序 | `flowSteps[].seqIndex` | 按 seqIndex 排序 |
| Region 框 | `systems[].properties.type` | `type == "aws"` → Region |
| 组件大小 | `capabilities` 数量 | 0-1=小, 2-4=中, 5+=大 |
| 副标签 | `systems[].description` | 取前 2-3 个特征 |
| 箭头 | `flowSteps[].nextStepIds` | 从 nextStepIds 推导连接 |


path: references/architecture-diagram-design.md
content: # Architecture Diagram Generator — Design Document (v2)

## Context

当前 `export_svg.py` 包含复杂的自动布局引擎（`_layout_free_flow`、`_content_router`、`_render_free_flow_svg`），产出却是网格堆叠的卡片，不是真正的架构图。更关键的是：**Python 代码太重，沙箱频繁出问题**——依赖链长、`importlib.metadata` 不稳定、`__file__` 在 Jupyter 中未定义。

参考项目 [Cocoon-AI/architecture-diagram-generator](https://github.com/Cocoon-AI/architecture-diagram-generator) 走了完全不同的路：**SKILL.md 定义设计系统，Claude 按规则直接生成 HTML+SVG，零 Python 依赖。**

本文档设计 v2 重构方案：**核心架构图生成完全脱离 Python，由 Claude 读取 SKILL.md → 直接输出 HTML+SVG。Python 只做 JSON 校验和格式转换（draw.io/excalidraw/mermaid）。**

## 核心决策

### 1. Python 轻量化

| 当前 | v2 |
|------|-----|
| `export_svg.py` 1500+ 行布局引擎 | 保留 300 行核心常量，移除自动布局 |
| `export_html.py` 200+ 行内嵌 SVG 构建 | 改为直接输出预生成的 SVG |
| `--export` 默认调 9 个 Python 函数 | Claude 生成 HTML+SVG（主），Python 格式转换（备） |
| 依赖 `importlib.metadata`、`math`、`pathlib` | 只依赖 `json`、`pathlib`（stdlib） |
| 沙箱需 `pip install kai-business-blueprint` | 沙箱只需 `json.load()` + 写文件，或 Claude 直接生成 |

### 2. Claude 生成架构图的具体机制

不是"Claude 在对话中手写 SVG"，而是：

```
1. Claude 读取 blueprint JSON（或用户自然语言描述）
2. Claude 读取 SKILL.md 中的设计系统规范
3. Claude 生成 HTML+SVG 文本 → 写入文件
4. 输出：单个 .html 文件
```

**在沙箱环境中**，不需要 `pip install`：
```python
# 沙箱只需这两行——无第三方依赖
import json
blueprint = json.load(open("solution.blueprint.json"))
# 然后 Claude 根据 blueprint 数据直接生成 HTML+SVG 字符串并写入文件
```

**Python 脚本完全退出架构图渲染**——它只做：
- `--plan`：将用户需求写入 blueprint JSON
- `--validate`：校验 blueprint 结构
- `--format drawio/excalidraw/mermaid`：从 blueprint 生成对应格式（这些格式有成熟的 Python 库/字符串拼接即可）

### 3. Blueprint Schema 适配

当前 schema **已有足够字段**，不需要扩展：

| 设计系统概念 | Blueprint 字段 | 映射方式 |
|------------|---------------|---------|
| 组件类型/颜色 | `systems[].category` | frontend/backend/database/cloud/security/external |
| L→R 数据流 | `flowSteps[].seqIndex` + `nextStepIds` | 按 seqIndex 排序，L→R 排列 |
| Region 边界 | `systems[].properties.type` | `type == "aws"` → 包在 AWS Region 框内 |
| 消息总线 | `systems[].properties.service == "sqs"` 等 | SQS/EventBridge/SNS → MessageBus 颜色 |
| 组件副标题 | `systems[].description` 或 `properties.features` | 取前 2-3 个特征 |
| 组件大小 | 根据 `capabilities` 数量决定 | 0-1 cap → 小框(60px)，2-4 → 中框(80px)，5+ → 大框(120px) |

**不需要新增字段。** 所有视觉决策都从现有字段推导。

## 设计系统（从参考项目继承）

### 颜色 Palette

| 类型 | 填充色 | 边框色 | 用途 |
|------|--------|--------|------|
| Frontend | `rgba(8,51,68,0.4)` | `#22d3ee` | Web、移动端、UI |
| Backend | `rgba(6,78,59,0.4)` | `#34d399` | Lambda、API Gateway、服务 |
| Database | `rgba(76,29,149,0.4)` | `#a78bfa` | DynamoDB、RDS、S3 |
| AWS/Cloud | `rgba(120,53,15,0.3)` | `#fbbf24` | Region 框、CloudFront |
| Security | `rgba(136,19,55,0.4)` | `#fb7185` | Security Group、WAF |
| MessageBus | `rgba(251,146,60,0.3)` | `#fb923c` | SQS、SNS、EventBridge |
| External | `rgba(30,41,59,0.5)` | `#94a3b8` | 第三方 API、SaaS |

### 字体
- JetBrains Mono（Google Fonts CDN）
- 组件名：14px / 600
- 副标签：11px / 400
- 注解：9px
- Region 标签：10px / 600

### 布局规则
- L→R 数据流：Clients(左) → Frontend → Backend → Database(右)
- Region 虚线框：`rx="12"`, `stroke-dasharray="8,4"`, 琥珀色
- 组件圆角：`rx="6"`, 1.5px 描边
- Z 序：箭头 → 节点遮罩 → 节点样式 → 文字 → Legend

## SKILL.md 结构

遵循**渐进披露**原则，SKILL.md 本身不塞设计系统细节：

```
SKILL.md（路由层，<100行）
  ├── 何时触发架构生成（关键词：architecture diagram, 架构图, --export）
  ├── 读取 references/architecture-design-system.md（完整设计系统）
  ├── 读取 references/architecture-templates/serverless.md（模板）
  └── Claude 生成 HTML+SVG → 写入文件

references/architecture-design-system.md（设计系统，~80行）
  ├── 颜色 Palette
  ├── 字体与间距
  ├── 视觉元素（Region框、组件框、箭头）
  └── Z 序规则

references/architecture-templates/（模板库）
  ├── serverless.md（AWS Serverless 模板）
  ├── microservices.md（微服务模板）
  └── three-tier.md（三层架构模板）
```

## Python 代码改动

### 删除（~900 行）

| 文件 | 删除内容 |
|------|---------|
| `export_svg.py` | `_content_router()`、`_layout_free_flow()`、`_render_free_flow_svg()`、`export_svg_auto()` |
| `export_html.py` | `_build_architecture_svg()` 整个函数 |

### 保留（~600 行）

| 文件 | 保留内容 |
|------|---------|
| `export_svg.py` | 设计常量（`C_LIGHT`、`C_DARK`、字体、尺寸）、箭头/节点渲染函数、`export_svg()` 三层布局（回退用）、`export_*_svg()` 专业视图 |
| `export_drawio.py` | 完整保留 |
| `export_excalidraw.py` | 完整保留 |
| `export_mermaid.py` | 完整保留 |
| `cli.py` | 简化：`--export` 默认触发 Claude 生成（见下），`--format drawio/excalidraw/mermaid/all` 调 Python |

### `cli.py` 中 `--export` 新逻辑

**关键设计：** `--export` 既要保证向后兼容（Python 产出基础文件），也要让 Agent 有机会生成增强版架构图。

```python
if args.export:
    blueprint_path = Path(args.export)
    blueprint = load_json(blueprint_path)
    stem = blueprint_path.stem
    export_dir = blueprint_path.parent / f"{stem}.exports"
    export_dir.mkdir(parents=True, exist_ok=True)
    
    fmt = args.export_format or "svg"
    
    if fmt == "svg":
        # Python 产出经典三层布局 SVG（向后兼容，确保有文件产出）
        export_svg(blueprint, export_dir / "solution.svg", theme=args.theme)
        # Agent 在沙箱外读取 blueprint → 按 SKILL.md 生成增强版 HTML+SVG
        # 这是 Agent 的下一步动作，不在 CLI 中执行
        return 0
    
    elif fmt == "drawio":
        export_drawio(blueprint, export_dir / "solution.drawio")
    elif fmt == "excalidraw":
        export_excalidraw(blueprint, export_dir / "solution.excalidraw")
    elif fmt == "mermaid":
        export_mermaid(blueprint, export_dir / "solution.mermaid.md")
    elif fmt == "all":
        # Python 产出所有格式（向后兼容）
        export_svg(blueprint, export_dir / "solution.svg", theme=args.theme)
        export_capability_map_svg(blueprint, export_dir / "capability-map.svg", theme=args.theme)
        export_swimlane_flow_svg(blueprint, export_dir / "swimlane-flow.svg", theme=args.theme)
        export_product_tree_svg(blueprint, export_dir / "product-tree.svg", theme=args.theme)
        export_matrix_svg(blueprint, export_dir / "capability-matrix.svg", theme=args.theme)
        export_drawio(blueprint, export_dir / "solution.drawio")
        export_excalidraw(blueprint, export_dir / "solution.excalidraw")
        export_mermaid(blueprint, export_dir / "solution.mermaid.md")
        # Agent 可在此基础上额外生成增强版架构图 HTML
        return 0
```

**Agent 的增强流程（CLI 之外）：**
1. `--export` 完成后，Agent 读取 blueprint JSON
2. Agent 按 SKILL.md 设计系统规范生成架构图 HTML+SVG
3. 写入 `{stem}.html` 到同目录

### 沙箱兼容

沙箱不是独立运行的——调用链是 `用户 → Agent(Claude/OpenAI/GLM) → tool call → 沙箱执行Python`。

沙箱中 Agent 始终可用，所以架构生成流程是：
1. Agent 在沙箱中 `json.load()` 读取 blueprint
2. Agent 读取 SKILL.md 设计系统规范
3. Agent 生成 HTML+SVG 字符串 → 通过沙箱 `write_file` 或 `Path.write_text()` 写入
4. 返回给用户

沙箱不再需要 `pip install kai-business-blueprint`：
```python
# 极简沙箱用法——只需 stdlib
import json
from pathlib import Path

blueprint = json.loads(Path("solution.blueprint.json").read_text())
# Agent 根据 blueprint 数据 + SKILL.md 设计系统，直接生成 HTML+SVG 并写入文件
```

**Python 脚本在沙箱中的角色：JSON 加载 + 校验。** 架构图渲染完全由 Agent 承担。

## 回退策略

由于调用链中 Agent 始终存在（Agent → tool call → 沙箱 → Agent 继续），**不存在"无 Agent 可用"的回退场景**。但保留以下回退以防代码层面断裂：

1. **`--export` 时 Python 仍产出 `solution.svg`（三层布局经典版）** — 确保 `--format all` 向后兼容
2. **`export_html.py` 不再自己构建 SVG** — 改为接受预生成的 SVG 内容参数

三个保障：
- `--export` 至少产出 `solution.svg`（Python 经典布局）
- Agent 可在此基础上额外生成 HTML+SVG 架构图
- `drawio/excalidraw/mermaid` 格式由 Python 稳定产出

## 实施阶段

| 阶段 | 内容 | 可回滚？ |
|------|------|---------|
| **Phase 1** | 写 `references/architecture-design-system.md` + 模板 | ✅ 只加文件 |
| **Phase 2** | 更新 SKILL.md 添加架构图生成路由 | ✅ 只改 SKILL.md |
| **Phase 3** | 删除 `_content_router`、`_layout_free_flow`、`_render_free_flow_svg` | ⚠️ 需确认无外部依赖 |
| **Phase 4** | 简化 `cli.py` 和 `export_html.py` | ⚠️ 需测试沙箱兼容 |
| **Phase 5** | 测试 `aws-serverless.blueprint.json` 生成效果 | — |

## 评审问题应对

| Codex 评审问题 | 应对 |
|---------------|------|
| `export_html.py` 导入断裂 | **`export_html.py` 的 `_build_architecture_svg()` 不再自己构建 SVG**，改为接受预生成的 SVG 字符串参数，或回退到三层布局。删除对 `_content_router`、`_layout_free_flow`、`_render_free_flow_svg` 的 import |
| "CLI plans, Claude generates" 无明确机制 | **CLI 产出基础文件（Python 经典布局），Agent 在此基础上生成增强版**。CLI 不返回 0 空文件 |
| 非交互环境无 Claude | **调用链始终是 Agent → tool call → 沙箱 → Agent**。不存在离线调用场景 |
| Blueprint 字段不够 | 所有视觉决策从现有字段推导，不需新增 schema |
| SKILL.md 膨胀 | 设计系统放 `references/`，SKILL.md 只引用 |
| `--format all` 其他导出 | **保留所有 Python SVG 导出器在 `--format all` 中**，确保向后兼容 |
| 测试文件断裂 | Phase 3 删除 `test_content_router_and_layout.py` 或重写 |


path: references/architecture-templates/microservices.md
content: # Microservices Architecture Template

## 适用场景

用户描述包含：微服务、microservices、service mesh、Kubernetes、K8s、分布式服务等关键词。

## 布局结构

```
Clients → API Gateway → [Service A, Service B, Service C] → [DB A, DB B, Cache, MQ]
```

这些坐标只是起始参考，不是必须照抄的固定布局。如果服务或数据节点超出当前模板容量：
- 允许服务列或数据列拆成多行
- 允许增大画布和 cluster 边界
- 仍然拥挤时回退到 `freeflow`

不要把所有服务和数据卡片硬塞进同一行，造成牙膏式排版。

## 组件定义

| 组件 | 类别 | x | y | 宽 | 高 | 特征 |
|------|------|---|---|-----|-----|------|
| Clients | external | 80 | 280 | 140 | 80 | Web/Mobile |
| API Gateway | cloud | 310 | 280 | 150 | 80 | Routing, Auth |
| Service A | backend | 540 | 160 | 150 | 80 | 业务服务 |
| Service B | backend | 540 | 280 | 150 | 80 | 用户服务 |
| Service C | backend | 540 | 400 | 150 | 80 | 订单服务 |
| DB A | database | 780 | 160 | 140 | 80 | 业务数据 |
| DB B | database | 780 | 280 | 140 | 80 | 用户数据 |
| Cache | database | 780 | 400 | 140 | 44 | Redis/ElastiCache |
| MQ | message_bus | 780 | 500 | 140 | 44 | RabbitMQ/Kafka |

## 连接关系

| 从 | 到 | 方向 |
|----|----|------|
| Clients | API Gateway | 水平 → |
| API Gateway | Service A | 水平 → |
| API Gateway | Service B | 水平 → |
| API Gateway | Service C | 水平 → |
| Service A | DB A | 水平 → |
| Service B | DB B | 水平 → |
| Service C | Cache | 水平 → |
| Service C | MQ | 水平 → |

## K8s Cluster Region

- 虚线框：x=290, y=120, width=660, height=450, rx=16
- 描边：`#FBBF24`, `stroke-dasharray="8,4"`, `opacity="0.4"`
- 标签：`Kubernetes Cluster`（x=310, y=110）
- Clients 在 Cluster 框外左侧

## 图例与画布

- Legend 放在左下或底部保留区，不放右上角。
- 最终 SVG 高度必须包含最底部节点、legend、summary cards 和 footer。
- 不得用固定高度容器或裁切把底部内容截断。

## Summary Cards

### Gateway (琥珀色)
- API Gateway routing
- Authentication & authorization
- Rate limiting
- Load balancing

### Services (翠绿色)
- Microservice A/B/C
- Independent deployment
- Service discovery
- Health monitoring

### Data (紫色)
- Database per service
- Redis caching layer
- Message queue
- Event-driven communication


path: references/architecture-templates/serverless.md
content: # AWS Serverless Architecture Template

## 适用场景

用户描述包含：Lambda、API Gateway、DynamoDB、Serverless、无服务器等关键词。

## 布局结构

```
Clients → CloudFront → API Gateway → Lambda → DynamoDB
                                    → SQS
                                    → S3
```

这些坐标是结构参考，不是必须死守的固定像素模板。如果内容变多、标签变长、或增加额外节点：
- 先扩容画布或调整节点位置
- 再把相关节点拆成多行
- 仍然放不下时回退到 `freeflow`

不要为了维持这一版模板，把整张图挤成单行牙膏布局。

## 组件定义

| 组件 | 类别 | x | y | 宽 | 高 | 特征 |
|------|------|---|---|-----|-----|------|
| Clients | external | 80 | 230 | 140 | 80 | Web/Mobile |
| CloudFront | cloud | 310 | 230 | 140 | 80 | CDN |
| API Gateway | cloud | 500 | 230 | 160 | 80 | REST API, WebSocket, HTTPS |
| Lambda | backend | 720 | 230 | 150 | 80 | Functions, Auto-scaling |
| SQS | message_bus | 720 | 130 | 150 | 44 | Message Queue |
| S3 | cloud | 720 | 360 | 150 | 80 | Object Storage |
| DynamoDB | database | 930 | 230 | 160 | 80 | NoSQL, On-demand |

## 连接关系

| 从 | 到 | 方向 |
|----|----|------|
| Clients | CloudFront | 水平 → |
| CloudFront | API Gateway | 水平 → |
| API Gateway | Lambda | 水平 → |
| Lambda | SQS | 垂直 ↑ |
| Lambda | S3 | 垂直 ↓ |
| Lambda | DynamoDB | 水平 → |

## AWS Region

- 虚线框：x=260, y=110, width=900, height=350, rx=16
- 描边：`#F59E0B`, `stroke-dasharray="8,4"`, `opacity="0.4"`
- 标签：`AWS Region: us-east-1`（x=280, y=100）
- Clients 在 Region 框外左侧

## 图例与画布

- Legend 放在左下或底部保留区，不放右上角。
- 最终 SVG 高度必须包含最底部节点、legend、summary cards 和 footer。
- 不得用固定高度容器或裁切把底部内容截断。

## Summary Cards

### Infrastructure (琥珀色)
- CloudFront CDN distribution
- API Gateway REST endpoints
- S3 static asset hosting
- SQS message queues

### Compute (翠绿色)
- Lambda functions
- Auto-scaling to zero
- Pay-per-invocation
- 15 min max execution

### Data (紫色)
- DynamoDB tables
- On-demand capacity
- Global secondary indexes
- Point-in-time recovery


path: references/archive/architecture-diagram-design.md
content: # Architecture Diagram Generator — Design Document (v2)

## Context

当前 `export_svg.py` 包含复杂的自动布局引擎（`_layout_free_flow`、`_content_router`、`_render_free_flow_svg`），产出却是网格堆叠的卡片，不是真正的架构图。更关键的是：**Python 代码太重，沙箱频繁出问题**——依赖链长、`importlib.metadata` 不稳定、`__file__` 在 Jupyter 中未定义。

参考项目 [Cocoon-AI/architecture-diagram-generator](https://github.com/Cocoon-AI/architecture-diagram-generator) 走了完全不同的路：**SKILL.md 定义设计系统，Claude 按规则直接生成 HTML+SVG，零 Python 依赖。**

本文档设计 v2 重构方案：**核心架构图生成完全脱离 Python，由 Claude 读取 SKILL.md → 直接输出 HTML+SVG。Python 只做 JSON 校验和格式转换（draw.io/excalidraw/mermaid）。**

## 核心决策

### 1. Python 轻量化

| 当前 | v2 |
|------|-----|
| `export_svg.py` 1500+ 行布局引擎 | 保留 300 行核心常量，移除自动布局 |
| `export_html.py` 200+ 行内嵌 SVG 构建 | 改为直接输出预生成的 SVG |
| `--export` 默认调 9 个 Python 函数 | Claude 生成 HTML+SVG（主），Python 格式转换（备） |
| 依赖 `importlib.metadata`、`math`、`pathlib` | 只依赖 `json`、`pathlib`（stdlib） |
| 沙箱需 `pip install kai-business-blueprint` | 沙箱只需 `json.load()` + 写文件，或 Claude 直接生成 |

### 2. Claude 生成架构图的具体机制

不是"Claude 在对话中手写 SVG"，而是：

```
1. Claude 读取 blueprint JSON（或用户自然语言描述）
2. Claude 读取 SKILL.md 中的设计系统规范
3. Claude 生成 HTML+SVG 文本 → 写入文件
4. 输出：单个 .html 文件
```

**在沙箱环境中**，不需要 `pip install`：
```python
# 沙箱只需这两行——无第三方依赖
import json
blueprint = json.load(open("solution.blueprint.json"))
# 然后 Claude 根据 blueprint 数据直接生成 HTML+SVG 字符串并写入文件
```

**Python 脚本完全退出架构图渲染**——它只做：
- `--plan`：将用户需求写入 blueprint JSON
- `--validate`：校验 blueprint 结构
- `--format drawio/excalidraw/mermaid`：从 blueprint 生成对应格式（这些格式有成熟的 Python 库/字符串拼接即可）

### 3. Blueprint Schema 适配

当前 schema **已有足够字段**，不需要扩展：

| 设计系统概念 | Blueprint 字段 | 映射方式 |
|------------|---------------|---------|
| 组件类型/颜色 | `systems[].category` | frontend/backend/database/cloud/security/external |
| L→R 数据流 | `flowSteps[].seqIndex` + `nextStepIds` | 按 seqIndex 排序，L→R 排列 |
| Region 边界 | `systems[].properties.type` | `type == "aws"` → 包在 AWS Region 框内 |
| 消息总线 | `systems[].properties.service == "sqs"` 等 | SQS/EventBridge/SNS → MessageBus 颜色 |
| 组件副标题 | `systems[].description` 或 `properties.features` | 取前 2-3 个特征 |
| 组件大小 | 根据 `capabilities` 数量决定 | 0-1 cap → 小框(60px)，2-4 → 中框(80px)，5+ → 大框(120px) |

**不需要新增字段。** 所有视觉决策都从现有字段推导。

## 设计系统（从参考项目继承）

### 颜色 Palette

| 类型 | 填充色 | 边框色 | 用途 |
|------|--------|--------|------|
| Frontend | `rgba(8,51,68,0.4)` | `#22d3ee` | Web、移动端、UI |
| Backend | `rgba(6,78,59,0.4)` | `#34d399` | Lambda、API Gateway、服务 |
| Database | `rgba(76,29,149,0.4)` | `#a78bfa` | DynamoDB、RDS、S3 |
| AWS/Cloud | `rgba(120,53,15,0.3)` | `#fbbf24` | Region 框、CloudFront |
| Security | `rgba(136,19,55,0.4)` | `#fb7185` | Security Group、WAF |
| MessageBus | `rgba(251,146,60,0.3)` | `#fb923c` | SQS、SNS、EventBridge |
| External | `rgba(30,41,59,0.5)` | `#94a3b8` | 第三方 API、SaaS |

### 字体
- JetBrains Mono（Google Fonts CDN）
- 组件名：14px / 600
- 副标签：11px / 400
- 注解：9px
- Region 标签：10px / 600

### 布局规则
- L→R 数据流：Clients(左) → Frontend → Backend → Database(右)
- Region 虚线框：`rx="12"`, `stroke-dasharray="8,4"`, 琥珀色
- 组件圆角：`rx="6"`, 1.5px 描边
- Z 序：箭头 → 节点遮罩 → 节点样式 → 文字 → Legend

## SKILL.md 结构

遵循**渐进披露**原则，SKILL.md 本身不塞设计系统细节：

```
SKILL.md（路由层，<100行）
  ├── 何时触发架构生成（关键词：architecture diagram, 架构图, --export）
  ├── 读取 references/architecture-design-system.md（完整设计系统）
  ├── 读取 references/architecture-templates/serverless.md（模板）
  └── Claude 生成 HTML+SVG → 写入文件

references/architecture-design-system.md（设计系统，~80行）
  ├── 颜色 Palette
  ├── 字体与间距
  ├── 视觉元素（Region框、组件框、箭头）
  └── Z 序规则

references/architecture-templates/（模板库）
  ├── serverless.md（AWS Serverless 模板）
  ├── microservices.md（微服务模板）
  └── three-tier.md（三层架构模板）
```

## Python 代码改动

### 删除（~900 行）

| 文件 | 删除内容 |
|------|---------|
| `export_svg.py` | `_content_router()`、`_layout_free_flow()`、`_render_free_flow_svg()`、`export_svg_auto()` |
| `export_html.py` | `_build_architecture_svg()` 整个函数 |

### 保留（~600 行）

| 文件 | 保留内容 |
|------|---------|
| `export_svg.py` | 设计常量（`C_LIGHT`、`C_DARK`、字体、尺寸）、箭头/节点渲染函数、`export_svg()` 三层布局（回退用）、`export_*_svg()` 专业视图 |
| `export_drawio.py` | 完整保留 |
| `export_excalidraw.py` | 完整保留 |
| `export_mermaid.py` | 完整保留 |
| `cli.py` | 简化：`--export` 默认触发 Claude 生成（见下），`--format drawio/excalidraw/mermaid/all` 调 Python |

### `cli.py` 中 `--export` 新逻辑

**关键设计：** `--export` 既要保证向后兼容（Python 产出基础文件），也要让 Agent 有机会生成增强版架构图。

```python
if args.export:
    blueprint_path = Path(args.export)
    blueprint = load_json(blueprint_path)
    stem = blueprint_path.stem
    export_dir = blueprint_path.parent / f"{stem}.exports"
    export_dir.mkdir(parents=True, exist_ok=True)
    
    fmt = args.export_format or "svg"
    
    if fmt == "svg":
        # Python 产出经典三层布局 SVG（向后兼容，确保有文件产出）
        export_svg(blueprint, export_dir / "solution.svg", theme=args.theme)
        # Agent 在沙箱外读取 blueprint → 按 SKILL.md 生成增强版 HTML+SVG
        # 这是 Agent 的下一步动作，不在 CLI 中执行
        return 0
    
    elif fmt == "drawio":
        export_drawio(blueprint, export_dir / "solution.drawio")
    elif fmt == "excalidraw":
        export_excalidraw(blueprint, export_dir / "solution.excalidraw")
    elif fmt == "mermaid":
        export_mermaid(blueprint, export_dir / "solution.mermaid.md")
    elif fmt == "all":
        # Python 产出所有格式（向后兼容）
        export_svg(blueprint, export_dir / "solution.svg", theme=args.theme)
        export_capability_map_svg(blueprint, export_dir / "capability-map.svg", theme=args.theme)
        export_swimlane_flow_svg(blueprint, export_dir / "swimlane-flow.svg", theme=args.theme)
        export_product_tree_svg(blueprint, export_dir / "product-tree.svg", theme=args.theme)
        export_matrix_svg(blueprint, export_dir / "capability-matrix.svg", theme=args.theme)
        export_drawio(blueprint, export_dir / "solution.drawio")
        export_excalidraw(blueprint, export_dir / "solution.excalidraw")
        export_mermaid(blueprint, export_dir / "solution.mermaid.md")
        # Agent 可在此基础上额外生成增强版架构图 HTML
        return 0
```

**Agent 的增强流程（CLI 之外）：**
1. `--export` 完成后，Agent 读取 blueprint JSON
2. Agent 按 SKILL.md 设计系统规范生成架构图 HTML+SVG
3. 写入 `{stem}.html` 到同目录

### 沙箱兼容

沙箱不是独立运行的——调用链是 `用户 → Agent(Claude/OpenAI/GLM) → tool call → 沙箱执行Python`。

沙箱中 Agent 始终可用，所以架构生成流程是：
1. Agent 在沙箱中 `json.load()` 读取 blueprint
2. Agent 读取 SKILL.md 设计系统规范
3. Agent 生成 HTML+SVG 字符串 → 通过沙箱 `write_file` 或 `Path.write_text()` 写入
4. 返回给用户

沙箱不再需要 `pip install kai-business-blueprint`：
```python
# 极简沙箱用法——只需 stdlib
import json
from pathlib import Path

blueprint = json.loads(Path("solution.blueprint.json").read_text())
# Agent 根据 blueprint 数据 + SKILL.md 设计系统，直接生成 HTML+SVG 并写入文件
```

**Python 脚本在沙箱中的角色：JSON 加载 + 校验。** 架构图渲染完全由 Agent 承担。

## 回退策略

由于调用链中 Agent 始终存在（Agent → tool call → 沙箱 → Agent 继续），**不存在"无 Agent 可用"的回退场景**。但保留以下回退以防代码层面断裂：

1. **`--export` 时 Python 仍产出 `solution.svg`（三层布局经典版）** — 确保 `--format all` 向后兼容
2. **`export_html.py` 不再自己构建 SVG** — 改为接受预生成的 SVG 内容参数

三个保障：
- `--export` 至少产出 `solution.svg`（Python 经典布局）
- Agent 可在此基础上额外生成 HTML+SVG 架构图
- `drawio/excalidraw/mermaid` 格式由 Python 稳定产出

## 实施阶段

| 阶段 | 内容 | 可回滚？ |
|------|------|---------|
| **Phase 1** | 写 `references/architecture-design-system.md` + 模板 | ✅ 只加文件 |
| **Phase 2** | 更新 SKILL.md 添加架构图生成路由 | ✅ 只改 SKILL.md |
| **Phase 3** | 删除 `_content_router`、`_layout_free_flow`、`_render_free_flow_svg` | ⚠️ 需确认无外部依赖 |
| **Phase 4** | 简化 `cli.py` 和 `export_html.py` | ⚠️ 需测试沙箱兼容 |
| **Phase 5** | 测试 `aws-serverless.blueprint.json` 生成效果 | — |

## 评审问题应对

| Codex 评审问题 | 应对 |
|---------------|------|
| `export_html.py` 导入断裂 | **`export_html.py` 的 `_build_architecture_svg()` 不再自己构建 SVG**，改为接受预生成的 SVG 字符串参数，或回退到三层布局。删除对 `_content_router`、`_layout_free_flow`、`_render_free_flow_svg` 的 import |
| "CLI plans, Claude generates" 无明确机制 | **CLI 产出基础文件（Python 经典布局），Agent 在此基础上生成增强版**。CLI 不返回 0 空文件 |
| 非交互环境无 Claude | **调用链始终是 Agent → tool call → 沙箱 → Agent**。不存在离线调用场景 |
| Blueprint 字段不够 | 所有视觉决策从现有字段推导，不需新增 schema |
| SKILL.md 膨胀 | 设计系统放 `references/`，SKILL.md 只引用 |
| `--format all` 其他导出 | **保留所有 Python SVG 导出器在 `--format all` 中**，确保向后兼容 |
| 测试文件断裂 | Phase 3 删除 `test_content_router_and_layout.py` 或重写 |


path: references/archive/blueprint-skill-optimization-proposal.md
content: # Business Blueprint Skill 优化方案

## 问题诊断

### 现状分析

**现有skill定位**：系统架构蓝图生成器
- 实体类型：capabilities（能力）、actors（角色）、flowSteps（流程）、systems（系统）
- 输出形式：架构分层图、泳道流程图、系统支撑关系图
- 适用场景：售前方案设计、IT系统规划、业务流程梳理

**缺失需求**：业务领域know-how知识图谱
- 痛点挑战、关键策略、平台规则、数据指标、最佳实践、常见误区
- 用于展示"我们懂这个领域"的专业度
- 客户pitch时需要业务洞察，而非技术架构

### 根本原因

skill设计时将"业务蓝图"等同于"系统架构蓝图"，实体定义固化在IT系统视角：
- `systems` 实体强制映射到技术架构层（客户端层、网关层、业务服务层）
- 缺失"策略要素"、"行业规则"、"数据基准"等业务洞察实体
- AI只能按IT架构思维提取实体，无法生成领域知识图谱

---

## 设计方案对比

### 方案A：扩展实体类型（最小改动）

**改造思路**：
在现有`library`中新增实体类型：
```json
{
  "library": {
    "capabilities": [],
    "actors": [],
    "flowSteps": [],
    "systems": [],
    // 新增实体类型
    "painPoints": [
      {"id": "pain-001", "name": "ROI不稳", "description": "广告投放ROI波动大，缺乏稳定增长路径", "severity": "high"}
    ],
    "strategies": [
      {"id": "str-001", "name": "测款节奏", "description": "3天测款周期，预算分配策略", "applicableCapabilityIds": ["cap-004"]}
    ],
    "platformRules": [
      {"id": "rule-001", "name": "Facebook政策红线", "description": "禁止误导性宣传、过度夸大效果", "riskLevel": "critical"}
    ],
    "metrics": [
      {"id": "met-001", "name": "ROAS基准", "value": ">3.0", "unit": "ratio", "benchmarkContext": "欧美市场"}
    ],
    "bestPractices": [
      {"id": "bp-001", "name": "素材迭代周期", "description": "每7天测试新素材版本，避免疲劳"}
    ],
    "pitfalls": [
      {"id": "pit-001", "name": "过度依赖单一平台", "description": "Facebook封号后业务瘫痪风险", "impact": "critical"}
    ]
  }
}
```

**优点**：
- 兼容现有JSON schema和export逻辑，改动最小
- 一个蓝图可以同时包含架构和know-how

**缺点**：
- 实体职责混淆，一个JSON既要画架构图又要画知识图谱
- 导出视图选择复杂化（需要判断显示哪些实体类型）
- 与现有schema文档的"实体概览表"冲突（需要重新编写schema文档）

---

### 方案B：引入蓝图类型区分（路由层改造）

**改造思路**：
在SKILL.md中引入显式的蓝图类型参数：
```bash
python scripts/business_blueprint/cli.py --plan blueprint.json --type architecture
python scripts/business_blueprint/cli.py --plan blueprint.json --type domain-knowledge
```

两种类型使用不同的schema和hints：
- `--type architecture`：使用现有实体体系（capabilities/actors/flowSteps/systems）
- `--type domain-knowledge`：使用新的实体体系（painPoints/strategies/rules/metrics/practices/pitfalls）

**优点**：
- 职责清晰，互不干扰
- 每种类型有独立的hints模板和导出视图
- schema文档可以分别编写

**缺点**：
- 需要用户显式指定类型（增加使用门槛）
- 需要双倍维护成本（两套schema、两套模板、两套导出逻辑）
- 不符合skill的"渐进式披露"设计原则（AI应该自动判断意图）

---

### 方案C：轻量级schema扩展（推荐方案）

**改造思路**：
保持核心schema不变，新增可选的`knowledge`块：

```json
{
  "version": "1.0",
  "meta": {
    "title": "...",
    "industry": "retail",
    "blueprintType": "architecture",  // 新增字段：默认"architecture"，可选"domain-knowledge"或"hybrid"
    "revisionId": "...",
    "lastModifiedAt": "...",
    "lastModifiedBy": "ai"
  },
  "context": {...},
  "library": {
    // 保留现有实体（架构类）
    "capabilities": [],
    "actors": [],
    "flowSteps": [],
    "systems": [],
    // 新增可选块（know-how类）
    "knowledge": {
      "painPoints": [],
      "strategies": [],
      "rules": [],
      "metrics": [],
      "practices": [],
      "pitfalls": []
    }
  },
  "relations": [],
  "views": [],
  "editor": {...},
  "artifacts": {}
}
```

**AI意图判断逻辑**（写在SKILL.md）：
```
用户需求关键词匹配：
- "架构图"、"系统设计"、"IT规划" → blueprintType = "architecture"，只填充library核心实体
- "know-how"、"领域知识"、"业务洞察"、"最佳实践"、"行业玩法" → blueprintType = "domain-knowledge"，只填充knowledge块
- 混合需求（同时提到架构和策略） → blueprintType = "hybrid"，同时填充两类实体
```

**导出视图路由逻辑**（在export_routes.py中）：
```python
if blueprintType == "architecture":
    使用现有视图模板（poster/swimlane/freeflow）
elif blueprintType == "domain-knowledge":
    使用新的knowledge视图模板（knowledge-graph/knowledge-cards）
elif blueprintType == "hybrid":
    分页渲染（第一页架构图，第二页知识图谱）
```

**优点**：
- 不破坏现有架构蓝图能力（向后兼容）
- AI自动判断意图，无需用户显式参数（符合渐进式披露）
- 同一个JSON schema，不同视图模板（维护成本低）
- 可以支持混合蓝图（架构+know-how并存）

**缺点**：
- 需要新增knowledge块的schema文档
- 需要开发新的导出视图模板

---

## 推荐方案C的详细设计

### 一、schema扩展设计

#### 1. meta字段扩展

```json
{
  "meta": {
    "blueprintType": "architecture"  // 新增，枚举值：architecture | domain-knowledge | hybrid
  }
}
```

#### 2. library.knowledge实体定义

新增`knowledge`块，包含6类know-how实体：

| 实体类型 | 定义 | 示例数量 | 必填字段 |
|---------|------|---------|---------|
| **painPoints** | 痛点挑战 | 3-8 | id, name, description, severity |
| **strategies** | 关键策略 | 3-10 | id, name, description, applicableCapabilityIds |
| **rules** | 平台/政策规则 | 3-8 | id, name, description, riskLevel |
| **metrics** | 数据指标/基准 | 3-10 | id, name, value, unit, benchmarkContext |
| **practices** | 最佳实践 | 3-10 | id, name, description |
| **pitfalls** | 常见误区 | 3-8 | id, name, description, impact |

#### 3. knowledge实体字段详细定义

**painPoints（痛点）**
```json
{
  "id": "pain-001",
  "name": "ROI不稳",
  "description": "广告投放ROI波动大，缺乏稳定增长路径",
  "severity": "high",  // 枚举：low | medium | high | critical
  "relatedCapabilityIds": ["cap-004", "cap-005"]  // 可选，关联到能力
}
```

**strategies（策略）**
```json
{
  "id": "str-001",
  "name": "测款节奏策略",
  "description": "3天测款周期，预算分配70%测款+30%放量",
  "applicableCapabilityIds": ["cap-004"],  // 可选，应用到哪些能力
  "prerequisites": ["数据分析能力"]  // 可选，前置条件
}
```

**rules（规则）**
```json
{
  "id": "rule-001",
  "name": "Facebook广告政策红线",
  "description": "禁止误导性宣传、过度夸大效果、虚假折扣",
  "riskLevel": "critical",  // 枚举：low | medium | high | critical
  "platform": "Facebook Ads",  // 可选，适用平台
  "penalty": "账户封禁"  // 可选，违规后果
}
```

**metrics（指标）**
```json
{
  "id": "met-001",
  "name": "ROAS基准",
  "value": ">3.0",
  "unit": "ratio",
  "benchmarkContext": "欧美市场，电商类目",
  "calculationMethod": "GMV / Ad Spend"  // 可选，计算公式
}
```

**practices（最佳实践）**
```json
{
  "id": "bp-001",
  "name": "素材迭代周期",
  "description": "每7天测试新素材版本，CTR下降10%时立即更换",
  "frequency": "weekly",  // 可选，执行频率
  "successMetric": "CTR提升15%"  // 可选，成功指标
}
```

**pitfalls（误区）**
```json
{
  "id": "pit-001",
  "name": "过度依赖单一平台",
  "description": "只投放Facebook，平台封号后业务瘫痪",
  "impact": "critical",  // 枚举：low | medium | high | critical
  "avoidanceStrategy": "多平台分散投放，预算占比不超过60%"  // 可选，规避建议
}
```

---

### 二、hints模板扩展

#### 1. 行业hints增加know-how checklist

修改`templates/{industry}/seed.json`：

```json
{
  "industryHints": {
    "title": "零售行业蓝图关注点",
    "checklist": [...],  // 现有的架构类hints
    "knowledgeHints": {  // 新增块
      "title": "零售行业know-how关注点",
      "checklist": [
        "痛点：库存积压、客流下滑、会员流失、POS效率低",
        "策略：会员分层运营、智能补货、导购赋能、全渠道融合",
        "规则：食品安全合规、价格欺诈风险、数据隐私法规",
        "指标：坪效基准、客单价目标、会员复购率、员工人效",
        "最佳实践：陈列迭代周期、促销节奏、会员召回时机",
        "误区：过度依赖促销、忽视会员运营、数据孤岛"
      ]
    }
  }
}
```

#### 2. 为跨境电商新建industry模板

新建`templates/cross-border-ecommerce/seed.json`：

```json
{
  "industryHints": {
    "title": "跨境电商广告投放know-how关注点",
    "checklist": [],  // 空列表，架构类hints可选
    "knowledgeHints": {
      "title": "跨境电商广告投放know-how",
      "checklist": [
        "痛点：ROI不稳、素材疲劳、平台封号、库存积压、汇率风险",
        "策略：测款节奏、出价策略、受众分层、再营销触发时机、预算动态分配",
        "规则：Facebook政策红线、Google Quality Score、TikTok审核要点、Amazon合规要求",
        "指标：ROAS基准(>3.0)、CPA阈值、CTR基准(>1.5%)、LTV测算",
        "最佳实践：素材迭代周期(7天)、测款预算分配(70%测款)、再营销触发时机(浏览>3次)",
        "误区：过度依赖单一平台、忽视合规风险、数据孤岛、盲目放量、忽视LTV"
      ]
    }
  }
}
```

---

### 三、导出视图设计

#### 1. 新增knowledge视图模板

新建`references/knowledge-view-templates/`目录：

**knowledge-graph.md**：知识图谱视图
- 布局：中心发散式，painPoints为核心节点
- 连线：painPoints → strategies → practices → metrics
- 视觉：按severity/riskLevel分级颜色（critical=红，high=橙，medium=黄，low=绿）
- 交互：点击节点展开详细描述卡片

**knowledge-cards.md**：卡片式视图
- 布局：分6列（痛点/策略/规则/指标/实践/误区）
- 每列内按severity排序
- 每个卡片显示name + description + 关联信息
- 支持导出为PPT单页

#### 2. export_routes.py路由逻辑

```python
def select_export_route(blueprint):
    blueprint_type = blueprint.get("meta", {}).get("blueprintType", "architecture")

    if blueprint_type == "architecture":
        # 现有路由逻辑
        return select_architecture_route(blueprint)
    elif blueprint_type == "domain-knowledge":
        # 新路由：knowledge优先
        return "knowledge-graph"  # 或 "knowledge-cards"
    elif blueprint_type == "hybrid":
        # 混合路由：双视图
        return "hybrid-view"
    else:
        # fallback
        return "freeflow"
```

---

### 四、SKILL.md改造

#### 1. AI意图判断指南

在SKILL.md的"How to Generate a Blueprint"章节前插入：

```markdown
## Blueprint Type Detection

AI must detect user intent before entity extraction:

| Intent keywords | Blueprint type | Entity focus |
|----------------|---------------|-------------|
| "架构图"、"系统设计"、"IT规划"、"技术蓝图" | `architecture` | capabilities, actors, flowSteps, systems |
| "know-how"、"领域知识"、"业务洞察"、"最佳实践"、"行业玩法"、"痛点"、"策略" | `domain-knowledge` | knowledge块（painPoints/strategies/rules/metrics/practices/pitfalls） |
| 混合需求（同时提到架构和策略） | `hybrid` | 两类实体同时提取 |

Default behavior:
- If unclear, default to `architecture` (backward compatibility)
- If industryHints contains `knowledgeHints`, hint AI to also extract knowledge entities
```

#### 2. Step 2改造

```markdown
### Step 2: Extract entities from source text

**If blueprintType = "architecture"**:
Using the user's source material AND the industry hints checklist, extract:
- capabilities, actors, flowSteps, systems
  - See `references/entities-schema.md` for definitions

**If blueprintType = "domain-knowledge"**:
Using the user's source material AND the knowledge hints checklist, extract:
- painPoints, strategies, rules, metrics, practices, pitfalls
  - See `references/knowledge-schema.md` for definitions

**If blueprintType = "hybrid"**:
Extract both architecture and knowledge entities
```

---

### 五、实施步骤

#### Phase 1：Schema扩展（向后兼容）

1. 修改`scripts/business_blueprint/templates/common/seed.json`，新增`meta.blueprintType`字段（默认值"architecture"）
2. 新建`references/knowledge-schema.md`，定义knowledge块6类实体
3. 修改`references/entities-schema.md`，在"实体概览表"中新增knowledge块说明
4. 修改JSON schema validator，允许`library.knowledge`可选块

#### Phase 2：Hints模板扩展

1. 修改所有industry seed.json（common/finance/manufacturing/retail），新增`industryHints.knowledgeHints`块
2. 新建`templates/cross-border-ecommerce/seed.json`（跨境电商专属模板）
3. 新建`templates/ad-tech/seed.json`（广告技术专属模板）

#### Phase 3：导出视图开发

1. 新建`references/knowledge-view-templates/knowledge-graph.md`（知识图谱模板设计文档）
2. 新建`references/knowledge-view-templates/knowledge-cards.md`（卡片式模板设计文档）
3. 修改`business_blueprint/export_routes.py`，增加knowledge路由判断
4. 开发knowledge视图渲染器（HTML/SVG输出）

#### Phase 4：SKILL.md改造

1. 在SKILL.md开头新增"Blueprint Type Detection"章节
2. 修改"Step 2: Extract entities"章节，增加分支逻辑
3. 新增"Export Formats"章节的knowledge视图说明
4. 新增"Industry Selection"表的跨境电商、广告技术行业

---

## 改造清单

### 必须改造的文件

| 文件 | 改动内容 | 优先级 |
|------|---------|--------|
| `scripts/business_blueprint/templates/common/seed.json` | 新增meta.blueprintType字段 | P0 |
| `references/entities-schema.md` | 新增knowledge块说明 | P0 |
| 新建 `references/knowledge-schema.md` | 定义knowledge实体字段 | P0 |
| `SKILL.md` | 新增Blueprint Type Detection章节 | P0 |
| `scripts/business_blueprint/templates/retail/seed.json` | 新增knowledgeHints块 | P1 |
| `scripts/business_blueprint/templates/finance/seed.json` | 新增knowledgeHints块 | P1 |
| `scripts/business_blueprint/templates/manufacturing/seed.json` | 新增knowledgeHints块 | P1 |
| 新建 `templates/cross-border-ecommerce/seed.json` | 跨境电商专属模板 | P1 |
| 新建 `references/knowledge-view-templates/knowledge-graph.md` | 知识图谱视图设计 | P2 |
| 新建 `references/knowledge-view-templates/knowledge-cards.md` | 卡片式视图设计 | P2 |
| `scripts/business_blueprint/export_routes.py` | 新增knowledge路由逻辑 | P2 |

### 可选改造（后续迭代）

- 新建 `templates/ad-tech/seed.json`（广告技术行业模板）
- 新建 `templates/logistics/seed.json`（物流行业模板）
- 开发混合视图渲染器（architecture + knowledge并存）
- 开发知识图谱交互式编辑器（点击节点展开详情）

---

## 验证测试用例

### 测试1：向后兼容性

输入：
```
生成企业管理系统的架构蓝图
```

预期：
- blueprintType = "architecture"
- 只填充library核心实体（capabilities/actors/flowSteps/systems）
- 导出视图为现有模板（poster/swimlane/freeflow）
- JSON schema验证通过

### 测试2：纯knowledge蓝图

输入：
```
生成跨境电商广告投放的领域know-how大图，包含痛点、策略、平台规则、数据指标
```

预期：
- blueprintType = "domain-knowledge"
- 只填充library.knowledge块（painPoints/strategies/rules/metrics/practices/pitfalls）
- 导出视图为knowledge-graph或knowledge-cards
- industry自动选择"cross-border-ecommerce"

### 测试3：混合蓝图

输入：
```
生成跨境电商广告投放方案，既要系统架构，又要业务策略know-how
```

预期：
- blueprintType = "hybrid"
- 同时填充architecture实体和knowledge实体
- 导出视图为双页（第一页架构图，第二页知识图谱）
- 或者单页分区域显示

---

## 风险评估

### 低风险

- schema向后兼容（默认blueprintType="architecture"，现有调用不受影响）
- hints模板扩展不影响现有行业模板
- AI意图判断写在SKILL.md，不修改Python代码逻辑

### 中风险

- 导出视图路由逻辑需要修改export_routes.py（需要测试回归）
- knowledge实体字段定义可能与capabilities产生混淆（需要在schema文档中明确区分）

### 高风险

- 无（方案C避免了双schema的维护成本，也没有破坏性改动）

---

## 时间估算

- Phase 1（Schema扩展）：2-3小时
- Phase 2（Hints模板）：3-4小时
- Phase 3（导出视图）：8-10小时（需要开发新渲染器）
- Phase 4（SKILL.md改造）：1-2小时

总计：14-19小时（约2-3个工作日）

---

## 后续迭代建议

1. **知识图谱编辑器**：让用户可以在HTML viewer中点击节点，展开详情卡片，添加新的know-how节点
2. **行业know-how库**：沉淀各行业的know-how模板库（例如跨境电商的常见痛点、策略清单）
3. **know-how版本管理**：支持know-how的演化记录（例如Facebook政策规则的历史变更）
4. **know-how与架构联动**：在架构图中标注对应know-how（例如某个系统旁边显示"规避XX风险的最佳实践"）

path: references/archive/domain-knowledge-design-adversarial-review.md
content: # 对抗性评审报告：Domain-Knowledge实体扩展设计

**评审日期**: 2026-04-28
**评审者**: Claude Code（对抗性视角）
**目标**: 系统性识别设计缺陷、矛盾、遗漏、风险，确保设计质量

---

## 一、核心假设脆弱性分析

### 问题1：AI自动判断意图的可靠性假设

**设计假设**：
```
用户需求包含"know-how"、"领域知识"、"策略"、"痛点" → blueprintType = "domain-knowledge"
```

**对抗性质疑**：
- 用户输入模糊时，AI判断会出错吗？
- 例如：用户说"优化ROI策略" → "策略"关键词触发domain-knowledge，但用户实际想看的是系统架构（优化ROI的系统设计）
- 关键词匹配过于简单，缺乏上下文理解

**发现缺陷**：
- ❌ AI判断逻辑过于简单（关键词匹配），未考虑用户意图的语义理解
- ❌ 未定义fallback机制：AI判断错误时，用户如何纠正blueprintType？

**建议改进**：
- 新增判断优先级：用户明确指定蓝图类型 > 关键词频率分析 > 默认值
- 允许用户在JSON meta中手动设置blueprintType覆盖AI判断

---

### 问题2："强核心+弱扩展"的可行性假设

**设计假设**：
```
validator只校验核心字段（id/name/entityType），扩展字段直接放行
```

**对抗性质疑**：
- 扩展字段真的能完全放行吗？
- 用户可能在扩展字段中写入错误数据类型（如`severity: 123`而非字符串）
- freeflow渲染器可能崩溃于复杂嵌套结构（如`{"nested": {"deep": {"recursive": "object"}}}`）

**发现缺陷**：
- ❌ validator完全放行扩展字段，可能导致下游工具（viewer/export）崩溃
- ❌ 未定义扩展字段的数据类型约束：severity应该是枚举字符串，而非任意值
- ❌ freeflow渲染器缺乏容错设计：复杂结构降级显示策略未定义

**建议改进**：
- 定义常见扩展字段的soft schema（如severity: string枚举，level: integer）
- validator校验扩展字段时采用soft模式（警告而非报错）
- freeflow渲染器增加容错：嵌套层级>3时降级为文本卡片

---

### 问题3：freeflow自适应渲染的技术可行性假设

**设计假设**：
```
freeflow足够灵活，只需定义视觉样式，无需开发独立knowledge-graph视图模板
```

**对抗性质疑**：
- freeflow当前渲染逻辑基于system分层架构，knowledge实体没有layer/category字段
- freeflow如何布局大量knowledge实体（例如50个痛点、30个策略）？
- relations关系连线复杂时（多个solves、prevents交叉），freeflow能否正确渲染？

**发现缺陷**：
- ❌ freeflow布局算法未适配knowledge实体（无layer/category，无法自动分层）
- ❌ 未定义knowledge实体的布局策略（中心发散？网格布局？自由布局？）
- ❌ 大量实体场景下的性能问题未评估（100+实体时freeflow渲染速度）

**建议改进**：
- 定义knowledge布局策略：painPoints为中心，strategies围绕，其他实体外围
- 新增布局算法：entityType-based clustering（按实体类型聚类）
- 定义性能上限：超过50实体时分页渲染或简化连线

---

## 二、边界条件未覆盖

### 问题4：混合蓝图的处理逻辑缺失

**设计假设**：
```
两种类型互斥，不设计hybrid（避免复杂度）
```

**对抗性质疑**：
- 用户实际需求可能真的需要混合蓝图（既要系统架构，又要know-how策略）
- AI判断"优先domain-knowledge"的规则，会导致architecture实体被遗漏
- relations跨类型关联（strategy → capability）在纯domain-knowledge蓝图中失效（capability不存在）

**发现缺陷**：
- ❌ 混合需求强制选择单一蓝图类型，丢失部分用户需求
- ❌ 跨类型关联的实用性假设：如果blueprintType=domain-knowledge，用户不能添加capability实体，跨类型关联无法建立
- ❌ 未定义混合蓝图的处理策略（是否允许？如何存储？）

**建议改进**：
- 允许hybrid蓝图类型（blueprintType="hybrid"），同时填充architecture和knowledge实体
- 定义hybrid蓝图的处理规则：relations必须明确区分跨类型关系和同类型关系
- 或者：允许domain-knowledge蓝图中可选添加architecture实体（非强制）

---

### 问题5：用户自定义实体的边界模糊

**设计假设**：
```
允许用户自定义实体类型数组（validator不校验数组名称）
```

**对抗性质疑**：
- 用户自定义实体与预定义实体的命名冲突如何处理？（如用户自定义"strategies"数组）
- 用户自定义实体类型命名不规范时，freeflow如何渲染？（如`"MyCustomEntity"`而非`"myCustomEntity"`）
- 用户自定义实体如何建立关系？（entityType不在relations定义中）

**发现缺陷**：
- ❌ 未定义命名冲突处理策略：用户自定义数组名称与预定义实体类型冲突时，validator行为未明确
- ❌ 用户自定义entityType的命名规范未定义（推荐camelCase？允许任意字符串？）
- ❌ 用户自定义实体的relations关系类型未定义（如何建立custom → custom的关系？）

**建议改进**：
- 定义命名冲突策略：用户自定义数组名称优先级高于预定义（允许覆盖）
- 定义entityType命名规范：推荐camelCase，validator校验格式（至少3字符，无特殊符号）
- 新增通用关系类型：`relates`（任意实体之间的弱关联）

---

### 问题6：relations关系完整性约束缺失

**设计假设**：
```
relations数组表达实体关联，新增solves/prevents/measures等关系类型
```

**对抗性质疑**：
- relations中的from/to ID不存在时，validator如何处理？
- 循环依赖如何避免？（strategy → practice → strategy）
- 用户可能建立不合理关系（如metric → pitfall，无语义意义）

**发现缺陷**：
- ❌ relations ID引用完整性未校验：from/to ID不存在时，validator不报错
- ❌ 循环依赖检测缺失：AI或用户可能建立A→B→C→A的循环关系
- ❌ 关系语义合理性未校验：measures只能metric→strategy，但用户可能写metric→pitfall

**建议改进**：
- validator校验relations ID引用完整性（from/to ID必须在library中存在）
- validator检测循环依赖（A→B→C→A时报错）
- 定义关系语义约束表（measures只能metric→strategy等），validator校验

---

## 三、内部矛盾和冲突

### 问题7：决策3与决策1的矛盾

**决策3**：
```
knowledge实体可单向关联architecture实体（单向关联）
```

**决策1**：
```
blueprintType互斥：architecture | domain-knowledge（无hybrid）
```

**矛盾点**：
- 如果blueprintType=domain-knowledge，library中不存在architecture实体（capabilities等）
- 此时跨类型关联（strategy → capability）无法建立（capability不存在）
- 决策3的单向关联假设失效

**发现矛盾**：
- ❌ 决策3假设knowledge实体可以关联architecture实体，但决策1禁止混合蓝图
- ❌ "不强加architecture关联"的补充说明，在纯domain-knowledge蓝图中等价于"无法关联"

**建议改进**：
- 修改决策1：允许hybrid蓝图类型，或允许domain-knowledge蓝图中可选添加architecture实体
- 或修改决策3：删除跨类型关联定义，仅在用户明确需求时才建立跨类型关系

---

### 问题8：severity字段定义与实体类型定义表的矛盾

**实体类型定义表**：
```
| strategies | "strategy" | level（可选） | - | 3-10 |
```
表格显示strategies无severity字段。

**实体字段规范章节**：
```
strategies可选字段未提及severity字段
```

**Relations关系类型定义**：
```
未提及strategy的severity字段，但pitfall有severity字段
```

**矛盾点**：
- 实体类型定义表显示strategies无severity，但用户可能误用或自定义severity
- severity统一为"严重程度"，但策略的"严重程度"语义不清晰（策略的有效性？策略的风险性？）

**发现矛盾**：
- ❌ 决策5统一severity字段，但实体类型定义表排除strategies的severity字段
- ❌ severity语义不明确：painPoint的severity=痛点严重程度，strategy的severity=？（策略有效性？策略风险性？）

**建议改进**：
- 明确strategies的severity语义：策略风险等级（low=低风险策略，high=高风险策略）
- 或删除strategies的severity字段定义，明确severity仅适用于painPoints/rules/pitfalls

---

### 问题9：向后兼容保证与schema扩展的冲突

**向后兼容保证**：
```
blueprintType默认值"architecture"，现有JSON无需修改
```

**Schema扩展**：
```
新增meta.blueprintType字段，新增library.knowledge块
```

**冲突点**：
- 现有JSON schema validator可能采用schema-first策略（严格校验所有字段）
- 新增字段（blueprintType、knowledge）可能导致现有validator报错"未知字段"
- 向后兼容保证依赖于validator的field-first策略（只校验已知字段，放行未知字段）

**发现冲突**：
- ❌ 设计假设validator采用field-first策略，但现有validator可能采用schema-first策略
- ❌ 未检查现有validator的实现策略（需要代码审查）

**建议改进**：
- 检查现有schema_validator.py的实现策略（schema-first or field-first）
- 如果schema-first，需要改造为field-first + whitelist模式（校验已知字段，放行白名单字段）

---

## 四、遗漏的关键细节

### 问题10：entityType命名规范缺失

**设计假设**：
```
entityType字段标识实体类型，validator不校验entityType名称
```

**遗漏细节**：
- entityType命名规范未定义（推荐camelCase？允许任意字符串？允许中文？）
- entityType与knowledge数组名称的映射关系未定义（如`entityType="painPoint"`对应`painPoints`数组）
- 用户自定义entityType时，AI如何匹配到对应的数组？

**发现遗漏**：
- ❌ entityType命名规范未定义（大小写、字符集、长度限制）
- ❌ entityType与数组名称的映射规则未定义（`entityType="caseStudy"`应放在哪个数组？）

**建议改进**：
- 定义entityType命名规范：camelCase，至少3字符，仅字母，推荐与数组名称匹配
- 定义entityType与数组名称映射：`entityType="painPoint"` → `painPoints`数组，用户自定义entityType → 对应数组名称需手动指定

---

### 问题11：hints模板的编写质量保证缺失

**设计假设**：
```
hints模板包含checklist，AI从"痛点：..."描述中自动解析实体类型
```

**遗漏细节**：
- hints模板编写质量如何保证？（checklist条目格式不规范时，AI解析出错）
- hints模板的测试策略未定义（如何验证hints模板的有效性？）
- 行业模板的覆盖度如何评估？（跨境电商模板是否覆盖关键痛点？）

**发现遗漏**：
- ❌ hints checklist条目格式规范未定义（"痛点：..."格式是唯一标准吗？）
- ❌ hints模板的测试策略未定义（AI解析checklist时，提取准确率如何测试？）
- ❌ hints模板覆盖度评估缺失（如何确保模板包含行业关键实体？）

**建议改进**：
- 定义checklist条目格式规范：`实体类型：具体条目1、条目2`，允许AI自动解析
- 定义hints模板测试策略：生成10个测试蓝图，验证AI提取准确率（>80%）
- 定义hints模板覆盖度评估：每个实体类型至少3个典型条目，覆盖率>90%

---

### 问题12：freeflow渲染器的降级策略缺失

**设计假设**：
```
freeflow渲染knowledge实体，定义视觉样式
```

**遗漏细节**：
- freeflow渲染大量实体时的性能降级策略未定义（100+实体时如何处理？）
- freeflow渲染复杂嵌套字段时的容错策略未定义（用户自定义字段嵌套层级>3时如何显示？）
- freeflow渲染错误entityType时的fallback策略未定义（未知entityType如何显示？）

**发现遗漏**：
- ❌ 性能降级策略缺失：超过50实体时分页渲染或简化连线
- ❌ 容错策略缺失：复杂嵌套字段降级为文本卡片，避免渲染崩溃
- ❌ fallback策略缺失：未知entityType使用默认灰色样式

**建议改进**：
- 定义性能上限：超过50实体时简化渲染（隐藏次要连线，聚类显示）
- 定义容错策略：嵌套字段>3层级时显示为`{...}`文本卡片
- 定义fallback样式：未知entityType使用灰色默认样式 + generic图标

---

### 问题13：实施阶段的质量保证缺失

**设计假设**：
```
Phase 1 → Phase 2 → Phase 3顺序实施，每个Phase完成后回归测试
```

**遗漏细节**：
- Phase 1验收标准"AI可参照提取"如何量化？（提取准确率？）
- Phase 2验收标准"validator校验核心字段"如何测试？（单元测试覆盖率？）
- Phase 3验收标准"freeflow渲染knowledge实体"如何验证？（渲染质量评估？）

**发现遗漏**：
- ❌ Phase验收标准缺乏量化指标（准确率、覆盖率、渲染质量）
- ❌ 回归测试的具体测试用例未定义（现有architecture蓝图的测试清单）
- ❌ 跨Phase集成测试策略缺失（Phase 1 + Phase 2 + Phase 3集成后如何测试？）

**建议改进**：
- 定义量化验收标准：AI提取准确率>80%，validator单元测试覆盖率>90%，freeflow渲染质量评分>8/10
- 定义回归测试清单：现有10个architecture蓝图必须通过validator，导出视图不变
- 定义集成测试策略：生成5个domain-knowledge蓝图，完整流程验证（提取→校验→渲染→导出）

---

## 五、实施风险低估

### 问题14：Phase 2工作量低估

**设计估算**：
```
Phase 2：Validator改造（4-6小时）
```

**对抗性质疑**：
- validator改造可能涉及现有架构重构（schema-first → field-first）
- validator单元测试编写可能超出1-2小时（需要覆盖architecture、domain-knowledge、hybrid、用户自定义等场景）
- validator集成到cli.py可能需要修改多个命令（`--plan`、`--validate`、`--export`）

**发现风险**：
- ❌ validator改造工作量可能低估（现有validator架构不明确，可能需要重构）
- ❌ 单元测试编写工作量低估（需要覆盖10+测试场景）
- ❌ 集成工作量低估（需要修改多个cli命令）

**建议改进**：
- 调整Phase 2工作量估算：validator改造（3-4小时），单元测试（2-3小时），cli集成（1-2小时），总计6-9小时
- 新增Phase 2.5：validator架构审查（检查现有validator实现策略，0.5-1小时）

---

### 问题15：Phase 3技术难度低估

**设计估算**：
```
Phase 3：导出引擎改造（6-8小时）
```

**对抗性质疑**：
- freeflow渲染器改造可能涉及布局算法重构（从layer-based到entityType-based）
- freeflow渲染knowledge实体需要新增样式系统（颜色、形状、图标、severity分级）
- relations关系连线渲染需要新增箭头样式系统（实线、虚线、双向箭头）

**发现风险**：
- ❌ freeflow布局算法重构技术难度高（从layer-based改为entityType-based clustering）
- ❌ 样式系统设计复杂（颜色映射、形状渲染、图标集成、severity分级）
- ❌ 关系连线渲染复杂（不同关系类型的箭头样式、避免连线交叉）

**建议改进**：
- 调整Phase 3工作量估算：布局算法重构（3-4小时），样式系统（2-3小时），连线渲染（2-3小时），cli集成（1小时），总计8-11小时
- 新增Phase 3.5：freeflow渲染器原型验证（验证knowledge实体渲染可行性，2小时）

---

### 问题16：向后兼容测试覆盖率不足

**设计假设**：
```
所有现有architecture蓝图JSON必须通过validator校验
```

**对抗性质疑**：
- 现有多少个architecture蓝图？（demos目录下的蓝图数量）
- 回归测试清单未定义（具体测试哪些蓝图？）
- 导出视图兼容性未测试（现有architecture蓝图的导出视图是否改变？）

**发现风险**：
- ❌ 现有architecture蓝图数量未明确，回归测试覆盖率不足
- ❌ 导出视图兼容性未测试（freeflow渲染knowledge样式后，architecture实体的渲染是否受影响？）
- ❌ 性能兼容性未测试（新增knowledge渲染逻辑后，architecture蓝图导出速度是否下降？）

**建议改进**：
- 定义回归测试清单：遍历demos目录所有architecture蓝图（预计10-15个），逐一测试validator + export
- 定义导出视图兼容性测试：对比新旧导出结果（SVG diff），确保architecture视图不变
- 定义性能基准测试：导出速度应保持不变（允许±10%波动）

---

## 六、质量问题

### 问题17：文档结构不一致

**发现**：
- 实体字段规范章节详细（painPoints、strategies、rules等），但relations关系类型定义简略
- 导出视图渲染设计章节详细（样式定义），但AI提取指南章节简略（提取流程）
- Validator改造设计章节详细（代码示例），但实施路径章节简略（工作量估算）

**建议改进**：
- 补充relations关系类型详细定义（每个关系类型的语义、适用场景、错误示例）
- 补充AI提取详细流程（实体提取顺序的详细步骤、错误处理、hints解析逻辑）
- 补充实施路径详细清单（每个Phase的文件改动列表、测试用例清单、验收标准）

---

### 问题18：术语定义不一致

**发现**：
- "domain-knowledge蓝图"在不同章节表述不一致（有时称"knowledge蓝图"，有时称"know-how蓝图"，有时称"领域知识图谱"）
- "blueprintType"字段名称与"蓝图类型"概念混用（文档未明确区分字段名和概念名）
- "severity"字段在不同实体类型中语义不一致（painPoint的severity=痛点严重程度，strategy的severity=？）

**建议改进**：
- 统一术语：domain-knowledge蓝图（标准术语），knowledge蓝图（简写），禁止使用"know-how蓝图"、"领域知识图谱"
- 统一字段名与概念名：blueprintType（字段名），蓝图类型（概念名），明确区分
- 统一severity语义：severity=严重程度/风险等级，明确每个实体类型的severity语义

---

### 问题19：示例数据真实性不足

**发现**：
- 实体字段示例过于简单（如painPoint只有id/name/entityType，缺少真实业务上下文）
- relations关系示例过于抽象（如"测款节奏策略 → ROI不稳"，缺少完整JSON示例）
- 跨境电商hints模板的checklist过于简化（如"痛点：ROI不稳"，缺少具体业务场景描述）

**建议改进**：
- 补充完整JSON示例：包含10+实体的完整domain-knowledge蓝图JSON
- 补充relations完整示例：包含from/to/type/label的完整relations数组
- 补充跨境电商完整hints模板：包含业务上下文（如"痛点：ROI不稳（欧美市场电商类目，ROAS目标>3.0但实际波动2.0-5.0）")

---

## 七、对抗性评审总结

### 高危问题（P0，必须修复）

| 问题 | 影响 | 修复建议 |
|------|------|---------|
| 问题1：AI判断意图不可靠 | 用户需求被误解，生成错误蓝图类型 | 新增判断优先级 + 手动覆盖机制 |
| 问题4：混合蓝图处理逻辑缺失 | 用户混合需求被强制简化，丢失部分需求 | 允许hybrid蓝图类型或可选architecture实体 |
| 问题7：决策3与决策1矛盾 | 跨类型关联失效，无法建立strategy→capability关系 | 允许hybrid蓝图或删除跨类型关联定义 |
| 问题9：向后兼容保证与schema扩展冲突 | 现有validator可能报错，向后兼容失效 | 检查现有validator实现策略 + 改造方案 |
| 问题14：Phase 2工作量低估 | 实施延期，资源不足 | 调整工作量估算6-9小时 |

### 中危问题（P1，应该修复）

| 问题 | 影响 | 修复建议 |
|------|------|---------|
| 问题2：扩展字段完全放行 | 下游工具可能崩溃 | 定义soft schema + 容错设计 |
| 问题3：freeflow布局算法未适配 | knowledge实体无法正确布局 | 定义布局策略 + clustering算法 |
| 问题6：relations完整性约束缺失 | 循环依赖、不合理关系 | ID引用校验 + 循环依赖检测 + 语义约束 |
| 问题10：entityType命名规范缺失 | 用户自定义实体命名混乱 | 定义命名规范 + 映射规则 |
| 问题15：Phase 3技术难度低估 | 实施延期，质量不达标 | 调整工作量估算8-11小时 |
| 问题16：向后兼容测试不足 | 现有蓝图导出视图可能受影响 | 定义回归测试清单 + diff对比 |

### 低危问题（P2，建议修复）

| 问题 | 影响 | 修复建议 |
|------|------|---------|
| 问题5：用户自定义实体边界模糊 | 命名冲突、关系类型不清 | 定义命名冲突策略 + 通用关系类型 |
| 问题8：severity语义矛盾 | strategy的severity语义不清晰 | 明确strategy severity语义或删除定义 |
| 问题11：hints编写质量保证缺失 | AI提取准确率低 | 定义格式规范 + 测试策略 + 覆盖度评估 |
| 问题12：freeflow降级策略缺失 | 性能问题、渲染崩溃 | 定义性能上限 + 容错策略 + fallback样式 |
| 问题13：实施质量保证缺失 | 验收标准模糊、测试覆盖不足 | 定义量化验收标准 + 测试清单 + 集成测试 |
| 问题17：文档结构不一致 | 阅读困难、理解歧义 | 补充详细定义章节 |
| 问题18：术语定义不一致 | 理解歧义 | 统一术语使用 |
| 问题19：示例数据真实性不足 | 理解困难 | 补充完整JSON示例 |

---

## 八、修复优先级建议

**立即修复（P0）**：
- 问题1、4、7、9、14 → 这些问题直接影响设计可行性和实施成功率

**短期内修复（P1）**：
- 问题2、3、6、10、15、16 → 这些问题影响实施质量和稳定性

**长期迭代修复（P2）**：
- 问题5、8、11、12、13、17、18、19 → 这些问题影响使用体验和文档质量

---

## 九、对抗性评审结论

**总体评价**：
- 设计思路清晰，核心决策合理（强核心+弱扩展、freeflow渲染、单向关联）
- 但存在5个高危问题，直接影响设计可行性和实施成功率
- 中危问题影响实施质量和稳定性，需要在实施前修复
- 低危问题可以在实施过程中迭代修复

**修复建议**：
- 修复P0问题后，重新审查设计文档
- 补充缺失的关键细节（entityType命名规范、hints测试策略、freeflow降级策略）
- 调整工作量估算（Phase 2: 6-9小时，Phase 3: 8-11小时）
- 定义量化验收标准和回归测试清单

**下一步**：
- 修复高危问题
- 补充缺失细节
- 调整工作量估算
- 重新提交设计文档审查

---

**对抗性评审完成日期**: 2026-04-28
**评审者**: Claude Code（对抗性视角）

path: references/archive/industry-packs.md
content: # Industry Packs

Industry packs may provide:

- schema-valid seed data
- aliases and terminology defaults
- grouping defaults

Industry packs may not:

- change the canonical schema
- add renderer-specific behavior
- replace the common validation rules


path: references/authoring-rules.md
content: # Authoring Rules

- The viewer save action must export a new canonical revision package.
- `solution.patch.jsonl` records human edits.
- `editor.fieldLocks` protects human-edited semantic fields.
- Validation must run before downstream completion claims.


path: references/blueprint-schema.md
content: # Blueprint Schema Reference

## Top-level structure

```json
{
  "version": "1.0",
  "meta": {},
  "context": {},
  "library": {},
  "relations": [],
  "views": [],
  "editor": {},
  "artifacts": {}
}
```

## meta

```json
{
  "title": "string — blueprint title",
  "industry": "common | finance | manufacturing | retail",
  "blueprintType": "architecture | domain-knowledge",
  "revisionId": "rev-YYYYMMDD-NN",
  "parentRevisionId": "null | previous revisionId",
  "lastModifiedAt": "ISO8601",
  "lastModifiedBy": "ai | human"
}
```

- `blueprintType` is set by the seed template, not by user input.
- `architecture` → fill `library.capabilities/actors/flowSteps/systems`.
- `domain-knowledge` → fill `library.knowledge.*`.

## context

```json
{
  "goals": ["string"],
  "scope": ["string"],
  "assumptions": ["string"],
  "constraints": ["string"],
  "sourceRefs": [{"type": "inline-text", "excerpt": "..."}],
  "clarifyRequests": [],
  "clarifications": []
}
```

## library

Entity collections:

| Collection | blueprintType | Description |
|------------|---------------|-------------|
| `capabilities` | architecture | Business capability areas |
| `actors` | architecture | Roles / people involved |
| `flowSteps` | architecture | Business process steps |
| `systems` | architecture | IT systems supporting capabilities |
| `knowledge` | domain-knowledge | See `knowledge-entities-schema.md` |

### capabilities

```json
{"id": "cap-xxx", "name": "...", "level": 1, "description": "...", "ownerActorIds": [], "supportingSystemIds": []}
```

Field definitions: `references/entities-schema.md`.

### actors

```json
{"id": "actor-xxx", "name": "..."}
```

### flowSteps

```json
{"id": "flow-xxx", "name": "...", "actorId": "actor-xxx", "capabilityIds": ["cap-xxx"], "systemIds": [], "stepType": "task", "inputRefs": [], "outputRefs": []}
```

### systems

```json
{"id": "sys-xxx", "kind": "system", "name": "...", "aliases": [], "description": "...", "resolution": {"status": "canonical", "canonicalName": "..."}, "capabilityIds": ["cap-xxx"]}
```

Field definitions and layer rules: `references/systems-schema.md`.

## relations

```json
[{"id": "rel-xxx", "type": "supports", "from": "sys-xxx", "to": "cap-xxx", "label": "支撑"}]
```

Common relation types for architecture blueprints: `supports`, `depends_on`, `feeds_into`, `communicates_with`.
Knowledge-specific relation types: see `references/knowledge-entities-schema.md` → Relations section.

## views

Leave as `[]`. Views are generated by export tools, not authored manually.

## editor

```json
{"fieldLocks": {}, "theme": "enterprise-default"}
```

See `references/authoring-rules.md` for field lock behavior.

## artifacts

Leave as `{}`. Populated by export tools.


path: references/domain-knowledge-extraction.md
content: # Domain-Knowledge Entity Extraction Guide

This file is read only when `meta.blueprintType` is `"domain-knowledge"` (set by the seed template).

## When to use this mode

The seed template's `meta.blueprintType` field determines the mode. If `"domain-knowledge"`, entities go into `library.knowledge.*` — not the architecture buckets (capabilities/actors/flowSteps/systems).

## Entity types

Six knowledge entity types live in `library.knowledge`:

| Array | entityType | Example |
|-------|-----------|---------|
| `painPoints` | `painPoint` | ROI 不稳, 素材疲劳 |
| `strategies` | `strategy` | 测款节奏策略, 动态出价 |
| `rules` | `rule` | Facebook 政策红线 |
| `metrics` | `metric` | ROAS 基准 |
| `practices` | `practice` | 素材迭代周期 |
| `pitfalls` | `pitfall` | 过度依赖单一平台 |

Field definitions: `references/knowledge-entities-schema.md`.
Self-check questions: `references/knowledge-self-check.md`.

## Naming rules from seed

The seed's `industryHints.knowledgeHints.namingHints` section dictates content granularity:

### strategy.name

Must be a **4-10 字 product-grade noun phrase**, not an action or dimension.

| Good | Bad | Why |
|------|-----|-----|
| 统一归因模型 | 优化素材 | Action, not noun phrase |
| AIGC 素材工厂 | 测款节奏 | Dimension, not product |
| 全链路归因引擎 | 策略一 | Generic label |

Reference the seed's `strategy_named_examples` array for concrete samples.

### audience field

`painPoint.audience` and `strategy.audience` are free-string fields tagging the primary persona:
- "品牌方/DTC", "平台卖家", "代运营/服务商"
- Multiple values comma-separated
- No standalone persona entity is required

### metric.forecast

`metric.forecast: {direction, magnitude, unit}` is optional and used for commitments to the customer:
- "ROAS 提升 25%"
- Keep `value`/`benchmarkContext` for current baseline
- The two coexist as "now X, can reach Y"

## Validation

These fields are pass-through under v2 minimal-validation: the validator does not enforce them, but renderers and pitch flows consume them.

## Relations

Knowledge entities use dedicated relation types (`solves`, `prevents`, `measures`, `enforces`, `requires`, `causes`). See `references/knowledge-entities-schema.md` → Relations section for the full whitelist.


path: references/industry-packs.md
content: # Industry Packs

Industry packs may provide:

- schema-valid seed data
- aliases and terminology defaults
- grouping defaults

Industry packs may not:

- change the canonical schema
- add renderer-specific behavior
- replace the common validation rules


path: reports/phase0_migration_report.json
content: {
  "test_phase": "Phase 0",
  "test_date": "2026-04-25",
  "metrics": {
    "migration_consistency_rate": [
      0.0,
      0.95
    ]
  },
  "failed_cases_count": 0,
  "failed_cases": [],
  "pass_status": false
}

path: reports/score.txt
content: fail 75


path: scripts/business_blueprint/export_drawio.py
content: from __future__ import annotations

from pathlib import Path
from typing import Any

from renderers import build_drawio_spec, render_drawio

_WATERMARK = "<!-- business-blueprint-skill v{version} -->"


def _get_version() -> str:
    try:
        from importlib.metadata import version
        return version("business-blueprint-skill")
    except Exception:
        return "0.1.0"


def export_drawio(blueprint: dict[str, Any], target: Path) -> None:
    spec = build_drawio_spec(blueprint)
    xml = render_drawio(spec)
    watermark = _WATERMARK.format(version=_get_version())
    target.write_text(watermark + "\n" + xml, encoding="utf-8")


path: scripts/business_blueprint/templates/common/base_blueprint.json
content: {
  "version": "1.0",
  "meta": {},
  "context": {
    "goals": [],
    "scope": [],
    "assumptions": [],
    "constraints": [],
    "sourceRefs": [],
    "clarifyRequests": [],
    "clarifications": []
  },
  "library": {
    "capabilities": [],
    "actors": [],
    "flowSteps": [],
    "systems": []
  },
  "relations": [],
  "views": [],
  "editor": {
    "fieldLocks": {},
    "theme": "enterprise-default"
  },
  "artifacts": {}
}


Security scan verdicts — ClawScan: suspicious | static analysis: clean | VirusTotal: clean | SkillSpector: suspicious (CRITICAL)