feat: Add code analysis and LLM action templates with detailed configurations and examples

- Introduced a comprehensive code analysis action template for integrating code exploration and analysis capabilities.
- Added LLM action template for seamless integration of LLM calls with customizable prompts and tools.
- Implemented a benchmark search script to compare multiple search methods across various dimensions including speed, result quality, ranking stability, and coverage.
- Provided preset configurations for common analysis tasks and LLM actions, enhancing usability and flexibility.
This commit is contained in:
catlog22
2026-01-03 17:37:49 +08:00
parent 6a45035e3f
commit be498acf59
10 changed files with 3076 additions and 217 deletions

View File

@@ -0,0 +1,448 @@
# CLI Integration Specification
CCW CLI 集成规范,定义 Skill 中如何正确调用外部 CLI 工具。
---
## 执行模式
### 1. 同步执行 (Blocking)
适用于需要立即获取结果的场景。
```javascript
// Agent 调用 - 同步
const result = Task({
subagent_type: 'universal-executor',
prompt: '执行任务...',
run_in_background: false // 关键: 同步执行
});
// 结果立即可用
console.log(result);
```
### 2. 异步执行 (Background)
适用于长时间运行的 CLI 命令。
```javascript
// CLI 调用 - 异步
const task = Bash({
command: 'ccw cli -p "..." --tool gemini --mode analysis',
run_in_background: true // 关键: 后台执行
});
// 立即返回,不等待结果
// task.task_id 可用于后续查询
```
---
## CCW CLI 调用规范
### 基础命令结构
```bash
ccw cli -p "<PROMPT>" --tool <gemini|qwen|codex> --mode <analysis|write>
```
### 参数说明
| 参数 | 必需 | 说明 |
|------|------|------|
| `-p "<prompt>"` | ✓ | 提示词(使用双引号) |
| `--tool <tool>` | ✓ | 工具选择: gemini, qwen, codex |
| `--mode <mode>` | ✓ | 执行模式: analysis, write |
| `--cd <path>` | - | 工作目录 |
| `--includeDirs <dirs>` | - | 包含额外目录(逗号分隔) |
| `--resume [id]` | - | 恢复会话 |
### 模式选择
```
┌─ 分析/文档任务?
│ └─→ --mode analysis (只读)
└─ 实现/修改任务?
└─→ --mode write (读写)
```
---
## Agent 类型与选择
### universal-executor
通用执行器,最常用的 Agent 类型。
```javascript
Task({
subagent_type: 'universal-executor',
prompt: `
执行任务:
1. 读取配置文件
2. 分析依赖关系
3. 生成报告到 ${outputPath}
`,
run_in_background: false
});
```
**适用场景**:
- 多步骤任务执行
- 文件操作(读/写/编辑)
- 需要工具调用的任务
### Explore
代码探索 Agent快速理解代码库。
```javascript
Task({
subagent_type: 'Explore',
prompt: `
探索 src/ 目录:
- 识别主要模块
- 理解目录结构
- 找到入口点
Thoroughness: medium
`,
run_in_background: false
});
```
**适用场景**:
- 代码库探索
- 文件发现
- 结构理解
### cli-explore-agent
深度代码分析 Agent。
```javascript
Task({
subagent_type: 'cli-explore-agent',
prompt: `
深度分析 src/auth/ 模块:
- 认证流程
- 会话管理
- 安全机制
`,
run_in_background: false
});
```
**适用场景**:
- 深度代码理解
- 设计模式识别
- 复杂逻辑分析
---
## 会话管理
### 会话恢复
```javascript
// 保存会话 ID
const session = Bash({
command: 'ccw cli -p "初始分析..." --tool gemini --mode analysis',
run_in_background: true
});
// 后续恢复
const continuation = Bash({
command: `ccw cli -p "继续分析..." --tool gemini --mode analysis --resume ${session.id}`,
run_in_background: true
});
```
### 多会话合并
```javascript
// 合并多个会话的上下文
const merged = Bash({
command: `ccw cli -p "汇总分析..." --tool gemini --mode analysis --resume ${id1},${id2}`,
run_in_background: true
});
```
---
## Skill 中的 CLI 集成模式
### 模式 1: 单次调用
简单任务,一次调用完成。
```javascript
// Phase 执行
async function executePhase(context) {
const result = Bash({
command: `ccw cli -p "
PURPOSE: 分析项目结构
TASK: 识别模块、依赖、入口点
MODE: analysis
CONTEXT: @src/**/*
EXPECTED: JSON 格式的结构报告
" --tool gemini --mode analysis --cd ${context.projectRoot}`,
run_in_background: true,
timeout: 600000
});
// 等待完成
return await waitForCompletion(result.task_id);
}
```
### 模式 2: 链式调用
多步骤任务,每步依赖前一步结果。
```javascript
async function executeChain(context) {
// Step 1: 收集
const collectId = await runCLI('collect', context);
// Step 2: 分析 (依赖 Step 1)
const analyzeId = await runCLI('analyze', context, `--resume ${collectId}`);
// Step 3: 生成 (依赖 Step 2)
const generateId = await runCLI('generate', context, `--resume ${analyzeId}`);
return generateId;
}
async function runCLI(step, context, resumeFlag = '') {
const prompts = {
collect: 'PURPOSE: 收集代码文件...',
analyze: 'PURPOSE: 分析代码模式...',
generate: 'PURPOSE: 生成文档...'
};
const result = Bash({
command: `ccw cli -p "${prompts[step]}" --tool gemini --mode analysis ${resumeFlag}`,
run_in_background: true
});
return await waitForCompletion(result.task_id);
}
```
### 模式 3: 并行调用
独立任务并行执行。
```javascript
async function executeParallel(context) {
const tasks = [
{ type: 'structure', tool: 'gemini' },
{ type: 'dependencies', tool: 'gemini' },
{ type: 'patterns', tool: 'qwen' }
];
// 并行启动
const taskIds = tasks.map(task =>
Bash({
command: `ccw cli -p "分析 ${task.type}..." --tool ${task.tool} --mode analysis`,
run_in_background: true
}).task_id
);
// 等待全部完成
const results = await Promise.all(
taskIds.map(id => waitForCompletion(id))
);
return results;
}
```
### 模式 4: Fallback 链
工具失败时自动切换。
```javascript
async function executeWithFallback(context) {
const tools = ['gemini', 'qwen', 'codex'];
let result = null;
for (const tool of tools) {
try {
result = await runWithTool(tool, context);
if (result.success) break;
} catch (error) {
console.log(`${tool} failed, trying next...`);
}
}
if (!result?.success) {
throw new Error('All tools failed');
}
return result;
}
async function runWithTool(tool, context) {
const task = Bash({
command: `ccw cli -p "..." --tool ${tool} --mode analysis`,
run_in_background: true,
timeout: 600000
});
return await waitForCompletion(task.task_id);
}
```
---
## 提示词模板集成
### 引用协议模板
```bash
# 分析模式 - 必须引用 analysis-protocol.md
ccw cli -p "
RULES: $(cat ~/.claude/workflows/cli-templates/protocols/analysis-protocol.md)
$(cat ~/.claude/workflows/cli-templates/prompts/analysis/02-analyze-code-patterns.txt)
..." --tool gemini --mode analysis
# 写入模式 - 必须引用 write-protocol.md
ccw cli -p "
RULES: $(cat ~/.claude/workflows/cli-templates/protocols/write-protocol.md)
$(cat ~/.claude/workflows/cli-templates/prompts/development/02-implement-feature.txt)
..." --tool codex --mode write
```
### 动态模板构建
```javascript
function buildPrompt(config) {
const { purpose, task, mode, context, expected, template } = config;
const protocolPath = mode === 'write'
? '~/.claude/workflows/cli-templates/protocols/write-protocol.md'
: '~/.claude/workflows/cli-templates/protocols/analysis-protocol.md';
return `
PURPOSE: ${purpose}
TASK: ${task.map(t => `${t}`).join('\n')}
MODE: ${mode}
CONTEXT: ${context}
EXPECTED: ${expected}
RULES: $(cat ${protocolPath}) $(cat ${template})
`;
}
```
---
## 超时配置
### 推荐超时值
| 任务类型 | 超时 (ms) | 说明 |
|---------|----------|------|
| 快速分析 | 300000 | 5 分钟 |
| 标准分析 | 600000 | 10 分钟 |
| 深度分析 | 1200000 | 20 分钟 |
| 代码生成 | 1800000 | 30 分钟 |
| 复杂任务 | 3600000 | 60 分钟 |
### Codex 特殊处理
Codex 需要更长的超时时间(建议 3x
```javascript
const timeout = tool === 'codex' ? baseTimeout * 3 : baseTimeout;
Bash({
command: `ccw cli -p "..." --tool ${tool} --mode write`,
run_in_background: true,
timeout: timeout
});
```
---
## 错误处理
### 常见错误
| 错误 | 原因 | 处理 |
|------|------|------|
| ETIMEDOUT | 网络超时 | 重试或切换工具 |
| Exit code 1 | 命令执行失败 | 检查参数,切换工具 |
| Context overflow | 上下文过大 | 减少输入范围 |
### 重试策略
```javascript
async function executeWithRetry(command, maxRetries = 3) {
let lastError = null;
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
const task = Bash({
command,
run_in_background: true,
timeout: 600000
});
return await waitForCompletion(task.task_id);
} catch (error) {
lastError = error;
console.log(`Attempt ${attempt} failed: ${error.message}`);
// 指数退避
if (attempt < maxRetries) {
await sleep(Math.pow(2, attempt) * 1000);
}
}
}
throw lastError;
}
```
---
## 最佳实践
### 1. run_in_background 规则
```
Agent 调用 (Task):
run_in_background: false → 同步,立即获取结果
CLI 调用 (Bash + ccw cli):
run_in_background: true → 异步,后台执行
```
### 2. 工具选择
```
分析任务: gemini > qwen
生成任务: codex > gemini > qwen
代码修改: codex > gemini
```
### 3. 会话管理
- 相关任务使用 `--resume` 保持上下文
- 独立任务不使用 `--resume`
### 4. 提示词规范
- 始终使用 PURPOSE/TASK/MODE/CONTEXT/EXPECTED/RULES 结构
- 必须引用协议模板analysis-protocol 或 write-protocol
- 使用 `$(cat ...)` 动态加载模板
### 5. 结果处理
- 持久化重要结果到 workDir
- Brief returns: 路径 + 摘要,避免上下文溢出
- JSON 格式便于后续处理

View File

@@ -19,10 +19,32 @@
| 字段 | 类型 | 必需 | 说明 |
|------|------|------|------|
| `execution_mode` | enum | ✓ | `sequential` \| `autonomous` |
| `execution_mode` | enum | ✓ | `sequential` \| `autonomous` \| `hybrid` |
| `phase_count` | number | 条件 | Sequential 模式下的阶段数 |
| `action_count` | number | 条件 | Autonomous 模式下的动作数 |
### 2.5 上下文策略 (P0 增强)
| 字段 | 类型 | 必需 | 说明 |
|------|------|------|------|
| `context_strategy` | enum | ✓ | `file` \| `memory` |
**策略对比**:
| 策略 | 持久化 | 可调试 | 可恢复 | 适用场景 |
|------|--------|--------|--------|----------|
| `file` | ✓ | ✓ | ✓ | 复杂多阶段任务(推荐) |
| `memory` | ✗ | ✗ | ✗ | 简单线性任务 |
### 2.6 LLM 集成配置 (P1 增强)
| 字段 | 类型 | 必需 | 说明 |
|------|------|------|------|
| `llm_integration` | object | 可选 | LLM 调用配置 |
| `llm_integration.enabled` | boolean | - | 是否启用 LLM 调用 |
| `llm_integration.default_tool` | enum | - | `gemini` \| `qwen` \| `codex` |
| `llm_integration.fallback_chain` | string[] | - | 失败时的备选工具链 |
### 3. 工具依赖
| 字段 | 类型 | 必需 | 说明 |
@@ -50,8 +72,19 @@ interface SkillConfig {
triggers: string[]; // ["keyword1", "keyword2"]
// 执行模式
execution_mode: 'sequential' | 'autonomous';
execution_mode: 'sequential' | 'autonomous' | 'hybrid';
// 上下文策略 (P0 增强)
context_strategy: 'file' | 'memory'; // 默认: 'file'
// LLM 集成配置 (P1 增强)
llm_integration?: {
enabled: boolean; // 是否启用 LLM 调用
default_tool: 'gemini' | 'qwen' | 'codex';
fallback_chain: string[]; // ['gemini', 'qwen', 'codex']
mode: 'analysis' | 'write'; // 默认 mode
};
// Sequential 模式配置
sequential_config?: {
phases: Array<{
@@ -211,7 +244,73 @@ AskUserQuestion({
});
```
### Phase 4: 工具依赖
### Phase 4: 上下文策略 (P0 增强)
```javascript
AskUserQuestion({
questions: [
{
question: "选择上下文管理策略:",
header: "上下文策略",
multiSelect: false,
options: [
{
label: "文件策略 (file)",
description: "持久化到 .scratchpad支持调试和恢复推荐"
},
{
label: "内存策略 (memory)",
description: "仅在运行时保持,速度快但无法恢复"
}
]
}
]
});
```
### Phase 5: LLM 集成 (P1 增强)
```javascript
AskUserQuestion({
questions: [
{
question: "是否需要 LLM 调用能力?",
header: "LLM 集成",
multiSelect: false,
options: [
{
label: "启用 LLM 调用",
description: "使用 gemini/qwen/codex 进行分析或生成"
},
{
label: "不需要",
description: "仅使用本地工具"
}
]
}
]
});
// 如果启用 LLM
if (llmEnabled) {
AskUserQuestion({
questions: [
{
question: "选择默认 LLM 工具:",
header: "LLM 工具",
multiSelect: false,
options: [
{ label: "Gemini", description: "大上下文,适合分析任务(推荐)" },
{ label: "Qwen", description: "代码生成能力强" },
{ label: "Codex", description: "自主执行能力强,适合实现任务" }
]
}
]
});
}
```
### Phase 6: 工具依赖
```javascript
AskUserQuestion({
@@ -224,7 +323,8 @@ AskUserQuestion({
{ label: "基础工具", description: "Task, Read, Write, Glob, Grep, Bash" },
{ label: "用户交互", description: "AskUserQuestion" },
{ label: "Chrome 截图", description: "mcp__chrome__*" },
{ label: "外部搜索", description: "mcp__exa__search" }
{ label: "外部搜索", description: "mcp__exa__search" },
{ label: "CCW CLI 调用", description: "ccw cli (gemini/qwen/codex)" }
]
}
]
@@ -285,7 +385,7 @@ function validateSkillConfig(config) {
## 示例配置
### Sequential 模式示例
### Sequential 模式示例 (增强版)
```json
{
@@ -294,11 +394,33 @@ function validateSkillConfig(config) {
"description": "Generate API documentation from source code",
"triggers": ["generate api docs", "api documentation"],
"execution_mode": "sequential",
"context_strategy": "file",
"llm_integration": {
"enabled": true,
"default_tool": "gemini",
"fallback_chain": ["gemini", "qwen"],
"mode": "analysis"
},
"sequential_config": {
"phases": [
{ "id": "01-scan", "name": "Code Scanning", "output": "endpoints.json" },
{ "id": "02-parse", "name": "Schema Parsing", "output": "schemas.json" },
{ "id": "03-generate", "name": "Doc Generation", "output": "api-docs.md" }
{
"id": "01-scan",
"name": "Code Scanning",
"output": "endpoints.json",
"agent": { "type": "universal-executor", "run_in_background": false }
},
{
"id": "02-analyze",
"name": "LLM Analysis",
"output": "analysis.json",
"agent": { "type": "llm", "tool": "gemini", "mode": "analysis" }
},
{
"id": "03-generate",
"name": "Doc Generation",
"output": "api-docs.md",
"agent": { "type": "universal-executor", "run_in_background": false }
}
]
},
"allowed_tools": ["Task", "Read", "Write", "Glob", "Grep", "Bash"],