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

第七章:CLI 命令详解

OpenMatrix 提供完整的 CLI 命令系统,支持多种执行模式和状态管理。

7.1 CLI 架构总览

命令结构

graph TD
    CLI[openmatrix CLI] --> CMDS[Commands]
    
    CMDS --> START[start]
    CMDS --> AUTO[auto]
    CMDS --> STATUS[status]
    CMDS --> APPROVE[approve]
    CMDS --> MEETING[meeting]
    CMDS --> RESUME[resume]
    CMDS --> RETRY[retry]
    CMDS --> REPORT[report]
    CMDS --> STEP[step]
    CMDS --> COMPLETE[complete]
    CMDS --> BRAIN[brainstorm]
    CMDS --> RESEARCH[research]
    CMDS --> CHECK[check]
    CMDS --> INSTALL[install-skills]

基本使用

# 查看帮助
openmatrix --help

# 查看命令帮助
openmatrix start --help

# 执行命令
openmatrix start --quality strict --mode semi-auto

7.2 start 命令

启动新的任务执行周期。

命令签名

openmatrix start [options]

选项

选项类型默认值说明
--qualitystringbalanced质量等级 (strict/balanced/fast)
--modestringsemi-auto执行模式 (interactive/semi-auto/full-auto)
--e2ebooleanfalse启用 E2E 测试
--jsonbooleanfalseJSON 格式输出

执行流程

sequenceDiagram
    participant U as 用户
    participant CLI as CLI
    participant SM as StateManager
    participant TP as TaskPlanner
    participant OR as Orchestrator
    
    U->>CLI: openmatrix start
    CLI->>CLI: 检查现有状态
    
    alt "有未完成状态"
        CLI->>U: 提示恢复或新建
        U->>CLI: 选择
    end
    
    CLI->>U: 交互式配置
    U->>CLI: 质量等级、执行模式
    
    CLI->>SM: initialize()
    SM->>SM: 创建 .openmatrix/
    
    CLI->>U: 输入任务指令
    U->>CLI: "实现用户认证系统"
    
    CLI->>TP: plan(input)
    TP->>TP: AI 分析拆解
    TP->>SM: 保存任务列表
    
    CLI->>U: 展示任务计划
    U->>CLI: 确认/修改
    
    CLI->>OR: execute()
    OR->>CLI: 返回 SubagentTask[]
    
    CLI->>U: 输出执行配置

输出格式

普通输出

OpenMatrix Execution Started
─────────────────────────────
Run ID: run-2024-01-15-001
Quality: strict
Mode: semi-auto

Task Plan:
  TASK-001: Create user model [priority: 10]
  TASK-002: Implement auth API [priority: 8]
  TASK-003: Add validation [priority: 5]

Total Tasks: 3
Ready for execution with /om:step

JSON 输出

{
  "runId": "run-2024-01-15-001",
  "status": "running",
  "config": {
    "quality": "strict",
    "mode": "semi-auto",
    "e2eTests": false
  },
  "subagentTasks": [
    {
      "taskId": "TASK-001",
      "agentType": "coder",
      "description": "Create user model",
      "prompt": "...",
      "timeout": 300000
    }
  ]
}

实现代码

// cli/commands/start.ts

import { Command } from 'commander';
import inquirer from 'inquirer';

export function registerStartCommand(program: Command) {
  program
    .command('start')
    .description('Start new task execution')
    .option('--quality <level>', 'Quality level (strict/balanced/fast)')
    .option('--mode <mode>', 'Execution mode (interactive/semi-auto/full-auto)')
    .option('--e2e', 'Enable E2E tests')
    .option('--json', 'JSON output format')
    .action(async (options) => {
      // 检查现有状态
      const existingState = stateManager.recoverState();
      if (existingState && existingState.status === 'running') {
        const { action } = await inquirer.prompt([
          {
            type: 'list',
            name: 'action',
            message: 'Found existing running state. What to do?',
            choices: [
              { name: 'Resume existing execution', value: 'resume' },
              { name: 'Start new execution (will clear existing)', value: 'new' }
            ]
          }
        ]);
        
        if (action === 'resume') {
          console.log('Use openmatrix resume to continue');
          return;
        }
        
        // 清理旧状态
        stateManager.cleanup();
      }
      
      // 交互式配置
      if (!options.quality) {
        const { quality } = await inquirer.prompt([
          {
            type: 'list',
            name: 'quality',
            message: 'Select quality level',
            choices: [
              { name: 'strict - Full TDD, >80% coverage, strict lint', value: 'strict' },
              { name: 'balanced - No TDD, >60% coverage, standard lint', value: 'balanced' },
              { name: 'fast - No quality gates', value: 'fast' }
            ]
          }
        ]);
        options.quality = quality;
      }
      
      if (!options.mode) {
        const { mode } = await inquirer.prompt([
          {
            type: 'list',
            name: 'mode',
            message: 'Select execution mode',
            choices: [
              { name: 'interactive - Confirm every step', value: 'interactive' },
              { name: 'semi-auto - Confirm critical points', value: 'semi-auto' },
              { name: 'full-auto - No interruptions', value: 'full-auto' }
            ]
          }
        ]);
        options.mode = mode;
      }
      
      // 获取用户指令
      const { instruction } = await inquirer.prompt([
        {
          type: 'input',
          name: 'instruction',
          message: 'Enter your task instruction:'
        }
      ]);
      
      // 初始化
      const runId = generateRunId();
      stateManager.initialize(runId, { instruction });
      
      // 规划任务
      const taskPlanner = new TaskPlanner();
      const tasks = await taskPlanner.plan({ instruction });
      
      // 保存任务
      for (const task of tasks) {
        stateManager.saveTask(task);
      }
      
      // 展示计划
      if (!options.json) {
        displayPlan(tasks, options);
      }
      
      // 请求审批(interactive/semi-auto 模式)
      if (options.mode !== 'full-auto') {
        const { approved } = await inquirer.prompt([
          {
            type: 'confirm',
            name: 'approved',
            message: 'Approve task plan?',
            default: true
          }
        ]);
        
        if (!approved) {
          console.log('Execution cancelled');
          stateManager.cleanup();
          return;
        }
      }
      
      // 开始执行
      const executor = new Executor();
      const result = await executor.execute({ instruction });
      
      // 输出结果
      if (options.json) {
        console.log(JSON.stringify(result, null, 2));
      } else {
        displayResult(result);
      }
    });
}

7.3 auto 命令

完全自动执行,无阻塞。

命令签名

openmatrix auto [options]

选项

选项类型默认值说明
--bypass-approvalsbooleantrue绕过所有审批
--qualitystringbalanced质量等级
--jsonbooleanfalseJSON 输出

执行流程

sequenceDiagram
    participant U as 用户
    participant CLI as CLI
    participant OR as Orchestrator
    participant AG as Agents
    
    U->>CLI: openmatrix auto --quality strict
    CLI->>OR: execute({ bypassApprovals: true })
    
    OR->>AG: 执行 TASK-001
    
    loop "直到完成"
        AG->>OR: 任务结果
        
        alt "成功"
            OR->>OR: 下一个任务
        alt "阻塞"
            OR->>OR: 创建 Meeting
            OR->>OR: 继续其他任务
        alt "失败"
            OR->>OR: 加入 retry_queue
        end
    end
    
    OR->>CLI: 完成
    CLI->>U: 报告 + Meeting 列表

与 start 的区别

特性startauto
审批可配置自动绕过
阻塞处理可暂停创建 Meeting 继续
用户交互可配置交互无交互
适用场景生产开发CI/CD、批量

7.4 status 命令

查看当前执行状态。

命令签名

openmatrix status [options]

选项

选项类型默认值说明
--jsonbooleanfalseJSON 输出
--detailedbooleanfalse详细输出(包含每个任务)

输出格式

普通输出

OpenMatrix Status
─────────────────────────────
Run ID: run-2024-01-15-001
Status: running
Quality: strict
Mode: semi-auto

Progress:
  Total:     10 tasks
  Completed:  3 tasks (30%)
  Failed:     1 task
  Blocked:    2 tasks

Current Task: TASK-004 (Develop phase)

Pending Meetings: 2
Pending Approvals: 0

Started:  2024-01-15 10:00:00
Updated:  2024-01-15 12:30:00
Duration: 2h 30m

详细输出

Tasks Detail:
─────────────────────────────
TASK-001: Create user model
  Status: completed
  Agent: coder
  Phases: TDD ✓, Develop ✓, Verify ✓, Accept ✓
  Duration: 45m

TASK-002: Implement auth API
  Status: failed
  Agent: coder
  Error: Tests failed after 3 retries
  Retry Queue: pending

TASK-003: Add validation
  Status: waiting
  Agent: coder
  Meeting: MEETING-001 (need API spec)

TASK-004: Create UI components
  Status: in_progress
  Agent: coder
  Phase: Develop
  Started: 2024-01-15 11:45:00
...

JSON 输出

{
  "runId": "run-2024-01-15-001",
  "status": "running",
  "config": {
    "quality": "strict",
    "mode": "semi-auto"
  },
  "statistics": {
    "totalTasks": 10,
    "completedTasks": 3,
    "failedTasks": 1,
    "blockedTasks": 2
  },
  "currentTask": "TASK-004",
  "tasks": [
    {
      "id": "TASK-001",
      "status": "completed",
      "phases": ["TDD", "Develop", "Verify", "Accept"]
    }
  ],
  "meetings": ["MEETING-001", "MEETING-002"],
  "approvals": []
}

7.5 approve 命令

处理待审批项。

命令签名

openmatrix approve [options]
openmatrix approve <approval-id> [options]

选项

选项类型默认值说明
--allbooleanfalse批准所有待审批
--rejectbooleanfalse拒绝(而非批准)
--messagestring-反馈消息

审批类型处理

// cli/commands/approve.ts

async function handleApproval(approval: Approval, options: any) {
  switch (approval.type) {
    case 'plan':
      // 展示任务计划
      displayPlan(approval.content.tasks);
      
      const { decision } = await inquirer.prompt([
        {
          type: 'confirm',
          name: 'decision',
          message: 'Approve this task plan?'
        }
      ]);
      
      approvalManager.processApproval(
        approval.id,
        decision ? 'approve' : 'reject'
      );
      break;
      
    case 'merge':
      // 展示变更
      displayChanges(approval.content.files);
      
      const { mergeDecision } = await inquirer.prompt([
        {
          type: 'confirm',
          name: 'mergeDecision',
          message: 'Approve merge?'
        }
      ]);
      
      approvalManager.processApproval(
        approval.id,
        mergeDecision ? 'approve' : 'reject'
      );
      break;
      
    case 'deploy':
      // 展示部署配置
      displayDeployConfig(approval.content);
      
      const { deployDecision } = await inquirer.prompt([
        {
          type: 'confirm',
          name: 'deployDecision',
          message: 'Approve deployment?'
        }
      ]);
      
      approvalManager.processApproval(
        approval.id,
        deployDecision ? 'approve' : 'reject'
      );
      break;
      
    case 'meeting':
      // 处理 Meeting 决策
      await handleMeetingDecision(approval.content.meeting);
      break;
  }
}

7.6 meeting 命令

处理阻塞的 Meeting。

命令签名

openmatrix meeting [options]
openmatrix meeting <meeting-id> [options]

选项

选项类型默认值说明
--skipbooleanfalse跳过 Meeting
--resolvebooleanfalse解决 Meeting
--answerstring-提供答案(JSON 格式)

Meeting 处理流程

sequenceDiagram
    participant U as 用户
    participant CLI as CLI
    participant MM as MeetingManager
    participant SM as StateManager
    
    U->>CLI: openmatrix meeting
    CLI->>MM: getPendingMeetings()
    MM->>CLI: Meeting 列表
    
    CLI->>U: 展示 Meeting 详情
    
    alt "提供信息"
        U->>CLI: --answer '{"q1": "answer"}'
        CLI->>MM: resolveMeeting(id, answers)
        MM->>SM: 任务状态 → scheduled
    end
    
    alt "跳过"
        U->>CLI: --skip
        CLI->>MM: skipMeeting(id)
        MM->>SM: 任务状态 → skipped
    end
    
    alt "重试"
        U->>CLI: 选择 retry
        CLI->>MM: resolveMeeting(id, {decision: 'retry'})
        MM->>SM: 任务状态 → retry_queue
    end

交互式处理

async function handleMeeting(meeting: Meeting) {
  console.log(`\nMeeting: ${meeting.title}`);
  console.log(`Type: ${meeting.type}`);
  console.log(`\nDescription:\n${meeting.description}`);
  
  // 展示问题
  for (const question of meeting.questions) {
    console.log(`\nQuestion: ${question.text}`);
    
    if (question.type === 'text') {
      const { answer } = await inquirer.prompt([
        {
          type: 'input',
          name: 'answer',
          message: question.text
        }
      ]);
      answers[question.id] = answer;
    } else if (question.type === 'choice') {
      const { answer } = await inquirer.prompt([
        {
          type: 'list',
          name: 'answer',
          message: question.text,
          choices: question.options
        }
      ]);
      answers[question.id] = answer;
    } else if (question.type === 'boolean') {
      const { answer } = await inquirer.prompt([
        {
          type: 'confirm',
          name: 'answer',
          message: question.text
        }
      ]);
      answers[question.id] = answer ? 'yes' : 'no';
    }
  }
  
  // 处理
  meetingManager.resolveMeeting(meeting.id, { answers });
}

7.7 resume 命令

恢复中断的任务执行。

命令签名

openmatrix resume [options]

选项

选项类型默认值说明
--taskstring-从指定任务恢复
--phasestring-从指定阶段恢复

恢复流程

sequenceDiagram
    participant U as 用户
    participant CLI as CLI
    participant SM as StateManager
    participant OR as Orchestrator
    
    U->>CLI: openmatrix resume
    CLI->>SM: recoverState()
    SM->>CLI: GlobalState
    
    CLI->>CLI: 验证状态完整性
    
    CLI->>SM: recoverTasks()
    SM->>CLI: Task[]
    
    CLI->>U: 展示恢复信息
    
    U->>CLI: 确认恢复
    
    CLI->>OR: resume(state, tasks)
    OR->>OR: 从中断点继续
    OR->>CLI: SubagentTask[]

7.8 retry 命令

重试失败的任务。

命令签名

openmatrix retry [options]
openmatrix retry <task-id> [options]

选项

选项类型默认值说明
--allbooleanfalse重试所有失败任务
--phasestring-从指定阶段重试

重试流程

flowchart TD
    A[openmatrix retry] --> B[获取失败任务]
    B --> C{指定任务?}
    
    C --> |"是"| D[获取指定任务]
    C --> |"否"| E[获取所有失败任务]
    
    D --> F[重置任务状态]
    E --> F
    
    F --> G[状态 → scheduled]
    G --> H[清空错误信息]
    H --> I[重置阶段]
    I --> J[触发重新调度]

7.9 report 命令

生成执行报告。

命令签名

openmatrix report [options]

选项

选项类型默认值说明
--formatstringmd输出格式 (md/json/html)
--outputstring-输出文件路径

报告内容

# OpenMatrix Execution Report

## Summary
- **Run ID**: run-2024-01-15-001
- **Status**: completed
- **Duration**: 4h 30m
- **Started**: 2024-01-15 10:00:00
- **Completed**: 2024-01-15 14:30:00

## Configuration
- **Quality**: strict
- **Mode**: semi-auto
- **E2E Tests**: Yes

## Task Statistics
| Metric | Count |
|--------|-------|
| Total Tasks | 10 |
| Completed | 8 |
| Failed | 1 |
| Skipped | 1 |

## Phase Statistics
| Phase | Completed | Failed |
|-------|-----------|--------|
| TDD | 8 | 1 |
| Develop | 8 | 1 |
| Verify | 8 | 0 |
| Accept | 8 | 0 |

## Quality Metrics
- **Average Coverage**: 85%
- **Average Review Score**: 8.5/10
- **Lint Errors**: 0
- **Security Issues**: 0

## Task Details

### TASK-001: Create user model
- **Status**: completed
- **Agent**: coder
- **Duration**: 45m
- **Coverage**: 92%
- **Review Score**: 9/10
- **Files**: src/models/user.ts, tests/user.test.ts

### TASK-002: Implement auth API
- **Status**: failed
- **Agent**: coder
- **Error**: Tests failed after 3 retries
- **Retry Attempts**: 3

...

## Meetings
| ID | Type | Status | Resolution |
|----|------|--------|------------|
| MEETING-001 | information | resolved | API spec provided |
| MEETING-002 | decision | skipped | Alternative approach |

## Recommendations
1. Review failed task TASK-002 for root cause
2. Consider adding integration tests for auth module
3. Update documentation for new user model

7.10 step/complete 命令

持久化执行循环的核心命令。

step 命令

从磁盘获取下一个任务。

openmatrix step [options]
选项类型默认值说明
--jsonbooleanfalseJSON 输出

输出

{
  "taskId": "TASK-004",
  "phase": "develop",
  "agentType": "coder",
  "prompt": "...",
  "timeout": 600000,
  "context": "..."
}

complete 命令

标记任务完成并保存结果。

openmatrix complete <task-id> [options]
选项类型默认值说明
--successbooleanfalse标记成功
--blockedbooleanfalse标记阻塞
--failedbooleanfalse标记失败
--summarystring-执行摘要
--artifactsstring-输出文件列表(逗号分隔)

step/complete 循环

sequenceDiagram
    participant CLI as CLI
    participant SM as StateManager
    participant SC as Scheduler
    participant SK as Skills/Agent
    
    CLI->>SM: step
    SM->>SC: getNextTask()
    SC->>SM: TASK-004
    SM->>CLI: SubagentTask
    
    CLI->>SK: Agent 执行
    SK->>CLI: 执行结果
    
    CLI->>SM: complete TASK-004 --success
    SM->>SM: 保存结果
    SM->>SM: 更新状态
    
    CLI->>SM: step
    SM->>SC: getNextTask()
    ...

用途

step/complete 循环用于:

  1. Context 压缩恢复 - 状态持久化到磁盘
  2. 分布式执行 - 多进程协作
  3. 手动调试 - 单步执行调试

7.11 brainstorm 命令

交互式头脑风暴,深入探索需求。

命令签名

openmatrix brainstorm [options]

执行流程

sequenceDiagram
    participant U as 用户
    participant CLI as CLI
    participant AG as Researcher Agent
    
    U->>CLI: openmatrix brainstorm "用户系统"
    
    CLI->>AG: 分析需求
    
    AG->>U: 问题1: 需要什么认证方式?
    U->>CLI: JWT + OAuth
    
    AG->>U: 问题2: 需要什么权限模型?
    U->>CLI: RBAC
    
    AG->>U: 问题3: 需要什么用户属性?
    U->>CLI: 基本 + 扩展
    
    AG->>CLI: 生成调研报告
    CLI->>U: 展示方案建议

7.12 research 命令

领域调研,收集背景知识。

命令签名

openmatrix research <topic> [options]

输出

# Research Report: OAuth 2.0 Implementation

## Overview
OAuth 2.0 is an authorization framework...

## Approaches
### Approach 1: Authorization Code Flow
- **Description**: Standard web app flow
- **Pros**: Secure, well-supported
- **Cons**: Requires backend

### Approach 2: Implicit Flow
- **Description**: Pure frontend flow
- **Pros**: No backend needed
- **Cons**: Less secure

## Recommended Libraries
1. **passport-oauth2** - Node.js OAuth middleware
2. **node-oauth2-server** - Complete OAuth server

## Implementation Guide
...

## Resources
- OAuth 2.0 Spec: https://oauth.net/2/
- Passport.js: http://www.passportjs.org/

7.13 check 命令

项目改进检测和建议。

命令签名

openmatrix check [options]

检查项目

类别检查内容
代码质量测试覆盖率、Lint 错误
安全性npm audit、敏感信息
配置tsconfig、package.json
文档README、API 文档
依赖过时依赖、冗余依赖

输出示例

OpenMatrix Check Report
─────────────────────────────

Code Quality:
  ✓ Test coverage: 85%
  ✓ No lint errors
  
Security:
  ⚠ 2 moderate vulnerabilities in dependencies
  ✗ Found .env file with secrets
  
Configuration:
  ✓ tsconfig.json valid
  ⚠ package.json missing description
  
Documentation:
  ✓ README.md exists
  ✗ API documentation missing
  
Dependencies:
  ⚠ 5 outdated packages
  ✓ No redundant dependencies

Recommendations:
1. Run npm audit fix to resolve vulnerabilities
2. Remove secrets from .env, use .env.example
3. Add API documentation (TypeDoc suggested)
4. Update outdated packages

7.14 install-skills 命令

安装 Skills 到 Claude Code。

命令签名

openmatrix install-skills [options]

选项

选项类型默认值说明
--forcebooleanfalse强制覆盖
--targetstring~/.claude/commands/om/安装目录

安装流程

// scripts/install-skills.js

async function installSkills() {
  const sourceDir = './skills';
  const targetDir = process.env.CLAUDE_COMMANDS_DIR 
    || path.join(os.homedir(), '.claude', 'commands', 'om');
  
  // 确保目标目录存在
  if (!fs.existsSync(targetDir)) {
    fs.mkdirSync(targetDir, { recursive: true });
  }
  
  // 复制所有 Skill 文件
  const skills = fs.readdirSync(sourceDir);
  
  for (const skill of skills) {
    const sourcePath = path.join(sourceDir, skill);
    const targetPath = path.join(targetDir, skill);
    
    if (fs.existsSync(targetPath) && !options.force) {
      console.log(`Skipping ${skill} (already exists)`);
      continue;
    }
    
    fs.copyFileSync(sourcePath, targetPath);
    console.log(`Installed: ${skill}`);
  }
  
  console.log(`\nSkills installed to: ${targetDir}`);
  console.log('Use with: /om:<skill-name>');
}

下一章将详细讲解 Skills 技能系统