ccw-cli-tools

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

CLI Tools - Unified Execution Framework

CLI工具 - 统一执行框架

Purpose: Structured CLI tool usage with configuration-driven tool selection, unified prompt templates, and quality-gated execution.
Configuration:
~/.claude/cli-tools.json
(Global, always read at initialization)
用途:通过配置驱动的工具选择、统一提示模板和质量管控的执行流程,实现CLI工具的结构化使用。
配置文件
~/.claude/cli-tools.json
(全局配置,初始化时始终读取)

Initialization (Required First Step)

初始化(必备第一步)

Before any tool selection or recommendation:
  1. Check if configuration exists in memory:
    • If configuration is already in conversation memory → Use it directly
    • If NOT in memory → Read the configuration file:
      bash
      Read(file_path="~/.claude/cli-tools.json")
  2. Parse the JSON to understand:
    • Available tools and their
      enabled
      status
    • Each tool's
      primaryModel
      and
      secondaryModel
    • Tags defined for tag-based routing
    • Tool types (builtin, cli-wrapper, api-endpoint)
  3. Use configuration throughout the selection process
Why: Tools, models, and tags may change. Configuration file is the single source of truth. Optimization: Reuse in-memory configuration to avoid redundant file reads.
在进行任何工具选择或推荐之前
  1. 检查配置是否已加载到内存中:
    • 若配置已在对话内存中 → 直接使用
    • 若未在内存中 → 读取配置文件:
      bash
      Read(file_path="~/.claude/cli-tools.json")
  2. 解析JSON以了解:
    • 可用工具及其
      enabled
      状态
    • 每个工具的
      primaryModel
      secondaryModel
    • 用于标签路由的定义标签
    • 工具类型(builtin、cli-wrapper、api-endpoint)
  3. 在整个选择过程中使用该配置
原因:工具、模型和标签可能会发生变化,配置文件是唯一的事实来源。 优化:复用内存中的配置,避免重复读取文件。

Process Flow

流程步骤

┌─ USER REQUEST
├─ STEP 1: Load Configuration
│  ├─ Check if configuration exists in conversation memory
│  └─ If NOT in memory → Read(file_path="~/.claude/cli-tools.json")
├─ STEP 2: Understand User Intent
│  ├─ Parse task type (analysis, implementation, security, etc.)
│  ├─ Extract required capabilities (tags)
│  └─ Identify scope (files, modules)
├─ STEP 3: Select Tool (based on config)
│  ├─ Explicit --tool specified?
│  │  YES → Validate in config → Use it
│  │  NO  → Match tags with enabled tools → Select best match
│  │       → No match → Use first enabled tool (default)
│  └─ Get primaryModel from config
├─ STEP 4: Build Prompt
│  └─ Use 6-field template: PURPOSE, TASK, MODE, CONTEXT, EXPECTED, CONSTRAINTS
├─ STEP 5: Select Rule Template
│  ├─ Determine rule from task type
│  └─ Pass via --rule parameter
├─ STEP 6: Execute CLI Command
│  └─ ccw cli -p "<PROMPT>" --tool <tool> --mode <mode> --rule <rule>
└─ STEP 7: Handle Results
   ├─ On success → Deliver output to user
   └─ On failure → Check secondaryModel or fallback tool
┌─ 用户请求
├─ 步骤1:加载配置
│  ├─ 检查对话内存中是否存在配置
│  └─ 若不存在 → 读取(file_path="~/.claude/cli-tools.json")
├─ 步骤2:理解用户意图
│  ├─ 解析任务类型(分析、实现、安全等)
│  ├─ 提取所需能力(标签)
│  └─ 确定范围(文件、模块)
├─ 步骤3:选择工具(基于配置)
│  ├─ 是否指定了--tool参数?
│  │  是 → 在配置中验证该工具 → 使用它
│  │  否 → 将标签与已启用工具匹配 → 选择最佳匹配
│  │       → 无匹配项 → 使用第一个已启用工具(默认)
│  └─ 从配置中获取primaryModel
├─ 步骤4:构建提示词
│  └─ 使用6字段模板:PURPOSE、TASK、MODE、CONTEXT、EXPECTED、CONSTRAINTS
├─ 步骤5:选择规则模板
│  ├─ 根据任务类型确定规则
│  └─ 通过--rule参数传递
├─ 步骤6:执行CLI命令
│  └─ ccw cli -p "<PROMPT>" --tool <tool> --mode <mode> --rule <rule>
└─ 步骤7:处理结果
   ├─ 成功 → 向用户交付输出
   └─ 失败 → 尝试secondaryModel或备用工具

Configuration Reference

配置参考

Configuration File Location

配置文件位置

Path:
~/.claude/cli-tools.json
(Global configuration)
IMPORTANT: Check conversation memory first. Only read file if configuration is not in memory.
路径
~/.claude/cli-tools.json
(全局配置)
重要提示:先检查对话内存,仅当配置未在内存中时才读取文件。

Reading Configuration

读取配置

Priority: Check conversation memory first
Loading Options:
  • Option 1 (Preferred): Use in-memory configuration if already loaded in conversation
  • Option 2 (Fallback): Read from file when not in memory
bash
undefined
优先级:先检查对话内存
加载选项
  • 选项1(推荐):若对话中已加载配置,则使用内存中的配置
  • 选项2(备用):若未在内存中,则从文件读取
bash
undefined

Read configuration file

读取配置文件

cat ~/.claude/cli-tools.json

The configuration defines all available tools with their enabled status, models, and tags.
cat ~/.claude/cli-tools.json

配置文件定义了所有可用工具及其启用状态、模型和标签。

Configuration Structure

配置结构

The JSON file contains a
tools
object where each tool has these fields:
FieldTypeDescriptionExample
enabled
booleanTool availability status
true
or
false
primaryModel
stringDefault model for execution
"gemini-2.5-pro"
secondaryModel
stringFallback model on primary failure
"gemini-2.5-flash"
tags
arrayCapability tags for routing
["分析", "Debug"]
type
stringTool type
"builtin"
,
"cli-wrapper"
,
"api-endpoint"
JSON文件包含一个
tools
对象,每个工具包含以下字段:
字段类型描述示例
enabled
布尔值工具可用状态
true
false
primaryModel
字符串执行的默认模型
"gemini-2.5-pro"
secondaryModel
字符串主模型失败时的备用模型
"gemini-2.5-flash"
tags
数组用于路由的能力标签
["分析", "Debug"]
type
字符串工具类型
"builtin"
,
"cli-wrapper"
,
"api-endpoint"

Expected Tools (Reference Only)

预期工具(仅作参考)

Typical tools found in configuration (actual availability determined by reading the file):
ToolTypical TypeCommon Use
gemini
builtinAnalysis, Debug (分析, Debug tags)
qwen
builtinGeneral coding
codex
builtinCode review, implementation
claude
builtinGeneral tasks
opencode
builtinOpen-source model fallback
Note: Tool availability, models, and tags may differ. Use in-memory configuration or read
~/.claude/cli-tools.json
if not cached.
配置文件中常见的工具(实际可用性需读取文件确定):
工具典型类型常见用途
gemini
builtin分析、调试(分析、Debug标签)
qwen
builtin通用编码
codex
builtin代码审查、功能实现
claude
builtin通用任务
opencode
builtin开源模型备用选项
注意:工具可用性、模型和标签可能有所不同。若未缓存,请使用内存中的配置或读取
~/.claude/cli-tools.json

Configuration Fields

配置字段说明

  • enabled
    : Tool availability (boolean)
  • primaryModel
    : Default model for execution
  • secondaryModel
    : Fallback model on primary failure
  • tags
    : Capability tags for routing (分析, Debug, implementation, etc.)
  • type
    : Tool type (builtin, cli-wrapper, api-endpoint)
  • enabled
    :工具可用状态(布尔值)
  • primaryModel
    :执行的默认模型
  • secondaryModel
    :主模型失败时的备用模型
  • tags
    :用于路由的能力标签(分析、Debug、实现等)
  • type
    :工具类型(builtin、cli-wrapper、api-endpoint)

Universal Prompt Template

通用提示模板

Structure: Every CLI command follows this 6-field template
bash
ccw cli -p "PURPOSE: [goal] + [why] + [success criteria] + [scope]
TASK: • [step 1: specific action] • [step 2: specific action] • [step 3: specific action]
MODE: [analysis|write|review]
CONTEXT: @[file patterns] | Memory: [session/tech/module context]
EXPECTED: [deliverable format] + [quality criteria] + [structure requirements]
CONSTRAINTS: [domain constraints]" --tool <tool-id> --mode <mode> --rule <template>
结构:每个CLI命令遵循以下6字段模板
bash
ccw cli -p "PURPOSE: [目标] + [原因] + [成功标准] + [范围]
TASK: • [步骤1:具体操作] • [步骤2:具体操作] • [步骤3:具体操作]
MODE: [analysis|write|review]
CONTEXT: @[文件匹配模式] | Memory: [会话/技术/模块上下文]
EXPECTED: [交付格式] + [质量标准] + [结构要求]
CONSTRAINTS: [领域约束]" --tool <tool-id> --mode <mode> --rule <template>

Field Specifications

字段规范

PURPOSE (Goal Definition)

PURPOSE(目标定义)

What: Clear objective + motivation + success criteria + scope boundary
Components:
  • What: Specific task goal
  • Why: Business/technical motivation
  • Success: Measurable success criteria
  • Scope: Bounded context/files
Example - Good:
PURPOSE: Identify OWASP Top 10 vulnerabilities in auth module to pass security audit;
success = all critical/high issues documented with remediation;
scope = src/auth/** only
Example - Bad:
PURPOSE: Analyze code
内容:明确的目标 + 动机 + 成功标准 + 范围边界
组成部分
  • 目标:具体的任务目标
  • 原因:业务/技术动机
  • 成功:可衡量的成功标准
  • 范围:限定的上下文/文件
示例 - 规范
PURPOSE: 识别认证模块中的OWASP Top 10漏洞以通过安全审计;成功标准=记录所有关键/高危问题并提供修复方案;范围=仅src/auth/**
示例 - 不规范
PURPOSE: 分析代码

TASK (Action Steps)

TASK(操作步骤)

What: Specific, actionable steps with clear verbs and targets
Format: Bullet list with concrete actions
Example - Good:
TASK:
• Scan for SQL injection in query builders
• Check XSS in template rendering
• Verify CSRF token validation
Example - Bad:
TASK: Review code and find issues
内容:具体、可执行的步骤,包含明确动词和目标
格式:带具体操作的项目符号列表
示例 - 规范
TASK:
• 扫描查询构建器中的SQL注入漏洞
• 检查模板渲染中的XSS漏洞
• 验证CSRF令牌验证机制
示例 - 不规范
TASK: 审查代码并找出问题

MODE (Permission Level)

MODE(权限级别)

Options:
  • analysis
    - Read-only, safe for auto-execution
  • write
    - Create/Modify/Delete files, full operations
  • review
    - Git-aware code review (codex only)
Rules:
  • Always specify explicitly
  • Default to
    analysis
    for read-only tasks
  • Require explicit
    --mode write
    for file modifications
  • Use
    --mode review
    with
    --tool codex
    for git-aware review
选项
  • analysis
    - 只读模式,适合自动执行
  • write
    - 创建/修改/删除文件,完整操作权限
  • review
    - 支持Git的代码审查(仅codex可用)
规则
  • 必须明确指定
  • 只读任务默认使用
    analysis
  • 文件修改需要显式指定
    --mode write
  • 支持Git的审查需使用
    --mode review
    并搭配
    --tool codex

CONTEXT (File Scope + Memory)

CONTEXT(文件范围 + 内存上下文)

Format:
CONTEXT: @[file patterns] | Memory: [memory context]
File Patterns:
  • @**/*
    - All files (default)
  • @src/**/*.ts
    - Specific pattern
  • @../shared/**/*
    - Parent/sibling (requires
    --includeDirs
    )
Memory Context (when building on previous work):
Memory: Building on auth refactoring (commit abc123), using JWT for sessions
Memory: Integration with auth module, shared error patterns from @shared/utils/errors.ts
格式
CONTEXT: @[文件匹配模式] | Memory: [内存上下文]
文件匹配模式
  • @**/*
    - 所有文件(默认)
  • @src/**/*.ts
    - 特定模式
  • @../shared/**/*
    - 父级/同级目录(需搭配
    --includeDirs
内存上下文(基于之前的工作内容):
Memory: 基于认证重构(提交abc123),使用JWT管理会话
Memory: 与认证模块集成,参考@shared/utils/errors.ts中的通用错误模式

EXPECTED (Output Specification)

EXPECTED(输出规范)

What: Output format + quality criteria + structure requirements
Example - Good:
EXPECTED: Markdown report with:
severity levels (Critical/High/Medium/Low),
file:line references,
remediation code snippets,
priority ranking
Example - Bad:
EXPECTED: Report
内容:输出格式 + 质量标准 + 结构要求
示例 - 规范
EXPECTED: Markdown格式报告,包含:
风险等级(Critical/High/Medium/Low)、
文件:行号引用、
修复代码片段、
优先级排序
示例 - 不规范
EXPECTED: 报告

CONSTRAINTS (Domain Boundaries)

CONSTRAINTS(领域边界)

What: Scope limits, special requirements, focus areas
Example - Good:
CONSTRAINTS: Focus on authentication | Ignore test files | No breaking changes
Example - Bad:
CONSTRAINTS: (missing or too vague)
内容:范围限制、特殊要求、重点领域
示例 - 规范
CONSTRAINTS: 聚焦认证模块 | 忽略测试文件 | 不允许破坏性变更
示例 - 不规范
CONSTRAINTS: (缺失或过于模糊)

CLI Execution Modes

CLI执行模式

MODE: analysis

MODE: analysis

  • Permission: Read-only
  • Use For: Code review, architecture analysis, pattern discovery, exploration
  • Safe: Yes - can auto-execute
  • Default: When not specified
  • 权限:只读
  • 用途:代码审查、架构分析、模式发现、探索性分析
  • 安全性:是 - 可自动执行
  • 默认值:未指定时使用

MODE: write

MODE: write

  • Permission: Create/Modify/Delete files
  • Use For: Feature implementation, bug fixes, documentation, code creation
  • Safe: No - requires explicit
    --mode write
  • Requirements: Must be explicitly requested by user
  • 权限:创建/修改/删除文件
  • 用途:功能实现、Bug修复、文档编写、代码生成
  • 安全性:否 - 需要显式指定
    --mode write
  • 要求:必须由用户明确请求

MODE: review

MODE: review

  • Permission: Read-only (git-aware review output)
  • Use For: Code review of uncommitted changes, branch diffs, specific commits
  • Tool Support:
    codex
    only (others treat as analysis)
  • Constraint: Target flags (
    --uncommitted
    ,
    --base
    ,
    --commit
    ) and prompt are mutually exclusive
  • 权限:只读(支持Git的审查输出)
  • 用途:未提交变更、分支差异、特定提交的代码审查
  • 工具支持:仅
    codex
    可用(其他工具视为analysis模式)
  • 约束:目标标志(
    --uncommitted
    --base
    --commit
    )与提示词互斥

Command Structure

命令结构

Basic Command

基础命令

bash
ccw cli -p "<PROMPT>" --tool <tool-id> --mode <analysis|write|review>
bash
ccw cli -p "<PROMPT>" --tool <tool-id> --mode <analysis|write|review>

Command Options

命令选项

OptionDescriptionExample
--tool <tool>
Tool from config
--tool gemini
--mode <mode>
REQUIRED: analysis/write/review
--mode analysis
--model <model>
Model override
--model gemini-2.5-flash
--cd <path>
Working directory
--cd src/auth
--includeDirs <dirs>
Additional directories
--includeDirs ../shared,../types
--rule <template>
Auto-load template
--rule analysis-review-architecture
--resume [id]
Resume session
--resume
or
--resume <id>
选项描述示例
--tool <tool>
配置中的工具
--tool gemini
--mode <mode>
必填:analysis/write/review
--mode analysis
--model <model>
覆盖默认模型
--model gemini-2.5-flash
--cd <path>
工作目录
--cd src/auth
--includeDirs <dirs>
附加目录
--includeDirs ../shared,../types
--rule <template>
自动加载模板
--rule analysis-review-architecture
--resume [id]
恢复会话
--resume
--resume <id>

Advanced Directory Configuration

高级目录配置

Working Directory (
--cd
)

工作目录(
--cd

When using
--cd
:
  • @**/*
    = Files within working directory tree only
  • Cannot reference parent/sibling without
    --includeDirs
  • Reduces token usage by scoping context
使用
--cd
时:
  • @**/*
    = 仅工作目录树内的文件
  • 未使用
    --includeDirs
    时无法引用父级/同级目录
  • 通过限定上下文减少令牌使用

Include Directories (
--includeDirs
)

包含目录(
--includeDirs

Two-step requirement for external files:
  1. Add
    --includeDirs
    parameter
  2. Reference in CONTEXT with @ patterns
bash
undefined
引用外部文件的两步要求
  1. 添加
    --includeDirs
    参数
  2. 在CONTEXT中使用@模式引用
bash
undefined

Single directory

单个目录

ccw cli -p "CONTEXT: @/* @../shared//*"
--tool gemini --mode analysis
--cd src/auth --includeDirs ../shared
ccw cli -p "CONTEXT: @/* @../shared//*"
--tool gemini --mode analysis
--cd src/auth --includeDirs ../shared

Multiple directories

多个目录

ccw cli -p "..."
--tool gemini --mode analysis
--cd src/auth --includeDirs ../shared,../types,../utils
undefined
ccw cli -p "..."
--tool gemini --mode analysis
--cd src/auth --includeDirs ../shared,../types,../utils
undefined

Session Resume

会话恢复

When to Use:
  • Multi-round planning (analysis → planning → implementation)
  • Multi-model collaboration (tool A → tool B on same topic)
  • Topic continuity (building on previous findings)
Usage:
bash
ccw cli -p "Continue analyzing" --tool <tool-id> --mode analysis --resume              # Resume last
ccw cli -p "Fix issues found" --tool <tool-id> --mode write --resume <id>              # Resume specific
ccw cli -p "Merge findings" --tool <tool-id> --mode analysis --resume <id1>,<id2>      # Merge sessions
使用场景
  • 多轮规划(分析 → 规划 → 实现)
  • 多模型协作(工具A → 同一主题的工具B)
  • 主题连续性(基于之前的发现继续工作)
用法
bash
ccw cli -p "继续分析" --tool <tool-id> --mode analysis --resume              # 恢复最后一个会话
ccw cli -p "修复发现的问题" --tool <tool-id> --mode write --resume <id>              # 恢复特定会话
ccw cli -p "合并发现结果" --tool <tool-id> --mode analysis --resume <id1>,<id2>      # 合并多个会话

Available Rule Templates

可用规则模板

Template System

模板系统

Use
--rule <template-name>
to auto-load protocol + template appended to prompt
使用
--rule <template-name>
自动加载协议和模板,并附加到提示词中

Universal Templates

通用模板

  • universal-rigorous-style
    - Precise tasks (default)
  • universal-creative-style
    - Exploratory tasks
  • universal-rigorous-style
    - 精确任务(默认)
  • universal-creative-style
    - 探索性任务

Analysis Templates

分析模板

  • analysis-trace-code-execution
    - Execution tracing
  • analysis-diagnose-bug-root-cause
    - Bug diagnosis
  • analysis-analyze-code-patterns
    - Code patterns
  • analysis-analyze-technical-document
    - Document analysis
  • analysis-review-architecture
    - Architecture review
  • analysis-review-code-quality
    - Code review
  • analysis-analyze-performance
    - Performance analysis
  • analysis-assess-security-risks
    - Security assessment
  • analysis-trace-code-execution
    - 执行追踪
  • analysis-diagnose-bug-root-cause
    - Bug诊断
  • analysis-analyze-code-patterns
    - 代码模式分析
  • analysis-analyze-technical-document
    - 技术文档分析
  • analysis-review-architecture
    - 架构审查
  • analysis-review-code-quality
    - 代码质量审查
  • analysis-analyze-performance
    - 性能分析
  • analysis-assess-security-risks
    - 安全风险评估

Planning Templates

规划模板

  • planning-plan-architecture-design
    - Architecture design
  • planning-breakdown-task-steps
    - Task breakdown
  • planning-design-component-spec
    - Component design
  • planning-plan-migration-strategy
    - Migration strategy
  • planning-plan-architecture-design
    - 架构设计规划
  • planning-breakdown-task-steps
    - 任务步骤拆分
  • planning-design-component-spec
    - 组件设计规范
  • planning-plan-migration-strategy
    - 迁移策略规划

Development Templates

开发模板

  • development-implement-feature
    - Feature implementation
  • development-refactor-codebase
    - Code refactoring
  • development-generate-tests
    - Test generation
  • development-implement-component-ui
    - UI component
  • development-debug-runtime-issues
    - Runtime debugging
  • development-implement-feature
    - 功能实现
  • development-refactor-codebase
    - 代码重构
  • development-generate-tests
    - 测试用例生成
  • development-implement-component-ui
    - UI组件实现
  • development-debug-runtime-issues
    - 运行时问题调试

Task-Type Specific Examples

任务类型特定示例

Example 1: Security Analysis (Read-Only)

示例1:安全分析(只读)

bash
ccw cli -p "PURPOSE: Identify OWASP Top 10 vulnerabilities in authentication module to pass security audit; success = all critical/high issues documented with remediation
TASK: • Scan for injection flaws (SQL, command, LDAP) • Check authentication bypass vectors • Evaluate session management • Assess sensitive data exposure
MODE: analysis
CONTEXT: @src/auth/**/* @src/middleware/auth.ts | Memory: Using bcrypt for passwords, JWT for sessions
EXPECTED: Security report with: severity matrix, file:line references, CVE mappings where applicable, remediation code snippets prioritized by risk
CONSTRAINTS: Focus on authentication | Ignore test files
" --tool gemini --mode analysis --rule analysis-assess-security-risks --cd src/auth
bash
ccw cli -p "PURPOSE: 识别认证模块中的OWASP Top 10漏洞以通过安全审计;成功标准=记录所有关键/高危问题并提供修复方案
TASK: • 扫描注入漏洞(SQL、命令、LDAP) • 检查认证绕过向量 • 评估会话管理机制 • 评估敏感数据暴露风险
MODE: analysis
CONTEXT: @src/auth/**/* @src/middleware/auth.ts | Memory: 使用bcrypt处理密码,JWT管理会话
EXPECTED: 安全报告包含:风险等级矩阵、文件:行号引用、适用的CVE映射、按风险优先级排序的修复代码片段
CONSTRAINTS: 聚焦认证模块 | 忽略测试文件
" --tool gemini --mode analysis --rule analysis-assess-security-risks --cd src/auth

Example 2: Feature Implementation (Write Mode)

示例2:功能实现(写入模式)

bash
ccw cli -p "PURPOSE: Implement rate limiting for API endpoints to prevent abuse; must be configurable per-endpoint; backward compatible with existing clients
TASK: • Create rate limiter middleware with sliding window • Implement per-route configuration • Add Redis backend for distributed state • Include bypass for internal services
MODE: write
CONTEXT: @src/middleware/**/* @src/config/**/* | Memory: Using Express.js, Redis already configured, existing middleware pattern in auth.ts
EXPECTED: Production-ready code with: TypeScript types, unit tests, integration test, configuration example, migration guide
CONSTRAINTS: Follow existing middleware patterns | No breaking changes
" --tool gemini --mode write --rule development-implement-feature
bash
ccw cli -p "PURPOSE: 为API端点实现速率限制以防止滥用;需支持按端点配置;与现有客户端向后兼容
TASK: • 创建带滑动窗口的速率限制中间件 • 实现按路由配置 • 添加Redis后端用于分布式状态管理 • 包含内部服务绕过机制
MODE: write
CONTEXT: @src/middleware/**/* @src/config/**/* | Memory: 使用Express.js,Redis已配置,参考auth.ts中的现有中间件模式
EXPECTED: 生产就绪代码包含:TypeScript类型定义、单元测试、集成测试、配置示例、迁移指南
CONSTRAINTS: 遵循现有中间件模式 | 不允许破坏性变更
" --tool gemini --mode write --rule development-implement-feature

Example 3: Bug Root Cause Analysis

示例3:Bug根因分析

bash
ccw cli -p "PURPOSE: Fix memory leak in WebSocket connection handler causing server OOM after 24h; root cause must be identified before any fix
TASK: • Trace connection lifecycle from open to close • Identify event listener accumulation • Check cleanup on disconnect • Verify garbage collection eligibility
MODE: analysis
CONTEXT: @src/websocket/**/* @src/services/connection-manager.ts | Memory: Using ws library, ~5000 concurrent connections in production
EXPECTED: Root cause analysis with: memory profile, leak source (file:line), fix recommendation with code, verification steps
CONSTRAINTS: Focus on resource cleanup
" --tool gemini --mode analysis --rule analysis-diagnose-bug-root-cause --cd src
bash
ccw cli -p "PURPOSE: 修复WebSocket连接处理程序中的内存泄漏问题,该问题导致服务器运行24小时后出现OOM;修复前必须先确定根因
TASK: • 追踪连接从建立到关闭的生命周期 • 识别事件监听器累积问题 • 检查断开连接时的清理逻辑 • 验证垃圾回收资格
MODE: analysis
CONTEXT: @src/websocket/**/* @src/services/connection-manager.ts | Memory: 使用ws库,生产环境约5000并发连接
EXPECTED: 根因分析报告包含:内存配置文件、泄漏源(文件:行号)、修复代码建议、验证步骤
CONSTRAINTS: 聚焦资源清理逻辑
" --tool gemini --mode analysis --rule analysis-diagnose-bug-root-cause --cd src

Example 4: Code Review (Codex Review Mode)

示例4:代码审查(Codex审查模式)

bash
undefined
bash
undefined

Option 1: Custom focus (reviews uncommitted by default)

选项1:自定义审查重点(默认审查未提交变更)

ccw cli -p "Focus on security vulnerabilities and error handling" --tool codex --mode review
ccw cli -p "聚焦安全漏洞和错误处理" --tool codex --mode review

Option 2: Target flag only (no prompt with target flags)

选项2:仅使用目标标志(目标标志与提示词互斥)

ccw cli --tool codex --mode review --uncommitted ccw cli --tool codex --mode review --base main ccw cli --tool codex --mode review --commit abc123
undefined
ccw cli --tool codex --mode review --uncommitted ccw cli --tool codex --mode review --base main ccw cli --tool codex --mode review --commit abc123
undefined

Tool Selection Strategy

工具选择策略

Selection Algorithm

选择算法

STEP 0 (REQUIRED): Load configuration (memory-first strategy)
bash
undefined
步骤0(必填):加载配置(内存优先策略)
bash
undefined

Check if configuration exists in conversation memory

检查对话内存中是否存在配置

If YES → Use in-memory configuration

是 → 使用内存中的配置

If NO → Read(file_path="~/.claude/cli-tools.json")

否 → 读取(file_path="~/.claude/cli-tools.json")


Then proceed with selection:

1. **Parse task intent** → Extract required capabilities
2. **Load configuration** → Parse enabled tools with tags from JSON
3. **Match tags** → Filter tools supporting required capabilities
4. **Select tool** → Choose by priority (explicit > tag-match > default)
5. **Select model** → Use primaryModel, fallback to secondaryModel

然后执行以下选择步骤:

1. **解析任务意图** → 提取所需能力
2. **加载配置** → 从JSON中解析带标签的已启用工具
3. **匹配标签** → 筛选支持所需能力的工具
4. **选择工具** → 按优先级选择(显式指定 > 标签匹配 > 默认)
5. **选择模型** → 使用primaryModel,失败时回退到secondaryModel

Selection Decision Tree

选择决策树

0. LOAD CONFIGURATION (memory-first)
   ├─ In memory? → Use it
   └─ Not in memory? → Read ~/.claude/cli-tools.json
1. Explicit --tool specified?
   YES → Validate tool is enabled in config → Use it
   NO  → Proceed to tag-based selection
         ├─ Extract task tags (security, analysis, implementation, etc.)
         │  ├─ Find tools with matching tags
         │  │  ├─ Multiple matches? Use first enabled
         │  │  └─ Single match? Use it
         │  └─ No tag match? Use default tool
         └─ Default: Use first enabled tool in config
0. 加载配置(内存优先)
   ├─ 在内存中? → 使用它
   └─ 不在内存中? → 读取~/.claude/cli-tools.json
1. 是否指定了--tool?
   是 → 验证工具在配置中已启用 → 使用它
   否 → 执行基于标签的选择
         ├─ 提取任务标签(安全、分析、实现等)
         │  ├─ 查找带匹配标签的工具
         │  │  ├─ 多个匹配项?使用第一个已启用工具
         │  │  └─ 单个匹配项?使用它
         │  └─ 无标签匹配?使用默认工具
         └─ 默认:使用配置中的第一个已启用工具

Common Tag Routing

常见标签路由

Note: Match task type to tags defined in
~/.claude/cli-tools.json
Task TypeCommon Tags to Match
Security audit
分析
,
analysis
,
security
Bug diagnosis
Debug
,
分析
,
analysis
Implementation
implementation
, (any enabled tool)
Testing
testing
, (any enabled tool)
Refactoring
refactoring
, (any enabled tool)
Documentation
documentation
, (any enabled tool)
Selection Logic: Find tools where
tags
array contains matching keywords, otherwise use first enabled tool.
注意:将任务类型与
~/.claude/cli-tools.json
中定义的标签匹配
任务类型匹配的常见标签
安全审计
分析
,
analysis
,
security
Bug诊断
Debug
,
分析
,
analysis
功能实现
implementation
, (任意已启用工具)
测试
testing
, (任意已启用工具)
代码重构
refactoring
, (任意已启用工具)
文档编写
documentation
, (任意已启用工具)
选择逻辑:查找
tags
数组包含匹配关键词的工具,否则使用第一个已启用工具。

Fallback Chain

回退链

When primary tool fails (based on
~/.claude/cli-tools.json
configuration):
  1. Check
    secondaryModel
    for same tool (use
    secondaryModel
    from config)
  2. Try next enabled tool with matching tags (scan config for enabled tools)
  3. Fall back to default enabled tool (first enabled tool in config)
Example Fallback:
Tool1: primaryModel fails
Try Tool1: secondaryModel
  ↓ (if fails)
Try Tool2: primaryModel (next enabled with matching tags)
  ↓ (if fails)
Try default: first enabled tool
当主工具失败时(基于
~/.claude/cli-tools.json
配置):
  1. 尝试同一工具的
    secondaryModel
    (使用配置中的secondaryModel)
  2. 尝试下一个带匹配标签的已启用工具(扫描配置中的已启用工具)
  3. 回退到默认已启用工具(配置中的第一个已启用工具)
回退示例
工具1:primaryModel失败
尝试工具1:secondaryModel
  ↓(若失败)
尝试工具2:primaryModel(下一个带匹配标签的已启用工具)
  ↓(若失败)
尝试默认:第一个已启用工具

Permission Framework

权限框架

Single-Use Authorization: Each execution requires explicit user instruction. Previous authorization does NOT carry over.
Mode Hierarchy:
  • analysis
    : Read-only, safe for auto-execution
  • write
    : Create/Modify/Delete files - requires explicit
    --mode write
  • review
    : Git-aware code review (codex only) - requires explicit
    --mode review
  • Exception: User provides clear instructions like "modify", "create", "implement"
单次授权:每次执行都需要用户明确指令,之前的授权不会延续。
模式层级
  • analysis
    :只读,适合自动执行
  • write
    :创建/修改/删除文件 - 需要显式指定
    --mode write
  • review
    :支持Git的代码审查(仅codex) - 需要显式指定
    --mode review
  • 例外:用户提供明确指令如“修改”、“创建”、“实现”

Auto-Invoke Triggers

自动调用触发器

Proactive CLI invocation - Auto-invoke
ccw cli
when encountering these scenarios:
TriggerSuggested RuleWhen
Self-repair fails
analysis-diagnose-bug-root-cause
After 1+ failed fix attempts
Ambiguous requirements
planning-breakdown-task-steps
Task description lacks clarity
Architecture decisions
planning-plan-architecture-design
Complex feature needs design
Pattern uncertainty
analysis-analyze-code-patterns
Unsure of existing conventions
Critical code paths
analysis-assess-security-risks
Security/performance sensitive
主动CLI调用 - 遇到以下场景时自动调用
ccw cli
触发器建议规则触发时机
自我修复失败
analysis-diagnose-bug-root-cause
1次以上修复尝试失败后
需求模糊
planning-breakdown-task-steps
任务描述不够清晰时
架构决策
planning-plan-architecture-design
复杂功能需要设计时
模式不确定
analysis-analyze-code-patterns
不确定现有约定时
关键代码路径
analysis-assess-security-risks
涉及安全/性能敏感路径时

Execution Principles for Auto-Invoke

自动调用执行原则

  • Default mode:
    --mode analysis
    (read-only, safe)
  • No confirmation needed: Invoke proactively when triggers match
  • Wait for results: Complete analysis before next action
  • Tool selection: Use context-appropriate tool or fallback chain
  • Rule flexibility: Suggested rules are guidelines, adapt as needed
  • 默认模式
    --mode analysis
    (只读,安全)
  • 无需确认:当触发器匹配时主动调用
  • 等待结果:完成分析后再执行下一步操作
  • 工具选择:使用适合上下文的工具或回退链
  • 规则灵活性:建议规则为指导方针,可根据需要调整

Best Practices

最佳实践

Core Principles

核心原则

  • Configuration-driven - All tool selection from
    cli-tools.json
  • Tag-based routing - Match task requirements to tool capabilities
  • Use tools early and often - Tools are faster and more thorough than manual analysis
  • Unified CLI - Always use
    ccw cli -p
    for consistent parameter handling
  • Default to analysis - Omit
    --mode
    for read-only, explicitly use
    --mode write
    for modifications
  • Use
    --rule
    for templates
    - Auto-loads protocol + template appended to prompt
  • Write protection - Require EXPLICIT
    --mode write
    for file operations
  • 配置驱动 - 所有工具选择均来自
    cli-tools.json
  • 标签路由 - 将任务需求与工具能力匹配
  • 尽早并频繁使用工具 - 工具比手动分析更快、更全面
  • 统一CLI - 始终使用
    ccw cli -p
    以确保参数处理一致
  • 默认使用analysis模式 - 省略
    --mode
    时为只读,修改时显式使用
    --mode write
  • 使用
    --rule
    加载模板
    - 自动加载协议和模板并附加到提示词
  • 写保护 - 文件操作需要显式指定
    --mode write

Workflow Principles

工作流原则

  • Use unified interface - Always
    ccw cli -p
    format
  • Always include template - Use
    --rule <template-name>
    to load templates
  • Be specific - Clear PURPOSE, TASK, EXPECTED fields
  • Include constraints - File patterns, scope in CONSTRAINTS
  • Leverage memory context - When building on previous work
  • Discover patterns first - Use rg/MCP before CLI execution
  • Default to full context - Use
    @**/*
    unless specific files needed
  • 使用统一接口 - 始终使用
    ccw cli -p
    格式
  • 始终包含模板 - 使用
    --rule <template-name>
    加载模板
  • 具体化 - 明确的PURPOSE、TASK、EXPECTED字段
  • 包含约束 - 在CONSTRAINTS字段中指定文件模式、范围
  • 利用内存上下文 - 基于之前的工作内容时使用
  • 先发现模式 - 在CLI执行前使用rg/MCP
  • 默认使用完整上下文 - 除非需要特定文件,否则使用
    @**/*

Planning Checklist

规划检查清单

  • Purpose defined - Clear goal and intent
  • Mode selected -
    --mode analysis|write|review
  • Context gathered - File references + memory (default
    @**/*
    )
  • Directory navigation -
    --cd
    and/or
    --includeDirs
    if needed
  • Tool selected - Explicit
    --tool
    or tag-based auto-selection
  • Rule template -
    --rule <template-name>
    loads template
  • Constraints - Domain constraints in CONSTRAINTS field
  • 目标已定义 - 明确的目标和意图
  • 模式已选择 -
    --mode analysis|write|review
  • 上下文已收集 - 文件引用 + 内存上下文(默认
    @**/*
  • 目录导航已配置 - 必要时使用
    --cd
    和/或
    --includeDirs
  • 工具已选择 - 显式指定
    --tool
    或基于标签自动选择
  • 规则模板已加载 - 使用
    --rule <template-name>
    加载模板
  • 约束已指定 - 在CONSTRAINTS字段中定义领域约束

Integration with CLAUDE.md Instructions

与CLAUDE.md说明的集成

From global CLAUDE.md:
  • Always use
    run_in_background: false
    for Task tool agent calls
  • Default: Use Bash
    run_in_background: true
    for CLI calls
  • After CLI call: Stop output immediately, wait for hook callback
  • Wait for results: MUST wait for CLI analysis before taking write actions
  • Value every call: Never waste analysis results, aggregate before proposing solutions
From cli-tools-usage.md:
  • Strict cli-tools.json configuration adherence
  • Configuration-driven tool selection
  • Template system with --rule auto-loading
  • Permission framework with single-use authorization
  • Auto-invoke triggers for common failure scenarios
来自全局CLAUDE.md
  • 任务工具代理调用始终使用
    run_in_background: false
  • 默认:CLI调用使用Bash
    run_in_background: true
  • CLI调用后:立即停止输出,等待钩子回调
  • 等待结果:执行写入操作前必须等待CLI分析完成
  • 重视每次调用:绝不浪费分析结果,在提出解决方案前先汇总结果
来自cli-tools-usage.md
  • 严格遵守cli-tools.json配置
  • 配置驱动的工具选择
  • 带--rule自动加载的模板系统
  • 带单次授权的权限框架
  • 针对常见失败场景的自动调用触发器