Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

第八章:Skills 技能系统

Skills 是 OpenMatrix 与 Claude Code 的集成接口,提供声明式的任务执行入口。

8.1 Skills 架构总览

Skills 定位

graph TD
    subgraph "Claude Code 环境"
        CC[Claude Code CLI]
        SK[Skills 目录<br/>~/.claude/commands/om/]
    end

    subgraph "OpenMatrix 核心"
        OM[OpenMatrix Package]
        CLI[CLI Commands]
        OR[Orchestrator]
    end

    CC --> |"/om:start"| SK
    SK --> |"调用"| CLI
    CLI --> OR

Skills vs CLI 对比

特性SkillsCLI
执行环境Claude Code 会话内独立终端
上下文共享自动共享会话上下文需要显式传递
Agent 执行通过 Agent Tool直接执行
适用场景交互式开发、AI 辅助CI/CD、脚本化
输出格式Markdown + 交互纯文本/JSON

Skills 工作原理

sequenceDiagram
    participant U as 用户
    participant CC as Claude Code
    participant SK as Skill 文件
    participant OM as OpenMatrix CLI
    participant AT as Agent Tool
    participant AG as Agent

    U->>CC: /om:start
    CC->>SK: 加载 start.md
    SK->>SK: 解析 frontmatter
    SK->>OM: openmatrix start --json
    OM->>SK: SubagentTask[]
    
    loop 每个 SubagentTask
        SK->>AT: invoke Agent tool
        AT->>AG: 执行 Agent
        AG->>AT: AgentResult
        AT->>SK: 返回结果
        SK->>OM: openmatrix complete
    end
    
    SK->>CC: 生成报告
    CC->>U: 展示结果

8.2 Skill 文件结构详解

文件格式

Skill 文件使用 Markdown 格式,包含 YAML frontmatter:

---
name: start
description: Interactive task start with quality/mode selection
version: 1.0.0
author: OpenMatrix Team
aliases: [begin, init]
---

# /om:start

Start a new OpenMatrix execution cycle.

## Usage

```bash
/om:start [options]
```

## Implementation

```bash
openmatrix start --quality "$quality" --mode "$mode"
```

Frontmatter 字段详解

字段类型必需说明示例
namestringSkill 名称start
descriptionstring描述(显示在帮助)Start new execution
versionstring-版本号1.0.0
authorstring-作者OpenMatrix Team
aliasesstring[]-别名列表[begin, init]
requiresstring[]-依赖的其他 Skill[status]

Skill 目录结构

~/.claude/commands/om/
├── om.md              # 默认入口
├── start.md           # 启动任务
├── auto.md            # 自动执行
├── status.md          # 查看状态
├── approve.md         # 处理审批
├── meeting.md         # 处理阻塞
├── resume.md          # 恢复执行
├── retry.md           # 重试失败
├── report.md          # 生成报告
├── brainstorm.md      # 头脑风暴
├── research.md        # 领域调研
└── check.md           # 项目检测

8.3 Prompt 设计模式

Prompt 模板结构

OpenMatrix 的 Agent Prompt 遵循统一模板:

# Task: {{task.title}}
# Phase: {{phase}}

## Task Description
{{task.description}}

## Context from Previous Agents
{{accumulatedContext}}

## Your Goal
{{phaseSpecificGoal}}

## Requirements
{{requirements}}

## Output Format
{{outputFormat}}

## Important
{{criticalNotes}}

各阶段 Prompt 设计

TDD 阶段 Prompt

# Task: {{task.title}}
# Phase: TDD (Test-Driven Development)

## Task Description
{{task.description}}

## Context from Previous Agents
{{accumulatedContext}}

## Your Goal: RED Phase
Write comprehensive tests that **MUST FAIL** currently.

The tests should:
1. Define the expected behavior clearly
2. Cover normal cases, edge cases, and error scenarios
3. Be well-structured and readable
4. Use the project's test framework

## Test Framework
{{detectTestFramework()}}

## Requirements
- Test files should be in appropriate test directory
- Test names should clearly describe what is being tested
- Each test should be independent
- Use descriptive assertions

## Output Format
After creating tests, report:
1. Files created
2. Test cases written (with descriptions)
3. Current test execution status (should be failing)

## Important
Tests MUST be failing (RED phase). If tests pass, the tests 
are not properly testing new functionality. This is critical 
for TDD methodology.

### TDD Cycle
RED (write failing tests) → GREEN (make tests pass) → REFACTOR

You are in the RED phase. Tests should fail.

Develop 阶段 Prompt

# Task: {{task.title}}
# Phase: Develop (Implementation)

## Task Description
{{task.description}}

## Context from Previous Agents
{{accumulatedContext}}

## Existing Tests (from TDD phase)
Read the test files and understand what needs to be implemented.

Test files:
{{testFiles}}

## Your Goal: GREEN Phase
Implement functionality that passes **ALL** tests written in TDD phase.

## Implementation Guidelines
1. Read and understand each test case
2. Implement the required functionality
3. Follow project coding conventions:
   {{projectConventions}}
4. Keep code clean and maintainable
5. Handle edge cases and errors as tests specify

## Requirements
- All tests must pass after implementation
- Code should be well-structured
- No unnecessary complexity
- Add necessary comments for complex logic

## Output Format
Report:
1. Files created/modified
2. Key implementation decisions
3. Test execution results (must be GREEN)
4. Suggestions for verify/accept phases

## Important
Tests MUST pass (GREEN phase). If tests fail, continue implementation.
Do not modify tests to make them pass - fix the implementation.

### Definition of Done
- All tests passing
- No TypeScript errors
- Code follows conventions
- Complex logic documented

Verify 阶段 Prompt

# Task: {{task.title}}
# Phase: Verify (Quality Gates)

## Quality Configuration
- Level: {{qualityLevel}}
- TDD: {{config.tdd}}
- Min Coverage: {{config.minCoverage}}%
- Strict Lint: {{config.strictLint}}
- Security Scan: {{config.securityScan}}
- E2E Tests: {{config.e2eTests}}

## Your Task: Run Quality Gates

Execute the following checks in order:

### 1. Build Check
```bash
npm run build
```
Must complete without errors.

### 2. Test Run
```bash
npm test
```
All tests must pass.

### 3. Coverage Check
Run coverage and verify minimum threshold.
- Required: {{config.minCoverage}}% coverage
- Report: Line, function, and branch coverage

### 4. Lint Check
```bash
npm run lint
```
{{config.strictLint ? 'No warnings or errors allowed' : 'No errors allowed'}}

### 5. Security Scan
{{config.securityScan ? `
```bash
npm audit
```
No high/critical vulnerabilities allowed.
` : 'Skipped'}}

### 6. E2E Tests
{{config.e2eTests ? `
```bash
npm run e2e
```
` : 'Skipped'}}

### 7. Acceptance Criteria
Verify task-specific acceptance criteria from description.

## Output Format
Return a JSON report for each gate:
```json
{
  "build": { "status": "pass/fail", "details": "..." },
  "test": { "status": "pass/fail", "passed": N, "failed": M },
  "coverage": { "status": "pass/fail", "percentage": X },
  "lint": { "status": "pass/fail", "errors": N, "warnings": M },
  "security": { "status": "pass/fail", "vulnerabilities": [...] },
  "e2e": { "status": "pass/fail/skipped" },
  "acceptance": { "status": "pass/fail", "criteria": [...] }
}
```

## Important
Run ALL gates. Report failures honestly. Do not skip gates.
If a gate fails, include detailed failure information.

Accept 阶段 Prompt

# Task: {{task.title}}
# Phase: Accept (Final Review)

## Changed Files
{{changedFiles}}

## Verify Phase Report
{{verifyReport}}

## Your Task: Final Review

Review the implementation for:

### 1. Code Quality (score 1-10)
- Structure: Is the code well-organized?
- Naming: Are names clear and consistent?
- Complexity: Is complexity appropriate?
- Duplication: Is there unnecessary duplication?

### 2. Best Practices (score 1-10)
- Patterns: Are appropriate patterns used?
- Conventions: Does code follow project conventions?
- Error Handling: Are errors handled properly?
- Testing: Is testing adequate?

### 3. Security (score 1-10)
- Input Validation: Is input validated?
- Authentication: Is auth handled properly?
- Authorization: Are permissions checked?
- Data Protection: Is sensitive data protected?

### 4. Documentation (score 1-10)
- Comments: Are complex parts commented?
- Types: Are types well-defined?
- README: Is README updated if needed?

## Output Format
```json
{
  "codeQuality": { 
    "score": 1-10,
    "issues": [...],
    "suggestions": [...]
  },
  "bestPractices": { "score": 1-10, "issues": [...] },
  "security": { "score": 1-10, "issues": [...] },
  "documentation": { "score": 1-10, "issues": [...] },
  "overallScore": 1-10,
  "approved": true/false,
  "blockers": [...],
  "recommendations": [...]
}
```

## Decision Criteria
- Score >= 7: Approve
- Score 5-6: Conditional approve with improvements
- Score < 5: Reject, require changes

## Important
Be thorough but practical. Focus on significant issues, not minor nitpicks.
Approve if code is good enough for production, suggest improvements separately.

Prompt 变量系统

interface PromptVariables {
  // 任务信息
  task: {
    id: string;
    title: string;
    description: string;
    estimatedComplexity: string;
  };

  // 阶段信息
  phase: 'tdd' | 'develop' | 'verify' | 'accept';

  // 累积上下文
  accumulatedContext: string;

  // 项目上下文
  projectContext: {
    techStack: string[];
    testFramework: string;
    lintTool: string;
    conventions: string;
  };

  // 配置
  config: QualityConfig;

  // 条件渲染
  conditions: {
    isStrict: boolean;
    hasE2E: boolean;
    needsSecurityScan: boolean;
  };
}

8.4 核心 Skills 详解

/om 默认入口

自动路由到合适的命令:

---
name: om
description: OpenMatrix default entry - auto-routes to appropriate command
aliases: [openmatrix, matrix]
---

# /om

OpenMatrix 的智能入口,根据输入自动选择命令。

## 自动路由规则

| 输入模式 | 路由目标 | 示例 |
|----------|----------|------|
| `implement...`, `add...`, `build...` | `/om:start` | `/om implement user auth` |
| `fix...`, `repair...` | `/om:start` | `/om fix login bug` |
| `optimize...`, `improve...` | `/om:start` | `/om improve performance` |
| `status`, `progress` | `/om:status` | `/om status` |
| 空输入 | 显示帮助 | `/om` |

## 实现

```bash
# 分析输入
input="{{user_input}}"

if [[ "$input" =~ ^(implement|add|build|create|fix|optimize|improve) ]]; then
    # 提取任务描述
    task="${input#* }"
    openmatrix start --instruction "$task"
elif [[ "$input" =~ ^(status|progress) ]]; then
    openmatrix status
else
    openmatrix --help
fi
```

/om:start 启动任务

完整的交互式启动流程:

flowchart TD
    A[/om:start] --> B[检查现有状态]
    B --> C{有未完成状态?}
    
    C --> |"是"| D[选择: 恢复/新建]
    C --> |"否"| E[开始配置]
    
    D --> |"恢复"| F[调用 /om:resume]
    D --> |"新建"| E
    
    E --> G[选择质量等级]
    G --> H[选择执行模式]
    H --> I[选择 E2E 测试]
    I --> J[输入任务指令]
    
    J --> K[AI 分析规划]
    K --> L[生成任务列表]
    L --> M[展示计划]
    
    M --> N{确认计划?}
    N --> |"是"| O[开始执行]
    N --> |"修改"| P[调整计划]
    N --> |"取消"| Q[退出]
    
    O --> R[返回 SubagentTask]
    R --> S[调用 Agent Tool]

/om:auto 自动执行

---
name: auto
description: Fully automatic execution without approvals or pauses
---

# /om:auto

完全自动执行,适用于 CI/CD 环境。

## 特点

1. **自动批准所有审批**
2. **阻塞创建 Meeting 后继续**
3. **无用户交互**
4. **生成完整报告**

## 执行流程

```mermaid
graph TD
    A[开始] --> B[任务规划]
    B --> C[调度执行]
    
    C --> D{执行结果}
    
    D --> |"成功"| E[下一个任务]
    D --> |"阻塞"| F[创建 Meeting]
    D --> |"失败"| G[加入重试队列]
    
    F --> E
    G --> H{重试次数}
    H --> |"< max"| E
    H --> |">= max"| I[标记失败]
    
    E --> J{还有任务?}
    J --> |"是"| C
    J --> |"否"| K[生成报告]
```

## 实现

```bash
openmatrix auto \
    --quality "${QUALITY:-balanced}" \
    --bypass-approvals \
    --json > execution.json

# 解析结果
status=$(jq -r '.status' execution.json)

if [ "$status" = "completed" ]; then
    echo "✓ Execution completed successfully"
    exit 0
else
    echo "✗ Execution failed or blocked"
    jq '.meetings' execution.json
    exit 1
fi
```

## CI/CD 集成示例

```yaml
# GitHub Actions
- name: Run OpenMatrix
  run: |
    npm install -g openmatrix
    openmatrix auto --quality strict --bypass-approvals
    
- name: Upload Report
  if: always()
  uses: actions/upload-artifact@v3
  with:
    name: openmatrix-report
    path: .openmatrix/report.md
```

/om:meeting 处理阻塞

---
name: meeting
description: Handle blocked tasks (Meetings) with information/decisions
---

# /om:meeting

处理阻塞任务的 Meeting。

## Meeting 类型与处理

| 类型 | 触发条件 | 处理方式 | 示例 |
|------|----------|----------|------|
| information | 缺少必要信息 | 用户提供信息 | API 端点地址 |
| decision | 多种可行方案 | 用户选择方案 | 认证方式选择 |
| approval | 需要用户确认 | 用户批准/拒绝 | 数据库迁移确认 |
| dependency | 外部依赖问题 | 用户解决依赖 | 第三方服务配置 |

## 交互式处理

```
Meeting: MEETING-001
Type: decision
Task: TASK-003 - Implement Authentication

Description:
需要选择认证方式,请从以下选项中选择:

Options:
1. JWT (推荐) - 无状态,适合微服务
2. Session - 有状态,适合传统应用
3. OAuth - 第三方认证集成

Your choice [1-3]: _
```

## 实现

```bash
# 获取 Meeting 列表
meetings=$(openmatrix meeting --json)

# 逐个处理
for meeting in $(echo "$meetings" | jq -c '.[]'); do
    id=$(echo "$meeting" | jq -r '.id')
    type=$(echo "$meeting" | jq -r '.type')
    
    echo "Processing Meeting: $id"
    
    case $type in
        information)
            # 收集信息
            read -p "Enter required info: " info
            openmatrix meeting $id --answer "{\"info\": \"$info\"}"
            ;;
        decision)
            # 选择方案
            echo "$meeting" | jq -r '.options[]'
            read -p "Select option: " choice
            openmatrix meeting $id --answer "{\"choice\": $choice}"
            ;;
        approval)
            # 审批确认
            read -p "Approve? (y/n): " confirm
            openmatrix meeting $id --$([ "$confirm" = "y" ] && echo "resolve" || echo "skip")
            ;;
    esac
done
```

8.5 Skills 与 Agent Tool 集成

Agent Tool 调用模式

// Skill 中调用 Agent Tool 的模式

async function executeSubagentTasks(tasks: SubagentTask[]) {
    for (const task of tasks) {
        // 1. 准备 Agent Tool 配置
        const agentConfig = {
            subagent_type: task.subagent_type,
            description: task.description,
            prompt: task.prompt,
            isolation: task.isolation,
            timeout: task.timeout
        };

        // 2. 调用 Agent Tool
        const result = await invokeAgentTool(agentConfig);

        // 3. 处理结果
        if (result.status === 'success') {
            // 调用 complete 保存状态
            await exec(`openmatrix complete ${task.taskId} --success --summary "${result.summary}"`);
        } else if (result.status === 'blocked') {
            // 创建 Meeting
            await exec(`openmatrix complete ${task.taskId} --blocked`);
        } else {
            // 标记失败
            await exec(`openmatrix complete ${task.taskId} --failed --error "${result.error}"`);
        }

        // 4. 检查是否继续
        const status = await getStatus();
        if (status.currentTask) {
            // 继续下一个任务
            continue;
        }
    }
}

状态同步机制

sequenceDiagram
    participant SK as Skill
    participant CLI as OpenMatrix CLI
    participant DISK as 磁盘状态
    participant AT as Agent Tool

    SK->>CLI: step --json
    CLI->>DISK: 读取 state.json
    DISK->>CLI: 返回状态
    CLI->>SK: SubagentTask

    Note over SK,AT: Context 可能被压缩

    SK->>AT: invoke Agent tool
    AT->>AT: 执行 Agent
    AT->>SK: AgentResult

    SK->>CLI: complete --success
    CLI->>DISK: 写入结果
    CLI->>DISK: 更新 state.json
    CLI->>SK: 确认

    SK->>CLI: step --json
    Note over SK,DISK: 状态从磁盘恢复

8.6 自定义 Skill 开发

Skill 模板

---
name: {{skill-name}}
description: {{one-line description}}
version: 1.0.0
---

# /om:{{skill-name}}

{{detailed description}}

## Usage

\`\`\`bash
/om:{{skill-name}} [options]
\`\`\`

## Options

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `--option1` | string | - | Option description |

## Examples

\`\`\`bash
# Example 1: Basic usage
/om:{{skill-name}}

# Example 2: With options
/om:{{skill-name}} --option1 value
\`\`\`

## Flow

\`\`\`mermaid
graph TD
    A[/om:{{skill-name}}] --> B[Step 1]
    B --> C[Step 2]
    C --> D[Complete]
\`\`\`

## Implementation

\`\`\`bash
# 1. 调用 OpenMatrix CLI
openmatrix {{cli-command}} --options

# 2. 处理结果
status=$?
if [ $status -eq 0 ]; then
    echo "✓ Success"
else
    echo "✗ Failed"
fi
\`\`\`

## Error Handling

\`\`\`bash
# 错误处理示例
if ! openmatrix {{cli-command}}; then
    echo "Command failed, checking state..."
    openmatrix status --detailed
fi
\`\`\`

## See Also

- /om:start
- /om:status

开发最佳实践

  1. 清晰的描述 - frontmatter 中准确描述功能
  2. 完整的使用示例 - 包含多种使用场景
  3. 流程图 - 用 Mermaid 展示执行流程
  4. 错误处理 - 处理可能的异常情况
  5. 与 CLI 集成 - 调用 OpenMatrix CLI 命令

8.7 Skills 安装与管理

安装命令

# 安装 Skills
openmatrix install-skills

# 强制覆盖安装
openmatrix install-skills --force

# 指定安装目录
openmatrix install-skills --target /custom/path

# 验证安装
ls ~/.claude/commands/om/

更新 Skills

# 更新 OpenMatrix 包
npm update -g openmatrix

# 重新安装 Skills
openmatrix install-skills --force

自定义 Skills 安装

# 复制自定义 Skill
cp my-custom-skill.md ~/.claude/commands/om/

# 验证
/om:my-custom-skill --help

下一章将详细讲解 质量保障体系