mirror of
https://github.com/catlog22/Claude-Code-Workflow.git
synced 2026-02-14 02:42:04 +08:00
refactor: Convert skill-generator from Chinese to English and remove emoji icons
- Convert all markdown files from Chinese to English - Remove all emoji/icon decorations (🔧📋⚙️✅🏁🔍📚⛔⭐) - Update all section headers, descriptions, and documentation - Keep all content logic, structure, code examples unchanged - Maintain template variables and file paths as-is Files converted (9 files total): - SKILL.md: Output structure comments - templates/skill-md.md: All Chinese descriptions and comments - specs/reference-docs-spec.md: All section headers and explanations - phases/01-requirements-discovery.md through 05-validation.md (5 files) - specs/execution-modes.md, skill-requirements.md, cli-integration.md, scripting-integration.md (4 files) - templates/sequential-phase.md, autonomous-orchestrator.md, autonomous-action.md, code-analysis-action.md, llm-action.md, script-template.md (6 files) All 16 files in skill-generator are now fully in English.
This commit is contained in:
@@ -1,22 +1,22 @@
|
||||
# Autonomous Action Template
|
||||
|
||||
自主模式动作文件的模板。
|
||||
Template for action files in Autonomous execution mode.
|
||||
|
||||
## Purpose
|
||||
|
||||
生成 Autonomous 执行模式的 Action 文件,定义可独立执行的动作单元。
|
||||
Generate Action files for Autonomous execution mode, defining independent executable action units.
|
||||
|
||||
## Usage Context
|
||||
|
||||
| Phase | Usage |
|
||||
|-------|-------|
|
||||
| Phase 3 (Phase Generation) | `config.execution_mode === 'autonomous'` 时生成 |
|
||||
| Generation Trigger | 为每个 `config.autonomous_config.actions` 生成一个 action 文件 |
|
||||
| Phase 3 (Phase Generation) | Generated when `config.execution_mode === 'autonomous'` |
|
||||
| Generation Trigger | Generate one action file for each `config.autonomous_config.actions` |
|
||||
| Output Location | `.claude/skills/{skill-name}/phases/actions/{action-id}.md` |
|
||||
|
||||
---
|
||||
|
||||
## 模板结构
|
||||
## Template Structure
|
||||
|
||||
```markdown
|
||||
# Action: {{action_name}}
|
||||
@@ -34,8 +34,8 @@
|
||||
## Scripts
|
||||
|
||||
\`\`\`yaml
|
||||
# 声明本动作使用的脚本(可选)
|
||||
# - script-id # 对应 scripts/script-id.py 或 .sh
|
||||
# Declare scripts used in this action (optional)
|
||||
# - script-id # Corresponds to scripts/script-id.py or .sh
|
||||
\`\`\`
|
||||
|
||||
## Execution
|
||||
@@ -44,7 +44,7 @@
|
||||
async function execute(state) {
|
||||
{{execution_code}}
|
||||
|
||||
// 调用脚本示例
|
||||
// Script execution example
|
||||
// const result = await ExecuteScript('script-id', { input: state.context.data });
|
||||
// if (!result.success) throw new Error(result.stderr);
|
||||
}
|
||||
@@ -71,63 +71,66 @@ return {
|
||||
{{next_actions_hints}}
|
||||
```
|
||||
|
||||
## 变量说明
|
||||
## Variable Descriptions
|
||||
|
||||
| 变量 | 说明 |
|
||||
|------|------|
|
||||
| `{{action_name}}` | 动作名称 |
|
||||
| `{{action_description}}` | 动作描述 |
|
||||
| `{{purpose}}` | 详细目的 |
|
||||
| `{{preconditions_list}}` | 前置条件列表 |
|
||||
| `{{execution_code}}` | 执行代码 |
|
||||
| `{{state_updates}}` | 状态更新 |
|
||||
| `{{error_handling_table}}` | 错误处理表格 |
|
||||
| `{{next_actions_hints}}` | 后续动作提示 |
|
||||
| Variable | Description |
|
||||
|----------|-------------|
|
||||
| `{{action_name}}` | Action name |
|
||||
| `{{action_description}}` | Action description |
|
||||
| `{{purpose}}` | Detailed purpose |
|
||||
| `{{preconditions_list}}` | List of preconditions |
|
||||
| `{{execution_code}}` | Execution code |
|
||||
| `{{state_updates}}` | State updates |
|
||||
| `{{error_handling_table}}` | Error handling table |
|
||||
| `{{next_actions_hints}}` | Next action hints |
|
||||
|
||||
## 动作生命周期
|
||||
## Action Lifecycle
|
||||
|
||||
```
|
||||
状态驱动执行流:
|
||||
State-driven execution flow:
|
||||
|
||||
state.status === 'pending'
|
||||
↓
|
||||
┌─ Init ─┐ ← 1次执行,环境准备
|
||||
│ 创建工作目录 │
|
||||
│ 初始化 context │
|
||||
│ status → running │
|
||||
└────┬────┘
|
||||
↓
|
||||
┌─ CRUD Loop ─┐ ← N次迭代,核心业务
|
||||
│ 编排器选择动作 │ List / Create / Edit / Delete
|
||||
│ execute(state) │ 共享模式: 收集输入 → 操作 context.items → 返回更新
|
||||
│ 更新 state │
|
||||
└────┬────┘
|
||||
↓
|
||||
┌─ Complete ─┐ ← 1次执行,保存结果
|
||||
│ 序列化输出 │
|
||||
│ status → completed │
|
||||
└──────────┘
|
||||
|
|
||||
v
|
||||
+-- Init --+ <- 1 execution, environment preparation
|
||||
| Create working directory
|
||||
| Initialize context
|
||||
| status -> running
|
||||
+----+----+
|
||||
|
|
||||
v
|
||||
+-- CRUD Loop --+ <- N iterations, core business
|
||||
| Orchestrator selects action | List / Create / Edit / Delete
|
||||
| execute(state) | Shared pattern: collect input -> operate context.items -> return updates
|
||||
| Update state
|
||||
+----+----+
|
||||
|
|
||||
v
|
||||
+-- Complete --+ <- 1 execution, save results
|
||||
| Serialize output
|
||||
| status -> completed
|
||||
+----------+
|
||||
|
||||
共享状态结构:
|
||||
state.status → 'pending' | 'running' | 'completed'
|
||||
state.context.items → 业务数据数组
|
||||
state.completed_actions → 已执行动作 ID 列表
|
||||
Shared state structure:
|
||||
state.status -> 'pending' | 'running' | 'completed'
|
||||
state.context.items -> Business data array
|
||||
state.completed_actions -> List of executed action IDs
|
||||
```
|
||||
|
||||
## 动作类型模板
|
||||
## Action Type Templates
|
||||
|
||||
### 1. 初始化动作 (Init)
|
||||
### 1. Initialize Action (Init)
|
||||
|
||||
**触发条件**: `state.status === 'pending'`,仅执行一次
|
||||
**Trigger condition**: `state.status === 'pending'`, executes once
|
||||
|
||||
```markdown
|
||||
# Action: Initialize
|
||||
|
||||
初始化 Skill 执行状态。
|
||||
Initialize Skill execution state.
|
||||
|
||||
## Purpose
|
||||
|
||||
设置初始状态,准备执行环境。
|
||||
Set initial state, prepare execution environment.
|
||||
|
||||
## Preconditions
|
||||
|
||||
@@ -151,24 +154,24 @@ async function execute(state) {
|
||||
|
||||
## Next Actions
|
||||
|
||||
- 成功: 进入主处理循环 (由编排器选择首个 CRUD 动作)
|
||||
- 失败: action-abort
|
||||
- Success: Enter main processing loop (Orchestrator selects first CRUD action)
|
||||
- Failure: action-abort
|
||||
```
|
||||
|
||||
### 2. CRUD 动作 (List / Create / Edit / Delete)
|
||||
### 2. CRUD Actions (List / Create / Edit / Delete)
|
||||
|
||||
**触发条件**: `state.status === 'running'`,循环执行直至用户退出
|
||||
**Trigger condition**: `state.status === 'running'`, loop until user exits
|
||||
|
||||
> 以 Create 为示例展示共享模式。List / Edit / Delete 遵循同一结构,仅 `执行逻辑` 和 `状态更新字段` 不同。
|
||||
> Example shows Create action demonstrating shared pattern. List / Edit / Delete follow same structure with different execution logic and state update fields.
|
||||
|
||||
```markdown
|
||||
# Action: Create Item
|
||||
|
||||
创建新项目。
|
||||
Create new item.
|
||||
|
||||
## Purpose
|
||||
|
||||
收集用户输入,向 context.items 追加新记录。
|
||||
Collect user input, append new record to context.items.
|
||||
|
||||
## Preconditions
|
||||
|
||||
@@ -178,25 +181,25 @@ async function execute(state) {
|
||||
|
||||
\`\`\`javascript
|
||||
async function execute(state) {
|
||||
// 1. 收集输入
|
||||
// 1. Collect input
|
||||
const input = await AskUserQuestion({
|
||||
questions: [{
|
||||
question: "请输入项目名称:",
|
||||
header: "名称",
|
||||
question: "Please enter item name:",
|
||||
header: "Name",
|
||||
multiSelect: false,
|
||||
options: [{ label: "手动输入", description: "输入自定义名称" }]
|
||||
options: [{ label: "Manual input", description: "Enter custom name" }]
|
||||
}]
|
||||
});
|
||||
|
||||
// 2. 操作 context.items (核心逻辑因动作类型而异)
|
||||
// 2. Operate context.items (core logic differs by action type)
|
||||
const newItem = {
|
||||
id: Date.now().toString(),
|
||||
name: input["名称"],
|
||||
name: input["Name"],
|
||||
status: 'pending',
|
||||
created_at: new Date().toISOString()
|
||||
};
|
||||
|
||||
// 3. 返回状态更新
|
||||
// 3. Return state update
|
||||
return {
|
||||
stateUpdates: {
|
||||
context: {
|
||||
@@ -211,31 +214,31 @@ async function execute(state) {
|
||||
|
||||
## Next Actions
|
||||
|
||||
- 继续操作: 编排器根据 state 选择下一动作
|
||||
- 用户退出: action-complete
|
||||
- Continue operations: Orchestrator selects next action based on state
|
||||
- User exit: action-complete
|
||||
```
|
||||
|
||||
**其他 CRUD 动作差异对照:**
|
||||
**Other CRUD Actions Differences:**
|
||||
|
||||
| 动作 | 核心逻辑 | 额外前置条件 | 关键状态字段 |
|
||||
|------|---------|------------|------------|
|
||||
| List | `items.forEach(→ console.log)` | 无 | `current_view: 'list'` |
|
||||
| Create | `items.push(newItem)` | 无 | `last_created_id` |
|
||||
| Edit | `items.map(→ 替换匹配项)` | `selected_item_id !== null` | `updated_at` |
|
||||
| Delete | `items.filter(→ 排除匹配项)` | `selected_item_id !== null` | 确认对话 → 执行 |
|
||||
| Action | Core Logic | Extra Preconditions | Key State Field |
|
||||
|--------|-----------|-------------------|-----------------|
|
||||
| List | `items.forEach(-> console.log)` | None | `current_view: 'list'` |
|
||||
| Create | `items.push(newItem)` | None | `last_created_id` |
|
||||
| Edit | `items.map(-> replace matching)` | `selected_item_id !== null` | `updated_at` |
|
||||
| Delete | `items.filter(-> exclude matching)` | `selected_item_id !== null` | Confirm dialog -> execute |
|
||||
|
||||
### 3. 完成动作 (Complete)
|
||||
### 3. Complete Action
|
||||
|
||||
**触发条件**: 用户明确退出或终止条件满足,仅执行一次
|
||||
**Trigger condition**: User explicitly exits or termination condition met, executes once
|
||||
|
||||
```markdown
|
||||
# Action: Complete
|
||||
|
||||
完成任务并退出。
|
||||
Complete task and exit.
|
||||
|
||||
## Purpose
|
||||
|
||||
序列化最终状态,结束 Skill 执行。
|
||||
Serialize final state, end Skill execution.
|
||||
|
||||
## Preconditions
|
||||
|
||||
@@ -253,7 +256,7 @@ async function execute(state) {
|
||||
actions_executed: state.completed_actions.length
|
||||
};
|
||||
|
||||
console.log(\`任务完成: \${summary.total_items} 项, \${summary.actions_executed} 次操作\`);
|
||||
console.log(\`Task complete: \${summary.total_items} items, \${summary.actions_executed} operations\`);
|
||||
|
||||
return {
|
||||
stateUpdates: {
|
||||
@@ -267,31 +270,31 @@ async function execute(state) {
|
||||
|
||||
## Next Actions
|
||||
|
||||
- 无(终止状态)
|
||||
- None (terminal state)
|
||||
```
|
||||
|
||||
## 生成函数
|
||||
## Generation Function
|
||||
|
||||
```javascript
|
||||
function generateAction(actionConfig, skillConfig) {
|
||||
return `# Action: ${actionConfig.name}
|
||||
|
||||
${actionConfig.description || `执行 ${actionConfig.name} 操作`}
|
||||
${actionConfig.description || `Execute ${actionConfig.name} operation`}
|
||||
|
||||
## Purpose
|
||||
|
||||
${actionConfig.purpose || 'TODO: 描述此动作的详细目的'}
|
||||
${actionConfig.purpose || 'TODO: Describe detailed purpose of this action'}
|
||||
|
||||
## Preconditions
|
||||
|
||||
${actionConfig.preconditions?.map(p => `- [ ] ${p}`).join('\n') || '- [ ] 无特殊前置条件'}
|
||||
${actionConfig.preconditions?.map(p => `- [ ] ${p}`).join('\n') || '- [ ] No special preconditions'}
|
||||
|
||||
## Execution
|
||||
|
||||
\`\`\`javascript
|
||||
async function execute(state) {
|
||||
// TODO: 实现动作逻辑
|
||||
|
||||
// TODO: Implement action logic
|
||||
|
||||
return {
|
||||
stateUpdates: {
|
||||
completed_actions: [...state.completed_actions, '${actionConfig.id}']
|
||||
@@ -305,7 +308,7 @@ async function execute(state) {
|
||||
\`\`\`javascript
|
||||
return {
|
||||
stateUpdates: {
|
||||
// TODO: 定义状态更新
|
||||
// TODO: Define state updates
|
||||
${actionConfig.effects?.map(e => ` // Effect: ${e}`).join('\n') || ''}
|
||||
}
|
||||
};
|
||||
@@ -315,13 +318,13 @@ ${actionConfig.effects?.map(e => ` // Effect: ${e}`).join('\n') || ''}
|
||||
|
||||
| Error Type | Recovery |
|
||||
|------------|----------|
|
||||
| 数据验证失败 | 返回错误,不更新状态 |
|
||||
| 执行异常 | 记录错误,增加 error_count |
|
||||
| Data validation failed | Return error, no state update |
|
||||
| Execution exception | Log error, increment error_count |
|
||||
|
||||
## Next Actions (Hints)
|
||||
|
||||
- 成功: 由编排器根据状态决定
|
||||
- 失败: 重试或 action-abort
|
||||
- Success: Orchestrator decides based on state
|
||||
- Failure: Retry or action-abort
|
||||
`;
|
||||
}
|
||||
```
|
||||
|
||||
@@ -1,59 +1,59 @@
|
||||
# Autonomous Orchestrator Template
|
||||
|
||||
自主模式编排器的模板。
|
||||
Template for orchestrator file in Autonomous execution mode.
|
||||
|
||||
## Purpose
|
||||
|
||||
生成 Autonomous 执行模式的 Orchestrator 文件,负责状态驱动的动作选择和执行循环。
|
||||
Generate Orchestrator file for Autonomous execution mode, responsible for state-driven action selection and execution loop.
|
||||
|
||||
## Usage Context
|
||||
|
||||
| Phase | Usage |
|
||||
|-------|-------|
|
||||
| Phase 3 (Phase Generation) | `config.execution_mode === 'autonomous'` 时生成 |
|
||||
| Generation Trigger | 创建编排器逻辑,管理动作选择和状态更新 |
|
||||
| Phase 3 (Phase Generation) | Generated when `config.execution_mode === 'autonomous'` |
|
||||
| Generation Trigger | Create orchestrator logic to manage action selection and state updates |
|
||||
| Output Location | `.claude/skills/{skill-name}/phases/orchestrator.md` |
|
||||
|
||||
---
|
||||
|
||||
## ⚠️ 重要提示
|
||||
## Important Notes
|
||||
|
||||
> **Phase 0 是强制前置阶段**:在 Orchestrator 启动执行循环之前,必须先完成 Phase 0 的规范研读。
|
||||
> **Phase 0 is mandatory prerequisite**: Before Orchestrator starts execution loop, Phase 0 specification review must be completed first.
|
||||
>
|
||||
> 生成 Orchestrator 时,需要确保:
|
||||
> 1. SKILL.md 中已包含 Phase 0 规范研读步骤
|
||||
> 2. Orchestrator 启动前验证规范已阅读
|
||||
> 3. 所有 Action 文件都引用相关的规范文档
|
||||
> 4. Architecture Overview 中 Phase 0 位于 Orchestrator 之前
|
||||
> When generating Orchestrator, ensure:
|
||||
> 1. Phase 0 specification review step is included in SKILL.md
|
||||
> 2. Orchestrator validates specification has been reviewed before starting execution loop
|
||||
> 3. All Action files reference related specification documents
|
||||
> 4. Architecture Overview places Phase 0 before Orchestrator
|
||||
|
||||
## 模板结构
|
||||
## Template Structure
|
||||
|
||||
```markdown
|
||||
# Orchestrator
|
||||
|
||||
## Role
|
||||
|
||||
根据当前状态选择并执行下一个动作。
|
||||
Select and execute next action based on current state.
|
||||
|
||||
## State Management
|
||||
|
||||
### 读取状态
|
||||
### Read State
|
||||
|
||||
\`\`\`javascript
|
||||
const state = JSON.parse(Read(`${workDir}/state.json`));
|
||||
const state = JSON.parse(Read(\`${workDir}/state.json\`));
|
||||
\`\`\`
|
||||
|
||||
### 更新状态
|
||||
### Update State
|
||||
|
||||
\`\`\`javascript
|
||||
function updateState(updates) {
|
||||
const state = JSON.parse(Read(`${workDir}/state.json`));
|
||||
const state = JSON.parse(Read(\`${workDir}/state.json\`));
|
||||
const newState = {
|
||||
...state,
|
||||
...updates,
|
||||
updated_at: new Date().toISOString()
|
||||
};
|
||||
Write(`${workDir}/state.json`, JSON.stringify(newState, null, 2));
|
||||
Write(\`${workDir}/state.json\`, JSON.stringify(newState, null, 2));
|
||||
return newState;
|
||||
}
|
||||
\`\`\`
|
||||
@@ -62,18 +62,18 @@ function updateState(updates) {
|
||||
|
||||
\`\`\`javascript
|
||||
function selectNextAction(state) {
|
||||
// 1. 终止条件检查
|
||||
// 1. Check termination conditions
|
||||
{{termination_checks}}
|
||||
|
||||
// 2. 错误限制检查
|
||||
|
||||
// 2. Check error limit
|
||||
if (state.error_count >= 3) {
|
||||
return 'action-abort';
|
||||
}
|
||||
|
||||
// 3. 动作选择逻辑
|
||||
|
||||
// 3. Action selection logic
|
||||
{{action_selection_logic}}
|
||||
|
||||
// 4. 默认完成
|
||||
|
||||
// 4. Default completion
|
||||
return 'action-complete';
|
||||
}
|
||||
\`\`\`
|
||||
@@ -83,34 +83,34 @@ function selectNextAction(state) {
|
||||
\`\`\`javascript
|
||||
async function runOrchestrator() {
|
||||
console.log('=== Orchestrator Started ===');
|
||||
|
||||
|
||||
let iteration = 0;
|
||||
const MAX_ITERATIONS = 100;
|
||||
|
||||
|
||||
while (iteration < MAX_ITERATIONS) {
|
||||
iteration++;
|
||||
|
||||
// 1. 读取当前状态
|
||||
const state = JSON.parse(Read(`${workDir}/state.json`));
|
||||
console.log(`[Iteration ${iteration}] Status: ${state.status}`);
|
||||
|
||||
// 2. 选择下一个动作
|
||||
|
||||
// 1. Read current state
|
||||
const state = JSON.parse(Read(\`${workDir}/state.json\`));
|
||||
console.log(\`[Iteration ${iteration}] Status: ${state.status}\`);
|
||||
|
||||
// 2. Select next action
|
||||
const actionId = selectNextAction(state);
|
||||
|
||||
|
||||
if (!actionId) {
|
||||
console.log('No action selected, terminating.');
|
||||
break;
|
||||
}
|
||||
|
||||
console.log(`[Iteration ${iteration}] Executing: ${actionId}`);
|
||||
|
||||
// 3. 更新状态:当前动作
|
||||
|
||||
console.log(\`[Iteration ${iteration}] Executing: ${actionId}\`);
|
||||
|
||||
// 3. Update state: current action
|
||||
updateState({ current_action: actionId });
|
||||
|
||||
// 4. 执行动作
|
||||
|
||||
// 4. Execute action
|
||||
try {
|
||||
const actionPrompt = Read(`phases/actions/${actionId}.md`);
|
||||
|
||||
const actionPrompt = Read(\`phases/actions/${actionId}.md\`);
|
||||
|
||||
const result = await Task({
|
||||
subagent_type: 'universal-executor',
|
||||
run_in_background: false,
|
||||
@@ -125,18 +125,18 @@ async function runOrchestrator() {
|
||||
Return JSON with stateUpdates field.
|
||||
\`
|
||||
});
|
||||
|
||||
|
||||
const actionResult = JSON.parse(result);
|
||||
|
||||
// 5. 更新状态:动作完成
|
||||
|
||||
// 5. Update state: action completed
|
||||
updateState({
|
||||
current_action: null,
|
||||
completed_actions: [...state.completed_actions, actionId],
|
||||
...actionResult.stateUpdates
|
||||
});
|
||||
|
||||
|
||||
} catch (error) {
|
||||
// 错误处理
|
||||
// Error handling
|
||||
updateState({
|
||||
current_action: null,
|
||||
errors: [...state.errors, {
|
||||
@@ -148,7 +148,7 @@ Return JSON with stateUpdates field.
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
console.log('=== Orchestrator Finished ===');
|
||||
}
|
||||
\`\`\`
|
||||
@@ -167,28 +167,28 @@ Return JSON with stateUpdates field.
|
||||
|
||||
| Error Type | Recovery Strategy |
|
||||
|------------|-------------------|
|
||||
| 动作执行失败 | 重试最多 3 次 |
|
||||
| 状态不一致 | 回滚到上一个稳定状态 |
|
||||
| 用户中止 | 保存当前状态,允许恢复 |
|
||||
| Action execution failed | Retry up to 3 times |
|
||||
| State inconsistency | Rollback to last stable state |
|
||||
| User abort | Save current state, allow recovery |
|
||||
```
|
||||
|
||||
## 变量说明
|
||||
## Variable Descriptions
|
||||
|
||||
| 变量 | 说明 |
|
||||
|------|------|
|
||||
| `{{termination_checks}}` | 终止条件检查代码 |
|
||||
| `{{action_selection_logic}}` | 动作选择逻辑代码 |
|
||||
| `{{action_catalog_table}}` | 动作目录表格 |
|
||||
| `{{termination_conditions_list}}` | 终止条件列表 |
|
||||
| Variable | Description |
|
||||
|----------|-------------|
|
||||
| `{{termination_checks}}` | Termination condition check code |
|
||||
| `{{action_selection_logic}}` | Action selection logic code |
|
||||
| `{{action_catalog_table}}` | Action directory table |
|
||||
| `{{termination_conditions_list}}` | List of termination conditions |
|
||||
|
||||
## 生成函数
|
||||
## Generation Function
|
||||
|
||||
```javascript
|
||||
function generateOrchestrator(config) {
|
||||
const actions = config.autonomous_config.actions;
|
||||
const terminations = config.autonomous_config.termination_conditions || [];
|
||||
|
||||
// 生成终止条件检查
|
||||
|
||||
// Generate termination checks
|
||||
const terminationChecks = terminations.map(t => {
|
||||
const checks = {
|
||||
'user_exit': 'if (state.status === "user_exit") return null;',
|
||||
@@ -198,24 +198,24 @@ function generateOrchestrator(config) {
|
||||
};
|
||||
return checks[t] || `if (state.${t}) return null;`;
|
||||
}).join('\n ');
|
||||
|
||||
// 生成动作选择逻辑
|
||||
|
||||
// Generate action selection logic
|
||||
const actionSelectionLogic = actions.map(action => {
|
||||
if (!action.preconditions?.length) {
|
||||
return `// ${action.name}: 无前置条件,需要手动添加选择逻辑`;
|
||||
return `// ${action.name}: No preconditions, add selection logic manually`;
|
||||
}
|
||||
const conditions = action.preconditions.map(p => `state.${p}`).join(' && ');
|
||||
return `if (${conditions}) return '${action.id}';`;
|
||||
}).join('\n ');
|
||||
|
||||
// 生成动作目录表格
|
||||
const actionCatalogTable = actions.map(a =>
|
||||
|
||||
// Generate action catalog table
|
||||
const actionCatalogTable = actions.map(a =>
|
||||
`| [${a.id}](actions/${a.id}.md) | ${a.description || a.name} | ${a.preconditions?.join(', ') || '-'} |`
|
||||
).join('\n');
|
||||
|
||||
// 生成终止条件列表
|
||||
|
||||
// Generate termination conditions list
|
||||
const terminationConditionsList = terminations.map(t => `- ${t}`).join('\n');
|
||||
|
||||
|
||||
return template
|
||||
.replace('{{termination_checks}}', terminationChecks)
|
||||
.replace('{{action_selection_logic}}', actionSelectionLogic)
|
||||
@@ -224,11 +224,11 @@ function generateOrchestrator(config) {
|
||||
}
|
||||
```
|
||||
|
||||
## 编排策略
|
||||
## Orchestration Strategies
|
||||
|
||||
### 1. 优先级策略
|
||||
### 1. Priority Strategy
|
||||
|
||||
按预定义优先级选择动作:
|
||||
Select action by predefined priority:
|
||||
|
||||
```javascript
|
||||
const PRIORITY = ['action-init', 'action-process', 'action-review', 'action-complete'];
|
||||
@@ -243,16 +243,16 @@ function selectByPriority(state, availableActions) {
|
||||
}
|
||||
```
|
||||
|
||||
### 2. 用户驱动策略
|
||||
### 2. User-Driven Strategy
|
||||
|
||||
询问用户选择下一个动作:
|
||||
Ask user to select next action:
|
||||
|
||||
```javascript
|
||||
async function selectByUser(state, availableActions) {
|
||||
const response = await AskUserQuestion({
|
||||
questions: [{
|
||||
question: "选择下一个操作:",
|
||||
header: "操作",
|
||||
question: "Select next operation:",
|
||||
header: "Operations",
|
||||
multiSelect: false,
|
||||
options: availableActions.map(a => ({
|
||||
label: a.name,
|
||||
@@ -260,32 +260,32 @@ async function selectByUser(state, availableActions) {
|
||||
}))
|
||||
}]
|
||||
});
|
||||
|
||||
return availableActions.find(a => a.name === response["操作"])?.id;
|
||||
|
||||
return availableActions.find(a => a.name === response["Operations"])?.id;
|
||||
}
|
||||
```
|
||||
|
||||
### 3. 状态驱动策略
|
||||
### 3. State-Driven Strategy
|
||||
|
||||
完全基于状态自动决策:
|
||||
Fully automatic decision based on state:
|
||||
|
||||
```javascript
|
||||
function selectByState(state) {
|
||||
// 初始化
|
||||
// Initialization
|
||||
if (state.status === 'pending') return 'action-init';
|
||||
|
||||
// 有待处理项
|
||||
|
||||
// Has pending items
|
||||
if (state.pending_items?.length > 0) return 'action-process';
|
||||
|
||||
// 需要审核
|
||||
|
||||
// Needs review
|
||||
if (state.needs_review) return 'action-review';
|
||||
|
||||
// 完成
|
||||
|
||||
// Completed
|
||||
return 'action-complete';
|
||||
}
|
||||
```
|
||||
|
||||
## 状态机示例
|
||||
## State Machine Example
|
||||
|
||||
```mermaid
|
||||
stateDiagram-v2
|
||||
|
||||
@@ -1,59 +1,59 @@
|
||||
# Code Analysis Action Template
|
||||
|
||||
代码分析动作模板,用于在 Skill 中集成代码探索和分析能力。
|
||||
Code analysis action template for integrating code exploration and analysis capabilities into a Skill.
|
||||
|
||||
## Purpose
|
||||
|
||||
为 Skill 生成代码分析动作,集成 MCP 工具 (ACE) 和 Agent 进行语义搜索和深度分析。
|
||||
Generate code analysis actions for a Skill, integrating MCP tools (ACE) and Agents for semantic search and in-depth analysis.
|
||||
|
||||
## Usage Context
|
||||
|
||||
| Phase | Usage |
|
||||
|-------|-------|
|
||||
| Optional | 当 Skill 需要代码探索和分析能力时使用 |
|
||||
| Generation Trigger | 用户选择添加 code-analysis 动作类型 |
|
||||
| Optional | Use when Skill requires code exploration and analysis capabilities |
|
||||
| Generation Trigger | User selects to add code-analysis action type |
|
||||
| Agent Types | Explore, cli-explore-agent, universal-executor |
|
||||
|
||||
---
|
||||
|
||||
## 配置结构
|
||||
## Configuration Structure
|
||||
|
||||
```typescript
|
||||
interface CodeAnalysisActionConfig {
|
||||
id: string; // "analyze-structure", "explore-patterns"
|
||||
name: string; // "Code Structure Analysis"
|
||||
type: 'code-analysis'; // 动作类型标识
|
||||
type: 'code-analysis'; // Action type identifier
|
||||
|
||||
// 分析范围
|
||||
// Analysis scope
|
||||
scope: {
|
||||
paths: string[]; // 目标路径
|
||||
patterns: string[]; // Glob 模式
|
||||
excludes?: string[]; // 排除模式
|
||||
paths: string[]; // Target paths
|
||||
patterns: string[]; // Glob patterns
|
||||
excludes?: string[]; // Exclude patterns
|
||||
};
|
||||
|
||||
// 分析类型
|
||||
// Analysis type
|
||||
analysis_type: 'structure' | 'patterns' | 'dependencies' | 'quality' | 'security';
|
||||
|
||||
// Agent 配置
|
||||
// Agent config
|
||||
agent: {
|
||||
type: 'Explore' | 'cli-explore-agent' | 'universal-executor';
|
||||
thoroughness: 'quick' | 'medium' | 'very thorough';
|
||||
};
|
||||
|
||||
// 输出配置
|
||||
// Output config
|
||||
output: {
|
||||
format: 'json' | 'markdown';
|
||||
file: string;
|
||||
};
|
||||
|
||||
// MCP 工具增强
|
||||
// MCP tool enhancement
|
||||
mcp_tools?: string[]; // ['mcp__ace-tool__search_context']
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 模板生成函数
|
||||
## Template Generation Function
|
||||
|
||||
```javascript
|
||||
function generateCodeAnalysisAction(config) {
|
||||
@@ -64,20 +64,20 @@ function generateCodeAnalysisAction(config) {
|
||||
|
||||
## Action: ${id}
|
||||
|
||||
### 分析范围
|
||||
### Analysis Scope
|
||||
|
||||
- **路径**: ${scope.paths.join(', ')}
|
||||
- **模式**: ${scope.patterns.join(', ')}
|
||||
${scope.excludes ? `- **排除**: ${scope.excludes.join(', ')}` : ''}
|
||||
- **Paths**: ${scope.paths.join(', ')}
|
||||
- **Patterns**: ${scope.patterns.join(', ')}
|
||||
${scope.excludes ? `- **Excludes**: ${scope.excludes.join(', ')}` : ''}
|
||||
|
||||
### 执行逻辑
|
||||
### Execution Logic
|
||||
|
||||
\`\`\`javascript
|
||||
async function execute${toPascalCase(id)}(context) {
|
||||
const workDir = context.workDir;
|
||||
const results = [];
|
||||
|
||||
// 1. 文件发现
|
||||
// 1. File discovery
|
||||
const files = await discoverFiles({
|
||||
paths: ${JSON.stringify(scope.paths)},
|
||||
patterns: ${JSON.stringify(scope.patterns)},
|
||||
@@ -86,34 +86,34 @@ async function execute${toPascalCase(id)}(context) {
|
||||
|
||||
console.log(\`Found \${files.length} files to analyze\`);
|
||||
|
||||
// 2. 使用 MCP 工具进行语义搜索(如果配置)
|
||||
${mcp_tools.length > 0 ? `
|
||||
// 2. Semantic search using MCP tools (if configured)
|
||||
${mcp_tools.length > 0 ? \`
|
||||
const semanticResults = await mcp__ace_tool__search_context({
|
||||
project_root_path: context.projectRoot,
|
||||
query: '${getQueryForAnalysisType(analysis_type)}'
|
||||
query: '\${getQueryForAnalysisType(analysis_type)}'
|
||||
});
|
||||
results.push({ type: 'semantic', data: semanticResults });
|
||||
` : '// No MCP tools configured'}
|
||||
\` : '// No MCP tools configured'}
|
||||
|
||||
// 3. 启动 Agent 进行深度分析
|
||||
// 3. Launch Agent for in-depth analysis
|
||||
const agentResult = await Task({
|
||||
subagent_type: '${agent.type}',
|
||||
subagent_type: '\${agent.type}',
|
||||
prompt: \`
|
||||
${generateAgentPrompt(analysis_type, scope)}
|
||||
\${generateAgentPrompt(analysis_type, scope)}
|
||||
\`,
|
||||
run_in_background: false
|
||||
});
|
||||
|
||||
results.push({ type: 'agent', data: agentResult });
|
||||
|
||||
// 4. 汇总结果
|
||||
// 4. Aggregate results
|
||||
const summary = aggregateResults(results);
|
||||
|
||||
// 5. 输出结果
|
||||
// 5. Output results
|
||||
const outputPath = \`\${workDir}/${output.file}\`;
|
||||
${output.format === 'json'
|
||||
? `Write(outputPath, JSON.stringify(summary, null, 2));`
|
||||
: `Write(outputPath, formatAsMarkdown(summary));`}
|
||||
? \`Write(outputPath, JSON.stringify(summary, null, 2));\`
|
||||
: \`Write(outputPath, formatAsMarkdown(summary));\`}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
@@ -122,8 +122,7 @@ ${generateAgentPrompt(analysis_type, scope)}
|
||||
analysis_type: '${analysis_type}'
|
||||
};
|
||||
}
|
||||
\`\`\`
|
||||
`;
|
||||
\`\`\`;
|
||||
}
|
||||
|
||||
function getQueryForAnalysisType(type) {
|
||||
@@ -139,101 +138,101 @@ function getQueryForAnalysisType(type) {
|
||||
|
||||
function generateAgentPrompt(type, scope) {
|
||||
const prompts = {
|
||||
structure: `分析以下路径的代码结构:
|
||||
${scope.paths.map(p => `- ${p}`).join('\\n')}
|
||||
structure: \`Analyze code structure of the following paths:
|
||||
\${scope.paths.map(p => \`- \${p}\`).join('\\n')}
|
||||
|
||||
任务:
|
||||
1. 识别主要模块和入口点
|
||||
2. 分析目录组织结构
|
||||
3. 提取模块间的导入导出关系
|
||||
4. 生成结构概览图 (Mermaid)
|
||||
Tasks:
|
||||
1. Identify main modules and entry points
|
||||
2. Analyze directory organization structure
|
||||
3. Extract module import/export relationships
|
||||
4. Generate structure overview diagram (Mermaid)
|
||||
|
||||
输出格式: JSON
|
||||
Output format: JSON
|
||||
{
|
||||
"modules": [...],
|
||||
"entry_points": [...],
|
||||
"structure_diagram": "mermaid code"
|
||||
}`,
|
||||
}\`,
|
||||
|
||||
patterns: `分析以下路径的设计模式:
|
||||
${scope.paths.map(p => `- ${p}`).join('\\n')}
|
||||
patterns: \`Analyze design patterns in the following paths:
|
||||
\${scope.paths.map(p => \`- \${p}\`).join('\\n')}
|
||||
|
||||
任务:
|
||||
1. 识别使用的设计模式 (Factory, Strategy, Observer 等)
|
||||
2. 分析抽象层级
|
||||
3. 评估模式使用的恰当性
|
||||
4. 提取可复用的模式实例
|
||||
Tasks:
|
||||
1. Identify design patterns used (Factory, Strategy, Observer, etc.)
|
||||
2. Analyze abstraction levels
|
||||
3. Evaluate appropriateness of pattern usage
|
||||
4. Extract reusable pattern instances
|
||||
|
||||
输出格式: JSON
|
||||
Output format: JSON
|
||||
{
|
||||
"patterns": [{ "name": "...", "location": "...", "usage": "..." }],
|
||||
"abstractions": [...],
|
||||
"reusable_components": [...]
|
||||
}`,
|
||||
}\`,
|
||||
|
||||
dependencies: `分析以下路径的依赖关系:
|
||||
${scope.paths.map(p => `- ${p}`).join('\\n')}
|
||||
dependencies: \`Analyze dependencies in the following paths:
|
||||
\${scope.paths.map(p => \`- \${p}\`).join('\\n')}
|
||||
|
||||
任务:
|
||||
1. 提取内部模块依赖
|
||||
2. 识别外部包依赖
|
||||
3. 分析耦合度
|
||||
4. 检测循环依赖
|
||||
Tasks:
|
||||
1. Extract internal module dependencies
|
||||
2. Identify external package dependencies
|
||||
3. Analyze coupling degree
|
||||
4. Detect circular dependencies
|
||||
|
||||
输出格式: JSON
|
||||
Output format: JSON
|
||||
{
|
||||
"internal_deps": [...],
|
||||
"external_deps": [...],
|
||||
"coupling_score": 0-100,
|
||||
"circular_deps": [...]
|
||||
}`,
|
||||
}\`,
|
||||
|
||||
quality: `分析以下路径的代码质量:
|
||||
${scope.paths.map(p => `- ${p}`).join('\\n')}
|
||||
quality: \`Analyze code quality in the following paths:
|
||||
\${scope.paths.map(p => \`- \${p}\`).join('\\n')}
|
||||
|
||||
任务:
|
||||
1. 评估代码复杂度
|
||||
2. 检查测试覆盖率
|
||||
3. 分析文档完整性
|
||||
4. 识别技术债务
|
||||
Tasks:
|
||||
1. Assess code complexity
|
||||
2. Check test coverage
|
||||
3. Analyze documentation completeness
|
||||
4. Identify technical debt
|
||||
|
||||
输出格式: JSON
|
||||
Output format: JSON
|
||||
{
|
||||
"complexity": { "avg": 0, "max": 0, "hotspots": [...] },
|
||||
"test_coverage": { "percentage": 0, "gaps": [...] },
|
||||
"documentation": { "score": 0, "missing": [...] },
|
||||
"tech_debt": [...]
|
||||
}`,
|
||||
}\`,
|
||||
|
||||
security: `分析以下路径的安全性:
|
||||
${scope.paths.map(p => `- ${p}`).join('\\n')}
|
||||
security: \`Analyze security in the following paths:
|
||||
\${scope.paths.map(p => \`- \${p}\`).join('\\n')}
|
||||
|
||||
任务:
|
||||
1. 检查认证授权实现
|
||||
2. 分析输入验证
|
||||
3. 检测敏感数据处理
|
||||
4. 识别常见漏洞模式
|
||||
Tasks:
|
||||
1. Check authentication/authorization implementation
|
||||
2. Analyze input validation
|
||||
3. Detect sensitive data handling
|
||||
4. Identify common vulnerability patterns
|
||||
|
||||
输出格式: JSON
|
||||
Output format: JSON
|
||||
{
|
||||
"auth": { "methods": [...], "issues": [...] },
|
||||
"input_validation": { "coverage": 0, "gaps": [...] },
|
||||
"sensitive_data": { "found": [...], "protected": true/false },
|
||||
"vulnerabilities": [{ "type": "...", "severity": "...", "location": "..." }]
|
||||
}`
|
||||
}\`
|
||||
};
|
||||
|
||||
return prompts[type] || prompts.structure;
|
||||
}
|
||||
```
|
||||
\`\`\`
|
||||
|
||||
---
|
||||
|
||||
## 预置代码分析动作
|
||||
## Preset Code Analysis Actions
|
||||
|
||||
### 1. 项目结构分析
|
||||
### 1. Project Structure Analysis
|
||||
|
||||
```yaml
|
||||
\`\`\`yaml
|
||||
id: analyze-project-structure
|
||||
name: Project Structure Analysis
|
||||
type: code-analysis
|
||||
@@ -255,11 +254,11 @@ output:
|
||||
file: structure-analysis.json
|
||||
mcp_tools:
|
||||
- mcp__ace-tool__search_context
|
||||
```
|
||||
\`\`\`
|
||||
|
||||
### 2. 设计模式提取
|
||||
### 2. Design Pattern Extraction
|
||||
|
||||
```yaml
|
||||
\`\`\`yaml
|
||||
id: extract-design-patterns
|
||||
name: Design Pattern Extraction
|
||||
type: code-analysis
|
||||
@@ -275,11 +274,11 @@ agent:
|
||||
output:
|
||||
format: markdown
|
||||
file: patterns-report.md
|
||||
```
|
||||
\`\`\`
|
||||
|
||||
### 3. 依赖关系分析
|
||||
### 3. Dependency Analysis
|
||||
|
||||
```yaml
|
||||
\`\`\`yaml
|
||||
id: analyze-dependencies
|
||||
name: Dependency Analysis
|
||||
type: code-analysis
|
||||
@@ -297,11 +296,11 @@ agent:
|
||||
output:
|
||||
format: json
|
||||
file: dependency-graph.json
|
||||
```
|
||||
\`\`\`
|
||||
|
||||
### 4. 安全审计
|
||||
### 4. Security Audit
|
||||
|
||||
```yaml
|
||||
\`\`\`yaml
|
||||
id: security-audit
|
||||
name: Security Audit
|
||||
type: code-analysis
|
||||
@@ -320,15 +319,15 @@ output:
|
||||
file: security-report.json
|
||||
mcp_tools:
|
||||
- mcp__ace-tool__search_context
|
||||
```
|
||||
\`\`\`
|
||||
|
||||
---
|
||||
|
||||
## 使用示例
|
||||
## Usage Examples
|
||||
|
||||
### 在 Phase 中使用
|
||||
### Using in Phase
|
||||
|
||||
```javascript
|
||||
\`\`\`javascript
|
||||
// phases/01-code-exploration.md
|
||||
|
||||
const analysisConfig = {
|
||||
@@ -351,14 +350,14 @@ const analysisConfig = {
|
||||
}
|
||||
};
|
||||
|
||||
// 执行
|
||||
// Execute
|
||||
const result = await executeCodeAnalysis(analysisConfig, context);
|
||||
```
|
||||
\`\`\`
|
||||
|
||||
### 组合多种分析
|
||||
### Combining Multiple Analyses
|
||||
|
||||
```javascript
|
||||
// 串行执行多种分析
|
||||
\`\`\`javascript
|
||||
// Serial execution of multiple analyses
|
||||
const analyses = [
|
||||
{ type: 'structure', file: 'structure.json' },
|
||||
{ type: 'patterns', file: 'patterns.json' },
|
||||
@@ -373,7 +372,7 @@ for (const analysis of analyses) {
|
||||
}, context);
|
||||
}
|
||||
|
||||
// 并行执行(独立分析)
|
||||
// Parallel execution (independent analyses)
|
||||
const parallelResults = await Promise.all(
|
||||
analyses.map(a => executeCodeAnalysis({
|
||||
...baseConfig,
|
||||
@@ -381,51 +380,51 @@ const parallelResults = await Promise.all(
|
||||
output: { format: 'json', file: a.file }
|
||||
}, context))
|
||||
);
|
||||
```
|
||||
\`\`\`
|
||||
|
||||
---
|
||||
|
||||
## Agent 选择指南
|
||||
## Agent Selection Guide
|
||||
|
||||
| 分析类型 | 推荐 Agent | Thoroughness | 原因 |
|
||||
|---------|-----------|--------------|------|
|
||||
| structure | Explore | medium | 快速获取目录结构 |
|
||||
| patterns | cli-explore-agent | very thorough | 需要深度代码理解 |
|
||||
| dependencies | Explore | medium | 主要分析 import 语句 |
|
||||
| quality | universal-executor | medium | 需要运行分析工具 |
|
||||
| security | universal-executor | very thorough | 需要全面扫描 |
|
||||
| Analysis Type | Recommended Agent | Thoroughness | Reason |
|
||||
|-------------|-----------------|--------------|--------|
|
||||
| structure | Explore | medium | Quick directory structure retrieval |
|
||||
| patterns | cli-explore-agent | very thorough | Requires deep code understanding |
|
||||
| dependencies | Explore | medium | Mainly analyzes import statements |
|
||||
| quality | universal-executor | medium | Requires running analysis tools |
|
||||
| security | universal-executor | very thorough | Requires comprehensive scanning |
|
||||
|
||||
---
|
||||
|
||||
## MCP 工具集成
|
||||
## MCP Tool Integration
|
||||
|
||||
### 语义搜索增强
|
||||
### Semantic Search Enhancement
|
||||
|
||||
```javascript
|
||||
// 使用 ACE 工具进行语义搜索
|
||||
\`\`\`javascript
|
||||
// Use ACE tool for semantic search
|
||||
const semanticContext = await mcp__ace_tool__search_context({
|
||||
project_root_path: projectRoot,
|
||||
query: 'authentication logic, user session management'
|
||||
});
|
||||
|
||||
// 将语义搜索结果作为 Agent 的输入上下文
|
||||
// Use semantic search results as Agent input context
|
||||
const agentResult = await Task({
|
||||
subagent_type: 'Explore',
|
||||
prompt: `
|
||||
基于以下语义搜索结果进行深度分析:
|
||||
prompt: \`
|
||||
Based on following semantic search results, perform in-depth analysis:
|
||||
|
||||
${semanticContext}
|
||||
\${semanticContext}
|
||||
|
||||
任务: 分析认证逻辑的实现细节...
|
||||
`,
|
||||
Task: Analyze authentication logic implementation details...
|
||||
\`,
|
||||
run_in_background: false
|
||||
});
|
||||
```
|
||||
\`\`\`
|
||||
|
||||
### smart_search 集成
|
||||
### smart_search Integration
|
||||
|
||||
```javascript
|
||||
// 使用 smart_search 进行精确搜索
|
||||
\`\`\`javascript
|
||||
// Use smart_search for exact matching
|
||||
const exactMatches = await mcp__ccw_tools__smart_search({
|
||||
action: 'search',
|
||||
query: 'class.*Controller',
|
||||
@@ -433,19 +432,19 @@ const exactMatches = await mcp__ccw_tools__smart_search({
|
||||
path: 'src/'
|
||||
});
|
||||
|
||||
// 使用 find_files 发现文件
|
||||
// Use find_files for file discovery
|
||||
const configFiles = await mcp__ccw_tools__smart_search({
|
||||
action: 'find_files',
|
||||
pattern: '**/*.config.ts',
|
||||
path: 'src/'
|
||||
});
|
||||
```
|
||||
\`\`\`
|
||||
|
||||
---
|
||||
|
||||
## 结果聚合
|
||||
## Results Aggregation
|
||||
|
||||
```javascript
|
||||
\`\`\`javascript
|
||||
function aggregateResults(results) {
|
||||
const aggregated = {
|
||||
timestamp: new Date().toISOString(),
|
||||
@@ -478,38 +477,38 @@ function aggregateResults(results) {
|
||||
}
|
||||
|
||||
function extractKeyFindings(agentResult) {
|
||||
// 从 Agent 结果中提取关键发现
|
||||
// 实现取决于 Agent 的输出格式
|
||||
// Extract key findings from Agent result
|
||||
// Implementation depends on Agent output format
|
||||
return {
|
||||
modules: agentResult.modules?.length || 0,
|
||||
patterns: agentResult.patterns?.length || 0,
|
||||
issues: agentResult.issues?.length || 0
|
||||
};
|
||||
}
|
||||
```
|
||||
\`\`\`
|
||||
|
||||
---
|
||||
|
||||
## 最佳实践
|
||||
## Best Practices
|
||||
|
||||
1. **范围控制**
|
||||
- 使用精确的 patterns 减少分析范围
|
||||
- 配置 excludes 排除无关文件
|
||||
1. **Scope Control**
|
||||
- Use precise patterns to reduce analysis scope
|
||||
- Configure excludes to ignore irrelevant files
|
||||
|
||||
2. **Agent 选择**
|
||||
- 快速探索用 Explore
|
||||
- 深度分析用 cli-explore-agent
|
||||
- 需要执行操作用 universal-executor
|
||||
2. **Agent Selection**
|
||||
- Use Explore for quick exploration
|
||||
- Use cli-explore-agent for in-depth analysis
|
||||
- Use universal-executor when execution is required
|
||||
|
||||
3. **MCP 工具组合**
|
||||
- 先用 mcp__ace-tool__search_context 获取语义上下文
|
||||
- 再用 Agent 进行深度分析
|
||||
- 最后用 smart_search 补充精确匹配
|
||||
3. **MCP Tool Combination**
|
||||
- First use mcp__ace-tool__search_context for semantic context
|
||||
- Then use Agent for in-depth analysis
|
||||
- Finally use smart_search for exact matching
|
||||
|
||||
4. **结果缓存**
|
||||
- 将分析结果持久化到 workDir
|
||||
- 后续阶段可直接读取,避免重复分析
|
||||
4. **Result Caching**
|
||||
- Persist analysis results to workDir
|
||||
- Subsequent phases can read directly, avoiding re-analysis
|
||||
|
||||
5. **Brief Returns**
|
||||
- Agent 返回路径 + 摘要,而非完整内容
|
||||
- 避免上下文溢出
|
||||
- Agent returns path + summary, not full content
|
||||
- Prevents context overflow
|
||||
|
||||
@@ -1,56 +1,56 @@
|
||||
# LLM Action Template
|
||||
|
||||
LLM 动作模板,用于在 Skill 中集成 LLM 调用能力。
|
||||
LLM action template for integrating LLM call capabilities into a Skill.
|
||||
|
||||
## Purpose
|
||||
|
||||
为 Skill 生成 LLM 动作,通过 CCW CLI 统一接口调用 Gemini/Qwen/Codex 进行分析或生成。
|
||||
Generate LLM actions for a Skill, call Gemini/Qwen/Codex through CCW CLI unified interface for analysis or generation.
|
||||
|
||||
## Usage Context
|
||||
|
||||
| Phase | Usage |
|
||||
|-------|-------|
|
||||
| Optional | 当 Skill 需要 LLM 能力时使用 |
|
||||
| Generation Trigger | 用户选择添加 llm 动作类型 |
|
||||
| Tools | gemini, qwen, codex (支持 fallback chain) |
|
||||
| Optional | Use when Skill requires LLM capabilities |
|
||||
| Generation Trigger | User selects to add llm action type |
|
||||
| Tools | gemini, qwen, codex (supports fallback chain) |
|
||||
|
||||
---
|
||||
|
||||
## 配置结构
|
||||
## Configuration Structure
|
||||
|
||||
```typescript
|
||||
interface LLMActionConfig {
|
||||
id: string; // "llm-analyze", "llm-generate"
|
||||
name: string; // "LLM Analysis"
|
||||
type: 'llm'; // 动作类型标识
|
||||
type: 'llm'; // Action type identifier
|
||||
|
||||
// LLM 工具配置
|
||||
// LLM tool config
|
||||
tool: {
|
||||
primary: 'gemini' | 'qwen' | 'codex';
|
||||
fallback_chain: string[]; // ['gemini', 'qwen', 'codex']
|
||||
};
|
||||
|
||||
// 执行模式
|
||||
// Execution mode
|
||||
mode: 'analysis' | 'write';
|
||||
|
||||
// 提示词配置
|
||||
// Prompt config
|
||||
prompt: {
|
||||
template: string; // 提示词模板路径或内联
|
||||
variables: string[]; // 需要替换的变量
|
||||
template: string; // Prompt template path or inline
|
||||
variables: string[]; // Variables to replace
|
||||
};
|
||||
|
||||
// 输入输出
|
||||
input: string[]; // 依赖的上下文文件
|
||||
output: string; // 输出文件路径
|
||||
// Input/Output
|
||||
input: string[]; // Dependent context files
|
||||
output: string; // Output file path
|
||||
|
||||
// 超时配置
|
||||
timeout?: number; // 毫秒,默认 600000 (10min)
|
||||
// Timeout config
|
||||
timeout?: number; // Milliseconds, default 600000 (10min)
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 模板生成函数
|
||||
## Template Generation Function
|
||||
|
||||
```javascript
|
||||
function generateLLMAction(config) {
|
||||
@@ -61,25 +61,25 @@ function generateLLMAction(config) {
|
||||
|
||||
## Action: ${id}
|
||||
|
||||
### 执行逻辑
|
||||
### Execution Logic
|
||||
|
||||
\`\`\`javascript
|
||||
async function execute${toPascalCase(id)}(context) {
|
||||
const workDir = context.workDir;
|
||||
const state = context.state;
|
||||
|
||||
// 1. 收集输入上下文
|
||||
// 1. Collect input context
|
||||
const inputContext = ${JSON.stringify(input)}.map(f => {
|
||||
const path = \`\${workDir}/\${f}\`;
|
||||
return Read(path);
|
||||
}).join('\\n\\n---\\n\\n');
|
||||
|
||||
// 2. 构建提示词
|
||||
// 2. Build prompt
|
||||
const promptTemplate = \`${prompt.template}\`;
|
||||
const finalPrompt = promptTemplate
|
||||
${prompt.variables.map(v => `.replace('{{${v}}}', context.${v} || '')`).join('\n ')};
|
||||
|
||||
// 3. 执行 LLM 调用 (带 fallback)
|
||||
// 3. Execute LLM call (with fallback)
|
||||
const tools = ['${tool.primary}', ${tool.fallback_chain.map(t => `'${t}'`).join(', ')}];
|
||||
let result = null;
|
||||
let usedTool = null;
|
||||
@@ -98,10 +98,10 @@ async function execute${toPascalCase(id)}(context) {
|
||||
throw new Error('All LLM tools failed');
|
||||
}
|
||||
|
||||
// 4. 保存结果
|
||||
// 4. Save result
|
||||
Write(\`\${workDir}/${output}\`, result);
|
||||
|
||||
// 5. 更新状态
|
||||
// 5. Update state
|
||||
state.llm_calls = (state.llm_calls || 0) + 1;
|
||||
state.last_llm_tool = usedTool;
|
||||
|
||||
@@ -112,38 +112,38 @@ async function execute${toPascalCase(id)}(context) {
|
||||
};
|
||||
}
|
||||
|
||||
// LLM 调用封装
|
||||
// LLM call wrapper
|
||||
async function callLLM(tool, prompt, mode, timeout) {
|
||||
const modeFlag = mode === 'write' ? '--mode write' : '--mode analysis';
|
||||
|
||||
// 使用 CCW CLI 统一接口
|
||||
// Use CCW CLI unified interface
|
||||
const command = \`ccw cli -p "\${escapePrompt(prompt)}" --tool \${tool} \${modeFlag}\`;
|
||||
|
||||
const result = Bash({
|
||||
command,
|
||||
timeout,
|
||||
run_in_background: true // 异步执行
|
||||
run_in_background: true // Async execution
|
||||
});
|
||||
|
||||
// 等待完成
|
||||
// Wait for completion
|
||||
return await waitForResult(result.task_id, timeout);
|
||||
}
|
||||
|
||||
function escapePrompt(prompt) {
|
||||
// 转义双引号和特殊字符
|
||||
// Escape double quotes and special characters
|
||||
return prompt.replace(/"/g, '\\\\"').replace(/\$/g, '\\\\$');
|
||||
}
|
||||
\`\`\`
|
||||
|
||||
### Prompt 模板
|
||||
### Prompt Template
|
||||
|
||||
\`\`\`
|
||||
${prompt.template}
|
||||
\`\`\`
|
||||
|
||||
### 变量说明
|
||||
### Variable Descriptions
|
||||
|
||||
${prompt.variables.map(v => `- \`{{${v}}}\`: ${v} 变量`).join('\n')}
|
||||
${prompt.variables.map(v => `- \`{{${v}}}\`: ${v} variable`).join('\n')}
|
||||
`;
|
||||
}
|
||||
|
||||
@@ -154,11 +154,11 @@ function toPascalCase(str) {
|
||||
|
||||
---
|
||||
|
||||
## 预置 LLM 动作模板
|
||||
## Preset LLM Action Templates
|
||||
|
||||
### 1. 代码分析动作
|
||||
### 1. Code Analysis Action
|
||||
|
||||
```yaml
|
||||
\`\`\`yaml
|
||||
id: llm-code-analysis
|
||||
name: LLM Code Analysis
|
||||
type: llm
|
||||
@@ -168,15 +168,15 @@ tool:
|
||||
mode: analysis
|
||||
prompt:
|
||||
template: |
|
||||
PURPOSE: 分析代码结构和模式,提取关键设计特征
|
||||
PURPOSE: Analyze code structure and patterns, extract key design features
|
||||
TASK:
|
||||
• 识别主要模块和组件
|
||||
• 分析依赖关系
|
||||
• 提取设计模式
|
||||
• 评估代码质量
|
||||
• Identify main modules and components
|
||||
• Analyze dependencies
|
||||
• Extract design patterns
|
||||
• Evaluate code quality
|
||||
MODE: analysis
|
||||
CONTEXT: {{code_context}}
|
||||
EXPECTED: JSON 格式的分析报告,包含 modules, dependencies, patterns, quality_score
|
||||
EXPECTED: JSON formatted analysis report with modules, dependencies, patterns, quality_score
|
||||
RULES: $(cat ~/.claude/workflows/cli-templates/protocols/analysis-protocol.md)
|
||||
variables:
|
||||
- code_context
|
||||
@@ -184,11 +184,11 @@ input:
|
||||
- collected-code.md
|
||||
output: analysis-report.json
|
||||
timeout: 900000
|
||||
```
|
||||
\`\`\`
|
||||
|
||||
### 2. 文档生成动作
|
||||
### 2. Documentation Generation Action
|
||||
|
||||
```yaml
|
||||
\`\`\`yaml
|
||||
id: llm-doc-generation
|
||||
name: LLM Documentation Generation
|
||||
type: llm
|
||||
@@ -198,15 +198,15 @@ tool:
|
||||
mode: write
|
||||
prompt:
|
||||
template: |
|
||||
PURPOSE: 根据分析结果生成高质量文档
|
||||
PURPOSE: Generate high-quality documentation based on analysis results
|
||||
TASK:
|
||||
• 基于分析报告生成文档大纲
|
||||
• 填充各章节内容
|
||||
• 添加代码示例和说明
|
||||
• 生成 Mermaid 图表
|
||||
• Generate documentation outline based on analysis report
|
||||
• Populate chapter content
|
||||
• Add code examples and explanations
|
||||
• Generate Mermaid diagrams
|
||||
MODE: write
|
||||
CONTEXT: {{analysis_report}}
|
||||
EXPECTED: 完整的 Markdown 文档,包含目录、章节、图表
|
||||
EXPECTED: Complete Markdown documentation with table of contents, chapters, diagrams
|
||||
RULES: $(cat ~/.claude/workflows/cli-templates/protocols/write-protocol.md)
|
||||
variables:
|
||||
- analysis_report
|
||||
@@ -214,11 +214,11 @@ input:
|
||||
- analysis-report.json
|
||||
output: generated-doc.md
|
||||
timeout: 1200000
|
||||
```
|
||||
\`\`\`
|
||||
|
||||
### 3. 代码重构建议动作
|
||||
### 3. Code Refactoring Suggestions Action
|
||||
|
||||
```yaml
|
||||
\`\`\`yaml
|
||||
id: llm-refactor-suggest
|
||||
name: LLM Refactoring Suggestions
|
||||
type: llm
|
||||
@@ -228,15 +228,15 @@ tool:
|
||||
mode: analysis
|
||||
prompt:
|
||||
template: |
|
||||
PURPOSE: 分析代码并提供重构建议
|
||||
PURPOSE: Analyze code and provide refactoring suggestions
|
||||
TASK:
|
||||
• 识别代码异味 (code smells)
|
||||
• 评估复杂度热点
|
||||
• 提出具体重构方案
|
||||
• 估算重构影响范围
|
||||
• Identify code smells
|
||||
• Evaluate complexity hotspots
|
||||
• Propose specific refactoring plans
|
||||
• Estimate refactoring impact scope
|
||||
MODE: analysis
|
||||
CONTEXT: {{source_code}}
|
||||
EXPECTED: 重构建议列表,每项包含 location, issue, suggestion, impact
|
||||
EXPECTED: List of refactoring suggestions with location, issue, suggestion, impact fields
|
||||
RULES: $(cat ~/.claude/workflows/cli-templates/protocols/analysis-protocol.md)
|
||||
variables:
|
||||
- source_code
|
||||
@@ -244,15 +244,15 @@ input:
|
||||
- source-files.md
|
||||
output: refactor-suggestions.json
|
||||
timeout: 600000
|
||||
```
|
||||
\`\`\`
|
||||
|
||||
---
|
||||
|
||||
## 使用示例
|
||||
## Usage Examples
|
||||
|
||||
### 在 Phase 中使用 LLM 动作
|
||||
### Using LLM Actions in Phase
|
||||
|
||||
```javascript
|
||||
\`\`\`javascript
|
||||
// phases/02-llm-analysis.md
|
||||
|
||||
const llmConfig = {
|
||||
@@ -265,39 +265,39 @@ const llmConfig = {
|
||||
},
|
||||
mode: 'analysis',
|
||||
prompt: {
|
||||
template: `
|
||||
PURPOSE: 分析现有 Skill 的设计模式
|
||||
template: \`
|
||||
PURPOSE: Analyze design patterns of existing Skills
|
||||
TASK:
|
||||
• 提取 Skill 结构规范
|
||||
• 识别 Phase 组织模式
|
||||
• 分析 Agent 调用模式
|
||||
• Extract Skill structure specification
|
||||
• Identify Phase organization patterns
|
||||
• Analyze Agent invocation patterns
|
||||
MODE: analysis
|
||||
CONTEXT: {{skill_source}}
|
||||
EXPECTED: 结构化的设计模式分析
|
||||
`,
|
||||
EXPECTED: Structured design pattern analysis
|
||||
\`,
|
||||
variables: ['skill_source']
|
||||
},
|
||||
input: ['collected-skills.md'],
|
||||
output: 'skill-patterns.json'
|
||||
};
|
||||
|
||||
// 执行
|
||||
// Execute
|
||||
const result = await executeLLMAction(llmConfig, {
|
||||
workDir: '.workflow/.scratchpad/skill-gen-xxx',
|
||||
skill_source: Read('.workflow/.scratchpad/skill-gen-xxx/collected-skills.md')
|
||||
});
|
||||
```
|
||||
\`\`\`
|
||||
|
||||
### 在 Orchestrator 中调度 LLM 动作
|
||||
### Scheduling LLM Actions in Orchestrator
|
||||
|
||||
```javascript
|
||||
// autonomous-orchestrator 中的 LLM 动作调度
|
||||
\`\`\`javascript
|
||||
// Schedule LLM actions in autonomous-orchestrator
|
||||
|
||||
const actions = [
|
||||
{ type: 'collect', priority: 100 },
|
||||
{ type: 'llm', id: 'llm-analyze', priority: 90 }, // LLM 分析
|
||||
{ type: 'llm', id: 'llm-analyze', priority: 90 }, // LLM analysis
|
||||
{ type: 'process', priority: 80 },
|
||||
{ type: 'llm', id: 'llm-generate', priority: 70 }, // LLM 生成
|
||||
{ type: 'llm', id: 'llm-generate', priority: 70 }, // LLM generation
|
||||
{ type: 'validate', priority: 60 }
|
||||
];
|
||||
|
||||
@@ -310,13 +310,13 @@ for (const action of sortByPriority(actions)) {
|
||||
context.state[action.id] = llmResult;
|
||||
}
|
||||
}
|
||||
```
|
||||
\`\`\`
|
||||
|
||||
---
|
||||
|
||||
## 错误处理
|
||||
## Error Handling
|
||||
|
||||
```javascript
|
||||
\`\`\`javascript
|
||||
async function executeLLMActionWithRetry(config, context, maxRetries = 3) {
|
||||
let lastError = null;
|
||||
|
||||
@@ -325,43 +325,43 @@ async function executeLLMActionWithRetry(config, context, maxRetries = 3) {
|
||||
return await executeLLMAction(config, context);
|
||||
} catch (error) {
|
||||
lastError = error;
|
||||
console.log(`Attempt ${attempt} failed: ${error.message}`);
|
||||
console.log(\`Attempt ${attempt} failed: ${error.message}\`);
|
||||
|
||||
// 指数退避
|
||||
// Exponential backoff
|
||||
if (attempt < maxRetries) {
|
||||
await sleep(Math.pow(2, attempt) * 1000);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 所有重试失败
|
||||
// All retries failed
|
||||
return {
|
||||
success: false,
|
||||
error: lastError.message,
|
||||
fallback: 'manual_review_required'
|
||||
};
|
||||
}
|
||||
```
|
||||
\`\`\`
|
||||
|
||||
---
|
||||
|
||||
## 最佳实践
|
||||
## Best Practices
|
||||
|
||||
1. **选择合适的工具**
|
||||
- 分析任务:Gemini(大上下文)> Qwen
|
||||
- 生成任务:Codex(自主执行)> Gemini > Qwen
|
||||
- 代码修改:Codex > Gemini
|
||||
1. **Select Appropriate Tool**
|
||||
- Analysis tasks: Gemini (large context) > Qwen
|
||||
- Generation tasks: Codex (autonomous execution) > Gemini > Qwen
|
||||
- Code modification: Codex > Gemini
|
||||
|
||||
2. **配置 Fallback Chain**
|
||||
- 总是配置至少一个 fallback
|
||||
- 考虑工具特性选择 fallback 顺序
|
||||
2. **Configure Fallback Chain**
|
||||
- Always configure at least one fallback
|
||||
- Consider tool characteristics when ordering fallbacks
|
||||
|
||||
3. **超时设置**
|
||||
- 分析任务:10-15 分钟
|
||||
- 生成任务:15-20 分钟
|
||||
- 复杂任务:20-60 分钟
|
||||
3. **Timeout Settings**
|
||||
- Analysis tasks: 10-15 minutes
|
||||
- Generation tasks: 15-20 minutes
|
||||
- Complex tasks: 20-60 minutes
|
||||
|
||||
4. **提示词设计**
|
||||
- 使用 PURPOSE/TASK/MODE/CONTEXT/EXPECTED/RULES 结构
|
||||
- 引用标准协议模板
|
||||
- 明确输出格式要求
|
||||
4. **Prompt Design**
|
||||
- Use PURPOSE/TASK/MODE/CONTEXT/EXPECTED/RULES structure
|
||||
- Reference standard protocol templates
|
||||
- Clearly specify output format requirements
|
||||
|
||||
@@ -1,56 +1,56 @@
|
||||
# Script Template
|
||||
|
||||
统一的脚本模板,覆盖 Bash 和 Python 两种运行时。
|
||||
Unified script template covering both Bash and Python runtimes.
|
||||
|
||||
## Usage Context
|
||||
|
||||
| Phase | Usage |
|
||||
|-------|-------|
|
||||
| Optional | Phase/Action 中声明 `## Scripts` 时使用 |
|
||||
| Execution | 通过 `ExecuteScript('script-id', params)` 调用 |
|
||||
| Optional | Use when declaring `## Scripts` in Phase/Action |
|
||||
| Execution | Invoke via `ExecuteScript('script-id', params)` |
|
||||
| Output Location | `.claude/skills/{skill-name}/scripts/{script-id}.{ext}` |
|
||||
|
||||
---
|
||||
|
||||
## 调用接口规范
|
||||
## Invocation Interface Specification
|
||||
|
||||
所有脚本共享相同的调用约定:
|
||||
All scripts share the same calling convention:
|
||||
|
||||
```
|
||||
调用者
|
||||
↓ ExecuteScript('script-id', { key: value })
|
||||
↓
|
||||
脚本入口
|
||||
├─ 参数解析 (--key value)
|
||||
├─ 输入验证 (必需参数检查, 文件存在)
|
||||
├─ 核心处理 (数据读取 → 转换 → 写入)
|
||||
└─ 输出结果 (最后一行: 单行 JSON → stdout)
|
||||
├─ 成功: {"status":"success", "output_file":"...", ...}
|
||||
└─ 失败: stderr 输出错误信息, exit 1
|
||||
Caller
|
||||
| ExecuteScript('script-id', { key: value })
|
||||
|
|
||||
Script Entry
|
||||
├─ Parameter parsing (--key value)
|
||||
├─ Input validation (required parameter checks, file exists)
|
||||
├─ Core processing (data read -> transform -> write)
|
||||
└─ Output result (last line: single-line JSON -> stdout)
|
||||
├─ Success: {"status":"success", "output_file":"...", ...}
|
||||
└─ Failure: stderr output error message, exit 1
|
||||
```
|
||||
|
||||
### 返回格式
|
||||
### Return Format
|
||||
|
||||
```typescript
|
||||
interface ScriptResult {
|
||||
success: boolean; // exit code === 0
|
||||
stdout: string; // 标准输出
|
||||
stderr: string; // 标准错误
|
||||
outputs: object; // 从 stdout 最后一行解析的 JSON
|
||||
stdout: string; // Standard output
|
||||
stderr: string; // Standard error
|
||||
outputs: object; // JSON output parsed from stdout last line
|
||||
}
|
||||
```
|
||||
|
||||
### 参数约定
|
||||
### Parameter Convention
|
||||
|
||||
| 参数 | 必需 | 说明 |
|
||||
|------|------|------|
|
||||
| `--input-path` | ✓ | 输入文件路径 |
|
||||
| `--output-dir` | ✓ | 输出目录(由调用方指定) |
|
||||
| 其他 | 按需 | 脚本特定参数 |
|
||||
| Parameter | Required | Description |
|
||||
|-----------|----------|-------------|
|
||||
| `--input-path` | Yes | Input file path |
|
||||
| `--output-dir` | Yes | Output directory (specified by caller) |
|
||||
| Others | Optional | Script-specific parameters |
|
||||
|
||||
---
|
||||
|
||||
## Bash 实现
|
||||
## Bash Implementation
|
||||
|
||||
```bash
|
||||
#!/bin/bash
|
||||
@@ -59,7 +59,7 @@ interface ScriptResult {
|
||||
set -euo pipefail
|
||||
|
||||
# ============================================================
|
||||
# 参数解析
|
||||
# Parameter Parsing
|
||||
# ============================================================
|
||||
|
||||
INPUT_PATH=""
|
||||
@@ -70,11 +70,11 @@ while [[ "$#" -gt 0 ]]; do
|
||||
--input-path) INPUT_PATH="$2"; shift ;;
|
||||
--output-dir) OUTPUT_DIR="$2"; shift ;;
|
||||
--help)
|
||||
echo "用法: $0 --input-path <path> --output-dir <dir>"
|
||||
echo "Usage: $0 --input-path <path> --output-dir <dir>"
|
||||
exit 0
|
||||
;;
|
||||
*)
|
||||
echo "错误: 未知参数 $1" >&2
|
||||
echo "Error: Unknown parameter $1" >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
@@ -82,31 +82,31 @@ while [[ "$#" -gt 0 ]]; do
|
||||
done
|
||||
|
||||
# ============================================================
|
||||
# 参数验证
|
||||
# Parameter Validation
|
||||
# ============================================================
|
||||
|
||||
[[ -z "$INPUT_PATH" ]] && { echo "错误: --input-path 是必需参数" >&2; exit 1; }
|
||||
[[ -z "$OUTPUT_DIR" ]] && { echo "错误: --output-dir 是必需参数" >&2; exit 1; }
|
||||
[[ ! -f "$INPUT_PATH" ]] && { echo "错误: 输入文件不存在: $INPUT_PATH" >&2; exit 1; }
|
||||
command -v jq &> /dev/null || { echo "错误: 需要安装 jq" >&2; exit 1; }
|
||||
[[ -z "$INPUT_PATH" ]] && { echo "Error: --input-path is required parameter" >&2; exit 1; }
|
||||
[[ -z "$OUTPUT_DIR" ]] && { echo "Error: --output-dir is required parameter" >&2; exit 1; }
|
||||
[[ ! -f "$INPUT_PATH" ]] && { echo "Error: Input file does not exist: $INPUT_PATH" >&2; exit 1; }
|
||||
command -v jq &> /dev/null || { echo "Error: jq is required" >&2; exit 1; }
|
||||
|
||||
mkdir -p "$OUTPUT_DIR"
|
||||
|
||||
# ============================================================
|
||||
# 核心逻辑
|
||||
# Core Logic
|
||||
# ============================================================
|
||||
|
||||
OUTPUT_FILE="$OUTPUT_DIR/result.txt"
|
||||
ITEMS_COUNT=0
|
||||
|
||||
# TODO: 实现处理逻辑
|
||||
# TODO: Implement processing logic
|
||||
while IFS= read -r line; do
|
||||
echo "$line" >> "$OUTPUT_FILE"
|
||||
((ITEMS_COUNT++))
|
||||
done < "$INPUT_PATH"
|
||||
|
||||
# ============================================================
|
||||
# 输出 JSON 结果(使用 jq 构建,避免转义问题)
|
||||
# Output JSON Result (use jq to build, avoid escaping issues)
|
||||
# ============================================================
|
||||
|
||||
jq -n \
|
||||
@@ -115,34 +115,34 @@ jq -n \
|
||||
'{output_file: $output_file, items_processed: $items_processed, status: "success"}'
|
||||
```
|
||||
|
||||
### Bash 常用模式
|
||||
### Bash Common Patterns
|
||||
|
||||
```bash
|
||||
# 文件遍历
|
||||
# File iteration
|
||||
for file in "$INPUT_DIR"/*.json; do
|
||||
[[ -f "$file" ]] || continue
|
||||
# 处理逻辑...
|
||||
# Processing logic...
|
||||
done
|
||||
|
||||
# 临时文件 (自动清理)
|
||||
# Temp file (auto cleanup)
|
||||
TEMP_FILE=$(mktemp)
|
||||
trap "rm -f $TEMP_FILE" EXIT
|
||||
|
||||
# 工具依赖检查
|
||||
# Tool dependency check
|
||||
require_command() {
|
||||
command -v "$1" &> /dev/null || { echo "错误: 需要 $1" >&2; exit 1; }
|
||||
command -v "$1" &> /dev/null || { echo "Error: $1 required" >&2; exit 1; }
|
||||
}
|
||||
require_command jq
|
||||
|
||||
# jq 处理
|
||||
VALUE=$(jq -r '.field' "$INPUT_PATH") # 读取字段
|
||||
jq '.field = "new"' input.json > output.json # 修改字段
|
||||
jq -s 'add' file1.json file2.json > merged.json # 合并文件
|
||||
# jq processing
|
||||
VALUE=$(jq -r '.field' "$INPUT_PATH") # Read field
|
||||
jq '.field = "new"' input.json > output.json # Modify field
|
||||
jq -s 'add' file1.json file2.json > merged.json # Merge files
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Python 实现
|
||||
## Python Implementation
|
||||
|
||||
```python
|
||||
#!/usr/bin/env python3
|
||||
@@ -158,33 +158,33 @@ from pathlib import Path
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description='{{script_description}}')
|
||||
parser.add_argument('--input-path', type=str, required=True, help='输入文件路径')
|
||||
parser.add_argument('--output-dir', type=str, required=True, help='输出目录')
|
||||
parser.add_argument('--input-path', type=str, required=True, help='Input file path')
|
||||
parser.add_argument('--output-dir', type=str, required=True, help='Output directory')
|
||||
args = parser.parse_args()
|
||||
|
||||
# 验证输入
|
||||
# Validate input
|
||||
input_path = Path(args.input_path)
|
||||
if not input_path.exists():
|
||||
print(f"错误: 输入文件不存在: {input_path}", file=sys.stderr)
|
||||
print(f"Error: Input file does not exist: {input_path}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
output_dir = Path(args.output_dir)
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# 执行处理
|
||||
# Execute processing
|
||||
try:
|
||||
result = process(input_path, output_dir)
|
||||
except Exception as e:
|
||||
print(f"错误: {e}", file=sys.stderr)
|
||||
print(f"Error: {e}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
# 输出 JSON 结果
|
||||
# Output JSON result
|
||||
print(json.dumps(result))
|
||||
|
||||
|
||||
def process(input_path: Path, output_dir: Path) -> dict:
|
||||
"""核心处理逻辑"""
|
||||
# TODO: 实现处理逻辑
|
||||
"""Core processing logic"""
|
||||
# TODO: Implement processing logic
|
||||
|
||||
output_file = output_dir / 'result.json'
|
||||
|
||||
@@ -207,17 +207,17 @@ if __name__ == '__main__':
|
||||
main()
|
||||
```
|
||||
|
||||
### Python 常用模式
|
||||
### Python Common Patterns
|
||||
|
||||
```python
|
||||
# 文件遍历
|
||||
# File iteration
|
||||
def process_files(input_dir: Path, pattern: str = '*.json') -> list:
|
||||
return [
|
||||
{'file': str(f), 'data': json.load(f.open())}
|
||||
for f in input_dir.glob(pattern)
|
||||
]
|
||||
|
||||
# 数据转换
|
||||
# Data transformation
|
||||
def transform(data: dict) -> dict:
|
||||
return {
|
||||
'id': data.get('id'),
|
||||
@@ -225,7 +225,7 @@ def transform(data: dict) -> dict:
|
||||
'timestamp': datetime.now().isoformat()
|
||||
}
|
||||
|
||||
# 外部命令调用
|
||||
# External command invocation
|
||||
import subprocess
|
||||
|
||||
def run_command(cmd: list) -> str:
|
||||
@@ -237,24 +237,24 @@ def run_command(cmd: list) -> str:
|
||||
|
||||
---
|
||||
|
||||
## 运行时选择指南
|
||||
## Runtime Selection Guide
|
||||
|
||||
```
|
||||
任务特征
|
||||
↓
|
||||
├─ 文件处理 / 系统命令 / 管道操作
|
||||
│ └─ 选 Bash (.sh)
|
||||
Task Characteristics
|
||||
|
|
||||
├─ File processing / system commands / pipeline operations
|
||||
│ └─ Choose Bash (.sh)
|
||||
│
|
||||
├─ JSON 数据处理 / 复杂转换 / 数据分析
|
||||
│ └─ 选 Python (.py)
|
||||
├─ JSON data processing / complex transformation / data analysis
|
||||
│ └─ Choose Python (.py)
|
||||
│
|
||||
└─ 简单读写 / 格式转换
|
||||
└─ 任选(Bash 更轻量)
|
||||
└─ Simple read/write / format conversion
|
||||
└─ Either (Bash is lighter)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 生成函数
|
||||
## Generation Function
|
||||
|
||||
```javascript
|
||||
function generateScript(scriptConfig) {
|
||||
@@ -280,7 +280,7 @@ function generateBashScript(scriptConfig) {
|
||||
|
||||
const paramValidation = inputs.filter(i => i.required).map(i => {
|
||||
const VAR = i.name.toUpperCase().replace(/-/g, '_');
|
||||
return `[[ -z "$${VAR}" ]] && { echo "错误: --${i.name} 是必需参数" >&2; exit 1; }`;
|
||||
return `[[ -z "$${VAR}" ]] && { echo "Error: --${i.name} is required parameter" >&2; exit 1; }`;
|
||||
}).join('\n');
|
||||
|
||||
return `#!/bin/bash
|
||||
@@ -293,16 +293,16 @@ ${paramDefs}
|
||||
while [[ "$#" -gt 0 ]]; do
|
||||
case $1 in
|
||||
${paramParse}
|
||||
*) echo "未知参数: $1" >&2; exit 1 ;;
|
||||
*) echo "Unknown parameter: $1" >&2; exit 1 ;;
|
||||
esac
|
||||
shift
|
||||
done
|
||||
|
||||
${paramValidation}
|
||||
|
||||
# TODO: 实现处理逻辑
|
||||
# TODO: Implement processing logic
|
||||
|
||||
# 输出结果 (jq 构建)
|
||||
# Output result (jq build)
|
||||
jq -n ${outputs.map(o =>
|
||||
`--arg ${o.name} "$${o.name.toUpperCase().replace(/-/g, '_')}"`
|
||||
).join(' \\\n ')} \
|
||||
@@ -339,7 +339,7 @@ def main():
|
||||
${argDefs}
|
||||
args = parser.parse_args()
|
||||
|
||||
# TODO: 实现处理逻辑
|
||||
# TODO: Implement processing logic
|
||||
result = {
|
||||
${resultFields}
|
||||
}
|
||||
@@ -355,7 +355,7 @@ if __name__ == '__main__':
|
||||
|
||||
---
|
||||
|
||||
## 目录约定
|
||||
## Directory Convention
|
||||
|
||||
```
|
||||
scripts/
|
||||
@@ -364,5 +364,5 @@ scripts/
|
||||
└── transform.js # id: transform, runtime: node
|
||||
```
|
||||
|
||||
- **命名即 ID**: 文件名(不含扩展名)= 脚本 ID
|
||||
- **扩展名即运行时**: `.py` → python, `.sh` → bash, `.js` → node
|
||||
- **Name is ID**: Filename (without extension) = script ID
|
||||
- **Extension is runtime**: `.py` -> python, `.sh` -> bash, `.js` -> node
|
||||
|
||||
@@ -1,31 +1,31 @@
|
||||
# Sequential Phase Template
|
||||
|
||||
顺序模式 Phase 文件的模板。
|
||||
Template for Phase files in Sequential execution mode.
|
||||
|
||||
## Purpose
|
||||
|
||||
生成 Sequential 执行模式的 Phase 文件,定义固定顺序的执行步骤。
|
||||
Generate Phase files for Sequential execution mode, defining fixed-order execution steps.
|
||||
|
||||
## Usage Context
|
||||
|
||||
| Phase | Usage |
|
||||
|-------|-------|
|
||||
| Phase 3 (Phase Generation) | `config.execution_mode === 'sequential'` 时生成 |
|
||||
| Generation Trigger | 为每个 `config.sequential_config.phases` 生成一个 phase 文件 |
|
||||
| Phase 3 (Phase Generation) | Generated when `config.execution_mode === 'sequential'` |
|
||||
| Generation Trigger | Generate one phase file for each `config.sequential_config.phases` |
|
||||
| Output Location | `.claude/skills/{skill-name}/phases/{phase-id}.md` |
|
||||
|
||||
---
|
||||
|
||||
## ⚠️ 重要提示
|
||||
## Important Notes
|
||||
|
||||
> **Phase 0 是强制前置阶段**:在实现任何 Phase (1, 2, 3...) 之前,必须先完成 Phase 0 的规范研读。
|
||||
> **Phase 0 is mandatory prerequisite**: Before implementing any Phase (1, 2, 3...), Phase 0 specification review must be completed first.
|
||||
>
|
||||
> 生成 Sequential Phase 时,需要确保:
|
||||
> 1. SKILL.md 中已包含 Phase 0 规范研读步骤
|
||||
> 2. 每个 Phase 文件都引用相关的规范文档
|
||||
> 3. 执行流程明确标注 Phase 0 为禁止跳过的前置步骤
|
||||
> When generating Sequential Phase, ensure:
|
||||
> 1. Phase 0 specification review step is included in SKILL.md
|
||||
> 2. Each Phase file references related specification documents
|
||||
> 3. Execution flow clearly marks Phase 0 as non-skippable prerequisite
|
||||
|
||||
## 模板结构
|
||||
## Template Structure
|
||||
|
||||
```markdown
|
||||
# Phase {{phase_number}}: {{phase_name}}
|
||||
@@ -38,14 +38,14 @@
|
||||
|
||||
## Input
|
||||
|
||||
- 依赖: `{{input_dependency}}`
|
||||
- 配置: `{workDir}/skill-config.json`
|
||||
- Dependency: `{{input_dependency}}`
|
||||
- Config: `{workDir}/skill-config.json`
|
||||
|
||||
## Scripts
|
||||
|
||||
\`\`\`yaml
|
||||
# 声明本阶段使用的脚本(可选)
|
||||
# - script-id # 对应 scripts/script-id.py 或 .sh
|
||||
# Declare scripts used in this phase (optional)
|
||||
# - script-id # Corresponds to scripts/script-id.py or .sh
|
||||
\`\`\`
|
||||
|
||||
## Execution Steps
|
||||
@@ -62,10 +62,10 @@
|
||||
{{step_2_code}}
|
||||
\`\`\`
|
||||
|
||||
### Step 3: 执行脚本(可选)
|
||||
### Step 3: Execute Script (Optional)
|
||||
|
||||
\`\`\`javascript
|
||||
// 调用脚本示例
|
||||
// Script execution example
|
||||
// const result = await ExecuteScript('script-id', { input_path: `${workDir}/data.json` });
|
||||
// if (!result.success) throw new Error(result.stderr);
|
||||
// console.log(result.outputs.output_file);
|
||||
@@ -85,25 +85,25 @@
|
||||
{{next_phase_link}}
|
||||
```
|
||||
|
||||
## 变量说明
|
||||
## Variable Descriptions
|
||||
|
||||
| 变量 | 说明 |
|
||||
|------|------|
|
||||
| `{{phase_number}}` | 阶段序号 (1, 2, 3...) |
|
||||
| `{{phase_name}}` | 阶段名称 |
|
||||
| `{{phase_description}}` | 一句话描述 |
|
||||
| `{{objectives}}` | 目标列表 |
|
||||
| `{{input_dependency}}` | 输入依赖文件 |
|
||||
| `{{step_N_name}}` | 步骤名称 |
|
||||
| `{{step_N_code}}` | 步骤代码 |
|
||||
| `{{output_file}}` | 输出文件名 |
|
||||
| `{{output_format}}` | 输出格式 |
|
||||
| `{{quality_checklist}}` | 质量检查项 |
|
||||
| `{{next_phase_link}}` | 下一阶段链接 |
|
||||
| Variable | Description |
|
||||
|----------|-------------|
|
||||
| `{{phase_number}}` | Phase number (1, 2, 3...) |
|
||||
| `{{phase_name}}` | Phase name |
|
||||
| `{{phase_description}}` | One-line description |
|
||||
| `{{objectives}}` | List of objectives |
|
||||
| `{{input_dependency}}` | Input dependency file |
|
||||
| `{{step_N_name}}` | Step name |
|
||||
| `{{step_N_code}}` | Step code |
|
||||
| `{{output_file}}` | Output filename |
|
||||
| `{{output_format}}` | Output format |
|
||||
| `{{quality_checklist}}` | Quality checklist items |
|
||||
| `{{next_phase_link}}` | Next phase link |
|
||||
|
||||
## 脚本调用说明
|
||||
## Script Invocation Guide
|
||||
|
||||
### 目录约定
|
||||
### Directory Convention
|
||||
|
||||
```
|
||||
scripts/
|
||||
@@ -112,154 +112,154 @@ scripts/
|
||||
└── transform.js # id: transform, runtime: node
|
||||
```
|
||||
|
||||
- **命名即 ID**:文件名(不含扩展名)= 脚本 ID
|
||||
- **扩展名即运行时**:`.py` → python, `.sh` → bash, `.js` → node
|
||||
- **Name is ID**: Filename (without extension) = script ID
|
||||
- **Extension is runtime**: `.py` → python, `.sh` → bash, `.js` → node
|
||||
|
||||
### 调用语法
|
||||
### Invocation Syntax
|
||||
|
||||
```javascript
|
||||
// 一行调用
|
||||
// Single-line invocation
|
||||
const result = await ExecuteScript('script-id', { key: value });
|
||||
|
||||
// 检查结果
|
||||
// Check result
|
||||
if (!result.success) throw new Error(result.stderr);
|
||||
|
||||
// 获取输出
|
||||
// Get output
|
||||
const { output_file } = result.outputs;
|
||||
```
|
||||
|
||||
### 返回格式
|
||||
### Return Format
|
||||
|
||||
```typescript
|
||||
interface ScriptResult {
|
||||
success: boolean; // exit code === 0
|
||||
stdout: string; // 标准输出
|
||||
stderr: string; // 标准错误
|
||||
outputs: object; // 从 stdout 解析的 JSON 输出
|
||||
stdout: string; // Standard output
|
||||
stderr: string; // Standard error
|
||||
outputs: object; // JSON output parsed from stdout
|
||||
}
|
||||
```
|
||||
|
||||
## Phase 类型模板
|
||||
## Phase Type Templates
|
||||
|
||||
### 1. 收集型 Phase (Collection)
|
||||
### 1. Collection Phase
|
||||
|
||||
```markdown
|
||||
# Phase 1: Requirements Collection
|
||||
|
||||
收集用户需求和项目配置。
|
||||
Collect user requirements and project configuration.
|
||||
|
||||
## Objective
|
||||
|
||||
- 收集用户输入
|
||||
- 自动检测项目信息
|
||||
- 生成配置文件
|
||||
- Collect user input
|
||||
- Auto-detect project information
|
||||
- Generate configuration file
|
||||
|
||||
## Execution Steps
|
||||
|
||||
### Step 1: 用户交互
|
||||
### Step 1: User Interaction
|
||||
|
||||
\`\`\`javascript
|
||||
const userInput = await AskUserQuestion({
|
||||
questions: [
|
||||
{
|
||||
question: "请选择...",
|
||||
header: "选项",
|
||||
question: "Please select...",
|
||||
header: "Option",
|
||||
multiSelect: false,
|
||||
options: [
|
||||
{ label: "选项A", description: "..." },
|
||||
{ label: "选项B", description: "..." }
|
||||
{ label: "Option A", description: "..." },
|
||||
{ label: "Option B", description: "..." }
|
||||
]
|
||||
}
|
||||
]
|
||||
});
|
||||
\`\`\`
|
||||
|
||||
### Step 2: 自动检测
|
||||
### Step 2: Auto-detection
|
||||
|
||||
\`\`\`javascript
|
||||
// 检测项目信息
|
||||
// Detect project information
|
||||
const packageJson = JSON.parse(Read('package.json'));
|
||||
const projectName = packageJson.name;
|
||||
\`\`\`
|
||||
|
||||
### Step 3: 生成配置
|
||||
### Step 3: Generate Configuration
|
||||
|
||||
\`\`\`javascript
|
||||
const config = {
|
||||
name: projectName,
|
||||
userChoice: userInput["选项"],
|
||||
userChoice: userInput["Option"],
|
||||
// ...
|
||||
};
|
||||
|
||||
Write(`${workDir}/config.json`, JSON.stringify(config, null, 2));
|
||||
Write(\`${workDir}/config.json\`, JSON.stringify(config, null, 2));
|
||||
\`\`\`
|
||||
|
||||
## Output
|
||||
|
||||
- **File**: `config.json`
|
||||
- **File**: \`config.json\`
|
||||
- **Format**: JSON
|
||||
```
|
||||
|
||||
### 2. 分析型 Phase (Analysis)
|
||||
### 2. Analysis Phase
|
||||
|
||||
```markdown
|
||||
# Phase 2: Deep Analysis
|
||||
|
||||
深度分析代码结构。
|
||||
Analyze code structure in depth.
|
||||
|
||||
## Objective
|
||||
|
||||
- 扫描代码文件
|
||||
- 提取关键信息
|
||||
- 生成分析报告
|
||||
- Scan code files
|
||||
- Extract key information
|
||||
- Generate analysis report
|
||||
|
||||
## Execution Steps
|
||||
|
||||
### Step 1: 文件扫描
|
||||
### Step 1: File Scanning
|
||||
|
||||
\`\`\`javascript
|
||||
const files = Glob('src/**/*.ts');
|
||||
\`\`\`
|
||||
|
||||
### Step 2: 内容分析
|
||||
### Step 2: Content Analysis
|
||||
|
||||
\`\`\`javascript
|
||||
const analysisResults = [];
|
||||
for (const file of files) {
|
||||
const content = Read(file);
|
||||
// 分析逻辑
|
||||
analysisResults.push({ file, /* 分析结果 */ });
|
||||
// Analysis logic
|
||||
analysisResults.push({ file, /* analysis results */ });
|
||||
}
|
||||
\`\`\`
|
||||
|
||||
### Step 3: 生成报告
|
||||
### Step 3: Generate Report
|
||||
|
||||
\`\`\`javascript
|
||||
Write(`${workDir}/analysis.json`, JSON.stringify(analysisResults, null, 2));
|
||||
Write(\`${workDir}/analysis.json\`, JSON.stringify(analysisResults, null, 2));
|
||||
\`\`\`
|
||||
|
||||
## Output
|
||||
|
||||
- **File**: `analysis.json`
|
||||
- **File**: \`analysis.json\`
|
||||
- **Format**: JSON
|
||||
```
|
||||
|
||||
### 3. 并行型 Phase (Parallel)
|
||||
### 3. Parallel Phase
|
||||
|
||||
```markdown
|
||||
# Phase 3: Parallel Processing
|
||||
|
||||
并行处理多个子任务。
|
||||
Process multiple subtasks in parallel.
|
||||
|
||||
## Objective
|
||||
|
||||
- 启动多个 Agent 并行执行
|
||||
- 收集各 Agent 结果
|
||||
- 合并输出
|
||||
- Launch multiple agents for parallel execution
|
||||
- Collect results from each agent
|
||||
- Merge outputs
|
||||
|
||||
## Execution Steps
|
||||
|
||||
### Step 1: 准备任务
|
||||
### Step 1: Prepare Tasks
|
||||
|
||||
\`\`\`javascript
|
||||
const tasks = [
|
||||
@@ -269,11 +269,11 @@ const tasks = [
|
||||
];
|
||||
\`\`\`
|
||||
|
||||
### Step 2: 并行执行
|
||||
### Step 2: Parallel Execution
|
||||
|
||||
\`\`\`javascript
|
||||
const results = await Promise.all(
|
||||
tasks.map(task =>
|
||||
tasks.map(task =>
|
||||
Task({
|
||||
subagent_type: 'universal-executor',
|
||||
run_in_background: false,
|
||||
@@ -283,7 +283,7 @@ const results = await Promise.all(
|
||||
);
|
||||
\`\`\`
|
||||
|
||||
### Step 3: 合并结果
|
||||
### Step 3: Merge Results
|
||||
|
||||
\`\`\`javascript
|
||||
const merged = results.map((r, i) => ({
|
||||
@@ -291,83 +291,83 @@ const merged = results.map((r, i) => ({
|
||||
result: JSON.parse(r)
|
||||
}));
|
||||
|
||||
Write(`${workDir}/parallel-results.json`, JSON.stringify(merged, null, 2));
|
||||
Write(\`${workDir}/parallel-results.json\`, JSON.stringify(merged, null, 2));
|
||||
\`\`\`
|
||||
|
||||
## Output
|
||||
|
||||
- **File**: `parallel-results.json`
|
||||
- **File**: \`parallel-results.json\`
|
||||
- **Format**: JSON
|
||||
```
|
||||
|
||||
### 4. 组装型 Phase (Assembly)
|
||||
### 4. Assembly Phase
|
||||
|
||||
```markdown
|
||||
# Phase 4: Document Assembly
|
||||
|
||||
组装最终输出文档。
|
||||
Assemble final output documents.
|
||||
|
||||
## Objective
|
||||
|
||||
- 读取各阶段产出
|
||||
- 合并内容
|
||||
- 生成最终文档
|
||||
- Read outputs from each phase
|
||||
- Merge content
|
||||
- Generate final document
|
||||
|
||||
## Execution Steps
|
||||
|
||||
### Step 1: 读取产出
|
||||
### Step 1: Read Outputs
|
||||
|
||||
\`\`\`javascript
|
||||
const config = JSON.parse(Read(`${workDir}/config.json`));
|
||||
const analysis = JSON.parse(Read(`${workDir}/analysis.json`));
|
||||
const sections = Glob(`${workDir}/sections/*.md`).map(f => Read(f));
|
||||
const config = JSON.parse(Read(\`${workDir}/config.json\`));
|
||||
const analysis = JSON.parse(Read(\`${workDir}/analysis.json\`));
|
||||
const sections = Glob(\`${workDir}/sections/*.md\`).map(f => Read(f));
|
||||
\`\`\`
|
||||
|
||||
### Step 2: 组装内容
|
||||
### Step 2: Assemble Content
|
||||
|
||||
\`\`\`javascript
|
||||
const document = \`
|
||||
# \${config.name}
|
||||
|
||||
## 概述
|
||||
## Overview
|
||||
\${config.description}
|
||||
|
||||
## 详细内容
|
||||
## Detailed Content
|
||||
\${sections.join('\\n\\n')}
|
||||
\`;
|
||||
\`\`\`
|
||||
|
||||
### Step 3: 写入文件
|
||||
### Step 3: Write File
|
||||
|
||||
\`\`\`javascript
|
||||
Write(`${workDir}/${config.name}-output.md`, document);
|
||||
Write(\`${workDir}/\${config.name}-output.md\`, document);
|
||||
\`\`\`
|
||||
|
||||
## Output
|
||||
|
||||
- **File**: `{name}-output.md`
|
||||
- **File**: \`{name}-output.md\`
|
||||
- **Format**: Markdown
|
||||
```
|
||||
|
||||
### 5. 验证型 Phase (Validation)
|
||||
### 5. Validation Phase
|
||||
|
||||
```markdown
|
||||
# Phase 5: Validation
|
||||
|
||||
验证输出质量。
|
||||
Verify output quality.
|
||||
|
||||
## Objective
|
||||
|
||||
- 检查输出完整性
|
||||
- 验证内容质量
|
||||
- 生成验证报告
|
||||
- Check output completeness
|
||||
- Verify content quality
|
||||
- Generate validation report
|
||||
|
||||
## Execution Steps
|
||||
|
||||
### Step 1: 完整性检查
|
||||
### Step 1: Completeness Check
|
||||
|
||||
\`\`\`javascript
|
||||
const outputFile = `${workDir}/${config.name}-output.md`;
|
||||
const outputFile = \`${workDir}/\${config.name}-output.md\`;
|
||||
const content = Read(outputFile);
|
||||
const completeness = {
|
||||
hasTitle: content.includes('# '),
|
||||
@@ -376,16 +376,16 @@ const completeness = {
|
||||
};
|
||||
\`\`\`
|
||||
|
||||
### Step 2: 质量评估
|
||||
### Step 2: Quality Assessment
|
||||
|
||||
\`\`\`javascript
|
||||
const quality = {
|
||||
completeness: Object.values(completeness).filter(v => v).length / 3 * 100,
|
||||
// 其他维度...
|
||||
// Other dimensions...
|
||||
};
|
||||
\`\`\`
|
||||
|
||||
### Step 3: 生成报告
|
||||
### Step 3: Generate Report
|
||||
|
||||
\`\`\`javascript
|
||||
const report = {
|
||||
@@ -394,55 +394,55 @@ const report = {
|
||||
issues: []
|
||||
};
|
||||
|
||||
Write(`${workDir}/validation-report.json`, JSON.stringify(report, null, 2));
|
||||
Write(\`${workDir}/validation-report.json\`, JSON.stringify(report, null, 2));
|
||||
\`\`\`
|
||||
|
||||
## Output
|
||||
|
||||
- **File**: `validation-report.json`
|
||||
- **File**: \`validation-report.json\`
|
||||
- **Format**: JSON
|
||||
```
|
||||
|
||||
## 生成函数
|
||||
## Generation Function
|
||||
|
||||
```javascript
|
||||
function generateSequentialPhase(phaseConfig, index, phases, skillConfig) {
|
||||
const prevPhase = index > 0 ? phases[index - 1] : null;
|
||||
const nextPhase = index < phases.length - 1 ? phases[index + 1] : null;
|
||||
|
||||
|
||||
return `# Phase ${index + 1}: ${phaseConfig.name}
|
||||
|
||||
${phaseConfig.description || `执行 ${phaseConfig.name}`}
|
||||
${phaseConfig.description || `Execute ${phaseConfig.name}`}
|
||||
|
||||
## Objective
|
||||
|
||||
- ${phaseConfig.objectives?.join('\n- ') || 'TODO: 定义目标'}
|
||||
- ${phaseConfig.objectives?.join('\n- ') || 'TODO: Define objectives'}
|
||||
|
||||
## Input
|
||||
|
||||
- 依赖: \`${prevPhase ? prevPhase.output : 'user input'}\`
|
||||
- 配置: \`{workDir}/skill-config.json\`
|
||||
- Dependency: \`${prevPhase ? prevPhase.output : 'user input'}\`
|
||||
- Config: \`{workDir}/skill-config.json\`
|
||||
|
||||
## Execution Steps
|
||||
|
||||
### Step 1: 准备
|
||||
### Step 1: Preparation
|
||||
|
||||
\`\`\`javascript
|
||||
${prevPhase ?
|
||||
`const prevOutput = JSON.parse(Read(\`\${workDir}/${prevPhase.output}\`));` :
|
||||
'// 首阶段,从配置开始'}
|
||||
${prevPhase ?
|
||||
`const prevOutput = JSON.parse(Read(\`${workDir}/${prevPhase.output}\`));` :
|
||||
'// First phase, start from configuration'}
|
||||
\`\`\`
|
||||
|
||||
### Step 2: 处理
|
||||
### Step 2: Processing
|
||||
|
||||
\`\`\`javascript
|
||||
// TODO: 实现核心逻辑
|
||||
// TODO: Implement core logic
|
||||
\`\`\`
|
||||
|
||||
### Step 3: 输出
|
||||
### Step 3: Output
|
||||
|
||||
\`\`\`javascript
|
||||
Write(\`\${workDir}/${phaseConfig.output}\`, JSON.stringify(result, null, 2));
|
||||
Write(\`${workDir}/${phaseConfig.output}\`, JSON.stringify(result, null, 2));
|
||||
\`\`\`
|
||||
|
||||
## Output
|
||||
@@ -452,13 +452,13 @@ Write(\`\${workDir}/${phaseConfig.output}\`, JSON.stringify(result, null, 2));
|
||||
|
||||
## Quality Checklist
|
||||
|
||||
- [ ] 输入验证通过
|
||||
- [ ] 核心逻辑执行成功
|
||||
- [ ] 输出格式正确
|
||||
- [ ] Input validation passed
|
||||
- [ ] Core logic executed successfully
|
||||
- [ ] Output format correct
|
||||
|
||||
${nextPhase ?
|
||||
${nextPhase ?
|
||||
`## Next Phase\n\n→ [Phase ${index + 2}: ${nextPhase.name}](${nextPhase.id}.md)` :
|
||||
'## Completion\n\n此为最后阶段。'}
|
||||
'## Completion\n\nThis is the final phase.'}
|
||||
`;
|
||||
}
|
||||
```
|
||||
|
||||
@@ -1,34 +1,34 @@
|
||||
# SKILL.md Template
|
||||
|
||||
用于生成新 Skill 入口文件的模板。
|
||||
Template for generating new Skill entry files.
|
||||
|
||||
## Purpose
|
||||
|
||||
生成新 Skill 的入口文件 (SKILL.md),作为 Skill 的主文档和执行入口点。
|
||||
Generate the entry file (SKILL.md) for new Skills, serving as the main documentation and execution entry point for the Skill.
|
||||
|
||||
## Usage Context
|
||||
|
||||
| Phase | Usage |
|
||||
|-------|-------|
|
||||
| Phase 2 (Structure Generation) | 创建 SKILL.md 入口文件 |
|
||||
| Generation Trigger | `config.execution_mode` 决定架构图样式 |
|
||||
| Phase 2 (Structure Generation) | Create SKILL.md entry file |
|
||||
| Generation Trigger | `config.execution_mode` determines architecture diagram style |
|
||||
| Output Location | `.claude/skills/{skill-name}/SKILL.md` |
|
||||
|
||||
---
|
||||
|
||||
## ⚠️ 重要:YAML Front Matter 规范
|
||||
## Important: YAML Front Matter Specification
|
||||
|
||||
> **CRITICAL**: SKILL.md 文件必须以 YAML front matter 开头,即以 `---` 作为文件第一行。
|
||||
> **CRITICAL**: The SKILL.md file MUST begin with YAML front matter, meaning `---` must be the first line of the file.
|
||||
>
|
||||
> **禁止**使用以下格式:
|
||||
> - `# Title` 然后 `## Metadata` + yaml 代码块 ❌
|
||||
> - 任何在 `---` 之前的内容 ❌
|
||||
> **Do NOT use** the following formats:
|
||||
> - `# Title` followed by `## Metadata` + yaml code block
|
||||
> - Any content before `---`
|
||||
>
|
||||
> **正确格式**:文件第一行必须是 `---`
|
||||
> **Correct format**: The first line MUST be `---`
|
||||
|
||||
## 可直接应用的模板
|
||||
## Ready-to-use Template
|
||||
|
||||
以下是完整的 SKILL.md 模板。生成时**直接复制应用**,将 `{{变量}}` 替换为实际值:
|
||||
The following is a complete SKILL.md template. When generating, **directly copy and apply** it, replacing `{{variables}}` with actual values:
|
||||
|
||||
---
|
||||
name: {{skill_name}}
|
||||
@@ -52,9 +52,9 @@ allowed-tools: {{allowed_tools}}
|
||||
|
||||
---
|
||||
|
||||
## ⚠️ Mandatory Prerequisites (强制前置条件)
|
||||
## Mandatory Prerequisites
|
||||
|
||||
> **⛔ 禁止跳过**: 在执行任何操作之前,**必须**完整阅读以下文档。未阅读规范直接执行将导致输出不符合质量标准。
|
||||
> **Do NOT skip**: Before performing any operations, you **must** completely read the following documents. Proceeding without reading the specifications will result in outputs that do not meet quality standards.
|
||||
|
||||
{{mandatory_prerequisites}}
|
||||
|
||||
@@ -82,31 +82,31 @@ Bash(\`mkdir -p "\${workDir}"\`);
|
||||
|
||||
## Reference Documents by Phase
|
||||
|
||||
> **重要**: 参考文档应按执行阶段组织,清晰标注使用时机和场景。避免平铺文档列表。
|
||||
> **Important**: Reference documents should be organized by execution phase, clearly marking when and in what scenarios they are used. Avoid listing documents in a flat manner.
|
||||
|
||||
{{reference_table}}
|
||||
|
||||
---
|
||||
|
||||
## 变量说明
|
||||
## Variable Descriptions
|
||||
|
||||
| 变量 | 类型 | 来源 |
|
||||
|------|------|------|
|
||||
| Variable | Type | Source |
|
||||
|----------|------|--------|
|
||||
| `{{skill_name}}` | string | config.skill_name |
|
||||
| `{{display_name}}` | string | config.display_name |
|
||||
| `{{description}}` | string | config.description |
|
||||
| `{{triggers}}` | string | config.triggers.join(", ") |
|
||||
| `{{allowed_tools}}` | string | config.allowed_tools.join(", ") |
|
||||
| `{{architecture_diagram}}` | string | 根据 execution_mode 生成 (包含 Phase 0) |
|
||||
| `{{design_principles}}` | string | 根据 execution_mode 生成 |
|
||||
| `{{mandatory_prerequisites}}` | string | 强制前置阅读文档列表 (specs + templates) |
|
||||
| `{{execution_flow}}` | string | 根据 phases/actions 生成 (Phase 0 在最前) |
|
||||
| `{{architecture_diagram}}` | string | Generated based on execution_mode (includes Phase 0) |
|
||||
| `{{design_principles}}` | string | Generated based on execution_mode |
|
||||
| `{{mandatory_prerequisites}}` | string | List of mandatory prerequisite reading documents (specs + templates) |
|
||||
| `{{execution_flow}}` | string | Generated from phases/actions (Phase 0 first) |
|
||||
| `{{output_location}}` | string | config.output.location |
|
||||
| `{{additional_dirs}}` | string | 根据 execution_mode 生成 |
|
||||
| `{{output_structure}}` | string | 根据配置生成 |
|
||||
| `{{reference_table}}` | string | 根据文件列表生成 |
|
||||
| `{{additional_dirs}}` | string | Generated based on execution_mode |
|
||||
| `{{output_structure}}` | string | Generated based on configuration |
|
||||
| `{{reference_table}}` | string | Generated from file list |
|
||||
|
||||
## 生成函数
|
||||
## Generation Function
|
||||
|
||||
```javascript
|
||||
function generateSkillMd(config) {
|
||||
@@ -118,32 +118,32 @@ function generateSkillMd(config) {
|
||||
.replace(/\{\{description\}\}/g, config.description)
|
||||
.replace(/\{\{triggers\}\}/g, config.triggers.map(t => `"${t}"`).join(", "))
|
||||
.replace(/\{\{allowed_tools\}\}/g, config.allowed_tools.join(", "))
|
||||
.replace(/\{\{architecture_diagram\}\}/g, generateArchitecture(config)) // 包含 Phase 0
|
||||
.replace(/\{\{architecture_diagram\}\}/g, generateArchitecture(config)) // Includes Phase 0
|
||||
.replace(/\{\{design_principles\}\}/g, generatePrinciples(config))
|
||||
.replace(/\{\{mandatory_prerequisites\}\}/g, generatePrerequisites(config)) // 强制前置条件
|
||||
.replace(/\{\{execution_flow\}\}/g, generateFlow(config)) // Phase 0 在最前
|
||||
.replace(/\{\{mandatory_prerequisites\}\}/g, generatePrerequisites(config)) // Mandatory prerequisites
|
||||
.replace(/\{\{execution_flow\}\}/g, generateFlow(config)) // Phase 0 first
|
||||
.replace(/\{\{output_location\}\}/g, config.output.location)
|
||||
.replace(/\{\{additional_dirs\}\}/g, generateAdditionalDirs(config))
|
||||
.replace(/\{\{output_structure\}\}/g, generateOutputStructure(config))
|
||||
.replace(/\{\{reference_table\}\}/g, generateReferenceTable(config));
|
||||
}
|
||||
|
||||
// 生成强制前置条件表格
|
||||
// Generate mandatory prerequisites table
|
||||
function generatePrerequisites(config) {
|
||||
const specs = config.specs || [];
|
||||
const templates = config.templates || [];
|
||||
|
||||
let result = '### 规范文档 (必读)\n\n';
|
||||
let result = '### Specification Documents (Required Reading)\n\n';
|
||||
result += '| Document | Purpose | When |\n';
|
||||
result += '|----------|---------|------|\n';
|
||||
|
||||
specs.forEach((spec, index) => {
|
||||
const when = index === 0 ? '**执行前必读**' : '执行前推荐';
|
||||
const when = index === 0 ? '**Must read before execution**' : 'Recommended before execution';
|
||||
result += `| [${spec.path}](${spec.path}) | ${spec.purpose} | ${when} |\n`;
|
||||
});
|
||||
|
||||
if (templates.length > 0) {
|
||||
result += '\n### 模板文件 (生成前必读)\n\n';
|
||||
result += '\n### Template Files (Must read before generation)\n\n';
|
||||
result += '| Document | Purpose |\n';
|
||||
result += '|----------|---------|\n';
|
||||
templates.forEach(tmpl => {
|
||||
@@ -154,7 +154,7 @@ function generatePrerequisites(config) {
|
||||
return result;
|
||||
}
|
||||
|
||||
// ⭐ 新增:生成分阶段参考文档指南
|
||||
// Generate phase-by-phase reference document guide
|
||||
function generateReferenceTable(config) {
|
||||
const phases = config.phases || config.actions || [];
|
||||
const specs = config.specs || [];
|
||||
@@ -162,65 +162,53 @@ function generateReferenceTable(config) {
|
||||
|
||||
let result = '';
|
||||
|
||||
// 为每个执行阶段生成文档导航
|
||||
// Generate document navigation for each execution phase
|
||||
phases.forEach((phase, index) => {
|
||||
const phaseNum = index + 1;
|
||||
const phaseEmoji = getPhaseEmoji(phase.type || 'default');
|
||||
const phaseTitle = phase.display_name || phase.name;
|
||||
|
||||
result += `### ${phaseEmoji} Phase ${phaseNum}: ${phaseTitle}\n`;
|
||||
result += `执行Phase ${phaseNum}时查阅的文档\n\n`;
|
||||
result += `### Phase ${phaseNum}: ${phaseTitle}\n`;
|
||||
result += `Documents to reference when executing Phase ${phaseNum}\n\n`;
|
||||
|
||||
// 列出该阶段相关的文档
|
||||
// List documents related to this phase
|
||||
const relatedDocs = filterDocsByPhase(specs, phase, index);
|
||||
if (relatedDocs.length > 0) {
|
||||
result += '| Document | Purpose | When to Use |\n';
|
||||
result += '|----------|---------|-------------|\n';
|
||||
relatedDocs.forEach(doc => {
|
||||
result += `| [${doc.path}](${doc.path}) | ${doc.purpose} | ${doc.context || '查阅内容'} |\n`;
|
||||
result += `| [${doc.path}](${doc.path}) | ${doc.purpose} | ${doc.context || 'Reference content'} |\n`;
|
||||
});
|
||||
result += '\n';
|
||||
}
|
||||
});
|
||||
|
||||
// 问题排查部分
|
||||
result += '### 🔍 Debugging & Troubleshooting (问题排查)\n';
|
||||
result += '遇到问题时查阅的文档\n\n';
|
||||
// Troubleshooting section
|
||||
result += '### Debugging & Troubleshooting\n';
|
||||
result += 'Documents to reference when encountering issues\n\n';
|
||||
result += '| Issue | Solution Document |\n';
|
||||
result += '|-------|-------------------|\n';
|
||||
result += `| Phase执行失败 | 查阅相应Phase的文档 |\n`;
|
||||
result += `| 输出不符合预期 | [specs/quality-standards.md](specs/quality-standards.md) - 验证质量标准 |\n`;
|
||||
result += `| Phase execution failed | Refer to the relevant Phase documentation |\n`;
|
||||
result += `| Output does not meet expectations | [specs/quality-standards.md](specs/quality-standards.md) - Verify quality standards |\n`;
|
||||
result += '\n';
|
||||
|
||||
// 深度学习参考
|
||||
result += '### 📚 Reference & Background (深度学习)\n';
|
||||
result += '用于理解原始实现和设计决策\n\n';
|
||||
// In-depth learning reference
|
||||
result += '### Reference & Background\n';
|
||||
result += 'For understanding the original implementation and design decisions\n\n';
|
||||
result += '| Document | Purpose | Notes |\n';
|
||||
result += '|----------|---------|-------|\n';
|
||||
templates.forEach(tmpl => {
|
||||
result += `| [${tmpl.path}](${tmpl.path}) | ${tmpl.purpose} | 生成时参考 |\n`;
|
||||
result += `| [${tmpl.path}](${tmpl.path}) | ${tmpl.purpose} | Reference during generation |\n`;
|
||||
});
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
// 辅助函数:获取Phase表情符号
|
||||
function getPhaseEmoji(phaseType) {
|
||||
const emojiMap = {
|
||||
'discovery': '📋',
|
||||
'generation': '🔧',
|
||||
'analysis': '🔍',
|
||||
'implementation': '⚙️',
|
||||
'validation': '✅',
|
||||
'completion': '🏁',
|
||||
'default': '📌'
|
||||
};
|
||||
return emojiMap[phaseType] || emojiMap['default'];
|
||||
}
|
||||
// Helper function: Get Phase emoji (removed)
|
||||
// Note: Emoji support has been removed. Consider using Phase numbers instead.
|
||||
|
||||
// 辅助函数:根据Phase过滤文档
|
||||
// Helper function: Filter documents by Phase
|
||||
function filterDocsByPhase(specs, phase, phaseIndex) {
|
||||
// 简单过滤逻辑:匹配phase名称关键词
|
||||
// Simple filtering logic: match phase name keywords
|
||||
const keywords = phase.name.toLowerCase().split('-');
|
||||
return specs.filter(spec => {
|
||||
const specName = spec.path.toLowerCase();
|
||||
@@ -229,7 +217,7 @@ function filterDocsByPhase(specs, phase, phaseIndex) {
|
||||
}
|
||||
```
|
||||
|
||||
## Sequential 模式示例
|
||||
## Sequential Mode Example
|
||||
|
||||
```markdown
|
||||
---
|
||||
@@ -245,36 +233,33 @@ Generate API documentation from source code.
|
||||
## Architecture Overview
|
||||
|
||||
\`\`\`
|
||||
┌─────────────────────────────────────────────────────────────────┐
|
||||
│ ⚠️ Phase 0: Specification → 阅读并理解设计规范 (强制前置) │
|
||||
│ Study │
|
||||
│ ↓ │
|
||||
│ Phase 1: Scanning → endpoints.json │
|
||||
│ ↓ │
|
||||
│ Phase 2: Parsing → schemas.json │
|
||||
│ ↓ │
|
||||
│ Phase 3: Generation → api-docs.md │
|
||||
└─────────────────────────────────────────────────────────────────┘
|
||||
Phase 0: Specification Study (Mandatory prerequisite - Read and understand design specifications)
|
||||
↓
|
||||
Phase 1: Scanning → endpoints.json
|
||||
↓
|
||||
Phase 2: Parsing → schemas.json
|
||||
↓
|
||||
Phase 3: Generation → api-docs.md
|
||||
\`\`\`
|
||||
|
||||
## ⚠️ Mandatory Prerequisites (强制前置条件)
|
||||
## Mandatory Prerequisites
|
||||
|
||||
> **⛔ 禁止跳过**: 在执行任何操作之前,**必须**完整阅读以下文档。
|
||||
> **Do NOT skip**: Before performing any operations, you **must** completely read the following documents.
|
||||
|
||||
### 规范文档 (必读)
|
||||
### Specification Documents (Required Reading)
|
||||
|
||||
| Document | Purpose | Priority |
|
||||
|----------|---------|----------|
|
||||
| [specs/api-standards.md](specs/api-standards.md) | API 文档标准规范 | **P0 - 最高** |
|
||||
| [specs/api-standards.md](specs/api-standards.md) | API documentation standards specification | **P0 - Highest** |
|
||||
|
||||
### 模板文件 (生成前必读)
|
||||
### Template Files (Must read before generation)
|
||||
|
||||
| Document | Purpose |
|
||||
|----------|---------|
|
||||
| [templates/endpoint-doc.md](templates/endpoint-doc.md) | 端点文档模板 |
|
||||
| [templates/endpoint-doc.md](templates/endpoint-doc.md) | Endpoint documentation template |
|
||||
```
|
||||
|
||||
## Autonomous 模式示例
|
||||
## Autonomous Mode Example
|
||||
|
||||
```markdown
|
||||
---
|
||||
@@ -290,36 +275,34 @@ Interactive task management with CRUD operations.
|
||||
## Architecture Overview
|
||||
|
||||
\`\`\`
|
||||
┌─────────────────────────────────────────────────────────────────┐
|
||||
│ ⚠️ Phase 0: Specification Study (强制前置) │
|
||||
└───────────────┬─────────────────────────────────────────────────┘
|
||||
↓
|
||||
┌─────────────────────────────────────────────────────────────────┐
|
||||
│ Orchestrator (状态驱动决策) │
|
||||
└───────────────┬─────────────────────────────────────────────────┘
|
||||
│
|
||||
┌───────────┼───────────┬───────────┐
|
||||
↓ ↓ ↓ ↓
|
||||
┌───────┐ ┌───────┐ ┌───────┐ ┌───────┐
|
||||
│ List │ │Create │ │ Edit │ │Delete │
|
||||
└───────┘ └───────┘ └───────┘ └───────┘
|
||||
Phase 0: Specification Study (Mandatory prerequisite)
|
||||
↓
|
||||
┌────────────────────────────────────────┐
|
||||
│ Orchestrator (State-driven decision) │
|
||||
└────────────┬───────────────────────────┘
|
||||
│
|
||||
┌────────┼────────┬────────┐
|
||||
↓ ↓ ↓ ↓
|
||||
┌────────┐ ┌────────┐ ┌────────┐ ┌────────┐
|
||||
│ List │ │ Create │ │ Edit │ │ Delete │
|
||||
└────────┘ └────────┘ └────────┘ └────────┘
|
||||
\`\`\`
|
||||
|
||||
## ⚠️ Mandatory Prerequisites (强制前置条件)
|
||||
## Mandatory Prerequisites
|
||||
|
||||
> **⛔ 禁止跳过**: 在执行任何操作之前,**必须**完整阅读以下文档。
|
||||
> **Do NOT skip**: Before performing any operations, you **must** completely read the following documents.
|
||||
|
||||
### 规范文档 (必读)
|
||||
### Specification Documents (Required Reading)
|
||||
|
||||
| Document | Purpose | Priority |
|
||||
|----------|---------|----------|
|
||||
| [specs/task-schema.md](specs/task-schema.md) | 任务数据结构规范 | **P0 - 最高** |
|
||||
| [specs/action-catalog.md](specs/action-catalog.md) | 动作目录 | P1 |
|
||||
| [specs/task-schema.md](specs/task-schema.md) | Task data structure specification | **P0 - Highest** |
|
||||
| [specs/action-catalog.md](specs/action-catalog.md) | Action catalog | P1 |
|
||||
|
||||
### 模板文件 (生成前必读)
|
||||
### Template Files (Must read before generation)
|
||||
|
||||
| Document | Purpose |
|
||||
|----------|---------|
|
||||
| [templates/orchestrator-base.md](templates/orchestrator-base.md) | 编排器模板 |
|
||||
| [templates/action-base.md](templates/action-base.md) | 动作模板 |
|
||||
| [templates/orchestrator-base.md](templates/orchestrator-base.md) | Orchestrator template |
|
||||
| [templates/action-base.md](templates/action-base.md) | Action template |
|
||||
```
|
||||
|
||||
Reference in New Issue
Block a user