mirror of
https://github.com/catlog22/Claude-Code-Workflow.git
synced 2026-02-12 02:37:45 +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,6 +1,6 @@
|
|||||||
---
|
---
|
||||||
name: skill-generator
|
name: skill-generator
|
||||||
description: Meta-skill for creating new Claude Code skills with configurable execution modes. Supports sequential (fixed order) and autonomous (stateless) phase patterns. Use for skill scaffolding, skill creation, or building new workflows. Triggers on "create skill", "new skill", "skill generator", "生成技能", "创建技能".
|
description: Meta-skill for creating new Claude Code skills with configurable execution modes. Supports sequential (fixed order) and autonomous (stateless) phase patterns. Use for skill scaffolding, skill creation, or building new workflows. Triggers on "create skill", "new skill", "skill generator".
|
||||||
allowed-tools: Task, AskUserQuestion, Read, Bash, Glob, Grep, Write
|
allowed-tools: Task, AskUserQuestion, Read, Bash, Glob, Grep, Write
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -36,96 +36,94 @@ Meta-skill for creating new Claude Code skills with configurable execution modes
|
|||||||
|
|
||||||
## Execution Modes
|
## Execution Modes
|
||||||
|
|
||||||
### Mode 1: Sequential (固定顺序)
|
### Mode 1: Sequential (Fixed Order)
|
||||||
|
|
||||||
传统线性执行模式,阶段按数字前缀顺序执行。
|
Traditional linear execution model, phases execute in numeric prefix order.
|
||||||
|
|
||||||
```
|
```
|
||||||
Phase 01 → Phase 02 → Phase 03 → ... → Phase N
|
Phase 01 -> Phase 02 -> Phase 03 -> ... -> Phase N
|
||||||
```
|
```
|
||||||
|
|
||||||
**适用场景**:
|
**Use Cases**:
|
||||||
- 流水线式任务(收集 → 分析 → 生成)
|
- Pipeline tasks (collect -> analyze -> generate)
|
||||||
- 阶段间有强依赖关系
|
- Strong dependencies between phases
|
||||||
- 输出结构固定
|
- Fixed output structure
|
||||||
|
|
||||||
**示例**: `software-manual`, `copyright-docs`
|
**Examples**: `software-manual`, `copyright-docs`
|
||||||
|
|
||||||
### Mode 2: Autonomous (无状态自主选择)
|
### Mode 2: Autonomous (Stateless Auto-Select)
|
||||||
|
|
||||||
智能路由模式,根据上下文动态选择执行路径。
|
Intelligent routing model, dynamically selects execution path based on context.
|
||||||
|
|
||||||
```
|
```
|
||||||
┌─────────────────────────────────────────┐
|
---------------------------------------------------
|
||||||
│ Orchestrator Agent │
|
Orchestrator Agent
|
||||||
│ (读取状态 → 选择 Phase → 执行 → 更新) │
|
(Read state -> Select Phase -> Execute -> Update)
|
||||||
└───────────────┬─────────────────────────┘
|
---------------------------------------------------
|
||||||
│
|
|
|
||||||
┌───────────┼───────────┐
|
---------+----------+----------
|
||||||
↓ ↓ ↓
|
| | |
|
||||||
┌───────┐ ┌───────┐ ┌───────┐
|
Phase A Phase B Phase C
|
||||||
│Phase A│ │Phase B│ │Phase C│
|
(standalone) (standalone) (standalone)
|
||||||
│(独立) │ │(独立) │ │(独立) │
|
|
||||||
└───────┘ └───────┘ └───────┘
|
|
||||||
```
|
```
|
||||||
|
|
||||||
**适用场景**:
|
**Use Cases**:
|
||||||
- 交互式任务(对话、问答)
|
- Interactive tasks (chat, Q&A)
|
||||||
- 阶段间无强依赖
|
- No strong dependencies between phases
|
||||||
- 需要动态响应用户意图
|
- Dynamic user intent response required
|
||||||
|
|
||||||
**示例**: `issue-manage`, `workflow-debug`
|
**Examples**: `issue-manage`, `workflow-debug`
|
||||||
|
|
||||||
## Key Design Principles
|
## Key Design Principles
|
||||||
|
|
||||||
1. **模式感知**: 根据任务特性自动推荐执行模式
|
1. **Mode Awareness**: Automatically recommend execution mode based on task characteristics
|
||||||
2. **骨架生成**: 生成完整目录结构和文件骨架
|
2. **Skeleton Generation**: Generate complete directory structure and file skeletons
|
||||||
3. **规范遵循**: 严格遵循 `_shared/SKILL-DESIGN-SPEC.md`
|
3. **Standards Compliance**: Strictly follow `_shared/SKILL-DESIGN-SPEC.md`
|
||||||
4. **可扩展性**: 生成的 Skill 易于扩展和修改
|
4. **Extensibility**: Generated Skills are easy to extend and modify
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## ⚠️ Mandatory Prerequisites (强制前置条件)
|
## Required Prerequisites
|
||||||
|
|
||||||
> **⛔ 禁止跳过**: 在执行任何生成操作之前,**必须**完整阅读以下文档。未阅读规范直接生成将导致输出不符合质量标准。
|
IMPORTANT: Before any generation operation, read the following specification documents. Generating without understanding these standards will result in non-conforming output.
|
||||||
|
|
||||||
### 核心规范 (必读)
|
### Core Specifications (Mandatory Read)
|
||||||
|
|
||||||
| Document | Purpose | Priority |
|
| Document | Purpose | Priority |
|
||||||
|----------|---------|----------|
|
|----------|---------|----------|
|
||||||
| [../_shared/SKILL-DESIGN-SPEC.md](../_shared/SKILL-DESIGN-SPEC.md) | 通用设计规范 - 定义所有 Skill 的结构、命名、质量标准 | **P0 - 最高** |
|
| [../_shared/SKILL-DESIGN-SPEC.md](../_shared/SKILL-DESIGN-SPEC.md) | Universal design spec - defines structure, naming, quality standards for all Skills | **P0 - Critical** |
|
||||||
| [specs/reference-docs-spec.md](specs/reference-docs-spec.md) | **参考文档生成规范** - 确保生成的skill中Reference Documents部分有正确的分阶段组织和使用时机指引 | **P0 - 最高** |
|
| [specs/reference-docs-spec.md](specs/reference-docs-spec.md) | Reference document generation spec - ensures generated Skills have proper phase-based Reference Documents with usage timing guidance | **P0 - Critical** |
|
||||||
|
|
||||||
### 模板文件 (生成前必读)
|
### Template Files (Read Before Generation)
|
||||||
|
|
||||||
| Document | Purpose |
|
| Document | Purpose |
|
||||||
|----------|---------|
|
|----------|---------|
|
||||||
| [templates/skill-md.md](templates/skill-md.md) | SKILL.md 入口文件模板 |
|
| [templates/skill-md.md](templates/skill-md.md) | SKILL.md entry file template |
|
||||||
| [templates/sequential-phase.md](templates/sequential-phase.md) | Sequential Phase 模板 |
|
| [templates/sequential-phase.md](templates/sequential-phase.md) | Sequential Phase template |
|
||||||
| [templates/autonomous-orchestrator.md](templates/autonomous-orchestrator.md) | Autonomous 编排器模板 |
|
| [templates/autonomous-orchestrator.md](templates/autonomous-orchestrator.md) | Autonomous Orchestrator template |
|
||||||
| [templates/autonomous-action.md](templates/autonomous-action.md) | Autonomous Action 模板 |
|
| [templates/autonomous-action.md](templates/autonomous-action.md) | Autonomous Action template |
|
||||||
| [templates/code-analysis-action.md](templates/code-analysis-action.md) | 代码分析 Action 模板 |
|
| [templates/code-analysis-action.md](templates/code-analysis-action.md) | Code Analysis Action template |
|
||||||
| [templates/llm-action.md](templates/llm-action.md) | LLM Action 模板 |
|
| [templates/llm-action.md](templates/llm-action.md) | LLM Action template |
|
||||||
| [templates/script-template.md](templates/script-template.md) | 统一脚本模板 (Bash + Python) |
|
| [templates/script-template.md](templates/script-template.md) | Unified Script Template (Bash + Python) |
|
||||||
|
|
||||||
### 规范文档 (按需阅读)
|
### Specification Documents (Read as Needed)
|
||||||
|
|
||||||
| Document | Purpose |
|
| Document | Purpose |
|
||||||
|----------|---------|
|
|----------|---------|
|
||||||
| [specs/execution-modes.md](specs/execution-modes.md) | 执行模式规范 |
|
| [specs/execution-modes.md](specs/execution-modes.md) | Execution Modes Specification |
|
||||||
| [specs/skill-requirements.md](specs/skill-requirements.md) | Skill 需求规范 |
|
| [specs/skill-requirements.md](specs/skill-requirements.md) | Skill Requirements Specification |
|
||||||
| [specs/cli-integration.md](specs/cli-integration.md) | CLI 集成规范 |
|
| [specs/cli-integration.md](specs/cli-integration.md) | CLI Integration Specification |
|
||||||
| [specs/scripting-integration.md](specs/scripting-integration.md) | 脚本集成规范 |
|
| [specs/scripting-integration.md](specs/scripting-integration.md) | Script Integration Specification |
|
||||||
|
|
||||||
### Phase 执行指南 (执行时参考)
|
### Phase Execution Guides (Reference During Execution)
|
||||||
|
|
||||||
| Document | Purpose |
|
| Document | Purpose |
|
||||||
|----------|---------|
|
|----------|---------|
|
||||||
| [phases/01-requirements-discovery.md](phases/01-requirements-discovery.md) | 收集 Skill 需求 |
|
| [phases/01-requirements-discovery.md](phases/01-requirements-discovery.md) | Collect Skill Requirements |
|
||||||
| [phases/02-structure-generation.md](phases/02-structure-generation.md) | 生成目录结构 |
|
| [phases/02-structure-generation.md](phases/02-structure-generation.md) | Generate Directory Structure |
|
||||||
| [phases/03-phase-generation.md](phases/03-phase-generation.md) | 生成 Phase 文件 |
|
| [phases/03-phase-generation.md](phases/03-phase-generation.md) | Generate Phase Files |
|
||||||
| [phases/04-specs-templates.md](phases/04-specs-templates.md) | 生成规范和模板 |
|
| [phases/04-specs-templates.md](phases/04-specs-templates.md) | Generate Specs and Templates |
|
||||||
| [phases/05-validation.md](phases/05-validation.md) | 验证和文档 |
|
| [phases/05-validation.md](phases/05-validation.md) | Validation and Documentation |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -135,92 +133,73 @@ Phase 01 → Phase 02 → Phase 03 → ... → Phase N
|
|||||||
Input Parsing:
|
Input Parsing:
|
||||||
└─ Convert user request to structured format (skill-name/purpose/mode)
|
└─ Convert user request to structured format (skill-name/purpose/mode)
|
||||||
|
|
||||||
Phase 0: Specification Study (⚠️ MANDATORY - 禁止跳过)
|
Phase 0: Specification Study (MANDATORY - Must complete before proceeding)
|
||||||
└─ Read specification documents
|
- Read specification documents
|
||||||
├─ Load: ../_shared/SKILL-DESIGN-SPEC.md
|
- Load: ../_shared/SKILL-DESIGN-SPEC.md
|
||||||
├─ Load: All templates/*.md files
|
- Load: All templates/*.md files
|
||||||
├─ Understand: Structure rules, naming conventions, quality standards
|
- Understand: Structure rules, naming conventions, quality standards
|
||||||
└─ Output: Internalized requirements (in-memory, no file output)
|
- Output: Internalized requirements (in-memory, no file output)
|
||||||
└─ Validation: ⛔ MUST complete before Phase 1
|
- Validation: MUST complete before Phase 1
|
||||||
|
|
||||||
Phase 1: Requirements Discovery
|
Phase 1: Requirements Discovery
|
||||||
└─ Gather skill requirements via user interaction
|
- Gather skill requirements via user interaction
|
||||||
├─ Tool: AskUserQuestion
|
- Tool: AskUserQuestion
|
||||||
│ ├─ Prompt: Skill name, purpose, execution mode
|
- Collect: Skill name, purpose, execution mode
|
||||||
│ ├─ Prompt: Phase/Action definition
|
- Collect: Phase/Action definition
|
||||||
│ └─ Prompt: Tool dependencies, output format
|
- Collect: Tool dependencies, output format
|
||||||
├─ Process: Generate configuration object
|
- Process: Generate configuration object
|
||||||
└─ Output: skill-config.json → ${workDir}/
|
- Output: skill-config.json
|
||||||
├─ skill_name: string
|
- Contains: skill_name, execution_mode, phases/actions, allowed_tools
|
||||||
├─ execution_mode: "sequential" | "autonomous"
|
|
||||||
├─ phases/actions: array
|
|
||||||
└─ allowed_tools: array
|
|
||||||
|
|
||||||
Phase 2: Structure Generation
|
Phase 2: Structure Generation
|
||||||
└─ Create directory structure and entry file
|
- Create directory structure and entry file
|
||||||
├─ Input: skill-config.json (from Phase 1)
|
- Input: skill-config.json (from Phase 1)
|
||||||
├─ Tool: Bash
|
- Tool: Bash
|
||||||
│ └─ Execute: mkdir -p .claude/skills/{skill-name}/{phases,specs,templates,scripts}
|
- Execute: mkdir -p .claude/skills/{skill-name}/{phases,specs,templates,scripts}
|
||||||
├─ Tool: Write
|
- Tool: Write
|
||||||
│ └─ Generate: SKILL.md (entry point with architecture diagram)
|
- Generate: SKILL.md (entry point with architecture diagram)
|
||||||
└─ Output: Complete directory structure
|
- Output: Complete directory structure
|
||||||
├─ .claude/skills/{skill-name}/SKILL.md
|
|
||||||
├─ .claude/skills/{skill-name}/phases/
|
|
||||||
├─ .claude/skills/{skill-name}/specs/
|
|
||||||
├─ .claude/skills/{skill-name}/templates/
|
|
||||||
└─ .claude/skills/{skill-name}/scripts/
|
|
||||||
|
|
||||||
Phase 3: Phase/Action Generation
|
Phase 3: Phase/Action Generation
|
||||||
└─ Decision (execution_mode check):
|
- Decision (execution_mode check):
|
||||||
├─ execution_mode === "sequential" → Generate Sequential Phases
|
- IF execution_mode === "sequential": Generate Sequential Phases
|
||||||
│ ├─ Tool: Read (template: templates/sequential-phase.md)
|
- Read template: templates/sequential-phase.md
|
||||||
│ ├─ Loop: For each phase in config.sequential_config.phases
|
- Loop: For each phase in config.sequential_config.phases
|
||||||
│ │ ├─ Generate: phases/{phase-id}.md
|
- Generate: phases/{phase-id}.md
|
||||||
│ │ └─ Link: Previous phase output → Current phase input
|
- Link: Previous phase output -> Current phase input
|
||||||
│ ├─ Tool: Write (orchestrator: phases/_orchestrator.md)
|
- Write: phases/_orchestrator.md
|
||||||
│ ├─ Tool: Write (workflow definition: workflow.json)
|
- Write: workflow.json
|
||||||
│ └─ Output: phases/01-{name}.md, phases/02-{name}.md, ...
|
- Output: phases/01-{name}.md, phases/02-{name}.md, ...
|
||||||
│
|
|
||||||
└─ execution_mode === "autonomous" → Generate Orchestrator + Actions
|
- ELSE IF execution_mode === "autonomous": Generate Orchestrator + Actions
|
||||||
├─ Tool: Read (template: templates/autonomous-orchestrator.md)
|
- Read template: templates/autonomous-orchestrator.md
|
||||||
├─ Tool: Write (state schema: phases/state-schema.md)
|
- Write: phases/state-schema.md
|
||||||
├─ Tool: Write (orchestrator: phases/orchestrator.md)
|
- Write: phases/orchestrator.md
|
||||||
├─ Tool: Write (action catalog: specs/action-catalog.md)
|
- Write: specs/action-catalog.md
|
||||||
├─ Loop: For each action in config.autonomous_config.actions
|
- Loop: For each action in config.autonomous_config.actions
|
||||||
│ ├─ Tool: Read (template: templates/autonomous-action.md)
|
- Read template: templates/autonomous-action.md
|
||||||
│ └─ Generate: phases/actions/{action-id}.md
|
- Generate: phases/actions/{action-id}.md
|
||||||
└─ Output: phases/orchestrator.md, phases/actions/*.md
|
- Output: phases/orchestrator.md, phases/actions/*.md
|
||||||
|
|
||||||
Phase 4: Specs & Templates
|
Phase 4: Specs & Templates
|
||||||
└─ Generate domain specifications and templates
|
- Generate domain specifications and templates
|
||||||
├─ Input: skill-config.json (domain context)
|
- Input: skill-config.json (domain context)
|
||||||
├─ ⚠️ 参考规范: [specs/reference-docs-spec.md](specs/reference-docs-spec.md) - 确保生成的参考文档有正确的分阶段组织
|
- Reference: [specs/reference-docs-spec.md](specs/reference-docs-spec.md) for document organization
|
||||||
├─ Tool: Write
|
- Tool: Write
|
||||||
│ ├─ Generate: specs/{domain}-requirements.md
|
- Generate: specs/{domain}-requirements.md
|
||||||
│ ├─ Generate: specs/quality-standards.md
|
- Generate: specs/quality-standards.md
|
||||||
│ └─ Generate: templates/agent-base.md (if needed)
|
- Generate: templates/agent-base.md (if needed)
|
||||||
└─ Output: Domain-specific documentation
|
- Output: Domain-specific documentation
|
||||||
├─ specs/{skill-name}-requirements.md
|
|
||||||
├─ specs/quality-standards.md
|
|
||||||
└─ templates/agent-base.md
|
|
||||||
|
|
||||||
Phase 5: Validation & Documentation
|
Phase 5: Validation & Documentation
|
||||||
└─ Verify completeness and generate usage guide
|
- Verify completeness and generate usage guide
|
||||||
├─ Input: All generated files from previous phases
|
- Input: All generated files from previous phases
|
||||||
├─ Tool: Glob + Read
|
- Tool: Glob + Read
|
||||||
│ └─ Check: Required files exist and contain proper structure
|
- Check: Required files exist and contain proper structure
|
||||||
├─ Tool: Write
|
- Tool: Write
|
||||||
│ ├─ Generate: README.md (usage instructions)
|
- Generate: README.md (usage instructions)
|
||||||
│ └─ Generate: validation-report.json (completeness check)
|
- Generate: validation-report.json (completeness check)
|
||||||
└─ Output: Final documentation
|
- Output: Final documentation
|
||||||
├─ README.md (how to use this skill)
|
|
||||||
└─ validation-report.json (quality gate results)
|
|
||||||
|
|
||||||
Return:
|
|
||||||
└─ Summary with skill location and next steps
|
|
||||||
├─ Skill path: .claude/skills/{skill-name}/
|
|
||||||
├─ Status: ✅ All phases completed
|
|
||||||
└─ Suggestion: "Review SKILL.md and customize phase files as needed"
|
|
||||||
```
|
```
|
||||||
|
|
||||||
**Execution Protocol**:
|
**Execution Protocol**:
|
||||||
@@ -278,83 +257,83 @@ Write(`${skillDir}/README.md`, generateReadme(config, validation));
|
|||||||
|
|
||||||
## Reference Documents by Phase
|
## Reference Documents by Phase
|
||||||
|
|
||||||
> **重要**: 本部分展示skill-generator如何组织自己的参考文档,这是生成的skill应该模仿的示例。详见 [specs/reference-docs-spec.md](specs/reference-docs-spec.md)
|
IMPORTANT: This section demonstrates how skill-generator organizes its own reference documentation. This is the pattern that all generated Skills should emulate. See [specs/reference-docs-spec.md](specs/reference-docs-spec.md) for details.
|
||||||
|
|
||||||
### 🔧 Phase 0: Specification Study (强制前置)
|
### Phase 0: Specification Study (Mandatory Prerequisites)
|
||||||
|
|
||||||
所有生成操作前必须阅读的规范
|
Specification documents that must be read before any generation operation
|
||||||
|
|
||||||
| Document | Purpose | When to Use |
|
| Document | Purpose | When to Use |
|
||||||
|----------|---------|-------------|
|
|----------|---------|-------------|
|
||||||
| [../_shared/SKILL-DESIGN-SPEC.md](../_shared/SKILL-DESIGN-SPEC.md) | Skill设计通用规范 | 理解Skill结构和命名规范 ✅ **必读** |
|
| [../_shared/SKILL-DESIGN-SPEC.md](../_shared/SKILL-DESIGN-SPEC.md) | Universal Skill design specification | Understand Skill structure and naming conventions - **REQUIRED** |
|
||||||
| [specs/reference-docs-spec.md](specs/reference-docs-spec.md) | 参考文档生成规范 | 确保Reference Documents有正确的组织方式 ✅ **必读** |
|
| [specs/reference-docs-spec.md](specs/reference-docs-spec.md) | Reference document generation specification | Ensure Reference Documents have proper phase-based organization - **REQUIRED** |
|
||||||
|
|
||||||
### 📋 Phase 1: Requirements Discovery
|
### Phase 1: Requirements Discovery
|
||||||
|
|
||||||
收集Skill需求和配置
|
Collect Skill requirements and configuration
|
||||||
|
|
||||||
| Document | Purpose | When to Use |
|
| Document | Purpose | When to Use |
|
||||||
|----------|---------|-------------|
|
|----------|---------|-------------|
|
||||||
| [phases/01-requirements-discovery.md](phases/01-requirements-discovery.md) | Phase 1执行指南 | 理解如何收集用户需求和生成配置 |
|
| [phases/01-requirements-discovery.md](phases/01-requirements-discovery.md) | Phase 1 execution guide | Understand how to collect user requirements and generate configuration |
|
||||||
| [specs/skill-requirements.md](specs/skill-requirements.md) | Skill需求规范 | 理解Skill应包含哪些信息 |
|
| [specs/skill-requirements.md](specs/skill-requirements.md) | Skill requirements specification | Understand what information a Skill should contain |
|
||||||
|
|
||||||
### 🔧 Phase 2: Structure Generation
|
### Phase 2: Structure Generation
|
||||||
|
|
||||||
生成目录结构和入口文件
|
Generate directory structure and entry file
|
||||||
|
|
||||||
| Document | Purpose | When to Use |
|
| Document | Purpose | When to Use |
|
||||||
|----------|---------|-------------|
|
|----------|---------|-------------|
|
||||||
| [phases/02-structure-generation.md](phases/02-structure-generation.md) | Phase 2执行指南 | 理解如何生成目录结构 |
|
| [phases/02-structure-generation.md](phases/02-structure-generation.md) | Phase 2 execution guide | Understand how to generate directory structure |
|
||||||
| [templates/skill-md.md](templates/skill-md.md) | SKILL.md模板 | 了解如何生成入口文件 |
|
| [templates/skill-md.md](templates/skill-md.md) | SKILL.md template | Learn how to generate the entry file |
|
||||||
|
|
||||||
### ⚙️ Phase 3: Phase/Action Generation
|
### Phase 3: Phase/Action Generation
|
||||||
|
|
||||||
根据执行模式生成具体的phase或action文件
|
Generate specific phase or action files based on execution mode
|
||||||
|
|
||||||
| Document | Purpose | When to Use |
|
| Document | Purpose | When to Use |
|
||||||
|----------|---------|-------------|
|
|----------|---------|-------------|
|
||||||
| [phases/03-phase-generation.md](phases/03-phase-generation.md) | Phase 3执行指南 | 理解Sequential vs Autonomous生成逻辑 |
|
| [phases/03-phase-generation.md](phases/03-phase-generation.md) | Phase 3 execution guide | Understand Sequential vs Autonomous generation logic |
|
||||||
| [templates/sequential-phase.md](templates/sequential-phase.md) | Sequential Phase模板 | 生成Sequential模式的phase文件 |
|
| [templates/sequential-phase.md](templates/sequential-phase.md) | Sequential Phase template | Generate phase files for Sequential mode |
|
||||||
| [templates/autonomous-orchestrator.md](templates/autonomous-orchestrator.md) | Orchestrator模板 | 生成Autonomous模式的编排器 |
|
| [templates/autonomous-orchestrator.md](templates/autonomous-orchestrator.md) | Orchestrator template | Generate orchestrator for Autonomous mode |
|
||||||
| [templates/autonomous-action.md](templates/autonomous-action.md) | Action模板 | 生成Autonomous模式的action |
|
| [templates/autonomous-action.md](templates/autonomous-action.md) | Action template | Generate action files for Autonomous mode |
|
||||||
|
|
||||||
### ✅ Phase 4: Specs & Templates
|
### Phase 4: Specs & Templates
|
||||||
|
|
||||||
生成领域特定的规范和模板
|
Generate domain-specific specifications and templates
|
||||||
|
|
||||||
| Document | Purpose | When to Use |
|
| Document | Purpose | When to Use |
|
||||||
|----------|---------|-------------|
|
|----------|---------|-------------|
|
||||||
| [phases/04-specs-templates.md](phases/04-specs-templates.md) | Phase 4执行指南 | 理解如何生成domain-specific文档 |
|
| [phases/04-specs-templates.md](phases/04-specs-templates.md) | Phase 4 execution guide | Understand how to generate domain-specific documentation |
|
||||||
| [specs/reference-docs-spec.md](specs/reference-docs-spec.md) | 参考文档规范 | ⭐ 生成Specs时要遵循的规范 |
|
| [specs/reference-docs-spec.md](specs/reference-docs-spec.md) | Reference document specification | IMPORTANT: Follow this spec when generating Specs |
|
||||||
|
|
||||||
### 🏁 Phase 5: Validation & Documentation
|
### Phase 5: Validation & Documentation
|
||||||
|
|
||||||
验证生成结果并生成最终文档
|
Verify results and generate final documentation
|
||||||
|
|
||||||
| Document | Purpose | When to Use |
|
| Document | Purpose | When to Use |
|
||||||
|----------|---------|-------------|
|
|----------|---------|-------------|
|
||||||
| [phases/05-validation.md](phases/05-validation.md) | Phase 5执行指南 | 理解如何验证生成的skill完整性 |
|
| [phases/05-validation.md](phases/05-validation.md) | Phase 5 execution guide | Understand how to verify generated Skill completeness |
|
||||||
|
|
||||||
### 🔍 Debugging & Troubleshooting
|
### Debugging & Troubleshooting
|
||||||
|
|
||||||
遇到问题时查阅
|
Reference documents when encountering issues
|
||||||
|
|
||||||
| Issue | Solution Document |
|
| Issue | Solution Document |
|
||||||
|-------|------------------|
|
|-------|------------------|
|
||||||
| 生成的Skill缺少Reference Documents | [specs/reference-docs-spec.md](specs/reference-docs-spec.md) - 检查是否遵循分阶段组织 |
|
| Generated Skill missing Reference Documents | [specs/reference-docs-spec.md](specs/reference-docs-spec.md) - verify phase-based organization is followed |
|
||||||
| 参考文档组织混乱 | [specs/reference-docs-spec.md](specs/reference-docs-spec.md) - 核心原则部分 |
|
| Reference document organization unclear | [specs/reference-docs-spec.md](specs/reference-docs-spec.md) - Core Principles section |
|
||||||
| 生成的文档不符合质量标准 | [../_shared/SKILL-DESIGN-SPEC.md](../_shared/SKILL-DESIGN-SPEC.md) |
|
| Generated documentation does not meet quality standards | [../_shared/SKILL-DESIGN-SPEC.md](../_shared/SKILL-DESIGN-SPEC.md) |
|
||||||
|
|
||||||
### 📚 Reference & Background
|
### Reference & Background
|
||||||
|
|
||||||
用于深度学习和设计决策
|
Documents for deep learning and design decisions
|
||||||
|
|
||||||
| Document | Purpose | Notes |
|
| Document | Purpose | Notes |
|
||||||
|----------|---------|-------|
|
|----------|---------|-------|
|
||||||
| [specs/execution-modes.md](specs/execution-modes.md) | 执行模式详细规范 | Sequential vs Autonomous的对比和适用场景 |
|
| [specs/execution-modes.md](specs/execution-modes.md) | Detailed execution modes specification | Comparison and use cases for Sequential vs Autonomous |
|
||||||
| [specs/cli-integration.md](specs/cli-integration.md) | CLI集成规范 | 生成的Skill如何与CLI集成 |
|
| [specs/cli-integration.md](specs/cli-integration.md) | CLI integration specification | How generated Skills integrate with CLI |
|
||||||
| [specs/scripting-integration.md](specs/scripting-integration.md) | 脚本集成规范 | Phase中如何使用脚本 |
|
| [specs/scripting-integration.md](specs/scripting-integration.md) | Script integration specification | How to use scripts in Phases |
|
||||||
| [templates/script-template.md](templates/script-template.md) | 脚本模板 | Bash + Python统一模板 |
|
| [templates/script-template.md](templates/script-template.md) | Script template | Unified Bash + Python template |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -364,13 +343,13 @@ Write(`${skillDir}/README.md`, generateReadme(config, validation));
|
|||||||
|
|
||||||
```
|
```
|
||||||
.claude/skills/{skill-name}/
|
.claude/skills/{skill-name}/
|
||||||
├── SKILL.md # 入口文件
|
├── SKILL.md # Entry file
|
||||||
├── phases/
|
├── phases/
|
||||||
│ ├── _orchestrator.md # 声明式编排器
|
│ ├── _orchestrator.md # Declarative orchestrator
|
||||||
│ ├── workflow.json # 工作流定义
|
│ ├── workflow.json # Workflow definition
|
||||||
│ ├── 01-{step-one}.md # 阶段 1
|
│ ├── 01-{step-one}.md # Phase 1
|
||||||
│ ├── 02-{step-two}.md # 阶段 2
|
│ ├── 02-{step-two}.md # Phase 2
|
||||||
│ └── 03-{step-three}.md # 阶段 3
|
│ └── 03-{step-three}.md # Phase 3
|
||||||
├── specs/
|
├── specs/
|
||||||
│ ├── {skill-name}-requirements.md
|
│ ├── {skill-name}-requirements.md
|
||||||
│ └── quality-standards.md
|
│ └── quality-standards.md
|
||||||
@@ -384,10 +363,10 @@ Write(`${skillDir}/README.md`, generateReadme(config, validation));
|
|||||||
|
|
||||||
```
|
```
|
||||||
.claude/skills/{skill-name}/
|
.claude/skills/{skill-name}/
|
||||||
├── SKILL.md # 入口文件
|
├── SKILL.md # Entry file
|
||||||
├── phases/
|
├── phases/
|
||||||
│ ├── orchestrator.md # 编排器 (状态驱动)
|
│ ├── orchestrator.md # Orchestrator (state-driven)
|
||||||
│ ├── state-schema.md # 状态结构定义
|
│ ├── state-schema.md # State schema definition
|
||||||
│ └── actions/
|
│ └── actions/
|
||||||
│ ├── action-init.md
|
│ ├── action-init.md
|
||||||
│ ├── action-create.md
|
│ ├── action-create.md
|
||||||
@@ -407,80 +386,80 @@ Write(`${skillDir}/README.md`, generateReadme(config, validation));
|
|||||||
|
|
||||||
## Reference Documents by Phase
|
## Reference Documents by Phase
|
||||||
|
|
||||||
> **重要**: 本部分展示skill-generator如何组织自己的参考文档,这是生成的skill应该模仿的示例。详见 [specs/reference-docs-spec.md](specs/reference-docs-spec.md)
|
IMPORTANT: This section demonstrates how skill-generator organizes its own reference documentation. This is the pattern that all generated Skills should emulate. See [specs/reference-docs-spec.md](specs/reference-docs-spec.md) for details.
|
||||||
|
|
||||||
### 🔧 Phase 0: Specification Study (强制前置)
|
### Phase 0: Specification Study (Mandatory Prerequisites)
|
||||||
|
|
||||||
所有生成操作前必须阅读的规范
|
Specification documents that must be read before any generation operation
|
||||||
|
|
||||||
| Document | Purpose | When to Use |
|
| Document | Purpose | When to Use |
|
||||||
|----------|---------|-------------|
|
|----------|---------|-------------|
|
||||||
| [../_shared/SKILL-DESIGN-SPEC.md](../_shared/SKILL-DESIGN-SPEC.md) | Skill设计通用规范 | 理解Skill结构和命名规范 ✅ **必读** |
|
| [../_shared/SKILL-DESIGN-SPEC.md](../_shared/SKILL-DESIGN-SPEC.md) | Universal Skill design specification | Understand Skill structure and naming conventions - **REQUIRED** |
|
||||||
| [specs/reference-docs-spec.md](specs/reference-docs-spec.md) | 参考文档生成规范 | 确保Reference Documents有正确的组织方式 ✅ **必读** |
|
| [specs/reference-docs-spec.md](specs/reference-docs-spec.md) | Reference document generation specification | Ensure Reference Documents have proper phase-based organization - **REQUIRED** |
|
||||||
|
|
||||||
### 📋 Phase 1: Requirements Discovery
|
### Phase 1: Requirements Discovery
|
||||||
|
|
||||||
收集Skill需求和配置
|
Collect Skill requirements and configuration
|
||||||
|
|
||||||
| Document | Purpose | When to Use |
|
| Document | Purpose | When to Use |
|
||||||
|----------|---------|-------------|
|
|----------|---------|-------------|
|
||||||
| [phases/01-requirements-discovery.md](phases/01-requirements-discovery.md) | Phase 1执行指南 | 理解如何收集用户需求和生成配置 |
|
| [phases/01-requirements-discovery.md](phases/01-requirements-discovery.md) | Phase 1 execution guide | Understand how to collect user requirements and generate configuration |
|
||||||
| [specs/skill-requirements.md](specs/skill-requirements.md) | Skill需求规范 | 理解Skill应包含哪些信息 |
|
| [specs/skill-requirements.md](specs/skill-requirements.md) | Skill requirements specification | Understand what information a Skill should contain |
|
||||||
|
|
||||||
### 🔧 Phase 2: Structure Generation
|
### Phase 2: Structure Generation
|
||||||
|
|
||||||
生成目录结构和入口文件
|
Generate directory structure and entry file
|
||||||
|
|
||||||
| Document | Purpose | When to Use |
|
| Document | Purpose | When to Use |
|
||||||
|----------|---------|-------------|
|
|----------|---------|-------------|
|
||||||
| [phases/02-structure-generation.md](phases/02-structure-generation.md) | Phase 2执行指南 | 理解如何生成目录结构 |
|
| [phases/02-structure-generation.md](phases/02-structure-generation.md) | Phase 2 execution guide | Understand how to generate directory structure |
|
||||||
| [templates/skill-md.md](templates/skill-md.md) | SKILL.md模板 | 了解如何生成入口文件 |
|
| [templates/skill-md.md](templates/skill-md.md) | SKILL.md template | Learn how to generate the entry file |
|
||||||
|
|
||||||
### ⚙️ Phase 3: Phase/Action Generation
|
### Phase 3: Phase/Action Generation
|
||||||
|
|
||||||
根据执行模式生成具体的phase或action文件
|
Generate specific phase or action files based on execution mode
|
||||||
|
|
||||||
| Document | Purpose | When to Use |
|
| Document | Purpose | When to Use |
|
||||||
|----------|---------|-------------|
|
|----------|---------|-------------|
|
||||||
| [phases/03-phase-generation.md](phases/03-phase-generation.md) | Phase 3执行指南 | 理解Sequential vs Autonomous生成逻辑 |
|
| [phases/03-phase-generation.md](phases/03-phase-generation.md) | Phase 3 execution guide | Understand Sequential vs Autonomous generation logic |
|
||||||
| [templates/sequential-phase.md](templates/sequential-phase.md) | Sequential Phase模板 | 生成Sequential模式的phase文件 |
|
| [templates/sequential-phase.md](templates/sequential-phase.md) | Sequential Phase template | Generate phase files for Sequential mode |
|
||||||
| [templates/autonomous-orchestrator.md](templates/autonomous-orchestrator.md) | Orchestrator模板 | 生成Autonomous模式的编排器 |
|
| [templates/autonomous-orchestrator.md](templates/autonomous-orchestrator.md) | Orchestrator template | Generate orchestrator for Autonomous mode |
|
||||||
| [templates/autonomous-action.md](templates/autonomous-action.md) | Action模板 | 生成Autonomous模式的action |
|
| [templates/autonomous-action.md](templates/autonomous-action.md) | Action template | Generate action files for Autonomous mode |
|
||||||
|
|
||||||
### ✅ Phase 4: Specs & Templates
|
### Phase 4: Specs & Templates
|
||||||
|
|
||||||
生成领域特定的规范和模板
|
Generate domain-specific specifications and templates
|
||||||
|
|
||||||
| Document | Purpose | When to Use |
|
| Document | Purpose | When to Use |
|
||||||
|----------|---------|-------------|
|
|----------|---------|-------------|
|
||||||
| [phases/04-specs-templates.md](phases/04-specs-templates.md) | Phase 4执行指南 | 理解如何生成domain-specific文档 |
|
| [phases/04-specs-templates.md](phases/04-specs-templates.md) | Phase 4 execution guide | Understand how to generate domain-specific documentation |
|
||||||
| [specs/reference-docs-spec.md](specs/reference-docs-spec.md) | 参考文档规范 | ⭐ 生成Specs时要遵循的规范 |
|
| [specs/reference-docs-spec.md](specs/reference-docs-spec.md) | Reference document specification | IMPORTANT: Follow this spec when generating Specs |
|
||||||
|
|
||||||
### 🏁 Phase 5: Validation & Documentation
|
### Phase 5: Validation & Documentation
|
||||||
|
|
||||||
验证生成结果并生成最终文档
|
Verify results and generate final documentation
|
||||||
|
|
||||||
| Document | Purpose | When to Use |
|
| Document | Purpose | When to Use |
|
||||||
|----------|---------|-------------|
|
|----------|---------|-------------|
|
||||||
| [phases/05-validation.md](phases/05-validation.md) | Phase 5执行指南 | 理解如何验证生成的skill完整性 |
|
| [phases/05-validation.md](phases/05-validation.md) | Phase 5 execution guide | Understand how to verify generated Skill completeness |
|
||||||
|
|
||||||
### 🔍 Debugging & Troubleshooting
|
### Debugging & Troubleshooting
|
||||||
|
|
||||||
遇到问题时查阅
|
Reference documents when encountering issues
|
||||||
|
|
||||||
| Issue | Solution Document |
|
| Issue | Solution Document |
|
||||||
|-------|------------------|
|
|-------|------------------|
|
||||||
| 生成的Skill缺少Reference Documents | [specs/reference-docs-spec.md](specs/reference-docs-spec.md) - 检查是否遵循分阶段组织 |
|
| Generated Skill missing Reference Documents | [specs/reference-docs-spec.md](specs/reference-docs-spec.md) - verify phase-based organization is followed |
|
||||||
| 参考文档组织混乱 | [specs/reference-docs-spec.md](specs/reference-docs-spec.md) - 核心原则部分 |
|
| Reference document organization unclear | [specs/reference-docs-spec.md](specs/reference-docs-spec.md) - Core Principles section |
|
||||||
| 生成的文档不符合质量标准 | [../_shared/SKILL-DESIGN-SPEC.md](../_shared/SKILL-DESIGN-SPEC.md) |
|
| Generated documentation does not meet quality standards | [../_shared/SKILL-DESIGN-SPEC.md](../_shared/SKILL-DESIGN-SPEC.md) |
|
||||||
|
|
||||||
### 📚 Reference & Background
|
### Reference & Background
|
||||||
|
|
||||||
用于深度学习和设计决策
|
Documents for deep learning and design decisions
|
||||||
|
|
||||||
| Document | Purpose | Notes |
|
| Document | Purpose | Notes |
|
||||||
|----------|---------|-------|
|
|----------|---------|-------|
|
||||||
| [specs/execution-modes.md](specs/execution-modes.md) | 执行模式详细规范 | Sequential vs Autonomous的对比和适用场景 |
|
| [specs/execution-modes.md](specs/execution-modes.md) | Detailed execution modes specification | Comparison and use cases for Sequential vs Autonomous |
|
||||||
| [specs/cli-integration.md](specs/cli-integration.md) | CLI集成规范 | 生成的Skill如何与CLI集成 |
|
| [specs/cli-integration.md](specs/cli-integration.md) | CLI integration specification | How generated Skills integrate with CLI |
|
||||||
| [specs/scripting-integration.md](specs/scripting-integration.md) | 脚本集成规范 | Phase中如何使用脚本 |
|
| [specs/scripting-integration.md](specs/scripting-integration.md) | Script integration specification | How to use scripts in Phases |
|
||||||
| [templates/script-template.md](templates/script-template.md) | 脚本模板 | Bash + Python统一模板 |
|
| [templates/script-template.md](templates/script-template.md) | Script template | Unified Bash + Python template |
|
||||||
@@ -1,114 +1,125 @@
|
|||||||
|
# Phase 1: Requirements Discovery
|
||||||
|
|
||||||
|
Collect basic skill information, configuration, and execution mode based on user input.
|
||||||
|
|
||||||
### Step 1: 基本信息收集
|
## Objective
|
||||||
|
|
||||||
|
- Collect skill basic information (name, description, trigger words)
|
||||||
|
- Determine execution mode (Sequential/Autonomous/Hybrid)
|
||||||
|
- Define phases or actions
|
||||||
|
- Generate initial configuration file
|
||||||
|
|
||||||
|
## Execution Steps
|
||||||
|
|
||||||
|
### Step 1: Basic Information Collection
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
const basicInfo = await AskUserQuestion({
|
const basicInfo = await AskUserQuestion({
|
||||||
questions: [
|
questions: [
|
||||||
{
|
{
|
||||||
question: "新 Skill 的名称是什么?(英文,小写-连字符格式,如 'api-docs')",
|
question: "What is the name of the new Skill? (English, lowercase with hyphens, e.g., 'api-docs')",
|
||||||
header: "Skill 名称",
|
header: "Skill Name",
|
||||||
multiSelect: false,
|
multiSelect: false,
|
||||||
options: [
|
options: [
|
||||||
{ label: "自动生成", description: "根据后续描述自动生成名称" },
|
{ label: "Auto-generate", description: "Generate name automatically based on description" },
|
||||||
{ label: "手动输入", description: "现在输入自定义名称" }
|
{ label: "Manual Input", description: "Enter custom name now" }
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
question: "Skill 的主要用途是什么?",
|
question: "What is the primary purpose of the Skill?",
|
||||||
header: "用途类型",
|
header: "Purpose Type",
|
||||||
multiSelect: false,
|
multiSelect: false,
|
||||||
options: [
|
options: [
|
||||||
{ label: "文档生成", description: "生成 Markdown/HTML 文档(如手册、报告)" },
|
{ label: "Document Generation", description: "Generate Markdown/HTML documents (manuals, reports)" },
|
||||||
{ label: "代码分析", description: "分析代码结构、质量、安全性" },
|
{ label: "Code Analysis", description: "Analyze code structure, quality, security" },
|
||||||
{ label: "交互管理", description: "管理 Issue、任务、工作流(CRUD 操作)" },
|
{ label: "Interactive Management", description: "Manage Issues, tasks, workflows (CRUD operations)" },
|
||||||
{ label: "数据处理", description: "ETL、格式转换、报告生成" }
|
{ label: "Data Processing", description: "ETL, format conversion, report generation" }
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
});
|
});
|
||||||
|
|
||||||
// 如果选择手动输入,进一步询问
|
// If manual input is selected, prompt further
|
||||||
if (basicInfo["Skill 名称"] === "手动输入") {
|
if (basicInfo["Skill Name"] === "Manual Input") {
|
||||||
// 用户会在 "Other" 中输入
|
// User will input in "Other"
|
||||||
}
|
}
|
||||||
|
|
||||||
// 根据用途类型推断描述模板
|
// Infer description template based on purpose type
|
||||||
const purposeTemplates = {
|
const purposeTemplates = {
|
||||||
"文档生成": "Generate {type} documents from {source}",
|
"Document Generation": "Generate {type} documents from {source}",
|
||||||
"代码分析": "Analyze {target} for {purpose}",
|
"Code Analysis": "Analyze {target} for {purpose}",
|
||||||
"交互管理": "Manage {entity} with interactive operations",
|
"Interactive Management": "Manage {entity} with interactive operations",
|
||||||
"数据处理": "Process {data} and generate {output}"
|
"Data Processing": "Process {data} and generate {output}"
|
||||||
};
|
};
|
||||||
```
|
```
|
||||||
|
|
||||||
### Step 2: 执行模式选择
|
### Step 2: Execution Mode Selection
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
const modeInfo = await AskUserQuestion({
|
const modeInfo = await AskUserQuestion({
|
||||||
questions: [
|
questions: [
|
||||||
{
|
{
|
||||||
question: "选择执行模式:",
|
question: "Select execution mode:",
|
||||||
header: "执行模式",
|
header: "Execution Mode",
|
||||||
multiSelect: false,
|
multiSelect: false,
|
||||||
options: [
|
options: [
|
||||||
{
|
{
|
||||||
label: "Sequential (顺序模式)",
|
label: "Sequential (Sequential Mode)",
|
||||||
description: "阶段按固定顺序执行(收集→分析→生成),适合流水线任务(推荐)"
|
description: "Phases execute in fixed order (collect→analyze→generate), suitable for pipeline tasks (recommended)"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
label: "Autonomous (自主模式)",
|
label: "Autonomous (Autonomous Mode)",
|
||||||
description: "动态选择执行路径,适合交互式任务(如 Issue 管理)"
|
description: "Dynamically select execution path, suitable for interactive tasks (e.g., Issue management)"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
label: "Hybrid (混合模式)",
|
label: "Hybrid (Hybrid Mode)",
|
||||||
description: "初始化和收尾固定,中间交互灵活"
|
description: "Fixed initialization and finalization, flexible interaction in the middle"
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
});
|
});
|
||||||
|
|
||||||
const executionMode = modeInfo["执行模式"].includes("Sequential") ? "sequential" :
|
const executionMode = modeInfo["Execution Mode"].includes("Sequential") ? "sequential" :
|
||||||
modeInfo["执行模式"].includes("Autonomous") ? "autonomous" : "hybrid";
|
modeInfo["Execution Mode"].includes("Autonomous") ? "autonomous" : "hybrid";
|
||||||
```
|
```
|
||||||
|
|
||||||
### Step 3: 阶段/动作定义
|
### Step 3: Phase/Action Definition
|
||||||
|
|
||||||
#### Sequential 模式
|
#### Sequential Mode
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
if (executionMode === "sequential") {
|
if (executionMode === "sequential") {
|
||||||
const phaseInfo = await AskUserQuestion({
|
const phaseInfo = await AskUserQuestion({
|
||||||
questions: [
|
questions: [
|
||||||
{
|
{
|
||||||
question: "需要多少个执行阶段?",
|
question: "How many execution phases are needed?",
|
||||||
header: "阶段数量",
|
header: "Phase Count",
|
||||||
multiSelect: false,
|
multiSelect: false,
|
||||||
options: [
|
options: [
|
||||||
{ label: "3 阶段(简单)", description: "收集 → 处理 → 输出" },
|
{ label: "3 Phases (Simple)", description: "Collection → Processing → Output" },
|
||||||
{ label: "5 阶段(标准)", description: "收集 → 探索 → 分析 → 组装 → 验证" },
|
{ label: "5 Phases (Standard)", description: "Collection → Exploration → Analysis → Assembly → Validation" },
|
||||||
{ label: "7 阶段(完整)", description: "含并行处理、汇总、迭代优化" }
|
{ label: "7 Phases (Complete)", description: "Includes parallel processing, consolidation, iterative optimization" }
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
});
|
});
|
||||||
|
|
||||||
// 根据选择生成阶段定义
|
// Generate phase definitions based on selection
|
||||||
const phaseTemplates = {
|
const phaseTemplates = {
|
||||||
"3 阶段": [
|
"3 Phases": [
|
||||||
{ id: "01-collection", name: "Data Collection" },
|
{ id: "01-collection", name: "Data Collection" },
|
||||||
{ id: "02-processing", name: "Processing" },
|
{ id: "02-processing", name: "Processing" },
|
||||||
{ id: "03-output", name: "Output Generation" }
|
{ id: "03-output", name: "Output Generation" }
|
||||||
],
|
],
|
||||||
"5 阶段": [
|
"5 Phases": [
|
||||||
{ id: "01-collection", name: "Requirements Collection" },
|
{ id: "01-collection", name: "Requirements Collection" },
|
||||||
{ id: "02-exploration", name: "Project Exploration" },
|
{ id: "02-exploration", name: "Project Exploration" },
|
||||||
{ id: "03-analysis", name: "Deep Analysis" },
|
{ id: "03-analysis", name: "Deep Analysis" },
|
||||||
{ id: "04-assembly", name: "Document Assembly" },
|
{ id: "04-assembly", name: "Document Assembly" },
|
||||||
{ id: "05-validation", name: "Validation" }
|
{ id: "05-validation", name: "Validation" }
|
||||||
],
|
],
|
||||||
"7 阶段": [
|
"7 Phases": [
|
||||||
{ id: "01-collection", name: "Requirements Collection" },
|
{ id: "01-collection", name: "Requirements Collection" },
|
||||||
{ id: "02-exploration", name: "Project Exploration" },
|
{ id: "02-exploration", name: "Project Exploration" },
|
||||||
{ id: "03-parallel", name: "Parallel Analysis" },
|
{ id: "03-parallel", name: "Parallel Analysis" },
|
||||||
@@ -121,23 +132,23 @@ if (executionMode === "sequential") {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
#### Autonomous 模式
|
#### Autonomous Mode
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
if (executionMode === "autonomous") {
|
if (executionMode === "autonomous") {
|
||||||
const actionInfo = await AskUserQuestion({
|
const actionInfo = await AskUserQuestion({
|
||||||
questions: [
|
questions: [
|
||||||
{
|
{
|
||||||
question: "核心动作有哪些?(可多选)",
|
question: "What are the core actions? (Multiple selection allowed)",
|
||||||
header: "动作定义",
|
header: "Action Definition",
|
||||||
multiSelect: true,
|
multiSelect: true,
|
||||||
options: [
|
options: [
|
||||||
{ label: "初始化 (init)", description: "设置初始状态" },
|
{ label: "Initialize (init)", description: "Set initial state" },
|
||||||
{ label: "列表 (list)", description: "显示当前项目列表" },
|
{ label: "List (list)", description: "Display current item list" },
|
||||||
{ label: "创建 (create)", description: "创建新项目" },
|
{ label: "Create (create)", description: "Create new item" },
|
||||||
{ label: "编辑 (edit)", description: "修改现有项目" },
|
{ label: "Edit (edit)", description: "Modify existing item" },
|
||||||
{ label: "删除 (delete)", description: "删除项目" },
|
{ label: "Delete (delete)", description: "Delete item" },
|
||||||
{ label: "搜索 (search)", description: "搜索/过滤项目" }
|
{ label: "Search (search)", description: "Search/filter items" }
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
@@ -145,37 +156,37 @@ if (executionMode === "autonomous") {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
### Step 4: 工具和输出配置
|
### Step 4: Tool and Output Configuration
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
const toolsInfo = await AskUserQuestion({
|
const toolsInfo = await AskUserQuestion({
|
||||||
questions: [
|
questions: [
|
||||||
{
|
{
|
||||||
question: "需要哪些特殊工具?(基础工具已默认包含)",
|
question: "Which special tools are needed? (Basic tools are included by default)",
|
||||||
header: "工具选择",
|
header: "Tool Selection",
|
||||||
multiSelect: true,
|
multiSelect: true,
|
||||||
options: [
|
options: [
|
||||||
{ label: "用户交互 (AskUserQuestion)", description: "需要与用户对话" },
|
{ label: "User Interaction (AskUserQuestion)", description: "Need to dialog with user" },
|
||||||
{ label: "Chrome 截图 (mcp__chrome__*)", description: "需要网页截图" },
|
{ label: "Chrome Screenshot (mcp__chrome__*)", description: "Need web page screenshots" },
|
||||||
{ label: "外部搜索 (mcp__exa__search)", description: "需要搜索外部信息" },
|
{ label: "External Search (mcp__exa__search)", description: "Need to search external information" },
|
||||||
{ label: "无特殊需求", description: "仅使用基础工具" }
|
{ label: "No Special Requirements", description: "Use basic tools only" }
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
question: "输出格式是什么?",
|
question: "What is the output format?",
|
||||||
header: "输出格式",
|
header: "Output Format",
|
||||||
multiSelect: false,
|
multiSelect: false,
|
||||||
options: [
|
options: [
|
||||||
{ label: "Markdown", description: "适合文档和报告" },
|
{ label: "Markdown", description: "Suitable for documents and reports" },
|
||||||
{ label: "HTML", description: "适合交互式文档" },
|
{ label: "HTML", description: "Suitable for interactive documents" },
|
||||||
{ label: "JSON", description: "适合数据和配置" }
|
{ label: "JSON", description: "Suitable for data and configuration" }
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
});
|
});
|
||||||
```
|
```
|
||||||
|
|
||||||
### Step 5: 生成配置文件
|
### Step 5: Generate Configuration File
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
const config = {
|
const config = {
|
||||||
@@ -185,7 +196,7 @@ const config = {
|
|||||||
triggers: triggers,
|
triggers: triggers,
|
||||||
execution_mode: executionMode,
|
execution_mode: executionMode,
|
||||||
|
|
||||||
// 模式特定配置
|
// Mode-specific configuration
|
||||||
...(executionMode === "sequential" ? {
|
...(executionMode === "sequential" ? {
|
||||||
sequential_config: { phases: phases }
|
sequential_config: { phases: phases }
|
||||||
} : {
|
} : {
|
||||||
@@ -211,14 +222,13 @@ const config = {
|
|||||||
version: "1.0.0"
|
version: "1.0.0"
|
||||||
};
|
};
|
||||||
|
|
||||||
// 写入配置文件
|
// Write configuration file
|
||||||
const workDir = `.workflow/.scratchpad/skill-gen-${timestamp}`;
|
const workDir = `.workflow/.scratchpad/skill-gen-${timestamp}`;
|
||||||
Bash(`mkdir -p "${workDir}"`);
|
Bash(`mkdir -p "${workDir}"`);
|
||||||
Write(`${workDir}/skill-config.json`, JSON.stringify(config, null, 2));
|
Write(`${workDir}/skill-config.json`, JSON.stringify(config, null, 2));
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
## Next Phase
|
## Next Phase
|
||||||
|
|
||||||
→ [Phase 2: Structure Generation](02-structure-generation.md)
|
→ [Phase 2: Structure Generation](02-structure-generation.md)
|
||||||
|
|||||||
@@ -1,41 +1,40 @@
|
|||||||
# Phase 2: Structure Generation
|
# Phase 2: Structure Generation
|
||||||
|
|
||||||
根据配置创建 Skill 目录结构和入口文件。
|
Create Skill directory structure and entry file based on configuration.
|
||||||
|
|
||||||
## Objective
|
## Objective
|
||||||
|
|
||||||
- 创建标准目录结构
|
- Create standard directory structure
|
||||||
- 生成 SKILL.md 入口文件
|
- Generate SKILL.md entry file
|
||||||
- 根据执行模式创建对应的子目录
|
- Create corresponding subdirectories based on execution mode
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
## Execution Steps
|
## Execution Steps
|
||||||
|
|
||||||
### Step 1: 读取配置
|
### Step 1: Read Configuration
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
const config = JSON.parse(Read(`${workDir}/skill-config.json`));
|
const config = JSON.parse(Read(`${workDir}/skill-config.json`));
|
||||||
const skillDir = `.claude/skills/${config.skill_name}`;
|
const skillDir = `.claude/skills/${config.skill_name}`;
|
||||||
```
|
```
|
||||||
|
|
||||||
### Step 2: 创建目录结构
|
### Step 2: Create Directory Structure
|
||||||
|
|
||||||
#### 基础目录(所有模式)
|
#### Base Directories (All Modes)
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
// 基础架构
|
// Base infrastructure
|
||||||
Bash(`mkdir -p "${skillDir}/{phases,specs,templates,scripts}"`);
|
Bash(`mkdir -p "${skillDir}/{phases,specs,templates,scripts}"`);
|
||||||
```
|
```
|
||||||
|
|
||||||
#### 执行模式特定目录
|
#### Execution Mode-Specific Directories
|
||||||
|
|
||||||
```
|
```
|
||||||
config.execution_mode
|
config.execution_mode
|
||||||
↓
|
↓
|
||||||
├─ "sequential"
|
├─ "sequential"
|
||||||
│ ↓ Creates:
|
│ ↓ Creates:
|
||||||
│ └─ phases/ (基础目录已包含)
|
│ └─ phases/ (base directory already included)
|
||||||
│ ├─ _orchestrator.md
|
│ ├─ _orchestrator.md
|
||||||
│ └─ workflow.json
|
│ └─ workflow.json
|
||||||
│
|
│
|
||||||
@@ -43,36 +42,36 @@ config.execution_mode
|
|||||||
↓ Creates:
|
↓ Creates:
|
||||||
└─ phases/actions/
|
└─ phases/actions/
|
||||||
├─ state-schema.md
|
├─ state-schema.md
|
||||||
└─ *.md (动作文件)
|
└─ *.md (action files)
|
||||||
```
|
```
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
// Autonomous/Hybrid 模式额外目录
|
// Additional directories for Autonomous/Hybrid mode
|
||||||
if (config.execution_mode === 'autonomous' || config.execution_mode === 'hybrid') {
|
if (config.execution_mode === 'autonomous' || config.execution_mode === 'hybrid') {
|
||||||
Bash(`mkdir -p "${skillDir}/phases/actions"`);
|
Bash(`mkdir -p "${skillDir}/phases/actions"`);
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
#### Context Strategy 特定目录 (P0 增强)
|
#### Context Strategy-Specific Directories (P0 Enhancement)
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
// ========== P0: 根据上下文策略创建目录 ==========
|
// ========== P0: Create directories based on context strategy ==========
|
||||||
const contextStrategy = config.context_strategy || 'file';
|
const contextStrategy = config.context_strategy || 'file';
|
||||||
|
|
||||||
if (contextStrategy === 'file') {
|
if (contextStrategy === 'file') {
|
||||||
// 文件策略:创建上下文持久化目录
|
// File strategy: Create persistent context directory
|
||||||
Bash(`mkdir -p "${skillDir}/.scratchpad-template/context"`);
|
Bash(`mkdir -p "${skillDir}/.scratchpad-template/context"`);
|
||||||
|
|
||||||
// 创建上下文模板文件
|
// Create context template file
|
||||||
Write(
|
Write(
|
||||||
`${skillDir}/.scratchpad-template/context/.gitkeep`,
|
`${skillDir}/.scratchpad-template/context/.gitkeep`,
|
||||||
"# Runtime context storage for file-based strategy"
|
"# Runtime context storage for file-based strategy"
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
// 内存策略无需创建目录 (in-memory only)
|
// Memory strategy does not require directory creation (in-memory only)
|
||||||
```
|
```
|
||||||
|
|
||||||
**目录树视图**:
|
**Directory Tree View**:
|
||||||
|
|
||||||
```
|
```
|
||||||
Sequential + File Strategy:
|
Sequential + File Strategy:
|
||||||
@@ -83,7 +82,7 @@ Sequential + File Strategy:
|
|||||||
│ ├── 01-*.md
|
│ ├── 01-*.md
|
||||||
│ └── 02-*.md
|
│ └── 02-*.md
|
||||||
├── .scratchpad-template/
|
├── .scratchpad-template/
|
||||||
│ └── context/ ← File strategy persistent storage
|
│ └── context/ <- File strategy persistent storage
|
||||||
└── specs/
|
└── specs/
|
||||||
|
|
||||||
Autonomous + Memory Strategy:
|
Autonomous + Memory Strategy:
|
||||||
@@ -96,7 +95,7 @@ Autonomous + Memory Strategy:
|
|||||||
└── specs/
|
└── specs/
|
||||||
```
|
```
|
||||||
|
|
||||||
### Step 3: 生成 SKILL.md
|
### Step 3: Generate SKILL.md
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
const skillMdTemplate = `---
|
const skillMdTemplate = `---
|
||||||
@@ -149,7 +148,7 @@ ${generateReferenceTable(config)}
|
|||||||
Write(`${skillDir}/SKILL.md`, skillMdTemplate);
|
Write(`${skillDir}/SKILL.md`, skillMdTemplate);
|
||||||
```
|
```
|
||||||
|
|
||||||
### Step 4: 架构图生成函数
|
### Step 4: Architecture Diagram Generation Functions
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
function generateArchitectureDiagram(config) {
|
function generateArchitectureDiagram(config) {
|
||||||
@@ -160,7 +159,7 @@ function generateArchitectureDiagram(config) {
|
|||||||
} else {
|
} else {
|
||||||
return `
|
return `
|
||||||
┌─────────────────────────────────────────────────────────────────┐
|
┌─────────────────────────────────────────────────────────────────┐
|
||||||
│ Orchestrator (状态驱动决策) │
|
│ Orchestrator (State-driven decision-making) │
|
||||||
└───────────────┬─────────────────────────────────────────────────┘
|
└───────────────┬─────────────────────────────────────────────────┘
|
||||||
│
|
│
|
||||||
┌───────────┼───────────┐
|
┌───────────┼───────────┐
|
||||||
@@ -176,19 +175,19 @@ ${config.autonomous_config.actions.slice(0, 3).map(a =>
|
|||||||
|
|
||||||
function generateDesignPrinciples(config) {
|
function generateDesignPrinciples(config) {
|
||||||
const common = [
|
const common = [
|
||||||
"1. **规范遵循**: 严格遵循 `_shared/SKILL-DESIGN-SPEC.md`",
|
"1. **Specification Compliance**: Strictly follow `_shared/SKILL-DESIGN-SPEC.md`",
|
||||||
"2. **简要返回**: Agent 返回路径+摘要,避免上下文溢出"
|
"2. **Brief Return**: Agent returns path+summary, avoiding context overflow"
|
||||||
];
|
];
|
||||||
|
|
||||||
if (config.execution_mode === 'sequential') {
|
if (config.execution_mode === 'sequential') {
|
||||||
return [...common,
|
return [...common,
|
||||||
"3. **阶段隔离**: 每个阶段独立可测",
|
"3. **Phase Isolation**: Each phase is independently testable",
|
||||||
"4. **链式输出**: 阶段产出作为下阶段输入"
|
"4. **Chained Output**: Phase output becomes next phase input"
|
||||||
].join('\n');
|
].join('\n');
|
||||||
} else {
|
} else {
|
||||||
return [...common,
|
return [...common,
|
||||||
"3. **状态驱动**: 显式状态管理,动态决策",
|
"3. **State-driven**: Explicit state management, dynamic decision-making",
|
||||||
"4. **动作独立**: 每个动作无副作用依赖"
|
"4. **Action Independence**: Each action has no side-effect dependencies"
|
||||||
].join('\n');
|
].join('\n');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -236,15 +235,15 @@ function generateReferenceTable(config) {
|
|||||||
rows.push(`| [phases/${p.id}.md](phases/${p.id}.md) | ${p.name} |`);
|
rows.push(`| [phases/${p.id}.md](phases/${p.id}.md) | ${p.name} |`);
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
rows.push(`| [phases/orchestrator.md](phases/orchestrator.md) | 编排器 |`);
|
rows.push(`| [phases/orchestrator.md](phases/orchestrator.md) | Orchestrator |`);
|
||||||
rows.push(`| [phases/state-schema.md](phases/state-schema.md) | 状态定义 |`);
|
rows.push(`| [phases/state-schema.md](phases/state-schema.md) | State Definition |`);
|
||||||
config.autonomous_config.actions.forEach(a => {
|
config.autonomous_config.actions.forEach(a => {
|
||||||
rows.push(`| [phases/actions/${a.id}.md](phases/actions/${a.id}.md) | ${a.name} |`);
|
rows.push(`| [phases/actions/${a.id}.md](phases/actions/${a.id}.md) | ${a.name} |`);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
rows.push(`| [specs/${config.skill_name}-requirements.md](specs/${config.skill_name}-requirements.md) | 领域规范 |`);
|
rows.push(`| [specs/${config.skill_name}-requirements.md](specs/${config.skill_name}-requirements.md) | Domain Requirements |`);
|
||||||
rows.push(`| [specs/quality-standards.md](specs/quality-standards.md) | 质量标准 |`);
|
rows.push(`| [specs/quality-standards.md](specs/quality-standards.md) | Quality Standards |`);
|
||||||
|
|
||||||
return `| Document | Purpose |\n|----------|---------||\n` + rows.join('\n');
|
return `| Document | Purpose |\n|----------|---------||\n` + rows.join('\n');
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,23 +1,22 @@
|
|||||||
# Phase 3: Phase Generation
|
# Phase 3: Phase Generation
|
||||||
|
|
||||||
根据执行模式生成 Phase 文件,包含声明式工作流编排和上下文策略支持。
|
Generate Phase files based on execution mode, including declarative workflow orchestration and context strategy support.
|
||||||
|
|
||||||
## Objective
|
## Objective
|
||||||
|
|
||||||
- Sequential 模式:生成顺序 Phase 文件 + **声明式编排器**
|
- Sequential Mode: Generate sequential Phase files + **declarative orchestrator**
|
||||||
- Autonomous 模式:生成编排器和动作文件
|
- Autonomous Mode: Generate orchestrator and action files
|
||||||
- 支持 **文件上下文** 和 **内存上下文** 两种策略
|
- Support **file-based context** and **memory context** strategies
|
||||||
|
|
||||||
|
|
||||||
|
## Context Strategy (P0 Enhancement)
|
||||||
|
|
||||||
## 上下文策略 (P0 增强)
|
Generate different context management code based on `config.context_strategy`:
|
||||||
|
|
||||||
根据 `config.context_strategy` 生成不同的上下文管理代码:
|
| Strategy | Use Case | Advantages | Disadvantages |
|
||||||
|
|----------|----------|------------|---------------|
|
||||||
| 策略 | 适用场景 | 优点 | 缺点 |
|
| `file` | Complex multi-phase tasks | Persistence, debuggable, recoverable | I/O overhead |
|
||||||
|------|----------|------|------|
|
| `memory` | Simple linear tasks | Fast speed | Not recoverable, hard to debug |
|
||||||
| `file` | 复杂多阶段任务 | 持久化、可调试、可恢复 | IO 开销 |
|
|
||||||
| `memory` | 简单线性任务 | 速度快 | 无法恢复、调试困难 |
|
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
const CONTEXT_STRATEGIES = {
|
const CONTEXT_STRATEGIES = {
|
||||||
@@ -36,36 +35,36 @@ const CONTEXT_STRATEGIES = {
|
|||||||
|
|
||||||
## Execution Steps
|
## Execution Steps
|
||||||
|
|
||||||
### Step 1: 读取配置和模板
|
### Step 1: Load Configuration and Templates
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
const config = JSON.parse(Read(`${workDir}/skill-config.json`));
|
const config = JSON.parse(Read(`${workDir}/skill-config.json`));
|
||||||
const skillDir = `.claude/skills/${config.skill_name}`;
|
const skillDir = `.claude/skills/${config.skill_name}`;
|
||||||
const contextStrategy = config.context_strategy || 'file'; // 默认文件策略
|
const contextStrategy = config.context_strategy || 'file'; // Default file strategy
|
||||||
|
|
||||||
// 读取模板
|
// Load templates
|
||||||
const skillRoot = '.claude/skills/skill-generator';
|
const skillRoot = '.claude/skills/skill-generator';
|
||||||
```
|
```
|
||||||
|
|
||||||
### Step 2: Sequential 模式 - 生成阶段文件 + 声明式编排器
|
### Step 2: Sequential Mode - Generate Phase Files + Declarative Orchestrator
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
if (config.execution_mode === 'sequential') {
|
if (config.execution_mode === 'sequential') {
|
||||||
const phases = config.sequential_config.phases;
|
const phases = config.sequential_config.phases;
|
||||||
|
|
||||||
// ========== P0 增强: 生成声明式编排器 ==========
|
// ========== P0 Enhancement: Generate declarative orchestrator ==========
|
||||||
const workflowOrchestrator = generateSequentialOrchestrator(config, phases);
|
const workflowOrchestrator = generateSequentialOrchestrator(config, phases);
|
||||||
Write(`${skillDir}/phases/_orchestrator.md`, workflowOrchestrator);
|
Write(`${skillDir}/phases/_orchestrator.md`, workflowOrchestrator);
|
||||||
|
|
||||||
// ========== P0 增强: 生成工作流定义 ==========
|
// ========== P0 Enhancement: Generate workflow definition ==========
|
||||||
const workflowDef = generateWorkflowDefinition(config, phases);
|
const workflowDef = generateWorkflowDefinition(config, phases);
|
||||||
Write(`${skillDir}/workflow.json`, JSON.stringify(workflowDef, null, 2));
|
Write(`${skillDir}/workflow.json`, JSON.stringify(workflowDef, null, 2));
|
||||||
|
|
||||||
// ========== P0 增强: 生成 Phase 0 (强制规范研读) ==========
|
// ========== P0 Enhancement: Generate Phase 0 (mandatory specification study) ==========
|
||||||
const phase0Content = generatePhase0Spec(config);
|
const phase0Content = generatePhase0Spec(config);
|
||||||
Write(`${skillDir}/phases/00-spec-study.md`, phase0Content);
|
Write(`${skillDir}/phases/00-spec-study.md`, phase0Content);
|
||||||
|
|
||||||
// ========== 生成用户定义的各阶段文件 ==========
|
// ========== Generate user-defined phase files ==========
|
||||||
for (let i = 0; i < phases.length; i++) {
|
for (let i = 0; i < phases.length; i++) {
|
||||||
const phase = phases[i];
|
const phase = phases[i];
|
||||||
const prevPhase = i > 0 ? phases[i-1] : null;
|
const prevPhase = i > 0 ? phases[i-1] : null;
|
||||||
@@ -76,7 +75,7 @@ if (config.execution_mode === 'sequential') {
|
|||||||
phaseId: phase.id,
|
phaseId: phase.id,
|
||||||
phaseName: phase.name,
|
phaseName: phase.name,
|
||||||
phaseDescription: phase.description || `Execute ${phase.name}`,
|
phaseDescription: phase.description || `Execute ${phase.name}`,
|
||||||
input: prevPhase ? prevPhase.output : "phase 0 output", // Phase 0 为首个输入源
|
input: prevPhase ? prevPhase.output : "phase 0 output", // Phase 0 as first input source
|
||||||
output: phase.output,
|
output: phase.output,
|
||||||
nextPhase: nextPhase ? nextPhase.id : null,
|
nextPhase: nextPhase ? nextPhase.id : null,
|
||||||
config: config,
|
config: config,
|
||||||
@@ -87,16 +86,16 @@ if (config.execution_mode === 'sequential') {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ========== P0 增强: 声明式工作流定义 ==========
|
// ========== P0 Enhancement: Declarative workflow definition ==========
|
||||||
function generateWorkflowDefinition(config, phases) {
|
function generateWorkflowDefinition(config, phases) {
|
||||||
// ========== P0: 添加强制 Phase 0 ==========
|
// ========== P0: Add mandatory Phase 0 ==========
|
||||||
const phase0 = {
|
const phase0 = {
|
||||||
id: '00-spec-study',
|
id: '00-spec-study',
|
||||||
name: 'Specification Study',
|
name: 'Specification Study',
|
||||||
order: 0,
|
order: 0,
|
||||||
input: null,
|
input: null,
|
||||||
output: 'spec-study-complete.flag',
|
output: 'spec-study-complete.flag',
|
||||||
description: '⚠️ MANDATORY: Read all specification documents before execution',
|
description: 'MANDATORY: Read all specification documents before execution',
|
||||||
parallel: false,
|
parallel: false,
|
||||||
condition: null,
|
condition: null,
|
||||||
agent: {
|
agent: {
|
||||||
@@ -111,21 +110,21 @@ function generateWorkflowDefinition(config, phases) {
|
|||||||
execution_mode: "sequential",
|
execution_mode: "sequential",
|
||||||
context_strategy: config.context_strategy || "file",
|
context_strategy: config.context_strategy || "file",
|
||||||
|
|
||||||
// ========== P0: Phase 0 置于首位 ==========
|
// ========== P0: Phase 0 placed first ==========
|
||||||
phases_to_run: ['00-spec-study', ...phases.map(p => p.id)],
|
phases_to_run: ['00-spec-study', ...phases.map(p => p.id)],
|
||||||
|
|
||||||
// ========== P0: Phase 0 + 用户定义阶段 ==========
|
// ========== P0: Phase 0 + user-defined phases ==========
|
||||||
phases: [
|
phases: [
|
||||||
phase0,
|
phase0,
|
||||||
...phases.map((p, i) => ({
|
...phases.map((p, i) => ({
|
||||||
id: p.id,
|
id: p.id,
|
||||||
name: p.name,
|
name: p.name,
|
||||||
order: i + 1,
|
order: i + 1,
|
||||||
input: i === 0 ? phase0.output : phases[i-1].output, // 第一个阶段依赖 Phase 0
|
input: i === 0 ? phase0.output : phases[i-1].output, // First phase depends on Phase 0
|
||||||
output: p.output,
|
output: p.output,
|
||||||
parallel: p.parallel || false,
|
parallel: p.parallel || false,
|
||||||
condition: p.condition || null,
|
condition: p.condition || null,
|
||||||
// Agent 配置 (支持 LLM 集成)
|
// Agent configuration (supports LLM integration)
|
||||||
agent: p.agent || (config.llm_integration?.enabled ? {
|
agent: p.agent || (config.llm_integration?.enabled ? {
|
||||||
type: "llm",
|
type: "llm",
|
||||||
tool: config.llm_integration.default_tool,
|
tool: config.llm_integration.default_tool,
|
||||||
@@ -139,7 +138,7 @@ function generateWorkflowDefinition(config, phases) {
|
|||||||
}))
|
}))
|
||||||
],
|
],
|
||||||
|
|
||||||
// 终止条件
|
// Termination conditions
|
||||||
termination: {
|
termination: {
|
||||||
on_success: "all_phases_completed",
|
on_success: "all_phases_completed",
|
||||||
on_error: "stop_and_report",
|
on_error: "stop_and_report",
|
||||||
@@ -148,31 +147,31 @@ function generateWorkflowDefinition(config, phases) {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// ========== P0 增强: 声明式编排器 ==========
|
// ========== P0 Enhancement: Declarative orchestrator ==========
|
||||||
function generateSequentialOrchestrator(config, phases) {
|
function generateSequentialOrchestrator(config, phases) {
|
||||||
return `# Sequential Orchestrator
|
return `# Sequential Orchestrator
|
||||||
|
|
||||||
声明式工作流编排器,按 \`workflow.json\` 定义顺序执行阶段。
|
Declarative workflow orchestrator that executes phases in order defined by \`workflow.json\`.
|
||||||
|
|
||||||
## 工作流定义
|
## Workflow Definition
|
||||||
|
|
||||||
\`\`\`javascript
|
\`\`\`javascript
|
||||||
const workflow = JSON.parse(Read(\`\${skillDir}/workflow.json\`));
|
const workflow = JSON.parse(Read(\`\${skillDir}/workflow.json\`));
|
||||||
\`\`\`
|
\`\`\`
|
||||||
|
|
||||||
## 编排逻辑
|
## Orchestration Logic
|
||||||
|
|
||||||
\`\`\`javascript
|
\`\`\`javascript
|
||||||
async function runSequentialWorkflow(workDir) {
|
async function runSequentialWorkflow(workDir) {
|
||||||
const workflow = JSON.parse(Read(\`\${skillDir}/workflow.json\`));
|
const workflow = JSON.parse(Read(\`\${skillDir}/workflow.json\`));
|
||||||
const contextStrategy = workflow.context_strategy;
|
const contextStrategy = workflow.context_strategy;
|
||||||
|
|
||||||
// 初始化上下文
|
// Initialize context
|
||||||
${config.context_strategy === 'file' ?
|
${config.context_strategy === 'file' ?
|
||||||
`Bash(\`mkdir -p "\${workDir}/context"\`);` :
|
`Bash(\`mkdir -p "\${workDir}/context"\`);` :
|
||||||
`const state = { context: {} };`}
|
`const state = { context: {} };`}
|
||||||
|
|
||||||
// 执行状态追踪
|
// Execution state tracking
|
||||||
const execution = {
|
const execution = {
|
||||||
started_at: new Date().toISOString(),
|
started_at: new Date().toISOString(),
|
||||||
phases_completed: [],
|
phases_completed: [],
|
||||||
@@ -182,18 +181,18 @@ async function runSequentialWorkflow(workDir) {
|
|||||||
|
|
||||||
Write(\`\${workDir}/execution-state.json\`, JSON.stringify(execution, null, 2));
|
Write(\`\${workDir}/execution-state.json\`, JSON.stringify(execution, null, 2));
|
||||||
|
|
||||||
// 按声明顺序执行阶段
|
// Execute phases in declared order
|
||||||
for (const phaseId of workflow.phases_to_run) {
|
for (const phaseId of workflow.phases_to_run) {
|
||||||
const phaseConfig = workflow.phases.find(p => p.id === phaseId);
|
const phaseConfig = workflow.phases.find(p => p.id === phaseId);
|
||||||
|
|
||||||
// 更新执行状态
|
// Update execution state
|
||||||
execution.current_phase = phaseId;
|
execution.current_phase = phaseId;
|
||||||
Write(\`\${workDir}/execution-state.json\`, JSON.stringify(execution, null, 2));
|
Write(\`\${workDir}/execution-state.json\`, JSON.stringify(execution, null, 2));
|
||||||
|
|
||||||
console.log(\`[Orchestrator] Executing: \${phaseId}\`);
|
console.log(\`[Orchestrator] Executing: \${phaseId}\`);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// 检查条件执行
|
// Check conditional execution
|
||||||
if (phaseConfig.condition) {
|
if (phaseConfig.condition) {
|
||||||
const shouldRun = evaluateCondition(phaseConfig.condition, execution);
|
const shouldRun = evaluateCondition(phaseConfig.condition, execution);
|
||||||
if (!shouldRun) {
|
if (!shouldRun) {
|
||||||
@@ -202,10 +201,10 @@ async function runSequentialWorkflow(workDir) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 执行阶段
|
// Execute phase
|
||||||
const result = await executePhase(phaseId, phaseConfig, workDir);
|
const result = await executePhase(phaseId, phaseConfig, workDir);
|
||||||
|
|
||||||
// 记录完成
|
// Record completion
|
||||||
execution.phases_completed.push({
|
execution.phases_completed.push({
|
||||||
id: phaseId,
|
id: phaseId,
|
||||||
completed_at: new Date().toISOString(),
|
completed_at: new Date().toISOString(),
|
||||||
@@ -219,7 +218,7 @@ async function runSequentialWorkflow(workDir) {
|
|||||||
timestamp: new Date().toISOString()
|
timestamp: new Date().toISOString()
|
||||||
});
|
});
|
||||||
|
|
||||||
// 错误处理策略
|
// Error handling strategy
|
||||||
if (workflow.termination.on_error === 'stop_and_report') {
|
if (workflow.termination.on_error === 'stop_and_report') {
|
||||||
console.error(\`[Orchestrator] Failed at \${phaseId}: \${error.message}\`);
|
console.error(\`[Orchestrator] Failed at \${phaseId}: \${error.message}\`);
|
||||||
break;
|
break;
|
||||||
@@ -229,7 +228,7 @@ async function runSequentialWorkflow(workDir) {
|
|||||||
Write(\`\${workDir}/execution-state.json\`, JSON.stringify(execution, null, 2));
|
Write(\`\${workDir}/execution-state.json\`, JSON.stringify(execution, null, 2));
|
||||||
}
|
}
|
||||||
|
|
||||||
// 完成
|
// Complete
|
||||||
execution.current_phase = null;
|
execution.current_phase = null;
|
||||||
execution.completed_at = new Date().toISOString();
|
execution.completed_at = new Date().toISOString();
|
||||||
Write(\`\${workDir}/execution-state.json\`, JSON.stringify(execution, null, 2));
|
Write(\`\${workDir}/execution-state.json\`, JSON.stringify(execution, null, 2));
|
||||||
@@ -240,7 +239,7 @@ async function runSequentialWorkflow(workDir) {
|
|||||||
async function executePhase(phaseId, phaseConfig, workDir) {
|
async function executePhase(phaseId, phaseConfig, workDir) {
|
||||||
const phasePrompt = Read(\`\${skillDir}/phases/\${phaseId}.md\`);
|
const phasePrompt = Read(\`\${skillDir}/phases/\${phaseId}.md\`);
|
||||||
|
|
||||||
// 使用 Task 调用 Agent
|
// Use Task to invoke Agent
|
||||||
const result = await Task({
|
const result = await Task({
|
||||||
subagent_type: phaseConfig.agent?.type || 'universal-executor',
|
subagent_type: phaseConfig.agent?.type || 'universal-executor',
|
||||||
run_in_background: phaseConfig.agent?.run_in_background || false,
|
run_in_background: phaseConfig.agent?.run_in_background || false,
|
||||||
@@ -258,9 +257,9 @@ async function executePhase(phaseId, phaseConfig, workDir) {
|
|||||||
}
|
}
|
||||||
\`\`\`
|
\`\`\`
|
||||||
|
|
||||||
## 阶段执行计划
|
## Phase Execution Plan
|
||||||
|
|
||||||
**执行流程**:
|
**Execution Flow**:
|
||||||
|
|
||||||
\`\`\`
|
\`\`\`
|
||||||
START
|
START
|
||||||
@@ -270,26 +269,26 @@ Phase 0: Specification Study
|
|||||||
↓
|
↓
|
||||||
Phase 1: ${phases[0]?.name || 'First Phase'}
|
Phase 1: ${phases[0]?.name || 'First Phase'}
|
||||||
↓ Output: ${phases[0]?.output || 'phase-1.json'}
|
↓ Output: ${phases[0]?.output || 'phase-1.json'}
|
||||||
${phases.slice(1).map((p, i) => ` ↓
|
${phases.slice(1).map((p, i) => \` ↓
|
||||||
Phase ${i+2}: ${p.name}
|
Phase \${i+2}: \${p.name}
|
||||||
↓ Output: ${p.output}`).join('\n')}
|
↓ Output: \${p.output}\`).join('\n')}
|
||||||
↓
|
↓
|
||||||
COMPLETE
|
COMPLETE
|
||||||
\`\`\`
|
\`\`\`
|
||||||
|
|
||||||
**阶段列表**:
|
**Phase List**:
|
||||||
|
|
||||||
| Order | Phase | Input | Output | Agent |
|
| Order | Phase | Input | Output | Agent |
|
||||||
|-------|-------|-------|--------|-------|
|
|-------|-------|-------|--------|-------|
|
||||||
| 0 | 00-spec-study | - | spec-study-complete.flag | universal-executor |
|
| 0 | 00-spec-study | - | spec-study-complete.flag | universal-executor |
|
||||||
${phases.map((p, i) =>
|
${phases.map((p, i) =>
|
||||||
`| ${i+1} | ${p.id} | ${i === 0 ? 'spec-study-complete.flag' : phases[i-1].output} | ${p.output} | ${p.agent?.type || 'universal-executor'} |`
|
\`| \${i+1} | \${p.id} | \${i === 0 ? 'spec-study-complete.flag' : phases[i-1].output} | \${p.output} | \${p.agent?.type || 'universal-executor'} |\`
|
||||||
).join('\n')}
|
).join('\n')}
|
||||||
|
|
||||||
## 错误恢复
|
## Error Recovery
|
||||||
|
|
||||||
\`\`\`javascript
|
\`\`\`javascript
|
||||||
// 从指定阶段恢复执行
|
// Resume execution from specified phase
|
||||||
async function resumeFromPhase(phaseId, workDir) {
|
async function resumeFromPhase(phaseId, workDir) {
|
||||||
const workflow = JSON.parse(Read(\`\${skillDir}/workflow.json\`));
|
const workflow = JSON.parse(Read(\`\${skillDir}/workflow.json\`));
|
||||||
const startIndex = workflow.phases_to_run.indexOf(phaseId);
|
const startIndex = workflow.phases_to_run.indexOf(phaseId);
|
||||||
@@ -298,15 +297,15 @@ async function resumeFromPhase(phaseId, workDir) {
|
|||||||
throw new Error(\`Phase not found: \${phaseId}\`);
|
throw new Error(\`Phase not found: \${phaseId}\`);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 从指定阶段开始执行
|
// Continue execution from specified phase
|
||||||
const remainingPhases = workflow.phases_to_run.slice(startIndex);
|
const remainingPhases = workflow.phases_to_run.slice(startIndex);
|
||||||
// ...继续执行
|
// ...continue execution
|
||||||
}
|
}
|
||||||
\`\`\`
|
\`\`\`
|
||||||
`;
|
`;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 生成阶段文件(增强上下文策略支持)
|
// Generate phase files (enhanced context strategy support)
|
||||||
function generateSequentialPhase(params) {
|
function generateSequentialPhase(params) {
|
||||||
const contextCode = params.contextStrategy === 'file' ? {
|
const contextCode = params.contextStrategy === 'file' ? {
|
||||||
readPrev: `const prevOutput = JSON.parse(Read(\`\${workDir}/${params.input}\`));`,
|
readPrev: `const prevOutput = JSON.parse(Read(\`\${workDir}/${params.input}\`));`,
|
||||||
@@ -326,32 +325,32 @@ ${params.phaseDescription}
|
|||||||
|
|
||||||
## Objective
|
## Objective
|
||||||
|
|
||||||
- 主要目标描述
|
- Primary objective description
|
||||||
- 具体任务列表
|
- Specific task list
|
||||||
|
|
||||||
## Input
|
## Input
|
||||||
|
|
||||||
- 依赖: \`${params.input}\`
|
- Dependency: \`${params.input}\`
|
||||||
- 配置: \`{workDir}/skill-config.json\`
|
- Configuration: \`{workDir}/skill-config.json\`
|
||||||
- 上下文策略: \`${params.contextStrategy}\`
|
- Context Strategy: \`${params.contextStrategy}\`
|
||||||
|
|
||||||
## Execution Steps
|
## Execution Steps
|
||||||
|
|
||||||
### Step 1: 读取输入
|
### Step 1: Read Input
|
||||||
|
|
||||||
\`\`\`javascript
|
\`\`\`javascript
|
||||||
// 上下文策略: ${params.contextStrategy}
|
// Context strategy: ${params.contextStrategy}
|
||||||
${params.phaseNumber > 1 ? contextCode.readPrev : '// 首阶段,直接从配置开始'}
|
${params.phaseNumber > 1 ? contextCode.readPrev : '// First phase, start directly from config'}
|
||||||
\`\`\`
|
\`\`\`
|
||||||
|
|
||||||
### Step 2: 核心处理
|
### Step 2: Core Processing
|
||||||
|
|
||||||
\`\`\`javascript
|
\`\`\`javascript
|
||||||
// TODO: 实现核心逻辑
|
// TODO: Implement core logic
|
||||||
const result = {
|
const result = {
|
||||||
status: 'completed',
|
status: 'completed',
|
||||||
data: {
|
data: {
|
||||||
// 处理结果
|
// Processing results
|
||||||
},
|
},
|
||||||
metadata: {
|
metadata: {
|
||||||
phase: '${params.phaseId}',
|
phase: '${params.phaseId}',
|
||||||
@@ -360,17 +359,17 @@ const result = {
|
|||||||
};
|
};
|
||||||
\`\`\`
|
\`\`\`
|
||||||
|
|
||||||
### Step 3: 输出结果
|
### Step 3: Output Results
|
||||||
|
|
||||||
\`\`\`javascript
|
\`\`\`javascript
|
||||||
// 写入阶段产出 (上下文策略: ${params.contextStrategy})
|
// Write phase output (context strategy: ${params.contextStrategy})
|
||||||
${contextCode.writeResult}
|
${contextCode.writeResult}
|
||||||
|
|
||||||
// 返回简要信息给编排器
|
// Return summary information to orchestrator
|
||||||
return {
|
return {
|
||||||
status: 'completed',
|
status: 'completed',
|
||||||
output_file: '${params.output}',
|
output_file: '${params.output}',
|
||||||
summary: '阶段 ${params.phaseNumber} 完成'
|
summary: 'Phase ${params.phaseNumber} completed'
|
||||||
};
|
};
|
||||||
\`\`\`
|
\`\`\`
|
||||||
|
|
||||||
@@ -382,57 +381,57 @@ return {
|
|||||||
|
|
||||||
## Quality Checklist
|
## Quality Checklist
|
||||||
|
|
||||||
- [ ] 输入数据验证通过
|
- [ ] Input data validation passed
|
||||||
- [ ] 核心逻辑执行成功
|
- [ ] Core logic executed successfully
|
||||||
- [ ] 输出格式正确
|
- [ ] Output format correct
|
||||||
- [ ] 上下文正确保存
|
- [ ] Context saved correctly
|
||||||
|
|
||||||
${params.nextPhase ?
|
${params.nextPhase ?
|
||||||
`## Next Phase\n\n→ [Phase ${params.phaseNumber + 1}: ${params.nextPhase}](${params.nextPhase}.md)` :
|
`## Next Phase\n\n→ [Phase ${params.phaseNumber + 1}: ${params.nextPhase}](${params.nextPhase}.md)` :
|
||||||
`## Completion\n\n此为最后阶段,输出最终产物。`}
|
`## Completion\n\nThis is the final phase, produce final deliverables.`}
|
||||||
`;
|
`;
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
### Step 3: Autonomous 模式 - 生成编排器 (增强版)
|
### Step 3: Autonomous Mode - Generate Enhanced Orchestrator
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
if (config.execution_mode === 'autonomous' || config.execution_mode === 'hybrid') {
|
if (config.execution_mode === 'autonomous' || config.execution_mode === 'hybrid') {
|
||||||
const contextStrategy = config.context_strategy || 'file';
|
const contextStrategy = config.context_strategy || 'file';
|
||||||
|
|
||||||
// 生成状态 Schema (增强文件策略支持)
|
// Generate state schema (enhanced file strategy support)
|
||||||
const stateSchema = generateStateSchema(config, contextStrategy);
|
const stateSchema = generateStateSchema(config, contextStrategy);
|
||||||
Write(`${skillDir}/phases/state-schema.md`, stateSchema);
|
Write(`${skillDir}/phases/state-schema.md`, stateSchema);
|
||||||
|
|
||||||
// 生成编排器 (增强版)
|
// Generate enhanced orchestrator
|
||||||
const orchestrator = generateEnhancedOrchestrator(config, contextStrategy);
|
const orchestrator = generateEnhancedOrchestrator(config, contextStrategy);
|
||||||
Write(`${skillDir}/phases/orchestrator.md`, orchestrator);
|
Write(`${skillDir}/phases/orchestrator.md`, orchestrator);
|
||||||
|
|
||||||
// 生成动作目录
|
// Generate action catalog
|
||||||
const actionCatalog = generateActionCatalog(config);
|
const actionCatalog = generateActionCatalog(config);
|
||||||
Write(`${skillDir}/specs/action-catalog.md`, actionCatalog);
|
Write(`${skillDir}/specs/action-catalog.md`, actionCatalog);
|
||||||
|
|
||||||
// 生成动作文件
|
// Generate action files
|
||||||
for (const action of config.autonomous_config.actions) {
|
for (const action of config.autonomous_config.actions) {
|
||||||
const actionContent = generateEnhancedAction(action, config, contextStrategy);
|
const actionContent = generateEnhancedAction(action, config, contextStrategy);
|
||||||
Write(`${skillDir}/phases/actions/${action.id}.md`, actionContent);
|
Write(`${skillDir}/phases/actions/${action.id}.md`, actionContent);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 增强版编排器生成
|
// Enhanced orchestrator generation
|
||||||
function generateEnhancedOrchestrator(config, contextStrategy) {
|
function generateEnhancedOrchestrator(config, contextStrategy) {
|
||||||
const actions = config.autonomous_config.actions;
|
const actions = config.autonomous_config.actions;
|
||||||
|
|
||||||
return `# Orchestrator (Enhanced)
|
return `# Orchestrator (Enhanced)
|
||||||
|
|
||||||
增强版编排器,支持声明式动作调度和文件上下文策略。
|
Enhanced orchestrator supporting declarative action scheduling and file-based context strategy.
|
||||||
|
|
||||||
## 配置
|
## Configuration
|
||||||
|
|
||||||
- **上下文策略**: ${contextStrategy}
|
- **Context Strategy**: ${contextStrategy}
|
||||||
- **终止条件**: ${config.autonomous_config.termination_conditions?.join(', ') || 'task_completed'}
|
- **Termination Conditions**: ${config.autonomous_config.termination_conditions?.join(', ') || 'task_completed'}
|
||||||
|
|
||||||
## 声明式动作目录
|
## Declarative Action Catalog
|
||||||
|
|
||||||
\`\`\`javascript
|
\`\`\`javascript
|
||||||
const ACTION_CATALOG = ${JSON.stringify(actions.map(a => ({
|
const ACTION_CATALOG = ${JSON.stringify(actions.map(a => ({
|
||||||
@@ -444,12 +443,12 @@ const ACTION_CATALOG = ${JSON.stringify(actions.map(a => ({
|
|||||||
})), null, 2)};
|
})), null, 2)};
|
||||||
\`\`\`
|
\`\`\`
|
||||||
|
|
||||||
## 上下文管理 (${contextStrategy} 策略)
|
## Context Management (${contextStrategy} Strategy)
|
||||||
|
|
||||||
\`\`\`javascript
|
\`\`\`javascript
|
||||||
const ContextManager = {
|
const ContextManager = {
|
||||||
${contextStrategy === 'file' ? `
|
${contextStrategy === 'file' ? \`
|
||||||
// 文件策略: 持久化到 .scratchpad
|
// File strategy: persist to .scratchpad
|
||||||
init: (workDir) => {
|
init: (workDir) => {
|
||||||
Bash(\`mkdir -p "\${workDir}/context"\`);
|
Bash(\`mkdir -p "\${workDir}/context"\`);
|
||||||
Write(\`\${workDir}/state.json\`, JSON.stringify(initialState, null, 2));
|
Write(\`\${workDir}/state.json\`, JSON.stringify(initialState, null, 2));
|
||||||
@@ -470,8 +469,8 @@ const ContextManager = {
|
|||||||
|
|
||||||
writeContext: (workDir, key, data) => {
|
writeContext: (workDir, key, data) => {
|
||||||
Write(\`\${workDir}/context/\${key}.json\`, JSON.stringify(data, null, 2));
|
Write(\`\${workDir}/context/\${key}.json\`, JSON.stringify(data, null, 2));
|
||||||
}` : `
|
}\` : \`
|
||||||
// 内存策略: 仅在运行时保持
|
// Memory strategy: maintain only at runtime
|
||||||
state: null,
|
state: null,
|
||||||
context: {},
|
context: {},
|
||||||
|
|
||||||
@@ -491,23 +490,23 @@ const ContextManager = {
|
|||||||
|
|
||||||
writeContext: (workDir, key, data) => {
|
writeContext: (workDir, key, data) => {
|
||||||
ContextManager.context[key] = data;
|
ContextManager.context[key] = data;
|
||||||
}`}
|
}\`}
|
||||||
};
|
};
|
||||||
\`\`\`
|
\`\`\`
|
||||||
|
|
||||||
## 决策逻辑
|
## Decision Logic
|
||||||
|
|
||||||
\`\`\`javascript
|
\`\`\`javascript
|
||||||
function selectNextAction(state) {
|
function selectNextAction(state) {
|
||||||
// 1. 终止条件检查
|
// 1. Check termination conditions
|
||||||
${config.autonomous_config.termination_conditions?.map(c =>
|
${config.autonomous_config.termination_conditions?.map(c =>
|
||||||
` if (${getTerminationCheck(c)}) return null;`
|
\` if (\${getTerminationCheck(c)}) return null;\`
|
||||||
).join('\n') || ' if (state.status === "completed") return null;'}
|
).join('\n') || ' if (state.status === "completed") return null;'}
|
||||||
|
|
||||||
// 2. 错误限制检查
|
// 2. Check error limit
|
||||||
if (state.error_count >= 3) return 'action-abort';
|
if (state.error_count >= 3) return 'action-abort';
|
||||||
|
|
||||||
// 3. 按优先级选择满足前置条件的动作
|
// 3. Select actions that meet preconditions, sorted by priority
|
||||||
const availableActions = ACTION_CATALOG
|
const availableActions = ACTION_CATALOG
|
||||||
.filter(a => checkPreconditions(a.preconditions, state))
|
.filter(a => checkPreconditions(a.preconditions, state))
|
||||||
.filter(a => !state.completed_actions.includes(a.id))
|
.filter(a => !state.completed_actions.includes(a.id))
|
||||||
@@ -517,14 +516,14 @@ ${config.autonomous_config.termination_conditions?.map(c =>
|
|||||||
return availableActions[0].id;
|
return availableActions[0].id;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 4. 默认完成
|
// 4. Default complete
|
||||||
return 'action-complete';
|
return 'action-complete';
|
||||||
}
|
}
|
||||||
|
|
||||||
function checkPreconditions(conditions, state) {
|
function checkPreconditions(conditions, state) {
|
||||||
if (!conditions || conditions.length === 0) return true;
|
if (!conditions || conditions.length === 0) return true;
|
||||||
return conditions.every(cond => {
|
return conditions.every(cond => {
|
||||||
// 支持多种条件格式
|
// Support multiple condition formats
|
||||||
if (cond.includes('===')) {
|
if (cond.includes('===')) {
|
||||||
const [left, right] = cond.split('===').map(s => s.trim());
|
const [left, right] = cond.split('===').map(s => s.trim());
|
||||||
return eval(\`state.\${left}\`) === eval(right);
|
return eval(\`state.\${left}\`) === eval(right);
|
||||||
@@ -534,14 +533,14 @@ function checkPreconditions(conditions, state) {
|
|||||||
}
|
}
|
||||||
\`\`\`
|
\`\`\`
|
||||||
|
|
||||||
## 执行循环 (增强版)
|
## Execution Loop (Enhanced)
|
||||||
|
|
||||||
\`\`\`javascript
|
\`\`\`javascript
|
||||||
async function runOrchestrator(workDir) {
|
async function runOrchestrator(workDir) {
|
||||||
console.log('=== Orchestrator Started ===');
|
console.log('=== Orchestrator Started ===');
|
||||||
console.log(\`Context Strategy: ${contextStrategy}\`);
|
console.log(\`Context Strategy: ${contextStrategy}\`);
|
||||||
|
|
||||||
// 初始化
|
// Initialize
|
||||||
ContextManager.init(workDir);
|
ContextManager.init(workDir);
|
||||||
|
|
||||||
let iteration = 0;
|
let iteration = 0;
|
||||||
@@ -550,11 +549,11 @@ async function runOrchestrator(workDir) {
|
|||||||
while (iteration < MAX_ITERATIONS) {
|
while (iteration < MAX_ITERATIONS) {
|
||||||
iteration++;
|
iteration++;
|
||||||
|
|
||||||
// 1. 读取状态
|
// 1. Read state
|
||||||
const state = ContextManager.readState(workDir);
|
const state = ContextManager.readState(workDir);
|
||||||
console.log(\`[Iteration \${iteration}] Status: \${state.status}, Completed: \${state.completed_actions.length}\`);
|
console.log(\`[Iteration \${iteration}] Status: \${state.status}, Completed: \${state.completed_actions.length}\`);
|
||||||
|
|
||||||
// 2. 选择动作
|
// 2. Select action
|
||||||
const actionId = selectNextAction(state);
|
const actionId = selectNextAction(state);
|
||||||
|
|
||||||
if (!actionId) {
|
if (!actionId) {
|
||||||
@@ -566,11 +565,11 @@ async function runOrchestrator(workDir) {
|
|||||||
|
|
||||||
console.log(\`[Iteration \${iteration}] Executing: \${actionId}\`);
|
console.log(\`[Iteration \${iteration}] Executing: \${actionId}\`);
|
||||||
|
|
||||||
// 3. 更新当前动作
|
// 3. Update current action
|
||||||
state.current_action = actionId;
|
state.current_action = actionId;
|
||||||
ContextManager.writeState(workDir, state);
|
ContextManager.writeState(workDir, state);
|
||||||
|
|
||||||
// 4. 执行动作
|
// 4. Execute action
|
||||||
try {
|
try {
|
||||||
const actionPrompt = Read(\`\${skillDir}/phases/actions/\${actionId}.md\`);
|
const actionPrompt = Read(\`\${skillDir}/phases/actions/\${actionId}.md\`);
|
||||||
|
|
||||||
@@ -597,7 +596,7 @@ Return JSON: { "status": "completed"|"failed", "stateUpdates": {...}, "summary":
|
|||||||
|
|
||||||
const actionResult = JSON.parse(result);
|
const actionResult = JSON.parse(result);
|
||||||
|
|
||||||
// 5. 更新状态
|
// 5. Update state
|
||||||
state.completed_actions.push(actionId);
|
state.completed_actions.push(actionId);
|
||||||
state.current_action = null;
|
state.current_action = null;
|
||||||
Object.assign(state, actionResult.stateUpdates || {});
|
Object.assign(state, actionResult.stateUpdates || {});
|
||||||
@@ -623,18 +622,18 @@ Return JSON: { "status": "completed"|"failed", "stateUpdates": {...}, "summary":
|
|||||||
}
|
}
|
||||||
\`\`\`
|
\`\`\`
|
||||||
|
|
||||||
## 动作目录
|
## Action Catalog
|
||||||
|
|
||||||
| Action | Priority | Preconditions | Effects |
|
| Action | Priority | Preconditions | Effects |
|
||||||
|--------|----------|---------------|---------|
|
|--------|----------|---------------|---------|
|
||||||
${actions.map(a =>
|
${actions.map(a =>
|
||||||
`| [${a.id}](actions/${a.id}.md) | ${a.priority || 0} | ${a.preconditions?.join(', ') || '-'} | ${a.effects?.join(', ') || '-'} |`
|
\`| [${a.id}](actions/${a.id}.md) | ${a.priority || 0} | ${a.preconditions?.join(', ') || '-'} | ${a.effects?.join(', ') || '-'} |\`
|
||||||
).join('\n')}
|
).join('\n')}
|
||||||
|
|
||||||
## 调试与恢复
|
## Debugging and Recovery
|
||||||
|
|
||||||
\`\`\`javascript
|
\`\`\`javascript
|
||||||
// 从特定状态恢复
|
// Resume from specific state
|
||||||
async function resumeFromState(workDir) {
|
async function resumeFromState(workDir) {
|
||||||
const state = ContextManager.readState(workDir);
|
const state = ContextManager.readState(workDir);
|
||||||
console.log(\`Resuming from: \${state.current_action || 'start'}\`);
|
console.log(\`Resuming from: \${state.current_action || 'start'}\`);
|
||||||
@@ -642,7 +641,7 @@ async function resumeFromState(workDir) {
|
|||||||
return runOrchestrator(workDir);
|
return runOrchestrator(workDir);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 重试失败的动作
|
// Retry failed action
|
||||||
async function retryFailedAction(workDir) {
|
async function retryFailedAction(workDir) {
|
||||||
const state = ContextManager.readState(workDir);
|
const state = ContextManager.readState(workDir);
|
||||||
if (state.errors.length > 0) {
|
if (state.errors.length > 0) {
|
||||||
@@ -657,62 +656,62 @@ async function retryFailedAction(workDir) {
|
|||||||
`;
|
`;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 增强版动作生成
|
// Enhanced action generation
|
||||||
function generateEnhancedAction(action, config, contextStrategy) {
|
function generateEnhancedAction(action, config, contextStrategy) {
|
||||||
return `# Action: ${action.name}
|
return `# Action: ${action.name}
|
||||||
|
|
||||||
${action.description || '执行 ' + action.name + ' 操作'}
|
${action.description || 'Execute ' + action.name + ' operation'}
|
||||||
|
|
||||||
## Purpose
|
## Purpose
|
||||||
|
|
||||||
${action.description || 'TODO: 描述此动作的目的'}
|
${action.description || 'TODO: Describe the purpose of this action'}
|
||||||
|
|
||||||
## Preconditions
|
## Preconditions
|
||||||
|
|
||||||
${action.preconditions?.map(p => `- [ ] \`${p}\``).join('\n') || '- [ ] 无特殊前置条件'}
|
${action.preconditions?.map(p => \`- [ ] \\\`${p}\\\`\`).join('\n') || '- [ ] No special preconditions'}
|
||||||
|
|
||||||
## Context Access (${contextStrategy} 策略)
|
## Context Access (${contextStrategy} Strategy)
|
||||||
|
|
||||||
\`\`\`javascript
|
\`\`\`javascript
|
||||||
// 读取共享上下文
|
// Read shared context
|
||||||
${contextStrategy === 'file' ?
|
${contextStrategy === 'file' ?
|
||||||
`const sharedData = JSON.parse(Read(\`\${workDir}/context/shared.json\`));` :
|
\`const sharedData = JSON.parse(Read(\\\`\${workDir}/context/shared.json\\\`));\` :
|
||||||
`const sharedData = state.context.shared || {};`}
|
\`const sharedData = state.context.shared || {};\`}
|
||||||
|
|
||||||
// 写入共享上下文
|
// Write shared context
|
||||||
${contextStrategy === 'file' ?
|
${contextStrategy === 'file' ?
|
||||||
`Write(\`\${workDir}/context/shared.json\`, JSON.stringify(updatedData, null, 2));` :
|
\`Write(\\\`\${workDir}/context/shared.json\\\`, JSON.stringify(updatedData, null, 2));\` :
|
||||||
`state.context.shared = updatedData;`}
|
\`state.context.shared = updatedData;\`}
|
||||||
\`\`\`
|
\`\`\`
|
||||||
|
|
||||||
## Execution
|
## Execution
|
||||||
|
|
||||||
\`\`\`javascript
|
\`\`\`javascript
|
||||||
async function execute(state, workDir) {
|
async function execute(state, workDir) {
|
||||||
// 1. 读取必要数据
|
// 1. Read necessary data
|
||||||
${contextStrategy === 'file' ?
|
${contextStrategy === 'file' ?
|
||||||
`const input = JSON.parse(Read(\`\${workDir}/context/input.json\`));` :
|
\`const input = JSON.parse(Read(\\\`\${workDir}/context/input.json\\\`));\` :
|
||||||
`const input = state.context.input || {};`}
|
\`const input = state.context.input || {};\`}
|
||||||
|
|
||||||
// 2. 执行核心逻辑
|
// 2. Execute core logic
|
||||||
// TODO: 实现动作逻辑
|
// TODO: Implement action logic
|
||||||
const result = {
|
const result = {
|
||||||
// 处理结果
|
// Processing results
|
||||||
};
|
};
|
||||||
|
|
||||||
// 3. 保存结果 (${contextStrategy} 策略)
|
// 3. Save results (${contextStrategy} strategy)
|
||||||
${contextStrategy === 'file' ?
|
${contextStrategy === 'file' ?
|
||||||
`Write(\`\${workDir}/context/${action.id.replace(/-/g, '_')}_result.json\`, JSON.stringify(result, null, 2));` :
|
\`Write(\\\`\${workDir}/context/${action.id.replace(/-/g, '_')}_result.json\\\`, JSON.stringify(result, null, 2));\` :
|
||||||
`// 结果通过 stateUpdates 返回`}
|
\`// Results returned via stateUpdates\`}
|
||||||
|
|
||||||
// 4. 返回状态更新
|
// 4. Return state updates
|
||||||
return {
|
return {
|
||||||
status: 'completed',
|
status: 'completed',
|
||||||
stateUpdates: {
|
stateUpdates: {
|
||||||
completed_actions: [...state.completed_actions, '${action.id}'],
|
completed_actions: [...state.completed_actions, '${action.id}'],
|
||||||
${contextStrategy === 'memory' ? `context: { ...state.context, ${action.id.replace(/-/g, '_')}_result: result }` : '// 文件策略:结果已保存到文件'}
|
${contextStrategy === 'memory' ? \`context: { ...state.context, ${action.id.replace(/-/g, '_')}_result: result }\` : '// File strategy: results saved to file'}
|
||||||
},
|
},
|
||||||
summary: '${action.name} 完成'
|
summary: '${action.name} completed'
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
\`\`\`
|
\`\`\`
|
||||||
@@ -724,35 +723,35 @@ return {
|
|||||||
status: 'completed',
|
status: 'completed',
|
||||||
stateUpdates: {
|
stateUpdates: {
|
||||||
completed_actions: [...state.completed_actions, '${action.id}'],
|
completed_actions: [...state.completed_actions, '${action.id}'],
|
||||||
${action.effects?.map(e => ` // Effect: ${e}`).join('\n') || ' // 无额外效果'}
|
${action.effects?.map(e => \` // Effect: ${e}\`).join('\n') || ' // No additional effects'}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
\`\`\`
|
\`\`\`
|
||||||
|
|
||||||
## Error Handling
|
## Error Handling
|
||||||
|
|
||||||
| 错误类型 | 处理方式 |
|
| Error Type | Handling |
|
||||||
|----------|----------|
|
|------------|----------|
|
||||||
| 数据验证失败 | 返回错误,不更新状态 |
|
| Data validation failure | Return error, do not update state |
|
||||||
| 执行异常 | 记录错误,增加 error_count |
|
| Execution exception | Log error, increment error_count |
|
||||||
| 上下文读取失败 | 使用默认值或跳过 |
|
| Context read failure | Use default value or skip |
|
||||||
|
|
||||||
## Next Actions (Hints)
|
## Next Actions (Hints)
|
||||||
|
|
||||||
- 成功: 由编排器根据 \`ACTION_CATALOG\` 优先级决定
|
- Success: Determined by orchestrator based on \`ACTION_CATALOG\` priority
|
||||||
- 失败: 重试或 \`action-abort\`
|
- Failure: Retry or \`action-abort\`
|
||||||
`;
|
`;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 生成动作目录
|
// Generate action catalog
|
||||||
function generateActionCatalog(config) {
|
function generateActionCatalog(config) {
|
||||||
const actions = config.autonomous_config.actions;
|
const actions = config.autonomous_config.actions;
|
||||||
|
|
||||||
return `# Action Catalog
|
return `# Action Catalog
|
||||||
|
|
||||||
${config.display_name} 的可用动作目录(声明式)。
|
Available action catalog for ${config.display_name} (declarative).
|
||||||
|
|
||||||
## 动作定义
|
## Action Definition
|
||||||
|
|
||||||
\`\`\`json
|
\`\`\`json
|
||||||
${JSON.stringify(actions.map(a => ({
|
${JSON.stringify(actions.map(a => ({
|
||||||
@@ -765,7 +764,7 @@ ${JSON.stringify(actions.map(a => ({
|
|||||||
})), null, 2)}
|
})), null, 2)}
|
||||||
\`\`\`
|
\`\`\`
|
||||||
|
|
||||||
## 动作依赖图
|
## Action Dependency Graph
|
||||||
|
|
||||||
\`\`\`mermaid
|
\`\`\`mermaid
|
||||||
graph TD
|
graph TD
|
||||||
@@ -775,30 +774,30 @@ ${actions.map((a, i) => {
|
|||||||
.filter(Boolean) || [];
|
.filter(Boolean) || [];
|
||||||
|
|
||||||
if (deps.length === 0 && i === 0) {
|
if (deps.length === 0 && i === 0) {
|
||||||
return ` START((Start)) --> ${a.id.replace(/-/g, '_')}[${a.name}]`;
|
return \` START((Start)) --> ${a.id.replace(/-/g, '_')}[${a.name}]\`;
|
||||||
} else if (deps.length > 0) {
|
} else if (deps.length > 0) {
|
||||||
return deps.map(d => ` ${d.replace(/-/g, '_')} --> ${a.id.replace(/-/g, '_')}[${a.name}]`).join('\n');
|
return deps.map(d => \` ${d.replace(/-/g, '_')} --> ${a.id.replace(/-/g, '_')}[${a.name}]\`).join('\n');
|
||||||
}
|
}
|
||||||
return '';
|
return '';
|
||||||
}).filter(Boolean).join('\n')}
|
}).filter(Boolean).join('\n')}
|
||||||
${actions[actions.length-1]?.id.replace(/-/g, '_') || 'last'} --> END((End))
|
${actions[actions.length-1]?.id.replace(/-/g, '_') || 'last'} --> END((End))
|
||||||
\`\`\`
|
\`\`\`
|
||||||
|
|
||||||
## 选择优先级
|
## Selection Priority
|
||||||
|
|
||||||
| Priority | Action | Description |
|
| Priority | Action | Description |
|
||||||
|----------|--------|-------------|
|
|----------|--------|-------------|
|
||||||
${actions.sort((a, b) => (b.priority || 0) - (a.priority || 0)).map(a =>
|
${actions.sort((a, b) => (b.priority || 0) - (a.priority || 0)).map(a =>
|
||||||
`| ${a.priority || 0} | ${a.id} | ${a.description || a.name} |`
|
\`| ${a.priority || 0} | ${a.id} | ${a.description || a.name} |\`
|
||||||
).join('\n')}
|
).join('\n')}
|
||||||
`;
|
`;
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
### Step 4: 辅助函数
|
### Step 4: Helper Functions
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
// ========== P0: Phase 0 生成函数 ==========
|
// ========== P0: Phase 0 generation function ==========
|
||||||
function generatePhase0Spec(config) {
|
function generatePhase0Spec(config) {
|
||||||
const skillRoot = '.claude/skills/skill-generator';
|
const skillRoot = '.claude/skills/skill-generator';
|
||||||
const specsToRead = [
|
const specsToRead = [
|
||||||
@@ -808,54 +807,54 @@ function generatePhase0Spec(config) {
|
|||||||
|
|
||||||
return `# Phase 0: Specification Study
|
return `# Phase 0: Specification Study
|
||||||
|
|
||||||
⚠️ **MANDATORY PREREQUISITE** - 此阶段不可跳过
|
MANDATORY PREREQUISITE - This phase cannot be skipped
|
||||||
|
|
||||||
## Objective
|
## Objective
|
||||||
|
|
||||||
在生成任何文件前,完整阅读所有规范文档,理解 Skill 设计标准。
|
Complete reading of all specification documents before generating any files, understand Skill design standards.
|
||||||
|
|
||||||
## Why This Matters
|
## Why This Matters
|
||||||
|
|
||||||
**不研读规范 (❌)**:
|
**Without reading specifications ()**:
|
||||||
\`\`\`
|
\`\`\`
|
||||||
跳过规范
|
Skip specifications
|
||||||
├─ ✗ 不符合标准
|
├─ Does not meet standards
|
||||||
├─ ✗ 结构混乱
|
├─ Messy structure
|
||||||
└─ ✗ 质量问题
|
└─ Quality issues
|
||||||
\`\`\`
|
\`\`\`
|
||||||
|
|
||||||
**研读规范 (✅)**:
|
**With reading specifications ()**:
|
||||||
\`\`\`
|
\`\`\`
|
||||||
完整研读
|
Complete reading
|
||||||
├─ ✓ 标准化输出
|
├─ Standardized output
|
||||||
├─ ✓ 高质量代码
|
├─ High quality code
|
||||||
└─ ✓ 易于维护
|
└─ Easy to maintain
|
||||||
\`\`\`
|
\`\`\`
|
||||||
|
|
||||||
## Required Reading
|
## Required Reading
|
||||||
|
|
||||||
### P0 - 核心设计规范
|
### P0 - Core Design Specification
|
||||||
|
|
||||||
\`\`\`javascript
|
\`\`\`javascript
|
||||||
// 通用设计标准 (MUST READ)
|
// Universal design standards (MUST READ)
|
||||||
const designSpec = Read('.claude/skills/_shared/SKILL-DESIGN-SPEC.md');
|
const designSpec = Read('.claude/skills/_shared/SKILL-DESIGN-SPEC.md');
|
||||||
|
|
||||||
// 关键内容检查点:
|
// Key content checkpoints:
|
||||||
const checkpoints = {
|
const checkpoints = {
|
||||||
structure: '目录结构约定',
|
structure: 'Directory structure conventions',
|
||||||
naming: '命名规范',
|
naming: 'Naming standards',
|
||||||
quality: '质量标准',
|
quality: 'Quality standards',
|
||||||
output: '输出格式要求'
|
output: 'Output format requirements'
|
||||||
};
|
};
|
||||||
\`\`\`
|
\`\`\`
|
||||||
|
|
||||||
### P1 - 模板文件 (生成前必读)
|
### P1 - Template Files (Must read before generation)
|
||||||
|
|
||||||
\`\`\`javascript
|
\`\`\`javascript
|
||||||
// 根据执行模式加载对应模板
|
// Load corresponding templates based on execution mode
|
||||||
const templates = {
|
const templates = {
|
||||||
all: [
|
all: [
|
||||||
'templates/skill-md.md' // SKILL.md 入口文件模板
|
'templates/skill-md.md' // SKILL.md entry file template
|
||||||
],
|
],
|
||||||
sequential: [
|
sequential: [
|
||||||
'templates/sequential-phase.md'
|
'templates/sequential-phase.md'
|
||||||
@@ -871,24 +870,24 @@ const requiredTemplates = [...templates.all, ...templates[mode]];
|
|||||||
|
|
||||||
requiredTemplates.forEach(template => {
|
requiredTemplates.forEach(template => {
|
||||||
const content = Read(\`.claude/skills/skill-generator/\${template}\`);
|
const content = Read(\`.claude/skills/skill-generator/\${template}\`);
|
||||||
// 理解模板结构、变量位置、生成规则
|
// Understand template structure, variable positions, generation rules
|
||||||
});
|
});
|
||||||
\`\`\`
|
\`\`\`
|
||||||
|
|
||||||
## Execution
|
## Execution
|
||||||
|
|
||||||
\`\`\`javascript
|
\`\`\`javascript
|
||||||
// ========== 加载规范 ==========
|
// ========== Load specifications ==========
|
||||||
const specs = [];
|
const specs = [];
|
||||||
|
|
||||||
// 1. 设计规范 (P0)
|
// 1. Design specification (P0)
|
||||||
specs.push({
|
specs.push({
|
||||||
file: '../_shared/SKILL-DESIGN-SPEC.md',
|
file: '../_shared/SKILL-DESIGN-SPEC.md',
|
||||||
content: Read('.claude/skills/_shared/SKILL-DESIGN-SPEC.md'),
|
content: Read('.claude/skills/_shared/SKILL-DESIGN-SPEC.md'),
|
||||||
priority: 'P0'
|
priority: 'P0'
|
||||||
});
|
});
|
||||||
|
|
||||||
// 2. 模板文件 (P1)
|
// 2. Template files (P1)
|
||||||
const templateFiles = Glob('.claude/skills/skill-generator/templates/*.md');
|
const templateFiles = Glob('.claude/skills/skill-generator/templates/*.md');
|
||||||
templateFiles.forEach(file => {
|
templateFiles.forEach(file => {
|
||||||
specs.push({
|
specs.push({
|
||||||
@@ -898,14 +897,14 @@ templateFiles.forEach(file => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
// ========== 内化规范 ==========
|
// ========== Internalize specifications ==========
|
||||||
console.log('📖 Reading specifications...');
|
console.log('Reading specifications...');
|
||||||
specs.forEach(spec => {
|
specs.forEach(spec => {
|
||||||
console.log(\` [\${spec.priority}] \${spec.file}\`);
|
console.log(\` [\${spec.priority}] \${spec.file}\`);
|
||||||
// 理解内容(无需生成文件,仅内存处理)
|
// Understand content (no need to generate files, only memory processing)
|
||||||
});
|
});
|
||||||
|
|
||||||
// ========== 生成完成标记 ==========
|
// ========== Generate completion flag ==========
|
||||||
const result = {
|
const result = {
|
||||||
status: 'completed',
|
status: 'completed',
|
||||||
specs_loaded: specs.length,
|
specs_loaded: specs.length,
|
||||||
@@ -917,27 +916,27 @@ Write(\`\${workDir}/spec-study-complete.flag\`, JSON.stringify(result, null, 2))
|
|||||||
|
|
||||||
## Output
|
## Output
|
||||||
|
|
||||||
- **标记文件**: \`spec-study-complete.flag\` (证明已完成阅读)
|
- **Flag File**: \`spec-study-complete.flag\` (proves reading completion)
|
||||||
- **副作用**: 内化规范知识,后续阶段遵循标准
|
- **Side Effect**: Internalize specification knowledge, subsequent phases follow standards
|
||||||
|
|
||||||
## Success Criteria
|
## Success Criteria
|
||||||
|
|
||||||
✅ **通过标准**:
|
Completion criteria:
|
||||||
- [ ] 已阅读 SKILL-DESIGN-SPEC.md
|
- [ ] Read SKILL-DESIGN-SPEC.md
|
||||||
- [ ] 已阅读执行模式对应的模板文件
|
- [ ] Read execution mode corresponding template files
|
||||||
- [ ] 理解目录结构约定
|
- [ ] Understand directory structure conventions
|
||||||
- [ ] 理解命名规范
|
- [ ] Understand naming standards
|
||||||
- [ ] 理解质量标准
|
- [ ] Understand quality standards
|
||||||
|
|
||||||
## Next Phase
|
## Next Phase
|
||||||
|
|
||||||
→ [Phase 1: Requirements Discovery](01-requirements-discovery.md)
|
→ [Phase 1: Requirements Discovery](01-requirements-discovery.md)
|
||||||
|
|
||||||
**关键**: 只有完成规范研读后,Phase 1 才能正确收集需求并生成符合标准的配置。
|
**Key**: Only after completing specification study can Phase 1 correctly collect requirements and generate specification-compliant configurations.
|
||||||
`;
|
`;
|
||||||
}
|
}
|
||||||
|
|
||||||
// ========== 其他辅助函数 ==========
|
// ========== Other helper functions ==========
|
||||||
function toPascalCase(str) {
|
function toPascalCase(str) {
|
||||||
return str.split('-').map(s => s.charAt(0).toUpperCase() + s.slice(1)).join('');
|
return str.split('-').map(s => s.charAt(0).toUpperCase() + s.slice(1)).join('');
|
||||||
}
|
}
|
||||||
@@ -967,3 +966,11 @@ function getPreconditionCheck(action) {
|
|||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
|
## Next Phase
|
||||||
|
|
||||||
|
→ [Phase 4: Specifications & Templates](04-specs-templates.md)
|
||||||
|
|
||||||
|
**Data Flow to Phase 4**:
|
||||||
|
- All phase/action files generated in phases/ directory
|
||||||
|
- Complete skill directory structure ready for specs and templates generation
|
||||||
|
- skill-config.json for reference in documentation generation
|
||||||
|
|||||||
@@ -40,7 +40,7 @@ Generate comprehensive specifications and templates:
|
|||||||
```markdown
|
```markdown
|
||||||
# {display_name} Requirements
|
# {display_name} Requirements
|
||||||
- When to Use (phase/action reference table)
|
- When to Use (phase/action reference table)
|
||||||
- Domain Requirements (功能要求, 输出要求, 质量要求)
|
- Domain Requirements (Functional requirements, Output requirements, Quality requirements)
|
||||||
- Validation Function (JavaScript code)
|
- Validation Function (JavaScript code)
|
||||||
- Error Handling (recovery strategies)
|
- Error Handling (recovery strategies)
|
||||||
```
|
```
|
||||||
@@ -57,10 +57,10 @@ Generate comprehensive specifications and templates:
|
|||||||
**Agent Base** (`templates/agent-base.md`):
|
**Agent Base** (`templates/agent-base.md`):
|
||||||
```markdown
|
```markdown
|
||||||
# Agent Base Template
|
# Agent Base Template
|
||||||
- 通用 Prompt 结构 (ROLE, PROJECT CONTEXT, TASK, CONSTRAINTS, OUTPUT_FORMAT, QUALITY_CHECKLIST)
|
- Universal Prompt Structure (ROLE, PROJECT CONTEXT, TASK, CONSTRAINTS, OUTPUT_FORMAT, QUALITY_CHECKLIST)
|
||||||
- 变量说明 (workDir, output_path)
|
- Variable Description (workDir, output_path)
|
||||||
- 返回格式 (AgentReturn interface)
|
- Return Format (AgentReturn interface)
|
||||||
- 角色定义参考 (phase/action specific agents)
|
- Role Definition Reference (phase/action specific agents)
|
||||||
```
|
```
|
||||||
|
|
||||||
**Action Catalog** (`specs/action-catalog.md`, Autonomous/Hybrid only):
|
**Action Catalog** (`specs/action-catalog.md`, Autonomous/Hybrid only):
|
||||||
@@ -114,39 +114,39 @@ ${config.execution_mode === 'sequential' ?
|
|||||||
config.sequential_config.phases.map((p, i) =>
|
config.sequential_config.phases.map((p, i) =>
|
||||||
`| Phase ${i+1} | ${p.name} | ${p.id}.md |`
|
`| Phase ${i+1} | ${p.name} | ${p.id}.md |`
|
||||||
).join('\n') :
|
).join('\n') :
|
||||||
`| Orchestrator | 动作选择 | orchestrator.md |
|
`| Orchestrator | Action selection | orchestrator.md |
|
||||||
| Actions | 动作执行 | actions/*.md |`}
|
| Actions | Action execution | actions/*.md |`}
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Domain Requirements
|
## Domain Requirements
|
||||||
|
|
||||||
### 功能要求
|
### Functional Requirements
|
||||||
|
|
||||||
- [ ] 要求1: TODO
|
- [ ] Requirement 1: TODO
|
||||||
- [ ] 要求2: TODO
|
- [ ] Requirement 2: TODO
|
||||||
- [ ] 要求3: TODO
|
- [ ] Requirement 3: TODO
|
||||||
|
|
||||||
### 输出要求
|
### Output Requirements
|
||||||
|
|
||||||
- [ ] 格式: ${config.output.format}
|
- [ ] Format: ${config.output.format}
|
||||||
- [ ] 位置: ${config.output.location}
|
- [ ] Location: ${config.output.location}
|
||||||
- [ ] 命名: ${config.output.filename_pattern}
|
- [ ] Naming: ${config.output.filename_pattern}
|
||||||
|
|
||||||
### 质量要求
|
### Quality Requirements
|
||||||
|
|
||||||
- [ ] 完整性: 所有必需内容存在
|
- [ ] Completeness: All necessary content exists
|
||||||
- [ ] 一致性: 术语和格式统一
|
- [ ] Consistency: Terminology and format unified
|
||||||
- [ ] 准确性: 内容基于实际分析
|
- [ ] Accuracy: Content based on actual analysis
|
||||||
|
|
||||||
## Validation Function
|
## Validation Function
|
||||||
|
|
||||||
\`\`\`javascript
|
\`\`\`javascript
|
||||||
function validate${toPascalCase(config.skill_name)}(output) {
|
function validate${toPascalCase(config.skill_name)}(output) {
|
||||||
const checks = [
|
const checks = [
|
||||||
// TODO: 添加验证规则
|
// TODO: Add validation rules
|
||||||
{ name: "格式正确", pass: output.format === "${config.output.format}" },
|
{ name: "Format correct", pass: output.format === "${config.output.format}" },
|
||||||
{ name: "内容完整", pass: output.content?.length > 0 }
|
{ name: "Content complete", pass: output.content?.length > 0 }
|
||||||
];
|
];
|
||||||
|
|
||||||
return {
|
return {
|
||||||
@@ -161,9 +161,9 @@ function validate${toPascalCase(config.skill_name)}(output) {
|
|||||||
|
|
||||||
| Error | Recovery |
|
| Error | Recovery |
|
||||||
|-------|----------|
|
|-------|----------|
|
||||||
| 输入数据缺失 | 返回明确错误信息 |
|
| Missing input data | Return clear error message |
|
||||||
| 处理超时 | 缩小范围,重试 |
|
| Processing timeout | Reduce scope, retry |
|
||||||
| 输出验证失败 | 记录问题,人工审核 |
|
| Output validation failure | Log issue, manual review |
|
||||||
`;
|
`;
|
||||||
|
|
||||||
Write(`${skillDir}/specs/${config.skill_name}-requirements.md`, domainRequirements);
|
Write(`${skillDir}/specs/${config.skill_name}-requirements.md`, domainRequirements);
|
||||||
@@ -171,68 +171,68 @@ Write(`${skillDir}/specs/${config.skill_name}-requirements.md`, domainRequiremen
|
|||||||
// Step 2: Generate quality standards
|
// Step 2: Generate quality standards
|
||||||
const qualityStandards = `# Quality Standards
|
const qualityStandards = `# Quality Standards
|
||||||
|
|
||||||
${config.display_name} 的质量评估标准。
|
Quality assessment standards for ${config.display_name}.
|
||||||
|
|
||||||
## Quality Dimensions
|
## Quality Dimensions
|
||||||
|
|
||||||
### 1. Completeness (完整性) - 25%
|
### 1. Completeness (Completeness) - 25%
|
||||||
|
|
||||||
| 要求 | 权重 | 检查方式 |
|
| Requirement | Weight | Validation Method |
|
||||||
|------|------|----------|
|
|------------|--------|-----------------|
|
||||||
| 所有必需输出存在 | 10 | 文件检查 |
|
| All necessary outputs exist | 10 | File check |
|
||||||
| 内容覆盖完整 | 10 | 内容分析 |
|
| Content coverage complete | 10 | Content analysis |
|
||||||
| 无占位符残留 | 5 | 文本搜索 |
|
| No placeholder remnants | 5 | Text search |
|
||||||
|
|
||||||
### 2. Consistency (一致性) - 25%
|
### 2. Consistency (Consistency) - 25%
|
||||||
|
|
||||||
| 方面 | 检查 |
|
| Aspect | Check |
|
||||||
|------|------|
|
|--------|-------|
|
||||||
| 术语 | 同一概念使用相同术语 |
|
| Terminology | Use same term for same concept |
|
||||||
| 格式 | 标题层级、代码块格式一致 |
|
| Format | Title levels, code block format consistent |
|
||||||
| 风格 | 语气和表达方式统一 |
|
| Style | Tone and expression unified |
|
||||||
|
|
||||||
### 3. Accuracy (准确性) - 25%
|
### 3. Accuracy (Accuracy) - 25%
|
||||||
|
|
||||||
| 要求 | 说明 |
|
| Requirement | Description |
|
||||||
|------|------|
|
|-------------|------------|
|
||||||
| 数据正确 | 引用和数据无错误 |
|
| Data correct | References and data error-free |
|
||||||
| 逻辑正确 | 流程和关系描述准确 |
|
| Logic correct | Process and relationship descriptions accurate |
|
||||||
| 代码正确 | 代码示例可运行 |
|
| Code correct | Code examples runnable |
|
||||||
|
|
||||||
### 4. Usability (可用性) - 25%
|
### 4. Usability (Usability) - 25%
|
||||||
|
|
||||||
| 指标 | 目标 |
|
| Metric | Goal |
|
||||||
|------|------|
|
|--------|------|
|
||||||
| 可读性 | 结构清晰,易于理解 |
|
| Readability | Clear structure, easy to understand |
|
||||||
| 可导航 | 目录和链接正确 |
|
| Navigability | Table of contents and links correct |
|
||||||
| 可操作 | 步骤明确,可执行 |
|
| Operability | Steps clear, executable |
|
||||||
|
|
||||||
## Quality Gates
|
## Quality Gates
|
||||||
|
|
||||||
| Gate | Threshold | Action |
|
| Gate | Threshold | Action |
|
||||||
|------|-----------|--------|
|
|------|-----------|--------|
|
||||||
| Pass | ≥ 80% | 输出最终产物 |
|
| Pass | >= 80% | Output final deliverables |
|
||||||
| Review | 60-79% | 处理警告后继续 |
|
| Review | 60-79% | Process warnings then continue |
|
||||||
| Fail | < 60% | 必须修复 |
|
| Fail | < 60% | Must fix |
|
||||||
|
|
||||||
## Issue Classification
|
## Issue Classification
|
||||||
|
|
||||||
### Errors (Must Fix)
|
### Errors (Must Fix)
|
||||||
|
|
||||||
- 必需输出缺失
|
- Necessary output missing
|
||||||
- 数据错误
|
- Data error
|
||||||
- 代码不可运行
|
- Code not runnable
|
||||||
|
|
||||||
### Warnings (Should Fix)
|
### Warnings (Should Fix)
|
||||||
|
|
||||||
- 格式不一致
|
- Format inconsistency
|
||||||
- 内容深度不足
|
- Content depth insufficient
|
||||||
- 缺少示例
|
- Missing examples
|
||||||
|
|
||||||
### Info (Nice to Have)
|
### Info (Nice to Have)
|
||||||
|
|
||||||
- 优化建议
|
- Optimization suggestions
|
||||||
- 增强机会
|
- Enhancement opportunities
|
||||||
|
|
||||||
## Automated Checks
|
## Automated Checks
|
||||||
|
|
||||||
@@ -267,44 +267,44 @@ Write(`${skillDir}/specs/quality-standards.md`, qualityStandards);
|
|||||||
// Step 3: Generate agent base template
|
// Step 3: Generate agent base template
|
||||||
const agentBase = `# Agent Base Template
|
const agentBase = `# Agent Base Template
|
||||||
|
|
||||||
${config.display_name} 的 Agent 基础模板。
|
Agent base template for ${config.display_name}.
|
||||||
|
|
||||||
## 通用 Prompt 结构
|
## Universal Prompt Structure
|
||||||
|
|
||||||
\`\`\`
|
\`\`\`
|
||||||
[ROLE] 你是{角色},专注于{职责}。
|
[ROLE] You are {role}, focused on {responsibility}.
|
||||||
|
|
||||||
[PROJECT CONTEXT]
|
[PROJECT CONTEXT]
|
||||||
Skill: ${config.skill_name}
|
Skill: ${config.skill_name}
|
||||||
目标: ${config.description}
|
Objective: ${config.description}
|
||||||
|
|
||||||
[TASK]
|
[TASK]
|
||||||
{任务描述}
|
{task description}
|
||||||
- 输出: {output_path}
|
- Output: {output_path}
|
||||||
- 格式: ${config.output.format}
|
- Format: ${config.output.format}
|
||||||
|
|
||||||
[CONSTRAINTS]
|
[CONSTRAINTS]
|
||||||
- 约束1
|
- Constraint 1
|
||||||
- 约束2
|
- Constraint 2
|
||||||
|
|
||||||
[OUTPUT_FORMAT]
|
[OUTPUT_FORMAT]
|
||||||
1. 执行任务
|
1. Execute task
|
||||||
2. 返回 JSON 简要信息
|
2. Return JSON summary information
|
||||||
|
|
||||||
[QUALITY_CHECKLIST]
|
[QUALITY_CHECKLIST]
|
||||||
- [ ] 输出格式正确
|
- [ ] Output format correct
|
||||||
- [ ] 内容完整无遗漏
|
- [ ] Content complete without omission
|
||||||
- [ ] 无占位符残留
|
- [ ] No placeholder remnants
|
||||||
\`\`\`
|
\`\`\`
|
||||||
|
|
||||||
## 变量说明
|
## Variable Description
|
||||||
|
|
||||||
| 变量 | 来源 | 示例 |
|
| Variable | Source | Example |
|
||||||
|------|------|------|
|
|----------|--------|---------|
|
||||||
| {workDir} | 运行时 | .workflow/.scratchpad/${config.skill_name}-xxx |
|
| {workDir} | Runtime | .workflow/.scratchpad/${config.skill_name}-xxx |
|
||||||
| {output_path} | 配置 | ${config.output.location}/${config.output.filename_pattern} |
|
| {output_path} | Configuration | ${config.output.location}/${config.output.filename_pattern} |
|
||||||
|
|
||||||
## 返回格式
|
## Return Format
|
||||||
|
|
||||||
\`\`\`typescript
|
\`\`\`typescript
|
||||||
interface AgentReturn {
|
interface AgentReturn {
|
||||||
@@ -318,14 +318,14 @@ interface AgentReturn {
|
|||||||
}
|
}
|
||||||
\`\`\`
|
\`\`\`
|
||||||
|
|
||||||
## 角色定义参考
|
## Role Definition Reference
|
||||||
|
|
||||||
${config.execution_mode === 'sequential' ?
|
${config.execution_mode === 'sequential' ?
|
||||||
config.sequential_config.phases.map((p, i) =>
|
config.sequential_config.phases.map((p, i) =>
|
||||||
`- **Phase ${i+1} Agent**: ${p.name} 专家`
|
`- **Phase ${i+1} Agent**: ${p.name} Expert`
|
||||||
).join('\n') :
|
).join('\n') :
|
||||||
config.autonomous_config.actions.map(a =>
|
config.autonomous_config.actions.map(a =>
|
||||||
`- **${a.name} Agent**: ${a.description || a.name + ' 执行者'}`
|
`- **${a.name} Agent**: ${a.description || a.name + ' Executor'}`
|
||||||
).join('\n')}
|
).join('\n')}
|
||||||
`;
|
`;
|
||||||
|
|
||||||
@@ -335,7 +335,7 @@ Write(`${skillDir}/templates/agent-base.md`, agentBase);
|
|||||||
if (config.execution_mode === 'autonomous' || config.execution_mode === 'hybrid') {
|
if (config.execution_mode === 'autonomous' || config.execution_mode === 'hybrid') {
|
||||||
const actionCatalog = `# Action Catalog
|
const actionCatalog = `# Action Catalog
|
||||||
|
|
||||||
${config.display_name} 的可用动作目录。
|
Available action catalog for ${config.display_name}.
|
||||||
|
|
||||||
## Available Actions
|
## Available Actions
|
||||||
|
|
||||||
@@ -350,9 +350,9 @@ ${config.autonomous_config.actions.map(a =>
|
|||||||
\`\`\`mermaid
|
\`\`\`mermaid
|
||||||
graph TD
|
graph TD
|
||||||
${config.autonomous_config.actions.map((a, i, arr) => {
|
${config.autonomous_config.actions.map((a, i, arr) => {
|
||||||
if (i === 0) return ` ${a.id.replace(/-/g, '_')}[${a.name}]`;
|
if (i === 0) return \` ${a.id.replace(/-/g, '_')}[${a.name}]\`;
|
||||||
const prev = arr[i-1];
|
const prev = arr[i-1];
|
||||||
return ` ${prev.id.replace(/-/g, '_')} --> ${a.id.replace(/-/g, '_')}[${a.name}]`;
|
return \` ${prev.id.replace(/-/g, '_')} --> ${a.id.replace(/-/g, '_')}[${a.name}]\`;
|
||||||
}).join('\n')}
|
}).join('\n')}
|
||||||
\`\`\`
|
\`\`\`
|
||||||
|
|
||||||
@@ -369,10 +369,10 @@ ${config.autonomous_config.actions.slice(1).map(a =>
|
|||||||
|
|
||||||
## Selection Priority
|
## Selection Priority
|
||||||
|
|
||||||
当多个动作的前置条件都满足时,按以下优先级选择:
|
When multiple actions' preconditions are met, select based on the following priority:
|
||||||
|
|
||||||
${config.autonomous_config.actions.map((a, i) =>
|
${config.autonomous_config.actions.map((a, i) =>
|
||||||
`${i + 1}. \`${a.id}\` - ${a.name}`
|
\`${i + 1}. \\\`${a.id}\\\` - ${a.name}\`
|
||||||
).join('\n')}
|
).join('\n')}
|
||||||
`;
|
`;
|
||||||
|
|
||||||
|
|||||||
@@ -246,16 +246,16 @@ function collectIssues(fileResults, contentResults) {
|
|||||||
const issues = [];
|
const issues = [];
|
||||||
|
|
||||||
fileResults.filter(f => !f.exists).forEach(f => {
|
fileResults.filter(f => !f.exists).forEach(f => {
|
||||||
issues.push({ type: 'ERROR', message: `文件缺失: ${f.file}` });
|
issues.push({ type: 'ERROR', message: `Missing file: ${f.file}` });
|
||||||
});
|
});
|
||||||
|
|
||||||
fileResults.filter(f => f.hasTodo).forEach(f => {
|
fileResults.filter(f => f.hasTodo).forEach(f => {
|
||||||
issues.push({ type: 'WARNING', message: `包含 TODO: ${f.file}` });
|
issues.push({ type: 'WARNING', message: `Contains TODO: ${f.file}` });
|
||||||
});
|
});
|
||||||
|
|
||||||
contentResults.forEach(c => {
|
contentResults.forEach(c => {
|
||||||
c.checks.filter(ch => !ch.pass).forEach(ch => {
|
c.checks.filter(ch => !ch.pass).forEach(ch => {
|
||||||
issues.push({ type: 'WARNING', message: `${c.file}: 缺少 ${ch.name}` });
|
issues.push({ type: 'WARNING', message: `${c.file}: Missing ${ch.name}` });
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -266,12 +266,12 @@ function generateRecommendations(fileResults, contentResults) {
|
|||||||
const recommendations = [];
|
const recommendations = [];
|
||||||
|
|
||||||
if (fileResults.some(f => f.hasTodo)) {
|
if (fileResults.some(f => f.hasTodo)) {
|
||||||
recommendations.push('替换所有 TODO 占位符为实际内容');
|
recommendations.push('Replace all TODO placeholders with actual content');
|
||||||
}
|
}
|
||||||
|
|
||||||
contentResults.forEach(c => {
|
contentResults.forEach(c => {
|
||||||
if (c.checks.some(ch => !ch.pass)) {
|
if (c.checks.some(ch => !ch.pass)) {
|
||||||
recommendations.push(`完善 ${c.file} 的结构`);
|
recommendations.push(`Improve structure of ${c.file}`);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -285,81 +285,81 @@ ${config.description}
|
|||||||
|
|
||||||
## Quick Start
|
## Quick Start
|
||||||
|
|
||||||
### 触发词
|
### Trigger Words
|
||||||
|
|
||||||
${config.triggers.map(t => `- "${t}"`).join('\n')}
|
${config.triggers.map(t => `- "${t}"`).join('\n')}
|
||||||
|
|
||||||
### 执行模式
|
### Execution Mode
|
||||||
|
|
||||||
**${config.execution_mode === 'sequential' ? 'Sequential (顺序)' : 'Autonomous (自主)'}**
|
**${config.execution_mode === 'sequential' ? 'Sequential (Sequential)' : 'Autonomous (Autonomous)'}**
|
||||||
|
|
||||||
${config.execution_mode === 'sequential' ?
|
${config.execution_mode === 'sequential' ?
|
||||||
`阶段按固定顺序执行:\n${config.sequential_config.phases.map((p, i) =>
|
\`Phases execute in fixed order:\n\${config.sequential_config.phases.map((p, i) =>
|
||||||
`${i + 1}. ${p.name}`
|
\`\${i + 1}. \${p.name}\`
|
||||||
).join('\n')}` :
|
).join('\n')}\` :
|
||||||
`动作由编排器动态选择:\n${config.autonomous_config.actions.map(a =>
|
\`Actions selected dynamically by orchestrator:\n\${config.autonomous_config.actions.map(a =>
|
||||||
`- ${a.name}: ${a.description || ''}`
|
\`- \${a.name}: \${a.description || ''}\`
|
||||||
).join('\n')}`}
|
).join('\n')}\`}
|
||||||
|
|
||||||
## Usage
|
## Usage
|
||||||
|
|
||||||
\`\`\`
|
\`\`\`
|
||||||
# 直接触发
|
# Direct trigger
|
||||||
用户: ${config.triggers[0]}
|
User: ${config.triggers[0]}
|
||||||
|
|
||||||
# 或使用 Skill 名称
|
# Or use Skill name
|
||||||
用户: /skill ${config.skill_name}
|
User: /skill ${config.skill_name}
|
||||||
\`\`\`
|
\`\`\`
|
||||||
|
|
||||||
## Output
|
## Output
|
||||||
|
|
||||||
- **格式**: ${config.output.format}
|
- **Format**: ${config.output.format}
|
||||||
- **位置**: \`${config.output.location}\`
|
- **Location**: \`${config.output.location}\`
|
||||||
- **文件名**: \`${config.output.filename_pattern}\`
|
- **Filename**: \`${config.output.filename_pattern}\`
|
||||||
|
|
||||||
## Directory Structure
|
## Directory Structure
|
||||||
|
|
||||||
\`\`\`
|
\`\`\`
|
||||||
.claude/skills/${config.skill_name}/
|
.claude/skills/${config.skill_name}/
|
||||||
├── SKILL.md # 入口文件
|
├── SKILL.md # Entry file
|
||||||
├── phases/ # 执行阶段
|
├── phases/ # Execution phases
|
||||||
${config.execution_mode === 'sequential' ?
|
${config.execution_mode === 'sequential' ?
|
||||||
config.sequential_config.phases.map(p => `│ ├── ${p.id}.md`).join('\n') :
|
config.sequential_config.phases.map(p => \`│ ├── \${p.id}.md\`).join('\n') :
|
||||||
`│ ├── orchestrator.md
|
\`│ ├── orchestrator.md
|
||||||
│ ├── state-schema.md
|
│ ├── state-schema.md
|
||||||
│ └── actions/
|
│ └── actions/
|
||||||
${config.autonomous_config.actions.map(a => `│ ├── ${a.id}.md`).join('\n')}`}
|
\${config.autonomous_config.actions.map(a => \`│ ├── \${a.id}.md\`).join('\n')}\`}
|
||||||
├── specs/ # 规范文件
|
├── specs/ # Specification files
|
||||||
│ ├── ${config.skill_name}-requirements.md
|
│ ├── ${config.skill_name}-requirements.md
|
||||||
│ ├── quality-standards.md
|
│ ├── quality-standards.md
|
||||||
${config.execution_mode === 'autonomous' ? '│ └── action-catalog.md' : ''}
|
${config.execution_mode === 'autonomous' ? '│ └── action-catalog.md' : ''}
|
||||||
└── templates/ # 模板文件
|
└── templates/ # Template files
|
||||||
└── agent-base.md
|
└── agent-base.md
|
||||||
\`\`\`
|
\`\`\`
|
||||||
|
|
||||||
## Customization
|
## Customization
|
||||||
|
|
||||||
### 修改执行逻辑
|
### Modify Execution Logic
|
||||||
|
|
||||||
编辑 \`phases/\` 目录下的阶段文件。
|
Edit phase files in the \`phases/\` directory.
|
||||||
|
|
||||||
### 调整质量标准
|
### Adjust Quality Standards
|
||||||
|
|
||||||
编辑 \`specs/quality-standards.md\`。
|
Edit \`specs/quality-standards.md\`.
|
||||||
|
|
||||||
### 添加新${config.execution_mode === 'sequential' ? '阶段' : '动作'}
|
### Add New ${config.execution_mode === 'sequential' ? 'Phase' : 'Action'}
|
||||||
|
|
||||||
${config.execution_mode === 'sequential' ?
|
${config.execution_mode === 'sequential' ?
|
||||||
`1. 在 \`phases/\` 创建新的阶段文件 (如 \`03.5-new-step.md\`)
|
\`1. Create new phase file in \`phases/\` (e.g., \`03.5-new-step.md\`)
|
||||||
2. 更新 SKILL.md 的执行流程` :
|
2. Update execution flow in SKILL.md\` :
|
||||||
`1. 在 \`phases/actions/\` 创建新的动作文件
|
\`1. Create new action file in \`phases/actions/\`
|
||||||
2. 更新 \`specs/action-catalog.md\`
|
2. Update \`specs/action-catalog.md\`
|
||||||
3. 在 \`phases/orchestrator.md\` 添加选择逻辑`}
|
3. Add selection logic in \`phases/orchestrator.md\`\`}
|
||||||
|
|
||||||
## Related Documents
|
## Related Documents
|
||||||
|
|
||||||
- [设计规范](../_shared/SKILL-DESIGN-SPEC.md)
|
- [Design Specification](../_shared/SKILL-DESIGN-SPEC.md)
|
||||||
- [执行模式规范](specs/../../../skill-generator/specs/execution-modes.md)
|
- [Execution Modes Specification](specs/../../../skill-generator/specs/execution-modes.md)
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -383,20 +383,20 @@ const finalResult = {
|
|||||||
validation: report.summary,
|
validation: report.summary,
|
||||||
|
|
||||||
next_steps: [
|
next_steps: [
|
||||||
'1. 审阅生成的文件结构',
|
'1. Review generated file structure',
|
||||||
'2. 替换 TODO 占位符',
|
'2. Replace TODO placeholders',
|
||||||
'3. 根据实际需求调整阶段逻辑',
|
'3. Adjust phase logic based on actual requirements',
|
||||||
'4. 测试 Skill 执行流程',
|
'4. Test Skill execution flow',
|
||||||
'5. 更新触发词和描述'
|
'5. Update trigger words and descriptions'
|
||||||
]
|
]
|
||||||
};
|
};
|
||||||
|
|
||||||
console.log('=== Skill 生成完成 ===');
|
console.log('=== Skill Generation Complete ===');
|
||||||
console.log(`路径: ${skillDir}`);
|
console.log(\`Path: \${skillDir}\`);
|
||||||
console.log(`模式: ${config.execution_mode}`);
|
console.log(\`Mode: \${config.execution_mode}\`);
|
||||||
console.log(`状态: ${report.summary.status}`);
|
console.log(\`Status: \${report.summary.status}\`);
|
||||||
console.log('');
|
console.log('');
|
||||||
console.log('下一步:');
|
console.log('Next Steps:');
|
||||||
finalResult.next_steps.forEach(s => console.log(s));
|
finalResult.next_steps.forEach(s => console.log(s));
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|||||||
@@ -1,111 +1,111 @@
|
|||||||
# CLI Integration Specification
|
# CLI Integration Specification
|
||||||
|
|
||||||
CCW CLI 集成规范,定义 Skill 中如何正确调用外部 CLI 工具。
|
CCW CLI integration specification that defines how to properly call external CLI tools within Skills.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 执行模式
|
## Execution Modes
|
||||||
|
|
||||||
### 1. 同步执行 (Blocking)
|
### 1. Synchronous Execution (Blocking)
|
||||||
|
|
||||||
适用于需要立即获取结果的场景。
|
Suitable for scenarios that need immediate results.
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
// Agent 调用 - 同步
|
// Agent call - synchronous
|
||||||
const result = Task({
|
const result = Task({
|
||||||
subagent_type: 'universal-executor',
|
subagent_type: 'universal-executor',
|
||||||
prompt: '执行任务...',
|
prompt: 'Execute task...',
|
||||||
run_in_background: false // 关键: 同步执行
|
run_in_background: false // Key: synchronous execution
|
||||||
});
|
});
|
||||||
|
|
||||||
// 结果立即可用
|
// Result immediately available
|
||||||
console.log(result);
|
console.log(result);
|
||||||
```
|
```
|
||||||
|
|
||||||
### 2. 异步执行 (Background)
|
### 2. Asynchronous Execution (Background)
|
||||||
|
|
||||||
适用于长时间运行的 CLI 命令。
|
Suitable for long-running CLI commands.
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
// CLI 调用 - 异步
|
// CLI call - asynchronous
|
||||||
const task = Bash({
|
const task = Bash({
|
||||||
command: 'ccw cli -p "..." --tool gemini --mode analysis',
|
command: 'ccw cli -p "..." --tool gemini --mode analysis',
|
||||||
run_in_background: true // 关键: 后台执行
|
run_in_background: true // Key: background execution
|
||||||
});
|
});
|
||||||
|
|
||||||
// 立即返回,不等待结果
|
// Returns immediately without waiting for result
|
||||||
// task.task_id 可用于后续查询
|
// task.task_id available for later queries
|
||||||
```
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## CCW CLI 调用规范
|
## CCW CLI Call Specification
|
||||||
|
|
||||||
### 基础命令结构
|
### Basic Command Structure
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
ccw cli -p "<PROMPT>" --tool <gemini|qwen|codex> --mode <analysis|write>
|
ccw cli -p "<PROMPT>" --tool <gemini|qwen|codex> --mode <analysis|write>
|
||||||
```
|
```
|
||||||
|
|
||||||
### 参数说明
|
### Parameter Description
|
||||||
|
|
||||||
| 参数 | 必需 | 说明 |
|
| Parameter | Required | Description |
|
||||||
|------|------|------|
|
|-----------|----------|-------------|
|
||||||
| `-p "<prompt>"` | ✓ | 提示词(使用双引号) |
|
| `-p "<prompt>"` | Yes | Prompt text (use double quotes) |
|
||||||
| `--tool <tool>` | ✓ | 工具选择: gemini, qwen, codex |
|
| `--tool <tool>` | Yes | Tool selection: gemini, qwen, codex |
|
||||||
| `--mode <mode>` | ✓ | 执行模式: analysis, write |
|
| `--mode <mode>` | Yes | Execution mode: analysis, write |
|
||||||
| `--cd <path>` | - | 工作目录 |
|
| `--cd <path>` | - | Working directory |
|
||||||
| `--includeDirs <dirs>` | - | 包含额外目录(逗号分隔) |
|
| `--includeDirs <dirs>` | - | Additional directories (comma-separated) |
|
||||||
| `--resume [id]` | - | 恢复会话 |
|
| `--resume [id]` | - | Resume session |
|
||||||
|
|
||||||
### 模式选择
|
### Mode Selection
|
||||||
|
|
||||||
```
|
```
|
||||||
┌─ 分析/文档任务?
|
- Analysis/Documentation tasks?
|
||||||
│ └─→ --mode analysis (只读)
|
→ --mode analysis (read-only)
|
||||||
│
|
|
||||||
└─ 实现/修改任务?
|
- Implementation/Modification tasks?
|
||||||
└─→ --mode write (读写)
|
→ --mode write (read-write)
|
||||||
```
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Agent 类型与选择
|
## Agent Types and Selection
|
||||||
|
|
||||||
### universal-executor
|
### universal-executor
|
||||||
|
|
||||||
通用执行器,最常用的 Agent 类型。
|
General-purpose executor, the most commonly used agent type.
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
Task({
|
Task({
|
||||||
subagent_type: 'universal-executor',
|
subagent_type: 'universal-executor',
|
||||||
prompt: `
|
prompt: `
|
||||||
执行任务:
|
Execute task:
|
||||||
1. 读取配置文件
|
1. Read configuration file
|
||||||
2. 分析依赖关系
|
2. Analyze dependencies
|
||||||
3. 生成报告到 ${outputPath}
|
3. Generate report to ${outputPath}
|
||||||
`,
|
`,
|
||||||
run_in_background: false
|
run_in_background: false
|
||||||
});
|
});
|
||||||
```
|
```
|
||||||
|
|
||||||
**适用场景**:
|
**Applicable Scenarios**:
|
||||||
- 多步骤任务执行
|
- Multi-step task execution
|
||||||
- 文件操作(读/写/编辑)
|
- File operations (read/write/edit)
|
||||||
- 需要工具调用的任务
|
- Tasks that require tool invocation
|
||||||
|
|
||||||
### Explore
|
### Explore
|
||||||
|
|
||||||
代码探索 Agent,快速理解代码库。
|
Code exploration agent for quick codebase understanding.
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
Task({
|
Task({
|
||||||
subagent_type: 'Explore',
|
subagent_type: 'Explore',
|
||||||
prompt: `
|
prompt: `
|
||||||
探索 src/ 目录:
|
Explore src/ directory:
|
||||||
- 识别主要模块
|
- Identify main modules
|
||||||
- 理解目录结构
|
- Understand directory structure
|
||||||
- 找到入口点
|
- Find entry points
|
||||||
|
|
||||||
Thoroughness: medium
|
Thoroughness: medium
|
||||||
`,
|
`,
|
||||||
@@ -113,104 +113,104 @@ Thoroughness: medium
|
|||||||
});
|
});
|
||||||
```
|
```
|
||||||
|
|
||||||
**适用场景**:
|
**Applicable Scenarios**:
|
||||||
- 代码库探索
|
- Codebase exploration
|
||||||
- 文件发现
|
- File discovery
|
||||||
- 结构理解
|
- Structure understanding
|
||||||
|
|
||||||
### cli-explore-agent
|
### cli-explore-agent
|
||||||
|
|
||||||
深度代码分析 Agent。
|
Deep code analysis agent.
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
Task({
|
Task({
|
||||||
subagent_type: 'cli-explore-agent',
|
subagent_type: 'cli-explore-agent',
|
||||||
prompt: `
|
prompt: `
|
||||||
深度分析 src/auth/ 模块:
|
Deep analysis of src/auth/ module:
|
||||||
- 认证流程
|
- Authentication flow
|
||||||
- 会话管理
|
- Session management
|
||||||
- 安全机制
|
- Security mechanisms
|
||||||
`,
|
`,
|
||||||
run_in_background: false
|
run_in_background: false
|
||||||
});
|
});
|
||||||
```
|
```
|
||||||
|
|
||||||
**适用场景**:
|
**Applicable Scenarios**:
|
||||||
- 深度代码理解
|
- Deep code understanding
|
||||||
- 设计模式识别
|
- Design pattern identification
|
||||||
- 复杂逻辑分析
|
- Complex logic analysis
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 会话管理
|
## Session Management
|
||||||
|
|
||||||
### 会话恢复
|
### Session Recovery
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
// 保存会话 ID
|
// Save session ID
|
||||||
const session = Bash({
|
const session = Bash({
|
||||||
command: 'ccw cli -p "初始分析..." --tool gemini --mode analysis',
|
command: 'ccw cli -p "Initial analysis..." --tool gemini --mode analysis',
|
||||||
run_in_background: true
|
run_in_background: true
|
||||||
});
|
});
|
||||||
|
|
||||||
// 后续恢复
|
// Resume later
|
||||||
const continuation = Bash({
|
const continuation = Bash({
|
||||||
command: `ccw cli -p "继续分析..." --tool gemini --mode analysis --resume ${session.id}`,
|
command: `ccw cli -p "Continue analysis..." --tool gemini --mode analysis --resume ${session.id}`,
|
||||||
run_in_background: true
|
run_in_background: true
|
||||||
});
|
});
|
||||||
```
|
```
|
||||||
|
|
||||||
### 多会话合并
|
### Multi-Session Merge
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
// 合并多个会话的上下文
|
// Merge context from multiple sessions
|
||||||
const merged = Bash({
|
const merged = Bash({
|
||||||
command: `ccw cli -p "汇总分析..." --tool gemini --mode analysis --resume ${id1},${id2}`,
|
command: `ccw cli -p "Aggregate analysis..." --tool gemini --mode analysis --resume ${id1},${id2}`,
|
||||||
run_in_background: true
|
run_in_background: true
|
||||||
});
|
});
|
||||||
```
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Skill 中的 CLI 集成模式
|
## CLI Integration Patterns in Skills
|
||||||
|
|
||||||
### 模式 1: 单次调用
|
### Pattern 1: Single Call
|
||||||
|
|
||||||
简单任务,一次调用完成。
|
Simple tasks completed in one call.
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
// Phase 执行
|
// Phase execution
|
||||||
async function executePhase(context) {
|
async function executePhase(context) {
|
||||||
const result = Bash({
|
const result = Bash({
|
||||||
command: `ccw cli -p "
|
command: `ccw cli -p "
|
||||||
PURPOSE: 分析项目结构
|
PURPOSE: Analyze project structure
|
||||||
TASK: 识别模块、依赖、入口点
|
TASK: Identify modules, dependencies, entry points
|
||||||
MODE: analysis
|
MODE: analysis
|
||||||
CONTEXT: @src/**/*
|
CONTEXT: @src/**/*
|
||||||
EXPECTED: JSON 格式的结构报告
|
EXPECTED: JSON format structure report
|
||||||
" --tool gemini --mode analysis --cd ${context.projectRoot}`,
|
" --tool gemini --mode analysis --cd ${context.projectRoot}`,
|
||||||
run_in_background: true,
|
run_in_background: true,
|
||||||
timeout: 600000
|
timeout: 600000
|
||||||
});
|
});
|
||||||
|
|
||||||
// 等待完成
|
// Wait for completion
|
||||||
return await waitForCompletion(result.task_id);
|
return await waitForCompletion(result.task_id);
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
### 模式 2: 链式调用
|
### Pattern 2: Chained Calls
|
||||||
|
|
||||||
多步骤任务,每步依赖前一步结果。
|
Multi-step tasks where each step depends on previous results.
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
async function executeChain(context) {
|
async function executeChain(context) {
|
||||||
// Step 1: 收集
|
// Step 1: Collect
|
||||||
const collectId = await runCLI('collect', context);
|
const collectId = await runCLI('collect', context);
|
||||||
|
|
||||||
// Step 2: 分析 (依赖 Step 1)
|
// Step 2: Analyze (depends on Step 1)
|
||||||
const analyzeId = await runCLI('analyze', context, `--resume ${collectId}`);
|
const analyzeId = await runCLI('analyze', context, `--resume ${collectId}`);
|
||||||
|
|
||||||
// Step 3: 生成 (依赖 Step 2)
|
// Step 3: Generate (depends on Step 2)
|
||||||
const generateId = await runCLI('generate', context, `--resume ${analyzeId}`);
|
const generateId = await runCLI('generate', context, `--resume ${analyzeId}`);
|
||||||
|
|
||||||
return generateId;
|
return generateId;
|
||||||
@@ -218,9 +218,9 @@ async function executeChain(context) {
|
|||||||
|
|
||||||
async function runCLI(step, context, resumeFlag = '') {
|
async function runCLI(step, context, resumeFlag = '') {
|
||||||
const prompts = {
|
const prompts = {
|
||||||
collect: 'PURPOSE: 收集代码文件...',
|
collect: 'PURPOSE: Collect code files...',
|
||||||
analyze: 'PURPOSE: 分析代码模式...',
|
analyze: 'PURPOSE: Analyze code patterns...',
|
||||||
generate: 'PURPOSE: 生成文档...'
|
generate: 'PURPOSE: Generate documentation...'
|
||||||
};
|
};
|
||||||
|
|
||||||
const result = Bash({
|
const result = Bash({
|
||||||
@@ -232,9 +232,9 @@ async function runCLI(step, context, resumeFlag = '') {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
### 模式 3: 并行调用
|
### Pattern 3: Parallel Calls
|
||||||
|
|
||||||
独立任务并行执行。
|
Independent tasks executed in parallel.
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
async function executeParallel(context) {
|
async function executeParallel(context) {
|
||||||
@@ -244,15 +244,15 @@ async function executeParallel(context) {
|
|||||||
{ type: 'patterns', tool: 'qwen' }
|
{ type: 'patterns', tool: 'qwen' }
|
||||||
];
|
];
|
||||||
|
|
||||||
// 并行启动
|
// Start tasks in parallel
|
||||||
const taskIds = tasks.map(task =>
|
const taskIds = tasks.map(task =>
|
||||||
Bash({
|
Bash({
|
||||||
command: `ccw cli -p "分析 ${task.type}..." --tool ${task.tool} --mode analysis`,
|
command: `ccw cli -p "Analyze ${task.type}..." --tool ${task.tool} --mode analysis`,
|
||||||
run_in_background: true
|
run_in_background: true
|
||||||
}).task_id
|
}).task_id
|
||||||
);
|
);
|
||||||
|
|
||||||
// 等待全部完成
|
// Wait for all to complete
|
||||||
const results = await Promise.all(
|
const results = await Promise.all(
|
||||||
taskIds.map(id => waitForCompletion(id))
|
taskIds.map(id => waitForCompletion(id))
|
||||||
);
|
);
|
||||||
@@ -261,9 +261,9 @@ async function executeParallel(context) {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
### 模式 4: Fallback 链
|
### Pattern 4: Fallback Chain
|
||||||
|
|
||||||
工具失败时自动切换。
|
Automatically switch tools on failure.
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
async function executeWithFallback(context) {
|
async function executeWithFallback(context) {
|
||||||
@@ -299,9 +299,9 @@ async function runWithTool(tool, context) {
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 提示词模板集成
|
## Prompt Template Integration
|
||||||
|
|
||||||
### 引用协议模板
|
### Reference Protocol Templates
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Analysis mode - use --rule to auto-load protocol and template (appended to prompt)
|
# Analysis mode - use --rule to auto-load protocol and template (appended to prompt)
|
||||||
@@ -315,7 +315,7 @@ CONSTRAINTS: ...
|
|||||||
..." --tool codex --mode write --rule development-feature
|
..." --tool codex --mode write --rule development-feature
|
||||||
```
|
```
|
||||||
|
|
||||||
### 动态模板构建
|
### Dynamic Template Building
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
function buildPrompt(config) {
|
function buildPrompt(config) {
|
||||||
@@ -334,21 +334,21 @@ CONSTRAINTS: ${constraints || ''}
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 超时配置
|
## Timeout Configuration
|
||||||
|
|
||||||
### 推荐超时值
|
### Recommended Timeout Values
|
||||||
|
|
||||||
| 任务类型 | 超时 (ms) | 说明 |
|
| Task Type | Timeout (ms) | Description |
|
||||||
|---------|----------|------|
|
|-----------|--------------|-------------|
|
||||||
| 快速分析 | 300000 | 5 分钟 |
|
| Quick analysis | 300000 | 5 minutes |
|
||||||
| 标准分析 | 600000 | 10 分钟 |
|
| Standard analysis | 600000 | 10 minutes |
|
||||||
| 深度分析 | 1200000 | 20 分钟 |
|
| Deep analysis | 1200000 | 20 minutes |
|
||||||
| 代码生成 | 1800000 | 30 分钟 |
|
| Code generation | 1800000 | 30 minutes |
|
||||||
| 复杂任务 | 3600000 | 60 分钟 |
|
| Complex tasks | 3600000 | 60 minutes |
|
||||||
|
|
||||||
### Codex 特殊处理
|
### Special Codex Handling
|
||||||
|
|
||||||
Codex 需要更长的超时时间(建议 3x)。
|
Codex requires longer timeout (recommend 3x).
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
const timeout = tool === 'codex' ? baseTimeout * 3 : baseTimeout;
|
const timeout = tool === 'codex' ? baseTimeout * 3 : baseTimeout;
|
||||||
@@ -362,17 +362,17 @@ Bash({
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 错误处理
|
## Error Handling
|
||||||
|
|
||||||
### 常见错误
|
### Common Errors
|
||||||
|
|
||||||
| 错误 | 原因 | 处理 |
|
| Error | Cause | Handler |
|
||||||
|------|------|------|
|
|-------|-------|---------|
|
||||||
| ETIMEDOUT | 网络超时 | 重试或切换工具 |
|
| ETIMEDOUT | Network timeout | Retry or switch tool |
|
||||||
| Exit code 1 | 命令执行失败 | 检查参数,切换工具 |
|
| Exit code 1 | Command execution failed | Check parameters, switch tool |
|
||||||
| Context overflow | 上下文过大 | 减少输入范围 |
|
| Context overflow | Input context too large | Reduce input scope |
|
||||||
|
|
||||||
### 重试策略
|
### Retry Strategy
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
async function executeWithRetry(command, maxRetries = 3) {
|
async function executeWithRetry(command, maxRetries = 3) {
|
||||||
@@ -391,7 +391,7 @@ async function executeWithRetry(command, maxRetries = 3) {
|
|||||||
lastError = error;
|
lastError = error;
|
||||||
console.log(`Attempt ${attempt} failed: ${error.message}`);
|
console.log(`Attempt ${attempt} failed: ${error.message}`);
|
||||||
|
|
||||||
// 指数退避
|
// Exponential backoff
|
||||||
if (attempt < maxRetries) {
|
if (attempt < maxRetries) {
|
||||||
await sleep(Math.pow(2, attempt) * 1000);
|
await sleep(Math.pow(2, attempt) * 1000);
|
||||||
}
|
}
|
||||||
@@ -404,30 +404,30 @@ async function executeWithRetry(command, maxRetries = 3) {
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 最佳实践
|
## Best Practices
|
||||||
|
|
||||||
### 1. run_in_background 规则
|
### 1. run_in_background Rule
|
||||||
|
|
||||||
```
|
```
|
||||||
Agent 调用 (Task):
|
Agent calls (Task):
|
||||||
run_in_background: false → 同步,立即获取结果
|
run_in_background: false → Synchronous, get result immediately
|
||||||
|
|
||||||
CLI 调用 (Bash + ccw cli):
|
CLI calls (Bash + ccw cli):
|
||||||
run_in_background: true → 异步,后台执行
|
run_in_background: true → Asynchronous, run in background
|
||||||
```
|
```
|
||||||
|
|
||||||
### 2. 工具选择
|
### 2. Tool Selection
|
||||||
|
|
||||||
```
|
```
|
||||||
分析任务: gemini > qwen
|
Analysis tasks: gemini > qwen
|
||||||
生成任务: codex > gemini > qwen
|
Generation tasks: codex > gemini > qwen
|
||||||
代码修改: codex > gemini
|
Code modification: codex > gemini
|
||||||
```
|
```
|
||||||
|
|
||||||
### 3. 会话管理
|
### 3. Session Management
|
||||||
|
|
||||||
- 相关任务使用 `--resume` 保持上下文
|
- Use `--resume` for related tasks to maintain context
|
||||||
- 独立任务不使用 `--resume`
|
- Do not use `--resume` for independent tasks
|
||||||
|
|
||||||
### 4. Prompt Specification
|
### 4. Prompt Specification
|
||||||
|
|
||||||
@@ -435,8 +435,8 @@ CLI 调用 (Bash + ccw cli):
|
|||||||
- Use `--rule <template>` to auto-append protocol + template to prompt
|
- Use `--rule <template>` to auto-append protocol + template to prompt
|
||||||
- Template name format: `category-function` (e.g., `analysis-code-patterns`)
|
- Template name format: `category-function` (e.g., `analysis-code-patterns`)
|
||||||
|
|
||||||
### 5. 结果处理
|
### 5. Result Processing
|
||||||
|
|
||||||
- 持久化重要结果到 workDir
|
- Persist important results to workDir
|
||||||
- Brief returns: 路径 + 摘要,避免上下文溢出
|
- Brief returns: path + summary, avoid context overflow
|
||||||
- JSON 格式便于后续处理
|
- JSON format convenient for downstream processing
|
||||||
|
|||||||
@@ -1,40 +1,40 @@
|
|||||||
# Execution Modes Specification
|
# Execution Modes Specification
|
||||||
|
|
||||||
两种 Skill 执行模式的详细规范定义。
|
Detailed specification definitions for two Skill execution modes.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 模式概览
|
## Mode Overview
|
||||||
|
|
||||||
| 特性 | Sequential (顺序) | Autonomous (自主) |
|
| Feature | Sequential (Fixed Order) | Autonomous (Dynamic) |
|
||||||
|------|-------------------|-------------------|
|
|---------|--------------------------|----------------------|
|
||||||
| 执行顺序 | 固定(数字前缀) | 动态(编排器决策) |
|
| Execution Order | Fixed (numeric prefix) | Dynamic (orchestrator decision) |
|
||||||
| 阶段依赖 | 强依赖 | 弱依赖/无依赖 |
|
| Phase Dependencies | Strong dependencies | Weak/no dependencies |
|
||||||
| 状态管理 | 隐式(阶段产出) | 显式(状态文件) |
|
| State Management | Implicit (phase output) | Explicit (state file) |
|
||||||
| 适用场景 | 流水线任务 | 交互式任务 |
|
| Use Cases | Pipeline tasks | Interactive tasks |
|
||||||
| 复杂度 | 低 | 中-高 |
|
| Complexity | Low | Medium-High |
|
||||||
| 可扩展性 | 插入子阶段 | 添加新动作 |
|
| Extensibility | Insert sub-phases | Add new actions |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Mode 1: Sequential (顺序模式)
|
## Mode 1: Sequential (Fixed Order Mode)
|
||||||
|
|
||||||
### 定义
|
### Definition
|
||||||
|
|
||||||
阶段按固定顺序线性执行,每个阶段的输出作为下一阶段的输入。
|
Phases execute linearly in fixed order, with each phase's output serving as input to the next phase.
|
||||||
|
|
||||||
### 目录结构
|
### Directory Structure
|
||||||
|
|
||||||
```
|
```
|
||||||
phases/
|
phases/
|
||||||
├── 01-{first-step}.md
|
├── 01-{first-step}.md
|
||||||
├── 02-{second-step}.md
|
├── 02-{second-step}.md
|
||||||
├── 02.5-{sub-step}.md # 可选:子阶段
|
├── 02.5-{sub-step}.md # Optional: sub-phase
|
||||||
├── 03-{third-step}.md
|
├── 03-{third-step}.md
|
||||||
└── ...
|
└── ...
|
||||||
```
|
```
|
||||||
|
|
||||||
### 执行流程
|
### Execution Flow
|
||||||
|
|
||||||
```
|
```
|
||||||
┌─────────┐ ┌─────────┐ ┌─────────┐
|
┌─────────┐ ┌─────────┐ ┌─────────┐
|
||||||
@@ -45,33 +45,33 @@ phases/
|
|||||||
output1.json output2.md output3.md
|
output1.json output2.md output3.md
|
||||||
```
|
```
|
||||||
|
|
||||||
### Phase 文件规范
|
### Phase File Specification
|
||||||
|
|
||||||
```markdown
|
```markdown
|
||||||
# Phase N: {阶段名称}
|
# Phase N: {Phase Name}
|
||||||
|
|
||||||
{一句话描述}
|
{One-sentence description}
|
||||||
|
|
||||||
## Objective
|
## Objective
|
||||||
|
|
||||||
{详细目标}
|
{Detailed objective}
|
||||||
|
|
||||||
## Input
|
## Input
|
||||||
|
|
||||||
- 依赖: {上一阶段产出}
|
- Dependencies: {Previous phase output}
|
||||||
- 配置: {配置文件}
|
- Configuration: {Configuration file}
|
||||||
|
|
||||||
## Execution Steps
|
## Execution Steps
|
||||||
|
|
||||||
### Step 1: {步骤}
|
### Step 1: {Step}
|
||||||
{执行代码或说明}
|
{Execution code or description}
|
||||||
|
|
||||||
### Step 2: {步骤}
|
### Step 2: {Step}
|
||||||
{执行代码或说明}
|
{Execution code or description}
|
||||||
|
|
||||||
## Output
|
## Output
|
||||||
|
|
||||||
- **File**: `{输出文件}`
|
- **File**: `{Output file}`
|
||||||
- **Format**: {JSON/Markdown}
|
- **Format**: {JSON/Markdown}
|
||||||
|
|
||||||
## Next Phase
|
## Next Phase
|
||||||
@@ -79,74 +79,74 @@ phases/
|
|||||||
→ [Phase N+1: xxx](0N+1-xxx.md)
|
→ [Phase N+1: xxx](0N+1-xxx.md)
|
||||||
```
|
```
|
||||||
|
|
||||||
### 适用场景
|
### Applicable Scenarios
|
||||||
|
|
||||||
- **文档生成**: 收集 → 分析 → 组装 → 优化
|
- **Document Generation**: Collect → Analyze → Assemble → Optimize
|
||||||
- **代码分析**: 扫描 → 解析 → 报告
|
- **Code Analysis**: Scan → Parse → Report
|
||||||
- **数据处理**: 提取 → 转换 → 加载
|
- **Data Processing**: Extract → Transform → Load
|
||||||
|
|
||||||
### 优点
|
### Advantages
|
||||||
|
|
||||||
- 逻辑清晰,易于理解
|
- Clear logic, easy to understand
|
||||||
- 调试简单,可逐阶段验证
|
- Simple debugging, can validate phase by phase
|
||||||
- 输出可预测
|
- Predictable output
|
||||||
|
|
||||||
### 缺点
|
### Disadvantages
|
||||||
|
|
||||||
- 灵活性低
|
- Low flexibility
|
||||||
- 难以处理分支逻辑
|
- Difficult to handle branching logic
|
||||||
- 用户交互受限
|
- Limited user interaction
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Mode 2: Autonomous (自主模式)
|
## Mode 2: Autonomous (Dynamic Mode)
|
||||||
|
|
||||||
### 定义
|
### Definition
|
||||||
|
|
||||||
无固定执行顺序,由编排器 (Orchestrator) 根据当前状态动态选择下一个动作。
|
No fixed execution order. The orchestrator dynamically selects the next action based on current state.
|
||||||
|
|
||||||
### 目录结构
|
### Directory Structure
|
||||||
|
|
||||||
```
|
```
|
||||||
phases/
|
phases/
|
||||||
├── orchestrator.md # 编排器:核心决策逻辑
|
├── orchestrator.md # Orchestrator: core decision logic
|
||||||
├── state-schema.md # 状态结构定义
|
├── state-schema.md # State structure definition
|
||||||
└── actions/ # 独立动作(无顺序)
|
└── actions/ # Independent actions (no order)
|
||||||
├── action-{a}.md
|
├── action-{a}.md
|
||||||
├── action-{b}.md
|
├── action-{b}.md
|
||||||
├── action-{c}.md
|
├── action-{c}.md
|
||||||
└── ...
|
└── ...
|
||||||
```
|
```
|
||||||
|
|
||||||
### 核心组件
|
### Core Components
|
||||||
|
|
||||||
#### 1. Orchestrator (编排器)
|
#### 1. Orchestrator
|
||||||
|
|
||||||
```markdown
|
```markdown
|
||||||
# Orchestrator
|
# Orchestrator
|
||||||
|
|
||||||
## Role
|
## Role
|
||||||
|
|
||||||
根据当前状态选择并执行下一个动作。
|
Select and execute the next action based on current state.
|
||||||
|
|
||||||
## State Reading
|
## State Reading
|
||||||
|
|
||||||
读取状态文件: `{workDir}/state.json`
|
Read state file: `{workDir}/state.json`
|
||||||
|
|
||||||
## Decision Logic
|
## Decision Logic
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
function selectNextAction(state) {
|
function selectNextAction(state) {
|
||||||
// 1. 检查终止条件
|
// 1. Check termination conditions
|
||||||
if (state.status === 'completed') return null;
|
if (state.status === 'completed') return null;
|
||||||
if (state.error_count > MAX_RETRIES) return 'action-abort';
|
if (state.error_count > MAX_RETRIES) return 'action-abort';
|
||||||
|
|
||||||
// 2. 根据状态选择动作
|
// 2. Select action based on state
|
||||||
if (!state.initialized) return 'action-init';
|
if (!state.initialized) return 'action-init';
|
||||||
if (state.pending_items.length > 0) return 'action-process';
|
if (state.pending_items.length > 0) return 'action-process';
|
||||||
if (state.needs_review) return 'action-review';
|
if (state.needs_review) return 'action-review';
|
||||||
|
|
||||||
// 3. 默认动作
|
// 3. Default action
|
||||||
return 'action-complete';
|
return 'action-complete';
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
@@ -165,35 +165,35 @@ while (true) {
|
|||||||
```
|
```
|
||||||
```
|
```
|
||||||
|
|
||||||
#### 2. State Schema (状态结构)
|
#### 2. State Schema
|
||||||
|
|
||||||
```markdown
|
```markdown
|
||||||
# State Schema
|
# State Schema
|
||||||
|
|
||||||
## 状态文件
|
## State File
|
||||||
|
|
||||||
位置: `{workDir}/state.json`
|
Location: `{workDir}/state.json`
|
||||||
|
|
||||||
## 结构定义
|
## Structure Definition
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
interface SkillState {
|
interface SkillState {
|
||||||
// 元信息
|
// Metadata
|
||||||
skill_name: string;
|
skill_name: string;
|
||||||
started_at: string;
|
started_at: string;
|
||||||
updated_at: string;
|
updated_at: string;
|
||||||
|
|
||||||
// 执行状态
|
// Execution state
|
||||||
status: 'pending' | 'running' | 'completed' | 'failed';
|
status: 'pending' | 'running' | 'completed' | 'failed';
|
||||||
current_action: string | null;
|
current_action: string | null;
|
||||||
completed_actions: string[];
|
completed_actions: string[];
|
||||||
|
|
||||||
// 业务数据
|
// Business data
|
||||||
context: Record<string, any>;
|
context: Record<string, any>;
|
||||||
pending_items: any[];
|
pending_items: any[];
|
||||||
results: Record<string, any>;
|
results: Record<string, any>;
|
||||||
|
|
||||||
// 错误追踪
|
// Error tracking
|
||||||
errors: Array<{
|
errors: Array<{
|
||||||
action: string;
|
action: string;
|
||||||
message: string;
|
message: string;
|
||||||
@@ -203,7 +203,7 @@ interface SkillState {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
## 初始状态
|
## Initial State
|
||||||
|
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
@@ -222,23 +222,23 @@ interface SkillState {
|
|||||||
```
|
```
|
||||||
```
|
```
|
||||||
|
|
||||||
#### 3. Action (动作)
|
#### 3. Action
|
||||||
|
|
||||||
```markdown
|
```markdown
|
||||||
# Action: {action-name}
|
# Action: {action-name}
|
||||||
|
|
||||||
## Purpose
|
## Purpose
|
||||||
|
|
||||||
{动作目的}
|
{Action purpose}
|
||||||
|
|
||||||
## Preconditions
|
## Preconditions
|
||||||
|
|
||||||
- [ ] 条件1
|
- [ ] Condition 1
|
||||||
- [ ] 条件2
|
- [ ] Condition 2
|
||||||
|
|
||||||
## Execution
|
## Execution
|
||||||
|
|
||||||
{执行逻辑}
|
{Execution logic}
|
||||||
|
|
||||||
## State Updates
|
## State Updates
|
||||||
|
|
||||||
@@ -247,19 +247,19 @@ return {
|
|||||||
completed_actions: [...state.completed_actions, 'action-name'],
|
completed_actions: [...state.completed_actions, 'action-name'],
|
||||||
results: {
|
results: {
|
||||||
...state.results,
|
...state.results,
|
||||||
action_name: { /* 结果 */ }
|
action_name: { /* result */ }
|
||||||
},
|
},
|
||||||
// 其他状态更新
|
// Other state updates
|
||||||
};
|
};
|
||||||
```
|
```
|
||||||
|
|
||||||
## Next Actions (Hints)
|
## Next Actions (Hints)
|
||||||
|
|
||||||
- 成功时: `action-{next}`
|
- On success: `action-{next}`
|
||||||
- 失败时: `action-retry` 或 `action-abort`
|
- On failure: `action-retry` or `action-abort`
|
||||||
```
|
```
|
||||||
|
|
||||||
### 执行流程
|
### Execution Flow
|
||||||
|
|
||||||
```
|
```
|
||||||
┌─────────────────────────────────────────────────────────────────┐
|
┌─────────────────────────────────────────────────────────────────┐
|
||||||
@@ -289,9 +289,9 @@ return {
|
|||||||
└─────────────────────────────────────────────────────────────────┘
|
└─────────────────────────────────────────────────────────────────┘
|
||||||
```
|
```
|
||||||
|
|
||||||
### 动作目录 (Action Catalog)
|
### Action Catalog
|
||||||
|
|
||||||
在 `specs/action-catalog.md` 中定义:
|
Defined in `specs/action-catalog.md`:
|
||||||
|
|
||||||
```markdown
|
```markdown
|
||||||
# Action Catalog
|
# Action Catalog
|
||||||
@@ -300,11 +300,11 @@ return {
|
|||||||
|
|
||||||
| Action | Purpose | Preconditions | Effects |
|
| Action | Purpose | Preconditions | Effects |
|
||||||
|--------|---------|---------------|---------|
|
|--------|---------|---------------|---------|
|
||||||
| action-init | 初始化状态 | status=pending | status=running |
|
| action-init | Initialize state | status=pending | status=running |
|
||||||
| action-process | 处理待办项 | pending_items.length>0 | pending_items-- |
|
| action-process | Process pending items | pending_items.length>0 | pending_items-- |
|
||||||
| action-review | 用户审核 | needs_review=true | needs_review=false |
|
| action-review | User review | needs_review=true | needs_review=false |
|
||||||
| action-complete | 完成任务 | pending_items.length=0 | status=completed |
|
| action-complete | Complete task | pending_items.length=0 | status=completed |
|
||||||
| action-abort | 中止任务 | error_count>MAX | status=failed |
|
| action-abort | Abort task | error_count>MAX | status=failed |
|
||||||
|
|
||||||
## Action Dependencies Graph
|
## Action Dependencies Graph
|
||||||
|
|
||||||
@@ -319,78 +319,81 @@ graph TD
|
|||||||
```
|
```
|
||||||
```
|
```
|
||||||
|
|
||||||
### 适用场景
|
### Applicable Scenarios
|
||||||
|
|
||||||
- **交互式任务**: 问答、对话、表单填写
|
- **Interactive Tasks**: Q&A, dialog, form filling
|
||||||
- **状态机任务**: Issue 管理、工作流审批
|
- **State Machine Tasks**: Issue management, workflow approval
|
||||||
- **探索式任务**: 调试、诊断、搜索
|
- **Exploratory Tasks**: Debugging, diagnosis, search
|
||||||
|
|
||||||
### 优点
|
### Advantages
|
||||||
|
|
||||||
- 高度灵活,适应动态需求
|
- Highly flexible, adapts to dynamic requirements
|
||||||
- 支持复杂分支逻辑
|
- Supports complex branching logic
|
||||||
- 易于扩展新动作
|
- Easy to extend with new actions
|
||||||
|
|
||||||
### 缺点
|
### Disadvantages
|
||||||
|
|
||||||
- 复杂度高
|
- High complexity
|
||||||
- 状态管理开销
|
- State management overhead
|
||||||
- 调试难度大
|
- Large debugging difficulty
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 模式选择指南
|
## Mode Selection Guide
|
||||||
|
|
||||||
### 决策流程
|
### Decision Flow
|
||||||
|
|
||||||
```
|
```
|
||||||
用户需求分析
|
Analyze user requirements
|
||||||
│
|
│
|
||||||
▼
|
▼
|
||||||
┌────────────────────────────┐
|
┌────────────────────────────┐
|
||||||
│ 阶段间是否有强依赖关系? │
|
│ Are there strong │
|
||||||
|
│ dependencies between │
|
||||||
|
│ phases? │
|
||||||
└────────────────────────────┘
|
└────────────────────────────┘
|
||||||
│
|
│
|
||||||
├── 是 → Sequential
|
├── Yes → Sequential
|
||||||
│
|
│
|
||||||
└── 否 → 继续判断
|
└── No → Continue decision
|
||||||
│
|
│
|
||||||
▼
|
▼
|
||||||
┌────────────────────────────┐
|
┌────────────────────────────┐
|
||||||
│ 是否需要动态响应用户意图? │
|
│ Do you need dynamic │
|
||||||
|
│ response to user intent? │
|
||||||
└────────────────────────────┘
|
└────────────────────────────┘
|
||||||
│
|
│
|
||||||
├── 是 → Autonomous
|
├── Yes → Autonomous
|
||||||
│
|
│
|
||||||
└── 否 → Sequential
|
└── No → Sequential
|
||||||
```
|
```
|
||||||
|
|
||||||
### 快速判断表
|
### Quick Decision Table
|
||||||
|
|
||||||
| 问题 | Sequential | Autonomous |
|
| Question | Sequential | Autonomous |
|
||||||
|------|------------|------------|
|
|----------|------------|------------|
|
||||||
| 输出结构是否固定? | ✓ | ✗ |
|
| Is output structure fixed? | Yes | No |
|
||||||
| 是否需要用户多轮交互? | ✗ | ✓ |
|
| Do you need multi-turn user interaction? | No | Yes |
|
||||||
| 阶段是否可以跳过/重复? | ✗ | ✓ |
|
| Can phases be skipped/repeated? | No | Yes |
|
||||||
| 是否有复杂分支逻辑? | ✗ | ✓ |
|
| Is there complex branching logic? | No | Yes |
|
||||||
| 调试是否需要简单? | ✓ | ✗ |
|
| Should debugging be simple? | Yes | No |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 混合模式
|
## Hybrid Mode
|
||||||
|
|
||||||
某些复杂 Skill 可能需要混合使用两种模式:
|
Some complex Skills may need to use both modes in combination:
|
||||||
|
|
||||||
```
|
```
|
||||||
phases/
|
phases/
|
||||||
├── 01-init.md # Sequential: 初始化
|
├── 01-init.md # Sequential: initialization
|
||||||
├── 02-orchestrator.md # Autonomous: 核心交互循环
|
├── 02-orchestrator.md # Autonomous: core interaction loop
|
||||||
│ └── actions/
|
│ └── actions/
|
||||||
│ ├── action-a.md
|
│ ├── action-a.md
|
||||||
│ └── action-b.md
|
│ └── action-b.md
|
||||||
└── 03-finalize.md # Sequential: 收尾
|
└── 03-finalize.md # Sequential: finalization
|
||||||
```
|
```
|
||||||
|
|
||||||
**适用场景**:
|
**Applicable Scenarios**:
|
||||||
- 初始化和收尾固定,中间交互灵活
|
- Initialization and finalization are fixed, middle interaction is flexible
|
||||||
- 多阶段任务,某阶段需要动态决策
|
- Multi-phase tasks where certain phases need dynamic decisions
|
||||||
|
|||||||
@@ -1,14 +1,14 @@
|
|||||||
# Reference Documents Generation Specification
|
# Reference Documents Generation Specification
|
||||||
|
|
||||||
> **重要**: 本规范定义如何在生成的skill中组织和展现参考文档,避免重复问题。
|
> **IMPORTANT**: This specification defines how to organize and present reference documents in generated skills to avoid duplication issues.
|
||||||
|
|
||||||
## 核心原则
|
## Core Principles
|
||||||
|
|
||||||
### 1. 分阶段组织 (Phase-Based Organization)
|
### 1. Phase-Based Organization
|
||||||
|
|
||||||
参考文档必须按照skill的执行阶段组织,而不是平铺列表。
|
Reference documents must be organized by skill execution phases, not as a flat list.
|
||||||
|
|
||||||
**❌ 错误方式** (平铺列表):
|
**Wrong Approach** (Flat List):
|
||||||
```markdown
|
```markdown
|
||||||
## Reference Documents
|
## Reference Documents
|
||||||
|
|
||||||
@@ -19,203 +19,203 @@
|
|||||||
| doc3.md | ... |
|
| doc3.md | ... |
|
||||||
```
|
```
|
||||||
|
|
||||||
**✅ 正确方式** (分阶段导航):
|
**Correct Approach** (Phase-Based Navigation):
|
||||||
```markdown
|
```markdown
|
||||||
## Reference Documents by Phase
|
## Reference Documents by Phase
|
||||||
|
|
||||||
### 📋 Phase 1: Analysis
|
### Phase 1: Analysis
|
||||||
执行Phase 1时查阅的文档
|
Documents to refer to when executing Phase 1
|
||||||
|
|
||||||
| Document | Purpose | When to Use |
|
| Document | Purpose | When to Use |
|
||||||
|----------|---------|-------------|
|
|----------|---------|-------------|
|
||||||
| doc1.md | ... | 理解x概念 |
|
| doc1.md | ... | Understand concept x |
|
||||||
|
|
||||||
### ⚙️ Phase 2: Implementation
|
### Phase 2: Implementation
|
||||||
执行Phase 2时查阅的文档
|
Documents to refer to when executing Phase 2
|
||||||
|
|
||||||
| Document | Purpose | When to Use |
|
| Document | Purpose | When to Use |
|
||||||
|----------|---------|-------------|
|
|----------|---------|-------------|
|
||||||
| doc2.md | ... | 实现y功能 |
|
| doc2.md | ... | Implement feature y |
|
||||||
```
|
```
|
||||||
|
|
||||||
### 2. 四个标准分组
|
### 2. Four Standard Groupings
|
||||||
|
|
||||||
参考文档必须分为以下四个分组:
|
Reference documents must be divided into the following four groupings:
|
||||||
|
|
||||||
| 分组 | 使用时机 | 内容 |
|
| Grouping | When to Use | Content |
|
||||||
|-----|---------|------|
|
|----------|------------|---------|
|
||||||
| **Phase N: [Name]** | 执行该Phase时 | 该阶段相关的所有文档 |
|
| **Phase N: [Name]** | When executing this phase | All documents related to this phase |
|
||||||
| **🔍 Debugging** | 遇到问题时 | 问题→文档映射表 |
|
| **Debugging** | When encountering problems | Issue to documentation mapping table |
|
||||||
| **📚 Reference** | 深度学习时 | 模板、原始实现、最佳实践 |
|
| **Reference** | When learning in depth | Templates, original implementations, best practices |
|
||||||
| (可选) **📌 Quick Links** | 快速导航 | 最常查阅的5-7个文档 |
|
| (Optional) **Quick Links** | Quick navigation | Most frequently consulted 5-7 documents |
|
||||||
|
|
||||||
### 3. 每个文档条目必须包含
|
### 3. Each Document Entry Must Include
|
||||||
|
|
||||||
```
|
```
|
||||||
| [path](path) | Purpose | When to Use |
|
| [path](path) | Purpose | When to Use |
|
||||||
```
|
```
|
||||||
|
|
||||||
**When to Use 列要求**:
|
**When to Use Column Requirements**:
|
||||||
- ✅ 清晰说明使用场景
|
- Clear explanation of usage scenarios
|
||||||
- ✅ 描述解决什么问题
|
- Describe what problem is solved
|
||||||
- ❌ 不要简单说 "参考" 或 "了解"
|
- Do not simply say "refer to" or "learn about"
|
||||||
|
|
||||||
**良好例子**:
|
**Good Examples**:
|
||||||
- "理解issue数据结构"
|
- "Understand issue data structure"
|
||||||
- "学习Planning Agent的角色"
|
- "Learn about the Planning Agent role"
|
||||||
- "检查implementation是否达到质量标准"
|
- "Check if implementation meets quality standards"
|
||||||
- "快速定位状态异常的原因"
|
- "Quickly locate the reason for status anomalies"
|
||||||
|
|
||||||
**糟糕例子**:
|
**Poor Examples**:
|
||||||
- "参考文档"
|
- "Reference document"
|
||||||
- "更多信息"
|
- "More information"
|
||||||
- "背景知识"
|
- "Background knowledge"
|
||||||
|
|
||||||
### 4. 执行流程中嵌入文档指引
|
### 4. Embedding Document Guidance in Execution Flow
|
||||||
|
|
||||||
在"Execution Flow"部分,每个Phase说明中应包含"查阅"提示:
|
In the "Execution Flow" section, each Phase description should include "Refer to" hints:
|
||||||
|
|
||||||
```markdown
|
```markdown
|
||||||
### Phase 2: Planning Pipeline
|
### Phase 2: Planning Pipeline
|
||||||
→ **查阅**: action-plan.md, subagent-roles.md
|
→ **Refer to**: action-plan.md, subagent-roles.md
|
||||||
→ 具体流程说明...
|
→ Detailed flow description...
|
||||||
```
|
```
|
||||||
|
|
||||||
### 5. 问题排查快速查询表
|
### 5. Quick Troubleshooting Reference Table
|
||||||
|
|
||||||
应包含常见问题到文档的映射:
|
Should contain common issue to documentation mapping:
|
||||||
|
|
||||||
```markdown
|
```markdown
|
||||||
### 🔍 Debugging & Troubleshooting
|
### Debugging & Troubleshooting
|
||||||
|
|
||||||
| Issue | Solution Document |
|
| Issue | Solution Document |
|
||||||
|-------|------------------|
|
|-------|------------------|
|
||||||
| Phase执行失败 | 查阅相应Phase文档 |
|
| Phase execution failed | Refer to corresponding phase documentation |
|
||||||
| 输出格式不符 | specs/quality-standards.md |
|
| Output format incorrect | specs/quality-standards.md |
|
||||||
| 数据验证失败 | specs/schema-validation.md |
|
| Data validation failed | specs/schema-validation.md |
|
||||||
```
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 生成规则
|
## Generation Rules
|
||||||
|
|
||||||
### 规则 1: 文档分类识别
|
### Rule 1: Document Classification Recognition
|
||||||
|
|
||||||
根据skill的phases自动生成分组:
|
Automatically generate groupings based on skill phases:
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
const phaseEmojis = {
|
const phaseEmojis = {
|
||||||
'discovery': '📋', // 收集、探索
|
'discovery': '📋', // Collection, exploration
|
||||||
'generation': '🔧', // 生成、创建
|
'generation': '🔧', // Generation, creation
|
||||||
'analysis': '🔍', // 分析、审查
|
'analysis': '🔍', // Analysis, review
|
||||||
'implementation': '⚙️', // 实现、执行
|
'implementation': '⚙️', // Implementation, execution
|
||||||
'validation': '✅', // 验证、测试
|
'validation': '✅', // Validation, testing
|
||||||
'completion': '🏁', // 完成、收尾
|
'completion': '🏁', // Completion, wrap-up
|
||||||
};
|
};
|
||||||
|
|
||||||
// 为每个phase生成一个章节
|
// Generate a section for each phase
|
||||||
phases.forEach((phase, index) => {
|
phases.forEach((phase, index) => {
|
||||||
const emoji = phaseEmojis[phase.type] || '📌';
|
const emoji = phaseEmojis[phase.type] || '📌';
|
||||||
const title = `### ${emoji} Phase ${index + 1}: ${phase.name}`;
|
const title = `### ${emoji} Phase ${index + 1}: ${phase.name}`;
|
||||||
// 列出该phase相关的所有文档
|
// List all documents related to this phase
|
||||||
});
|
});
|
||||||
```
|
```
|
||||||
|
|
||||||
### 规则 2: 文档到Phase的映射
|
### Rule 2: Document to Phase Mapping
|
||||||
|
|
||||||
在config中,specs和templates应标注所属的phases:
|
In config, specs and templates should be annotated with their belonging phases:
|
||||||
|
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
"specs": [
|
"specs": [
|
||||||
{
|
{
|
||||||
"path": "specs/issue-handling.md",
|
"path": "specs/issue-handling.md",
|
||||||
"purpose": "Issue数据规范",
|
"purpose": "Issue data specification",
|
||||||
"phases": ["phase-2", "phase-3"], // 这个spec与哪些phase相关
|
"phases": ["phase-2", "phase-3"], // Which phases this spec is related to
|
||||||
"context": "理解issue结构和验证规则"
|
"context": "Understand issue structure and validation rules"
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
### 规则 3: 优先级和必读性
|
### Rule 3: Priority and Mandatory Reading
|
||||||
|
|
||||||
用视觉符号区分文档的重要性:
|
Use visual symbols to distinguish document importance:
|
||||||
|
|
||||||
```markdown
|
```markdown
|
||||||
| Document | When | Notes |
|
| Document | When | Notes |
|
||||||
|----------|------|-------|
|
|----------|------|-------|
|
||||||
| spec.md | **执行前必读** | ✅ 强制前置 |
|
| spec.md | **Must Read Before Execution** | Mandatory prerequisite |
|
||||||
| action.md | 执行时查阅 | 操作指南 |
|
| action.md | Refer to during execution | Operation guide |
|
||||||
| template.md | 参考学习 | 可选深入 |
|
| template.md | Reference for learning | Optional in-depth |
|
||||||
```
|
```
|
||||||
|
|
||||||
### 规则 4: 避免重复
|
### Rule 4: Avoid Duplication
|
||||||
|
|
||||||
- **Mandatory Prerequisites** 部分:列出强制必读的P0规范
|
- **Mandatory Prerequisites** section: List mandatory P0 specifications
|
||||||
- **Reference Documents by Phase** 部分:列出所有文档 (包括强制必读的)
|
- **Reference Documents by Phase** section: List all documents (including mandatory prerequisites)
|
||||||
- 两个部分的文档可以重叠,但目的不同:
|
- Documents in both sections can overlap, but their purposes differ:
|
||||||
- Prerequisites:强调"必须先读"
|
- Prerequisites: Emphasize "must read first"
|
||||||
- Reference:提供"完整导航"
|
- Reference: Provide "complete navigation"
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 实现示例
|
## Implementation Example
|
||||||
|
|
||||||
### Sequential Skill 示例
|
### Sequential Skill Example
|
||||||
|
|
||||||
```markdown
|
```markdown
|
||||||
## ⚠️ Mandatory Prerequisites (强制前置条件)
|
## Mandatory Prerequisites
|
||||||
|
|
||||||
| Document | Purpose | When |
|
| Document | Purpose | When |
|
||||||
|----------|---------|------|
|
|----------|---------|------|
|
||||||
| [specs/issue-handling.md](specs/issue-handling.md) | Issue数据规范 | **执行前必读** |
|
| [specs/issue-handling.md](specs/issue-handling.md) | Issue data specification | **Must Read Before Execution** |
|
||||||
| [specs/solution-schema.md](specs/solution-schema.md) | 解决方案结构 | **执行前必读** |
|
| [specs/solution-schema.md](specs/solution-schema.md) | Solution structure | **Must Read Before Execution** |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Reference Documents by Phase
|
## Reference Documents by Phase
|
||||||
|
|
||||||
### 📋 Phase 1: Issue Collection
|
### Phase 1: Issue Collection
|
||||||
执行Phase 1时查阅的文档
|
Documents to refer to when executing Phase 1
|
||||||
|
|
||||||
| Document | Purpose | When to Use |
|
| Document | Purpose | When to Use |
|
||||||
|----------|---------|-------------|
|
|----------|---------|-------------|
|
||||||
| [phases/actions/action-list.md](phases/actions/action-list.md) | Issue加载逻辑 | 理解如何收集issues |
|
| [phases/actions/action-list.md](phases/actions/action-list.md) | Issue loading logic | Understand how to collect issues |
|
||||||
| [specs/issue-handling.md](specs/issue-handling.md) | Issue数据规范 | 验证issue格式 ✅ **必读** |
|
| [specs/issue-handling.md](specs/issue-handling.md) | Issue data specification | Verify issue format **Required Reading** |
|
||||||
|
|
||||||
### ⚙️ Phase 2: Planning
|
### Phase 2: Planning
|
||||||
执行Phase 2时查阅的文档
|
Documents to refer to when executing Phase 2
|
||||||
|
|
||||||
| Document | Purpose | When to Use |
|
| Document | Purpose | When to Use |
|
||||||
|----------|---------|-------------|
|
|----------|---------|-------------|
|
||||||
| [phases/actions/action-plan.md](phases/actions/action-plan.md) | Planning流程 | 理解issue→solution转换 |
|
| [phases/actions/action-plan.md](phases/actions/action-plan.md) | Planning process | Understand issue to solution transformation |
|
||||||
| [specs/solution-schema.md](specs/solution-schema.md) | 解决方案结构 | 验证solution JSON格式 ✅ **必读** |
|
| [specs/solution-schema.md](specs/solution-schema.md) | Solution structure | Verify solution JSON format **Required Reading** |
|
||||||
|
|
||||||
### 🔍 Debugging & Troubleshooting
|
### Debugging & Troubleshooting
|
||||||
|
|
||||||
| Issue | Solution Document |
|
| Issue | Solution Document |
|
||||||
|-------|------------------|
|
|-------|------------------|
|
||||||
| Phase 1失败 | [phases/actions/action-list.md](phases/actions/action-list.md) |
|
| Phase 1 failed | [phases/actions/action-list.md](phases/actions/action-list.md) |
|
||||||
| Planning输出不符 | [phases/actions/action-plan.md](phases/actions/action-plan.md) + [specs/solution-schema.md](specs/solution-schema.md) |
|
| Planning output incorrect | [phases/actions/action-plan.md](phases/actions/action-plan.md) + [specs/solution-schema.md](specs/solution-schema.md) |
|
||||||
| 数据验证失败 | [specs/issue-handling.md](specs/issue-handling.md) |
|
| Data validation failed | [specs/issue-handling.md](specs/issue-handling.md) |
|
||||||
|
|
||||||
### 📚 Reference & Background
|
### Reference & Background
|
||||||
|
|
||||||
| Document | Purpose | Notes |
|
| Document | Purpose | Notes |
|
||||||
|----------|---------|-------|
|
|----------|---------|-------|
|
||||||
| [../issue-plan.md](../../.codex/prompts/issue-plan.md) | 原始实现 | Planning Agent system prompt |
|
| [../issue-plan.md](../../.codex/prompts/issue-plan.md) | Original implementation | Planning Agent system prompt |
|
||||||
```
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 生成算法
|
## Generation Algorithm
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
function generateReferenceDocuments(config) {
|
function generateReferenceDocuments(config) {
|
||||||
let result = '## Reference Documents by Phase\n\n';
|
let result = '## Reference Documents by Phase\n\n';
|
||||||
|
|
||||||
// 为每个phase生成一个章节
|
// Generate a section for each phase
|
||||||
const phases = config.phases || config.actions || [];
|
const phases = config.phases || config.actions || [];
|
||||||
|
|
||||||
phases.forEach((phase, index) => {
|
phases.forEach((phase, index) => {
|
||||||
@@ -224,9 +224,9 @@ function generateReferenceDocuments(config) {
|
|||||||
const title = phase.display_name || phase.name;
|
const title = phase.display_name || phase.name;
|
||||||
|
|
||||||
result += `### ${emoji} Phase ${phaseNum}: ${title}\n`;
|
result += `### ${emoji} Phase ${phaseNum}: ${title}\n`;
|
||||||
result += `执行Phase ${phaseNum}时查阅的文档\n\n`;
|
result += `Documents to refer to when executing Phase ${phaseNum}\n\n`;
|
||||||
|
|
||||||
// 找出该phase相关的所有文档
|
// Find all documents related to this phase
|
||||||
const docs = config.specs.filter(spec =>
|
const docs = config.specs.filter(spec =>
|
||||||
(spec.phases || []).includes(`phase-${phaseNum}`) ||
|
(spec.phases || []).includes(`phase-${phaseNum}`) ||
|
||||||
matchesByName(spec.path, phase.name)
|
matchesByName(spec.path, phase.name)
|
||||||
@@ -236,19 +236,19 @@ function generateReferenceDocuments(config) {
|
|||||||
result += '| Document | Purpose | When to Use |\n';
|
result += '| Document | Purpose | When to Use |\n';
|
||||||
result += '|----------|---------|-------------|\n';
|
result += '|----------|---------|-------------|\n';
|
||||||
docs.forEach(doc => {
|
docs.forEach(doc => {
|
||||||
const required = doc.phases && doc.phases[0] === `phase-${phaseNum}` ? ' ✅ **必读**' : '';
|
const required = doc.phases && doc.phases[0] === `phase-${phaseNum}` ? ' **Required Reading**' : '';
|
||||||
result += `| [${doc.path}](${doc.path}) | ${doc.purpose} | ${doc.context}${required} |\n`;
|
result += `| [${doc.path}](${doc.path}) | ${doc.purpose} | ${doc.context}${required} |\n`;
|
||||||
});
|
});
|
||||||
result += '\n';
|
result += '\n';
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// 问题排查部分
|
// Troubleshooting section
|
||||||
result += '### 🔍 Debugging & Troubleshooting\n\n';
|
result += '### Debugging & Troubleshooting\n\n';
|
||||||
result += generateDebuggingTable(config);
|
result += generateDebuggingTable(config);
|
||||||
|
|
||||||
// 深度学习参考
|
// In-depth reference learning
|
||||||
result += '### 📚 Reference & Background\n\n';
|
result += '### Reference & Background\n\n';
|
||||||
result += generateReferenceTable(config);
|
result += generateReferenceTable(config);
|
||||||
|
|
||||||
return result;
|
return result;
|
||||||
@@ -257,15 +257,15 @@ function generateReferenceDocuments(config) {
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 检查清单
|
## Checklist
|
||||||
|
|
||||||
生成skill的SKILL.md时,参考文档部分应满足:
|
When generating skill's SKILL.md, the reference documents section should satisfy:
|
||||||
|
|
||||||
- [ ] 有明确的"## Reference Documents by Phase"标题
|
- [ ] Has clear "## Reference Documents by Phase" heading
|
||||||
- [ ] 每个Phase都有对应的章节 (用emoji标识)
|
- [ ] Each phase has a corresponding section (identified with symbols)
|
||||||
- [ ] 每个文档条目包含"When to Use"列
|
- [ ] Each document entry includes "When to Use" column
|
||||||
- [ ] 包含"🔍 Debugging & Troubleshooting"部分
|
- [ ] Includes "Debugging & Troubleshooting" section
|
||||||
- [ ] 包含"📚 Reference & Background"部分
|
- [ ] Includes "Reference & Background" section
|
||||||
- [ ] 强制必读文档用✅和**粗体**标记
|
- [ ] Mandatory reading documents are marked with **bold** text
|
||||||
- [ ] Execution Flow部分中有"→ **查阅**: ..."指引
|
- [ ] Execution Flow section includes "→ **Refer to**: ..." guidance
|
||||||
- [ ] 避免过长的文档列表 (一个Phase最多5-8个文档)
|
- [ ] Avoid overly long document lists (maximum 5-8 documents per phase)
|
||||||
|
|||||||
@@ -1,18 +1,18 @@
|
|||||||
# Scripting Integration Spec
|
# Scripting Integration Specification
|
||||||
|
|
||||||
技能脚本集成规范,定义如何在技能中使用外部脚本执行确定性任务。
|
Skill scripting integration specification that defines how to use external scripts for deterministic task execution.
|
||||||
|
|
||||||
## 核心原则
|
## Core Principles
|
||||||
|
|
||||||
1. **约定优于配置**:命名即 ID,扩展名即运行时
|
1. **Convention over configuration**: Naming is ID, file extension is runtime
|
||||||
2. **极简调用**:一行完成脚本调用
|
2. **Minimal invocation**: Complete script call in one line
|
||||||
3. **标准输入输出**:命令行参数输入,JSON 标准输出
|
3. **Standard input/output**: Command-line parameters as input, JSON as standard output
|
||||||
|
|
||||||
## 目录结构
|
## Directory Structure
|
||||||
|
|
||||||
```
|
```
|
||||||
.claude/skills/<skill-name>/
|
.claude/skills/<skill-name>/
|
||||||
├── scripts/ # 脚本专用目录
|
├── scripts/ # Scripts directory
|
||||||
│ ├── process-data.py # id: process-data
|
│ ├── process-data.py # id: process-data
|
||||||
│ ├── validate-output.sh # id: validate-output
|
│ ├── validate-output.sh # id: validate-output
|
||||||
│ └── transform-json.js # id: transform-json
|
│ └── transform-json.js # id: transform-json
|
||||||
@@ -20,17 +20,17 @@
|
|||||||
└── specs/
|
└── specs/
|
||||||
```
|
```
|
||||||
|
|
||||||
## 命名约定
|
## Naming Conventions
|
||||||
|
|
||||||
| 扩展名 | 运行时 | 执行命令 |
|
| Extension | Runtime | Execution Command |
|
||||||
|--------|--------|----------|
|
|-----------|---------|-------------------|
|
||||||
| `.py` | python | `python scripts/{id}.py` |
|
| `.py` | python | `python scripts/{id}.py` |
|
||||||
| `.sh` | bash | `bash scripts/{id}.sh` |
|
| `.sh` | bash | `bash scripts/{id}.sh` |
|
||||||
| `.js` | node | `node scripts/{id}.js` |
|
| `.js` | node | `node scripts/{id}.js` |
|
||||||
|
|
||||||
## 声明格式
|
## Declaration Format
|
||||||
|
|
||||||
在 Phase 或 Action 文件的 `## Scripts` 部分声明:
|
Declare in the `## Scripts` section of Phase or Action files:
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
## Scripts
|
## Scripts
|
||||||
@@ -39,27 +39,27 @@
|
|||||||
- validate-output
|
- validate-output
|
||||||
```
|
```
|
||||||
|
|
||||||
## 调用语法
|
## Invocation Syntax
|
||||||
|
|
||||||
### 基础调用
|
### Basic Call
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
const result = await ExecuteScript('script-id', { key: value });
|
const result = await ExecuteScript('script-id', { key: value });
|
||||||
```
|
```
|
||||||
|
|
||||||
### 参数命名转换
|
### Parameter Name Conversion
|
||||||
|
|
||||||
调用时 JS 对象中的键会**自动转换**为 `kebab-case` 命令行参数:
|
Keys in the JS object are **automatically converted** to `kebab-case` command-line parameters:
|
||||||
|
|
||||||
| JS 键名 | 转换后参数 |
|
| JS Key Name | Converted Parameter |
|
||||||
|---------|-----------|
|
|-------------|-------------------|
|
||||||
| `input_path` | `--input-path` |
|
| `input_path` | `--input-path` |
|
||||||
| `output_dir` | `--output-dir` |
|
| `output_dir` | `--output-dir` |
|
||||||
| `max_count` | `--max-count` |
|
| `max_count` | `--max-count` |
|
||||||
|
|
||||||
脚本中使用 `--input-path` 接收,调用时使用 `input_path` 传入。
|
Use `--input-path` in scripts, pass `input_path` when calling.
|
||||||
|
|
||||||
### 完整调用(含错误处理)
|
### Complete Call (with Error Handling)
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
const result = await ExecuteScript('process-data', {
|
const result = await ExecuteScript('process-data', {
|
||||||
@@ -68,46 +68,46 @@ const result = await ExecuteScript('process-data', {
|
|||||||
});
|
});
|
||||||
|
|
||||||
if (!result.success) {
|
if (!result.success) {
|
||||||
throw new Error(`脚本执行失败: ${result.stderr}`);
|
throw new Error(`Script execution failed: ${result.stderr}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const { output_file, count } = result.outputs;
|
const { output_file, count } = result.outputs;
|
||||||
```
|
```
|
||||||
|
|
||||||
## 返回格式
|
## Return Format
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
interface ScriptResult {
|
interface ScriptResult {
|
||||||
success: boolean; // exit code === 0
|
success: boolean; // exit code === 0
|
||||||
stdout: string; // 完整标准输出
|
stdout: string; // Complete standard output
|
||||||
stderr: string; // 完整标准错误
|
stderr: string; // Complete standard error
|
||||||
outputs: { // 从 stdout 最后一行解析的 JSON
|
outputs: { // JSON parsed from last line of stdout
|
||||||
[key: string]: any;
|
[key: string]: any;
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
## 脚本编写规范
|
## Script Writing Specification
|
||||||
|
|
||||||
### 输入:命令行参数
|
### Input: Command-line Parameters
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Python: argparse
|
# Python: argparse
|
||||||
--input-path /path/to/file --threshold 0.9
|
--input-path /path/to/file --threshold 0.9
|
||||||
|
|
||||||
# Bash: 手动解析
|
# Bash: manual parsing
|
||||||
--input-path /path/to/file
|
--input-path /path/to/file
|
||||||
```
|
```
|
||||||
|
|
||||||
### 输出:标准输出 JSON
|
### Output: Standard Output JSON
|
||||||
|
|
||||||
脚本最后一行必须打印单行 JSON:
|
Script must print single-line JSON on last line:
|
||||||
|
|
||||||
```json
|
```json
|
||||||
{"output_file": "/tmp/result.json", "count": 42}
|
{"output_file": "/tmp/result.json", "count": 42}
|
||||||
```
|
```
|
||||||
|
|
||||||
### Python 模板
|
### Python Template
|
||||||
|
|
||||||
```python
|
```python
|
||||||
import argparse
|
import argparse
|
||||||
@@ -119,10 +119,10 @@ def main():
|
|||||||
parser.add_argument('--threshold', type=float, default=0.9)
|
parser.add_argument('--threshold', type=float, default=0.9)
|
||||||
args = parser.parse_args()
|
args = parser.parse_args()
|
||||||
|
|
||||||
# 执行逻辑...
|
# Execution logic...
|
||||||
result_path = "/tmp/result.json"
|
result_path = "/tmp/result.json"
|
||||||
|
|
||||||
# 输出 JSON
|
# Output JSON
|
||||||
print(json.dumps({
|
print(json.dumps({
|
||||||
"output_file": result_path,
|
"output_file": result_path,
|
||||||
"items_processed": 100
|
"items_processed": 100
|
||||||
@@ -132,12 +132,12 @@ if __name__ == '__main__':
|
|||||||
main()
|
main()
|
||||||
```
|
```
|
||||||
|
|
||||||
### Bash 模板
|
### Bash Template
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
#!/bin/bash
|
#!/bin/bash
|
||||||
|
|
||||||
# 解析参数
|
# Parse parameters
|
||||||
while [[ "$#" -gt 0 ]]; do
|
while [[ "$#" -gt 0 ]]; do
|
||||||
case $1 in
|
case $1 in
|
||||||
--input-path) INPUT_PATH="$2"; shift ;;
|
--input-path) INPUT_PATH="$2"; shift ;;
|
||||||
@@ -146,21 +146,21 @@ while [[ "$#" -gt 0 ]]; do
|
|||||||
shift
|
shift
|
||||||
done
|
done
|
||||||
|
|
||||||
# 执行逻辑...
|
# Execution logic...
|
||||||
LOG_FILE="/tmp/process.log"
|
LOG_FILE="/tmp/process.log"
|
||||||
echo "Processing $INPUT_PATH" > "$LOG_FILE"
|
echo "Processing $INPUT_PATH" > "$LOG_FILE"
|
||||||
|
|
||||||
# 输出 JSON
|
# Output JSON
|
||||||
echo "{\"log_file\": \"$LOG_FILE\", \"status\": \"done\"}"
|
echo "{\"log_file\": \"$LOG_FILE\", \"status\": \"done\"}"
|
||||||
```
|
```
|
||||||
|
|
||||||
## ExecuteScript 实现
|
## ExecuteScript Implementation
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
async function ExecuteScript(scriptId, inputs = {}) {
|
async function ExecuteScript(scriptId, inputs = {}) {
|
||||||
const skillDir = GetSkillDir();
|
const skillDir = GetSkillDir();
|
||||||
|
|
||||||
// 查找脚本文件
|
// Find script file
|
||||||
const extensions = ['.py', '.sh', '.js'];
|
const extensions = ['.py', '.sh', '.js'];
|
||||||
let scriptPath, runtime;
|
let scriptPath, runtime;
|
||||||
|
|
||||||
@@ -177,22 +177,22 @@ async function ExecuteScript(scriptId, inputs = {}) {
|
|||||||
throw new Error(`Script not found: ${scriptId}`);
|
throw new Error(`Script not found: ${scriptId}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 构建命令行参数
|
// Build command-line parameters
|
||||||
const args = Object.entries(inputs)
|
const args = Object.entries(inputs)
|
||||||
.map(([k, v]) => `--${k.replace(/_/g, '-')} "${v}"`)
|
.map(([k, v]) => `--${k.replace(/_/g, '-')} "${v}"`)
|
||||||
.join(' ');
|
.join(' ');
|
||||||
|
|
||||||
// 执行脚本
|
// Execute script
|
||||||
const cmd = `${runtime} "${scriptPath}" ${args}`;
|
const cmd = `${runtime} "${scriptPath}" ${args}`;
|
||||||
const { stdout, stderr, exitCode } = await Bash(cmd);
|
const { stdout, stderr, exitCode } = await Bash(cmd);
|
||||||
|
|
||||||
// 解析输出
|
// Parse output
|
||||||
let outputs = {};
|
let outputs = {};
|
||||||
try {
|
try {
|
||||||
const lastLine = stdout.trim().split('\n').pop();
|
const lastLine = stdout.trim().split('\n').pop();
|
||||||
outputs = JSON.parse(lastLine);
|
outputs = JSON.parse(lastLine);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
// 无法解析 JSON,保持空对象
|
// Unable to parse JSON, keep empty object
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
@@ -204,62 +204,62 @@ async function ExecuteScript(scriptId, inputs = {}) {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
## 使用场景
|
## Use Cases
|
||||||
|
|
||||||
### 适合脚本化的任务
|
### Suitable for Scripting
|
||||||
|
|
||||||
- 数据处理和转换
|
- Data processing and transformation
|
||||||
- 文件格式转换
|
- File format conversion
|
||||||
- 批量文件操作
|
- Batch file operations
|
||||||
- 复杂计算逻辑
|
- Complex calculation logic
|
||||||
- 调用外部工具/库
|
- Call external tools/libraries
|
||||||
|
|
||||||
### 不适合脚本化的任务
|
### Not Suitable for Scripting
|
||||||
|
|
||||||
- 需要用户交互的任务
|
- Tasks requiring user interaction
|
||||||
- 需要访问 Claude 工具的任务
|
- Tasks needing access to Claude tools
|
||||||
- 简单的文件读写
|
- Simple file read/write
|
||||||
- 需要动态决策的任务
|
- Tasks requiring dynamic decision-making
|
||||||
|
|
||||||
## 路径约定
|
## Path Conventions
|
||||||
|
|
||||||
### 脚本路径
|
### Script Path
|
||||||
|
|
||||||
脚本路径相对于 `SKILL.md` 所在目录(技能根目录):
|
Script paths are relative to the directory containing `SKILL.md` (skill root directory):
|
||||||
|
|
||||||
```
|
```
|
||||||
.claude/skills/<skill-name>/ # 技能根目录(SKILL.md 所在位置)
|
.claude/skills/<skill-name>/ # Skill root directory (SKILL.md location)
|
||||||
├── SKILL.md
|
├── SKILL.md
|
||||||
├── scripts/ # 脚本目录
|
├── scripts/ # Scripts directory
|
||||||
│ └── process-data.py # 相对路径: scripts/process-data.py
|
│ └── process-data.py # Relative path: scripts/process-data.py
|
||||||
└── phases/
|
└── phases/
|
||||||
```
|
```
|
||||||
|
|
||||||
`ExecuteScript` 自动从技能根目录查找脚本:
|
`ExecuteScript` automatically finds scripts from skill root directory:
|
||||||
```javascript
|
```javascript
|
||||||
// 实际执行: python .claude/skills/<skill-name>/scripts/process-data.py
|
// Actually executes: python .claude/skills/<skill-name>/scripts/process-data.py
|
||||||
await ExecuteScript('process-data', { ... });
|
await ExecuteScript('process-data', { ... });
|
||||||
```
|
```
|
||||||
|
|
||||||
### 输出目录
|
### Output Directory
|
||||||
|
|
||||||
**推荐**:由调用方传递输出目录,而非脚本默认 `/tmp`:
|
**Recommended**: Pass output directory from caller, not hardcode in script to `/tmp`:
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
// 调用时指定输出目录(在工作流工作目录内)
|
// Specify output directory when calling (in workflow working directory)
|
||||||
const result = await ExecuteScript('process-data', {
|
const result = await ExecuteScript('process-data', {
|
||||||
input_path: `${workDir}/data.json`,
|
input_path: `${workDir}/data.json`,
|
||||||
output_dir: `${workDir}/output` // 明确指定输出位置
|
output_dir: `${workDir}/output` // Explicitly specify output location
|
||||||
});
|
});
|
||||||
```
|
```
|
||||||
|
|
||||||
脚本应接受 `--output-dir` 参数,而非硬编码输出路径。
|
Scripts should accept `--output-dir` parameter instead of hardcoding output paths.
|
||||||
|
|
||||||
## 最佳实践
|
## Best Practices
|
||||||
|
|
||||||
1. **单一职责**:每个脚本只做一件事
|
1. **Single Responsibility**: Each script does one thing
|
||||||
2. **无副作用**:脚本不应修改全局状态
|
2. **No Side Effects**: Scripts should not modify global state
|
||||||
3. **幂等性**:相同输入产生相同输出
|
3. **Idempotence**: Same input produces same output
|
||||||
4. **错误明确**:错误信息写入 stderr,正常输出写入 stdout
|
4. **Clear Errors**: Error messages to stderr, normal output to stdout
|
||||||
5. **快速失败**:参数验证失败立即退出
|
5. **Fail Fast**: Exit immediately on parameter validation failure
|
||||||
6. **路径参数化**:输出路径由调用方指定,不硬编码
|
6. **Parameterized Paths**: Output paths specified by caller, not hardcoded
|
||||||
|
|||||||
@@ -1,102 +1,102 @@
|
|||||||
# Skill Requirements Specification
|
# Skill Requirements Specification
|
||||||
|
|
||||||
新 Skill 创建的需求收集规范。
|
Requirements collection specification for new Skill creation.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 必需信息
|
## Required Information
|
||||||
|
|
||||||
### 1. 基本信息
|
### 1. Basic Information
|
||||||
|
|
||||||
| 字段 | 类型 | 必需 | 说明 |
|
| Field | Type | Required | Description |
|
||||||
|------|------|------|------|
|
|-------|------|----------|-------------|
|
||||||
| `skill_name` | string | ✓ | Skill 标识符(小写-连字符) |
|
| `skill_name` | string | Yes | Skill identifier (lowercase with hyphens) |
|
||||||
| `display_name` | string | ✓ | 显示名称 |
|
| `display_name` | string | Yes | Display name |
|
||||||
| `description` | string | ✓ | 一句话描述 |
|
| `description` | string | Yes | One-sentence description |
|
||||||
| `triggers` | string[] | ✓ | 触发关键词列表 |
|
| `triggers` | string[] | Yes | List of trigger keywords |
|
||||||
|
|
||||||
### 2. 执行模式
|
### 2. Execution Mode
|
||||||
|
|
||||||
| 字段 | 类型 | 必需 | 说明 |
|
| Field | Type | Required | Description |
|
||||||
|------|------|------|------|
|
|-------|------|----------|-------------|
|
||||||
| `execution_mode` | enum | ✓ | `sequential` \| `autonomous` \| `hybrid` |
|
| `execution_mode` | enum | Yes | `sequential` \| `autonomous` \| `hybrid` |
|
||||||
| `phase_count` | number | 条件 | Sequential 模式下的阶段数 |
|
| `phase_count` | number | Conditional | Number of phases in Sequential mode |
|
||||||
| `action_count` | number | 条件 | Autonomous 模式下的动作数 |
|
| `action_count` | number | Conditional | Number of actions in Autonomous mode |
|
||||||
|
|
||||||
### 2.5 上下文策略 (P0 增强)
|
### 2.5 Context Strategy (P0 Enhancement)
|
||||||
|
|
||||||
| 字段 | 类型 | 必需 | 说明 |
|
| Field | Type | Required | Description |
|
||||||
|------|------|------|------|
|
|-------|------|----------|-------------|
|
||||||
| `context_strategy` | enum | ✓ | `file` \| `memory` |
|
| `context_strategy` | enum | Yes | `file` \| `memory` |
|
||||||
|
|
||||||
**策略对比**:
|
**Strategy Comparison**:
|
||||||
|
|
||||||
| 策略 | 持久化 | 可调试 | 可恢复 | 适用场景 |
|
| Strategy | Persistence | Debuggable | Recoverable | Applicable Scenarios |
|
||||||
|------|--------|--------|--------|----------|
|
|----------|-------------|-----------|------------|----------------------|
|
||||||
| `file` | ✓ | ✓ | ✓ | 复杂多阶段任务(推荐) |
|
| `file` | Yes | Yes | Yes | Complex multi-phase tasks (recommended) |
|
||||||
| `memory` | ✗ | ✗ | ✗ | 简单线性任务 |
|
| `memory` | No | No | No | Simple linear tasks |
|
||||||
|
|
||||||
### 2.6 LLM 集成配置 (P1 增强)
|
### 2.6 LLM Integration Configuration (P1 Enhancement)
|
||||||
|
|
||||||
| 字段 | 类型 | 必需 | 说明 |
|
| Field | Type | Required | Description |
|
||||||
|------|------|------|------|
|
|-------|------|----------|-------------|
|
||||||
| `llm_integration` | object | 可选 | LLM 调用配置 |
|
| `llm_integration` | object | Optional | LLM invocation configuration |
|
||||||
| `llm_integration.enabled` | boolean | - | 是否启用 LLM 调用 |
|
| `llm_integration.enabled` | boolean | - | Enable LLM invocation |
|
||||||
| `llm_integration.default_tool` | enum | - | `gemini` \| `qwen` \| `codex` |
|
| `llm_integration.default_tool` | enum | - | `gemini` \| `qwen` \| `codex` |
|
||||||
| `llm_integration.fallback_chain` | string[] | - | 失败时的备选工具链 |
|
| `llm_integration.fallback_chain` | string[] | - | Fallback tool chain on failure |
|
||||||
|
|
||||||
### 3. 工具依赖
|
### 3. Tool Dependencies
|
||||||
|
|
||||||
| 字段 | 类型 | 必需 | 说明 |
|
| Field | Type | Required | Description |
|
||||||
|------|------|------|------|
|
|-------|------|----------|-------------|
|
||||||
| `allowed_tools` | string[] | ✓ | 允许使用的工具列表 |
|
| `allowed_tools` | string[] | Yes | List of allowed tools |
|
||||||
| `mcp_tools` | string[] | 可选 | 需要的 MCP 工具 |
|
| `mcp_tools` | string[] | Optional | Required MCP tools |
|
||||||
|
|
||||||
### 4. 输出配置
|
### 4. Output Configuration
|
||||||
|
|
||||||
| 字段 | 类型 | 必需 | 说明 |
|
| Field | Type | Required | Description |
|
||||||
|------|------|------|------|
|
|-------|------|----------|-------------|
|
||||||
| `output_format` | enum | ✓ | `markdown` \| `html` \| `json` |
|
| `output_format` | enum | Yes | `markdown` \| `html` \| `json` |
|
||||||
| `output_location` | string | ✓ | 输出目录模式 |
|
| `output_location` | string | Yes | Output directory pattern |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 配置文件结构
|
## Configuration File Structure
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
interface SkillConfig {
|
interface SkillConfig {
|
||||||
// 基本信息
|
// Basic information
|
||||||
skill_name: string; // "my-skill"
|
skill_name: string; // "my-skill"
|
||||||
display_name: string; // "My Skill"
|
display_name: string; // "My Skill"
|
||||||
description: string; // "一句话描述"
|
description: string; // "One-sentence description"
|
||||||
triggers: string[]; // ["keyword1", "keyword2"]
|
triggers: string[]; // ["keyword1", "keyword2"]
|
||||||
|
|
||||||
// 执行模式
|
// Execution mode
|
||||||
execution_mode: 'sequential' | 'autonomous' | 'hybrid';
|
execution_mode: 'sequential' | 'autonomous' | 'hybrid';
|
||||||
|
|
||||||
// 上下文策略 (P0 增强)
|
// Context strategy (P0 Enhancement)
|
||||||
context_strategy: 'file' | 'memory'; // 默认: 'file'
|
context_strategy: 'file' | 'memory'; // Default: 'file'
|
||||||
|
|
||||||
// LLM 集成配置 (P1 增强)
|
// LLM Integration Configuration (P1 Enhancement)
|
||||||
llm_integration?: {
|
llm_integration?: {
|
||||||
enabled: boolean; // 是否启用 LLM 调用
|
enabled: boolean; // Enable LLM invocation
|
||||||
default_tool: 'gemini' | 'qwen' | 'codex';
|
default_tool: 'gemini' | 'qwen' | 'codex';
|
||||||
fallback_chain: string[]; // ['gemini', 'qwen', 'codex']
|
fallback_chain: string[]; // ['gemini', 'qwen', 'codex']
|
||||||
mode: 'analysis' | 'write'; // 默认 mode
|
mode: 'analysis' | 'write'; // Default mode
|
||||||
};
|
};
|
||||||
|
|
||||||
// Sequential 模式配置
|
// Sequential mode configuration
|
||||||
sequential_config?: {
|
sequential_config?: {
|
||||||
phases: Array<{
|
phases: Array<{
|
||||||
id: string; // "01-init"
|
id: string; // "01-init"
|
||||||
name: string; // "Initialization"
|
name: string; // "Initialization"
|
||||||
description: string; // "收集初始配置"
|
description: string; // "Collect initial configuration"
|
||||||
input: string[]; // 输入依赖
|
input: string[]; // Input dependencies
|
||||||
output: string; // 输出文件
|
output: string; // Output file
|
||||||
}>;
|
}>;
|
||||||
};
|
};
|
||||||
|
|
||||||
// Autonomous 模式配置
|
// Autonomous mode configuration
|
||||||
autonomous_config?: {
|
autonomous_config?: {
|
||||||
state_schema: {
|
state_schema: {
|
||||||
fields: Array<{
|
fields: Array<{
|
||||||
@@ -108,31 +108,31 @@ interface SkillConfig {
|
|||||||
actions: Array<{
|
actions: Array<{
|
||||||
id: string; // "action-init"
|
id: string; // "action-init"
|
||||||
name: string; // "Initialize"
|
name: string; // "Initialize"
|
||||||
description: string; // "初始化状态"
|
description: string; // "Initialize state"
|
||||||
preconditions: string[]; // 前置条件
|
preconditions: string[]; // Preconditions
|
||||||
effects: string[]; // 执行效果
|
effects: string[]; // Execution effects
|
||||||
}>;
|
}>;
|
||||||
termination_conditions: string[];
|
termination_conditions: string[];
|
||||||
};
|
};
|
||||||
|
|
||||||
// 工具依赖
|
// Tool dependencies
|
||||||
allowed_tools: string[]; // ["Task", "Read", "Write", ...]
|
allowed_tools: string[]; // ["Task", "Read", "Write", ...]
|
||||||
mcp_tools?: string[]; // ["mcp__chrome__*"]
|
mcp_tools?: string[]; // ["mcp__chrome__*"]
|
||||||
|
|
||||||
// 输出配置
|
// Output configuration
|
||||||
output: {
|
output: {
|
||||||
format: 'markdown' | 'html' | 'json';
|
format: 'markdown' | 'html' | 'json';
|
||||||
location: string; // ".workflow/.scratchpad/{skill}-{timestamp}"
|
location: string; // ".workflow/.scratchpad/{skill}-{timestamp}"
|
||||||
filename_pattern: string; // "{name}-output.{ext}"
|
filename_pattern: string; // "{name}-output.{ext}"
|
||||||
};
|
};
|
||||||
|
|
||||||
// 质量配置
|
// Quality configuration
|
||||||
quality?: {
|
quality?: {
|
||||||
dimensions: string[]; // ["completeness", "consistency", ...]
|
dimensions: string[]; // ["completeness", "consistency", ...]
|
||||||
pass_threshold: number; // 80
|
pass_threshold: number; // 80
|
||||||
};
|
};
|
||||||
|
|
||||||
// 元数据
|
// Metadata
|
||||||
created_at: string;
|
created_at: string;
|
||||||
version: string;
|
version: string;
|
||||||
}
|
}
|
||||||
@@ -140,59 +140,59 @@ interface SkillConfig {
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 需求收集问题
|
## Requirements Collection Questions
|
||||||
|
|
||||||
### Phase 1: 基本信息
|
### Phase 1: Basic Information
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
AskUserQuestion({
|
AskUserQuestion({
|
||||||
questions: [
|
questions: [
|
||||||
{
|
{
|
||||||
question: "Skill 的名称是什么?(英文,小写-连字符格式)",
|
question: "What is the Skill name? (English, lowercase with hyphens)",
|
||||||
header: "Skill 名称",
|
header: "Skill Name",
|
||||||
multiSelect: false,
|
multiSelect: false,
|
||||||
options: [
|
options: [
|
||||||
{ label: "自动生成", description: "根据描述自动生成名称" },
|
{ label: "Auto-generate", description: "Auto-generate name from description" },
|
||||||
{ label: "手动输入", description: "输入自定义名称" }
|
{ label: "Manual input", description: "Enter custom name" }
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
question: "Skill 的主要用途是什么?",
|
question: "What is the primary purpose of this Skill?",
|
||||||
header: "用途类型",
|
header: "Purpose Type",
|
||||||
multiSelect: false,
|
multiSelect: false,
|
||||||
options: [
|
options: [
|
||||||
{ label: "文档生成", description: "生成 Markdown/HTML 文档" },
|
{ label: "Document Generation", description: "Generate Markdown/HTML documents" },
|
||||||
{ label: "代码分析", description: "分析代码结构、质量、安全" },
|
{ label: "Code Analysis", description: "Analyze code structure, quality, security" },
|
||||||
{ label: "交互管理", description: "管理 Issue、任务、工作流" },
|
{ label: "Interactive Management", description: "Manage Issues, tasks, workflows" },
|
||||||
{ label: "数据处理", description: "ETL、转换、报告生成" },
|
{ label: "Data Processing", description: "ETL, transformation, report generation" },
|
||||||
{ label: "自定义", description: "其他用途" }
|
{ label: "Custom", description: "Other purposes" }
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
});
|
});
|
||||||
```
|
```
|
||||||
|
|
||||||
### Phase 2: 执行模式
|
### Phase 2: Execution Mode
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
AskUserQuestion({
|
AskUserQuestion({
|
||||||
questions: [
|
questions: [
|
||||||
{
|
{
|
||||||
question: "选择执行模式:",
|
question: "Select execution mode:",
|
||||||
header: "执行模式",
|
header: "Execution Mode",
|
||||||
multiSelect: false,
|
multiSelect: false,
|
||||||
options: [
|
options: [
|
||||||
{
|
{
|
||||||
label: "Sequential (顺序)",
|
label: "Sequential (Fixed Order)",
|
||||||
description: "阶段按固定顺序执行,适合流水线任务(推荐)"
|
description: "Phases execute in fixed order, suitable for pipeline tasks (recommended)"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
label: "Autonomous (自主)",
|
label: "Autonomous (Dynamic)",
|
||||||
description: "动态选择执行路径,适合交互式任务"
|
description: "Dynamically select execution path, suitable for interactive tasks"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
label: "Hybrid (混合)",
|
label: "Hybrid (Mixed)",
|
||||||
description: "初始化和收尾固定,中间交互灵活"
|
description: "Fixed initialization and finalization, flexible middle interaction"
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
@@ -200,67 +200,67 @@ AskUserQuestion({
|
|||||||
});
|
});
|
||||||
```
|
```
|
||||||
|
|
||||||
### Phase 3: 阶段/动作定义
|
### Phase 3: Phase/Action Definition
|
||||||
|
|
||||||
#### Sequential 模式
|
#### Sequential Mode
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
AskUserQuestion({
|
AskUserQuestion({
|
||||||
questions: [
|
questions: [
|
||||||
{
|
{
|
||||||
question: "需要多少个执行阶段?",
|
question: "How many execution phases do you need?",
|
||||||
header: "阶段数量",
|
header: "Phase Count",
|
||||||
multiSelect: false,
|
multiSelect: false,
|
||||||
options: [
|
options: [
|
||||||
{ label: "3 阶段", description: "简单: 收集 → 处理 → 输出" },
|
{ label: "3 phases", description: "Simple: Collect → Process → Output" },
|
||||||
{ label: "5 阶段", description: "标准: 收集 → 探索 → 分析 → 组装 → 验证" },
|
{ label: "5 phases", description: "Standard: Collect → Explore → Analyze → Assemble → Validate" },
|
||||||
{ label: "7 阶段", description: "完整: 包含并行处理和迭代优化" },
|
{ label: "7 phases", description: "Complete: Include parallel processing and iterative optimization" },
|
||||||
{ label: "自定义", description: "手动指定阶段" }
|
{ label: "Custom", description: "Manually specify phases" }
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
});
|
});
|
||||||
```
|
```
|
||||||
|
|
||||||
#### Autonomous 模式
|
#### Autonomous Mode
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
AskUserQuestion({
|
AskUserQuestion({
|
||||||
questions: [
|
questions: [
|
||||||
{
|
{
|
||||||
question: "核心动作有哪些?",
|
question: "What are the core actions?",
|
||||||
header: "动作定义",
|
header: "Action Definition",
|
||||||
multiSelect: true,
|
multiSelect: true,
|
||||||
options: [
|
options: [
|
||||||
{ label: "初始化 (init)", description: "设置初始状态" },
|
{ label: "Initialize (init)", description: "Set initial state" },
|
||||||
{ label: "列表 (list)", description: "显示当前项目" },
|
{ label: "List (list)", description: "Display current items" },
|
||||||
{ label: "创建 (create)", description: "创建新项目" },
|
{ label: "Create (create)", description: "Create new item" },
|
||||||
{ label: "编辑 (edit)", description: "修改现有项目" },
|
{ label: "Edit (edit)", description: "Modify existing item" },
|
||||||
{ label: "删除 (delete)", description: "删除项目" },
|
{ label: "Delete (delete)", description: "Delete item" },
|
||||||
{ label: "完成 (complete)", description: "完成任务" }
|
{ label: "Complete (complete)", description: "Complete task" }
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
});
|
});
|
||||||
```
|
```
|
||||||
|
|
||||||
### Phase 4: 上下文策略 (P0 增强)
|
### Phase 4: Context Strategy (P0 Enhancement)
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
AskUserQuestion({
|
AskUserQuestion({
|
||||||
questions: [
|
questions: [
|
||||||
{
|
{
|
||||||
question: "选择上下文管理策略:",
|
question: "Select context management strategy:",
|
||||||
header: "上下文策略",
|
header: "Context Strategy",
|
||||||
multiSelect: false,
|
multiSelect: false,
|
||||||
options: [
|
options: [
|
||||||
{
|
{
|
||||||
label: "文件策略 (file)",
|
label: "File Strategy (file)",
|
||||||
description: "持久化到 .scratchpad,支持调试和恢复(推荐)"
|
description: "Persist to .scratchpad, supports debugging and recovery (recommended)"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
label: "内存策略 (memory)",
|
label: "Memory Strategy (memory)",
|
||||||
description: "仅在运行时保持,速度快但无法恢复"
|
description: "Keep only at runtime, fast but no recovery"
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
@@ -268,41 +268,41 @@ AskUserQuestion({
|
|||||||
});
|
});
|
||||||
```
|
```
|
||||||
|
|
||||||
### Phase 5: LLM 集成 (P1 增强)
|
### Phase 5: LLM Integration (P1 Enhancement)
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
AskUserQuestion({
|
AskUserQuestion({
|
||||||
questions: [
|
questions: [
|
||||||
{
|
{
|
||||||
question: "是否需要 LLM 调用能力?",
|
question: "Do you need LLM invocation capability?",
|
||||||
header: "LLM 集成",
|
header: "LLM Integration",
|
||||||
multiSelect: false,
|
multiSelect: false,
|
||||||
options: [
|
options: [
|
||||||
{
|
{
|
||||||
label: "启用 LLM 调用",
|
label: "Enable LLM Invocation",
|
||||||
description: "使用 gemini/qwen/codex 进行分析或生成"
|
description: "Use gemini/qwen/codex for analysis or generation"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
label: "不需要",
|
label: "Not needed",
|
||||||
description: "仅使用本地工具"
|
description: "Only use local tools"
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
});
|
});
|
||||||
|
|
||||||
// 如果启用 LLM
|
// If LLM enabled
|
||||||
if (llmEnabled) {
|
if (llmEnabled) {
|
||||||
AskUserQuestion({
|
AskUserQuestion({
|
||||||
questions: [
|
questions: [
|
||||||
{
|
{
|
||||||
question: "选择默认 LLM 工具:",
|
question: "Select default LLM tool:",
|
||||||
header: "LLM 工具",
|
header: "LLM Tool",
|
||||||
multiSelect: false,
|
multiSelect: false,
|
||||||
options: [
|
options: [
|
||||||
{ label: "Gemini", description: "大上下文,适合分析任务(推荐)" },
|
{ label: "Gemini", description: "Large context, suitable for analysis tasks (recommended)" },
|
||||||
{ label: "Qwen", description: "代码生成能力强" },
|
{ label: "Qwen", description: "Strong code generation capability" },
|
||||||
{ label: "Codex", description: "自主执行能力强,适合实现任务" }
|
{ label: "Codex", description: "Strong autonomous execution, suitable for implementation tasks" }
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
@@ -310,21 +310,21 @@ if (llmEnabled) {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
### Phase 6: 工具依赖
|
### Phase 6: Tool Dependencies
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
AskUserQuestion({
|
AskUserQuestion({
|
||||||
questions: [
|
questions: [
|
||||||
{
|
{
|
||||||
question: "需要哪些工具?",
|
question: "What tools do you need?",
|
||||||
header: "工具选择",
|
header: "Tool Selection",
|
||||||
multiSelect: true,
|
multiSelect: true,
|
||||||
options: [
|
options: [
|
||||||
{ label: "基础工具", description: "Task, Read, Write, Glob, Grep, Bash" },
|
{ label: "Basic tools", description: "Task, Read, Write, Glob, Grep, Bash" },
|
||||||
{ label: "用户交互", description: "AskUserQuestion" },
|
{ label: "User interaction", description: "AskUserQuestion" },
|
||||||
{ label: "Chrome 截图", description: "mcp__chrome__*" },
|
{ label: "Chrome screenshot", description: "mcp__chrome__*" },
|
||||||
{ label: "外部搜索", description: "mcp__exa__search" },
|
{ label: "External search", description: "mcp__exa__search" },
|
||||||
{ label: "CCW CLI 调用", description: "ccw cli (gemini/qwen/codex)" }
|
{ label: "CCW CLI invocation", description: "ccw cli (gemini/qwen/codex)" }
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
@@ -333,17 +333,17 @@ AskUserQuestion({
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 验证规则
|
## Validation Rules
|
||||||
|
|
||||||
### 名称验证
|
### Name Validation
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
function validateSkillName(name) {
|
function validateSkillName(name) {
|
||||||
const rules = [
|
const rules = [
|
||||||
{ test: /^[a-z][a-z0-9-]*$/, msg: "必须以小写字母开头,只包含小写字母、数字、连字符" },
|
{ test: /^[a-z][a-z0-9-]*$/, msg: "Must start with lowercase letter, only contain lowercase letters, digits, hyphens" },
|
||||||
{ test: /^.{3,30}$/, msg: "长度 3-30 字符" },
|
{ test: /^.{3,30}$/, msg: "Length 3-30 characters" },
|
||||||
{ test: /^(?!.*--)/, msg: "不能有连续连字符" },
|
{ test: /^(?!.*--)/, msg: "Cannot have consecutive hyphens" },
|
||||||
{ test: /[^-]$/, msg: "不能以连字符结尾" }
|
{ test: /[^-]$/, msg: "Cannot end with hyphen" }
|
||||||
];
|
];
|
||||||
|
|
||||||
for (const rule of rules) {
|
for (const rule of rules) {
|
||||||
@@ -355,25 +355,25 @@ function validateSkillName(name) {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
### 配置验证
|
### Configuration Validation
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
function validateSkillConfig(config) {
|
function validateSkillConfig(config) {
|
||||||
const errors = [];
|
const errors = [];
|
||||||
|
|
||||||
// 必需字段
|
// Required fields
|
||||||
if (!config.skill_name) errors.push("缺少 skill_name");
|
if (!config.skill_name) errors.push("Missing skill_name");
|
||||||
if (!config.description) errors.push("缺少 description");
|
if (!config.description) errors.push("Missing description");
|
||||||
if (!config.execution_mode) errors.push("缺少 execution_mode");
|
if (!config.execution_mode) errors.push("Missing execution_mode");
|
||||||
|
|
||||||
// 模式特定验证
|
// Mode-specific validation
|
||||||
if (config.execution_mode === 'sequential') {
|
if (config.execution_mode === 'sequential') {
|
||||||
if (!config.sequential_config?.phases?.length) {
|
if (!config.sequential_config?.phases?.length) {
|
||||||
errors.push("Sequential 模式需要定义 phases");
|
errors.push("Sequential mode requires phases definition");
|
||||||
}
|
}
|
||||||
} else if (config.execution_mode === 'autonomous') {
|
} else if (config.execution_mode === 'autonomous') {
|
||||||
if (!config.autonomous_config?.actions?.length) {
|
if (!config.autonomous_config?.actions?.length) {
|
||||||
errors.push("Autonomous 模式需要定义 actions");
|
errors.push("Autonomous mode requires actions definition");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -383,9 +383,9 @@ function validateSkillConfig(config) {
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 示例配置
|
## Example Configurations
|
||||||
|
|
||||||
### Sequential 模式示例 (增强版)
|
### Sequential Mode Example (Enhanced)
|
||||||
|
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
@@ -432,7 +432,7 @@ function validateSkillConfig(config) {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
### Autonomous 模式示例
|
### Autonomous Mode Example
|
||||||
|
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
@@ -444,15 +444,15 @@ function validateSkillConfig(config) {
|
|||||||
"autonomous_config": {
|
"autonomous_config": {
|
||||||
"state_schema": {
|
"state_schema": {
|
||||||
"fields": [
|
"fields": [
|
||||||
{ "name": "tasks", "type": "Task[]", "description": "任务列表" },
|
{ "name": "tasks", "type": "Task[]", "description": "Task list" },
|
||||||
{ "name": "current_view", "type": "string", "description": "当前视图" }
|
{ "name": "current_view", "type": "string", "description": "Current view" }
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
"actions": [
|
"actions": [
|
||||||
{ "id": "action-list", "name": "List Tasks", "preconditions": [], "effects": ["显示任务列表"] },
|
{ "id": "action-list", "name": "List Tasks", "preconditions": [], "effects": ["Display task list"] },
|
||||||
{ "id": "action-create", "name": "Create Task", "preconditions": [], "effects": ["添加新任务"] },
|
{ "id": "action-create", "name": "Create Task", "preconditions": [], "effects": ["Add new task"] },
|
||||||
{ "id": "action-edit", "name": "Edit Task", "preconditions": ["task_selected"], "effects": ["更新任务"] },
|
{ "id": "action-edit", "name": "Edit Task", "preconditions": ["task_selected"], "effects": ["Update task"] },
|
||||||
{ "id": "action-delete", "name": "Delete Task", "preconditions": ["task_selected"], "effects": ["删除任务"] }
|
{ "id": "action-delete", "name": "Delete Task", "preconditions": ["task_selected"], "effects": ["Delete task"] }
|
||||||
],
|
],
|
||||||
"termination_conditions": ["user_exit", "error_limit"]
|
"termination_conditions": ["user_exit", "error_limit"]
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -1,22 +1,22 @@
|
|||||||
# Autonomous Action Template
|
# Autonomous Action Template
|
||||||
|
|
||||||
自主模式动作文件的模板。
|
Template for action files in Autonomous execution mode.
|
||||||
|
|
||||||
## Purpose
|
## Purpose
|
||||||
|
|
||||||
生成 Autonomous 执行模式的 Action 文件,定义可独立执行的动作单元。
|
Generate Action files for Autonomous execution mode, defining independent executable action units.
|
||||||
|
|
||||||
## Usage Context
|
## Usage Context
|
||||||
|
|
||||||
| Phase | Usage |
|
| Phase | Usage |
|
||||||
|-------|-------|
|
|-------|-------|
|
||||||
| Phase 3 (Phase Generation) | `config.execution_mode === 'autonomous'` 时生成 |
|
| Phase 3 (Phase Generation) | Generated when `config.execution_mode === 'autonomous'` |
|
||||||
| Generation Trigger | 为每个 `config.autonomous_config.actions` 生成一个 action 文件 |
|
| Generation Trigger | Generate one action file for each `config.autonomous_config.actions` |
|
||||||
| Output Location | `.claude/skills/{skill-name}/phases/actions/{action-id}.md` |
|
| Output Location | `.claude/skills/{skill-name}/phases/actions/{action-id}.md` |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 模板结构
|
## Template Structure
|
||||||
|
|
||||||
```markdown
|
```markdown
|
||||||
# Action: {{action_name}}
|
# Action: {{action_name}}
|
||||||
@@ -34,8 +34,8 @@
|
|||||||
## Scripts
|
## Scripts
|
||||||
|
|
||||||
\`\`\`yaml
|
\`\`\`yaml
|
||||||
# 声明本动作使用的脚本(可选)
|
# Declare scripts used in this action (optional)
|
||||||
# - script-id # 对应 scripts/script-id.py 或 .sh
|
# - script-id # Corresponds to scripts/script-id.py or .sh
|
||||||
\`\`\`
|
\`\`\`
|
||||||
|
|
||||||
## Execution
|
## Execution
|
||||||
@@ -44,7 +44,7 @@
|
|||||||
async function execute(state) {
|
async function execute(state) {
|
||||||
{{execution_code}}
|
{{execution_code}}
|
||||||
|
|
||||||
// 调用脚本示例
|
// Script execution example
|
||||||
// const result = await ExecuteScript('script-id', { input: state.context.data });
|
// const result = await ExecuteScript('script-id', { input: state.context.data });
|
||||||
// if (!result.success) throw new Error(result.stderr);
|
// if (!result.success) throw new Error(result.stderr);
|
||||||
}
|
}
|
||||||
@@ -71,63 +71,66 @@ return {
|
|||||||
{{next_actions_hints}}
|
{{next_actions_hints}}
|
||||||
```
|
```
|
||||||
|
|
||||||
## 变量说明
|
## Variable Descriptions
|
||||||
|
|
||||||
| 变量 | 说明 |
|
| Variable | Description |
|
||||||
|------|------|
|
|----------|-------------|
|
||||||
| `{{action_name}}` | 动作名称 |
|
| `{{action_name}}` | Action name |
|
||||||
| `{{action_description}}` | 动作描述 |
|
| `{{action_description}}` | Action description |
|
||||||
| `{{purpose}}` | 详细目的 |
|
| `{{purpose}}` | Detailed purpose |
|
||||||
| `{{preconditions_list}}` | 前置条件列表 |
|
| `{{preconditions_list}}` | List of preconditions |
|
||||||
| `{{execution_code}}` | 执行代码 |
|
| `{{execution_code}}` | Execution code |
|
||||||
| `{{state_updates}}` | 状态更新 |
|
| `{{state_updates}}` | State updates |
|
||||||
| `{{error_handling_table}}` | 错误处理表格 |
|
| `{{error_handling_table}}` | Error handling table |
|
||||||
| `{{next_actions_hints}}` | 后续动作提示 |
|
| `{{next_actions_hints}}` | Next action hints |
|
||||||
|
|
||||||
## 动作生命周期
|
## Action Lifecycle
|
||||||
|
|
||||||
```
|
```
|
||||||
状态驱动执行流:
|
State-driven execution flow:
|
||||||
|
|
||||||
state.status === 'pending'
|
state.status === 'pending'
|
||||||
↓
|
|
|
||||||
┌─ Init ─┐ ← 1次执行,环境准备
|
v
|
||||||
│ 创建工作目录 │
|
+-- Init --+ <- 1 execution, environment preparation
|
||||||
│ 初始化 context │
|
| Create working directory
|
||||||
│ status → running │
|
| Initialize context
|
||||||
└────┬────┘
|
| status -> running
|
||||||
↓
|
+----+----+
|
||||||
┌─ CRUD Loop ─┐ ← N次迭代,核心业务
|
|
|
||||||
│ 编排器选择动作 │ List / Create / Edit / Delete
|
v
|
||||||
│ execute(state) │ 共享模式: 收集输入 → 操作 context.items → 返回更新
|
+-- CRUD Loop --+ <- N iterations, core business
|
||||||
│ 更新 state │
|
| Orchestrator selects action | List / Create / Edit / Delete
|
||||||
└────┬────┘
|
| execute(state) | Shared pattern: collect input -> operate context.items -> return updates
|
||||||
↓
|
| Update state
|
||||||
┌─ Complete ─┐ ← 1次执行,保存结果
|
+----+----+
|
||||||
│ 序列化输出 │
|
|
|
||||||
│ status → completed │
|
v
|
||||||
└──────────┘
|
+-- Complete --+ <- 1 execution, save results
|
||||||
|
| Serialize output
|
||||||
|
| status -> completed
|
||||||
|
+----------+
|
||||||
|
|
||||||
共享状态结构:
|
Shared state structure:
|
||||||
state.status → 'pending' | 'running' | 'completed'
|
state.status -> 'pending' | 'running' | 'completed'
|
||||||
state.context.items → 业务数据数组
|
state.context.items -> Business data array
|
||||||
state.completed_actions → 已执行动作 ID 列表
|
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
|
```markdown
|
||||||
# Action: Initialize
|
# Action: Initialize
|
||||||
|
|
||||||
初始化 Skill 执行状态。
|
Initialize Skill execution state.
|
||||||
|
|
||||||
## Purpose
|
## Purpose
|
||||||
|
|
||||||
设置初始状态,准备执行环境。
|
Set initial state, prepare execution environment.
|
||||||
|
|
||||||
## Preconditions
|
## Preconditions
|
||||||
|
|
||||||
@@ -151,24 +154,24 @@ async function execute(state) {
|
|||||||
|
|
||||||
## Next Actions
|
## Next Actions
|
||||||
|
|
||||||
- 成功: 进入主处理循环 (由编排器选择首个 CRUD 动作)
|
- Success: Enter main processing loop (Orchestrator selects first CRUD action)
|
||||||
- 失败: action-abort
|
- 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
|
```markdown
|
||||||
# Action: Create Item
|
# Action: Create Item
|
||||||
|
|
||||||
创建新项目。
|
Create new item.
|
||||||
|
|
||||||
## Purpose
|
## Purpose
|
||||||
|
|
||||||
收集用户输入,向 context.items 追加新记录。
|
Collect user input, append new record to context.items.
|
||||||
|
|
||||||
## Preconditions
|
## Preconditions
|
||||||
|
|
||||||
@@ -178,25 +181,25 @@ async function execute(state) {
|
|||||||
|
|
||||||
\`\`\`javascript
|
\`\`\`javascript
|
||||||
async function execute(state) {
|
async function execute(state) {
|
||||||
// 1. 收集输入
|
// 1. Collect input
|
||||||
const input = await AskUserQuestion({
|
const input = await AskUserQuestion({
|
||||||
questions: [{
|
questions: [{
|
||||||
question: "请输入项目名称:",
|
question: "Please enter item name:",
|
||||||
header: "名称",
|
header: "Name",
|
||||||
multiSelect: false,
|
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 = {
|
const newItem = {
|
||||||
id: Date.now().toString(),
|
id: Date.now().toString(),
|
||||||
name: input["名称"],
|
name: input["Name"],
|
||||||
status: 'pending',
|
status: 'pending',
|
||||||
created_at: new Date().toISOString()
|
created_at: new Date().toISOString()
|
||||||
};
|
};
|
||||||
|
|
||||||
// 3. 返回状态更新
|
// 3. Return state update
|
||||||
return {
|
return {
|
||||||
stateUpdates: {
|
stateUpdates: {
|
||||||
context: {
|
context: {
|
||||||
@@ -211,31 +214,31 @@ async function execute(state) {
|
|||||||
|
|
||||||
## Next Actions
|
## Next Actions
|
||||||
|
|
||||||
- 继续操作: 编排器根据 state 选择下一动作
|
- Continue operations: Orchestrator selects next action based on state
|
||||||
- 用户退出: action-complete
|
- User exit: action-complete
|
||||||
```
|
```
|
||||||
|
|
||||||
**其他 CRUD 动作差异对照:**
|
**Other CRUD Actions Differences:**
|
||||||
|
|
||||||
| 动作 | 核心逻辑 | 额外前置条件 | 关键状态字段 |
|
| Action | Core Logic | Extra Preconditions | Key State Field |
|
||||||
|------|---------|------------|------------|
|
|--------|-----------|-------------------|-----------------|
|
||||||
| List | `items.forEach(→ console.log)` | 无 | `current_view: 'list'` |
|
| List | `items.forEach(-> console.log)` | None | `current_view: 'list'` |
|
||||||
| Create | `items.push(newItem)` | 无 | `last_created_id` |
|
| Create | `items.push(newItem)` | None | `last_created_id` |
|
||||||
| Edit | `items.map(→ 替换匹配项)` | `selected_item_id !== null` | `updated_at` |
|
| Edit | `items.map(-> replace matching)` | `selected_item_id !== null` | `updated_at` |
|
||||||
| Delete | `items.filter(→ 排除匹配项)` | `selected_item_id !== null` | 确认对话 → 执行 |
|
| 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
|
```markdown
|
||||||
# Action: Complete
|
# Action: Complete
|
||||||
|
|
||||||
完成任务并退出。
|
Complete task and exit.
|
||||||
|
|
||||||
## Purpose
|
## Purpose
|
||||||
|
|
||||||
序列化最终状态,结束 Skill 执行。
|
Serialize final state, end Skill execution.
|
||||||
|
|
||||||
## Preconditions
|
## Preconditions
|
||||||
|
|
||||||
@@ -253,7 +256,7 @@ async function execute(state) {
|
|||||||
actions_executed: state.completed_actions.length
|
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 {
|
return {
|
||||||
stateUpdates: {
|
stateUpdates: {
|
||||||
@@ -267,30 +270,30 @@ async function execute(state) {
|
|||||||
|
|
||||||
## Next Actions
|
## Next Actions
|
||||||
|
|
||||||
- 无(终止状态)
|
- None (terminal state)
|
||||||
```
|
```
|
||||||
|
|
||||||
## 生成函数
|
## Generation Function
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
function generateAction(actionConfig, skillConfig) {
|
function generateAction(actionConfig, skillConfig) {
|
||||||
return `# Action: ${actionConfig.name}
|
return `# Action: ${actionConfig.name}
|
||||||
|
|
||||||
${actionConfig.description || `执行 ${actionConfig.name} 操作`}
|
${actionConfig.description || `Execute ${actionConfig.name} operation`}
|
||||||
|
|
||||||
## Purpose
|
## Purpose
|
||||||
|
|
||||||
${actionConfig.purpose || 'TODO: 描述此动作的详细目的'}
|
${actionConfig.purpose || 'TODO: Describe detailed purpose of this action'}
|
||||||
|
|
||||||
## Preconditions
|
## Preconditions
|
||||||
|
|
||||||
${actionConfig.preconditions?.map(p => `- [ ] ${p}`).join('\n') || '- [ ] 无特殊前置条件'}
|
${actionConfig.preconditions?.map(p => `- [ ] ${p}`).join('\n') || '- [ ] No special preconditions'}
|
||||||
|
|
||||||
## Execution
|
## Execution
|
||||||
|
|
||||||
\`\`\`javascript
|
\`\`\`javascript
|
||||||
async function execute(state) {
|
async function execute(state) {
|
||||||
// TODO: 实现动作逻辑
|
// TODO: Implement action logic
|
||||||
|
|
||||||
return {
|
return {
|
||||||
stateUpdates: {
|
stateUpdates: {
|
||||||
@@ -305,7 +308,7 @@ async function execute(state) {
|
|||||||
\`\`\`javascript
|
\`\`\`javascript
|
||||||
return {
|
return {
|
||||||
stateUpdates: {
|
stateUpdates: {
|
||||||
// TODO: 定义状态更新
|
// TODO: Define state updates
|
||||||
${actionConfig.effects?.map(e => ` // Effect: ${e}`).join('\n') || ''}
|
${actionConfig.effects?.map(e => ` // Effect: ${e}`).join('\n') || ''}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -315,13 +318,13 @@ ${actionConfig.effects?.map(e => ` // Effect: ${e}`).join('\n') || ''}
|
|||||||
|
|
||||||
| Error Type | Recovery |
|
| Error Type | Recovery |
|
||||||
|------------|----------|
|
|------------|----------|
|
||||||
| 数据验证失败 | 返回错误,不更新状态 |
|
| Data validation failed | Return error, no state update |
|
||||||
| 执行异常 | 记录错误,增加 error_count |
|
| Execution exception | Log error, increment error_count |
|
||||||
|
|
||||||
## Next Actions (Hints)
|
## Next Actions (Hints)
|
||||||
|
|
||||||
- 成功: 由编排器根据状态决定
|
- Success: Orchestrator decides based on state
|
||||||
- 失败: 重试或 action-abort
|
- Failure: Retry or action-abort
|
||||||
`;
|
`;
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|||||||
@@ -1,59 +1,59 @@
|
|||||||
# Autonomous Orchestrator Template
|
# Autonomous Orchestrator Template
|
||||||
|
|
||||||
自主模式编排器的模板。
|
Template for orchestrator file in Autonomous execution mode.
|
||||||
|
|
||||||
## Purpose
|
## Purpose
|
||||||
|
|
||||||
生成 Autonomous 执行模式的 Orchestrator 文件,负责状态驱动的动作选择和执行循环。
|
Generate Orchestrator file for Autonomous execution mode, responsible for state-driven action selection and execution loop.
|
||||||
|
|
||||||
## Usage Context
|
## Usage Context
|
||||||
|
|
||||||
| Phase | Usage |
|
| Phase | Usage |
|
||||||
|-------|-------|
|
|-------|-------|
|
||||||
| Phase 3 (Phase Generation) | `config.execution_mode === 'autonomous'` 时生成 |
|
| Phase 3 (Phase Generation) | Generated when `config.execution_mode === 'autonomous'` |
|
||||||
| Generation Trigger | 创建编排器逻辑,管理动作选择和状态更新 |
|
| Generation Trigger | Create orchestrator logic to manage action selection and state updates |
|
||||||
| Output Location | `.claude/skills/{skill-name}/phases/orchestrator.md` |
|
| 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 时,需要确保:
|
> When generating Orchestrator, ensure:
|
||||||
> 1. SKILL.md 中已包含 Phase 0 规范研读步骤
|
> 1. Phase 0 specification review step is included in SKILL.md
|
||||||
> 2. Orchestrator 启动前验证规范已阅读
|
> 2. Orchestrator validates specification has been reviewed before starting execution loop
|
||||||
> 3. 所有 Action 文件都引用相关的规范文档
|
> 3. All Action files reference related specification documents
|
||||||
> 4. Architecture Overview 中 Phase 0 位于 Orchestrator 之前
|
> 4. Architecture Overview places Phase 0 before Orchestrator
|
||||||
|
|
||||||
## 模板结构
|
## Template Structure
|
||||||
|
|
||||||
```markdown
|
```markdown
|
||||||
# Orchestrator
|
# Orchestrator
|
||||||
|
|
||||||
## Role
|
## Role
|
||||||
|
|
||||||
根据当前状态选择并执行下一个动作。
|
Select and execute next action based on current state.
|
||||||
|
|
||||||
## State Management
|
## State Management
|
||||||
|
|
||||||
### 读取状态
|
### Read State
|
||||||
|
|
||||||
\`\`\`javascript
|
\`\`\`javascript
|
||||||
const state = JSON.parse(Read(`${workDir}/state.json`));
|
const state = JSON.parse(Read(\`${workDir}/state.json\`));
|
||||||
\`\`\`
|
\`\`\`
|
||||||
|
|
||||||
### 更新状态
|
### Update State
|
||||||
|
|
||||||
\`\`\`javascript
|
\`\`\`javascript
|
||||||
function updateState(updates) {
|
function updateState(updates) {
|
||||||
const state = JSON.parse(Read(`${workDir}/state.json`));
|
const state = JSON.parse(Read(\`${workDir}/state.json\`));
|
||||||
const newState = {
|
const newState = {
|
||||||
...state,
|
...state,
|
||||||
...updates,
|
...updates,
|
||||||
updated_at: new Date().toISOString()
|
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;
|
return newState;
|
||||||
}
|
}
|
||||||
\`\`\`
|
\`\`\`
|
||||||
@@ -62,18 +62,18 @@ function updateState(updates) {
|
|||||||
|
|
||||||
\`\`\`javascript
|
\`\`\`javascript
|
||||||
function selectNextAction(state) {
|
function selectNextAction(state) {
|
||||||
// 1. 终止条件检查
|
// 1. Check termination conditions
|
||||||
{{termination_checks}}
|
{{termination_checks}}
|
||||||
|
|
||||||
// 2. 错误限制检查
|
// 2. Check error limit
|
||||||
if (state.error_count >= 3) {
|
if (state.error_count >= 3) {
|
||||||
return 'action-abort';
|
return 'action-abort';
|
||||||
}
|
}
|
||||||
|
|
||||||
// 3. 动作选择逻辑
|
// 3. Action selection logic
|
||||||
{{action_selection_logic}}
|
{{action_selection_logic}}
|
||||||
|
|
||||||
// 4. 默认完成
|
// 4. Default completion
|
||||||
return 'action-complete';
|
return 'action-complete';
|
||||||
}
|
}
|
||||||
\`\`\`
|
\`\`\`
|
||||||
@@ -90,11 +90,11 @@ async function runOrchestrator() {
|
|||||||
while (iteration < MAX_ITERATIONS) {
|
while (iteration < MAX_ITERATIONS) {
|
||||||
iteration++;
|
iteration++;
|
||||||
|
|
||||||
// 1. 读取当前状态
|
// 1. Read current state
|
||||||
const state = JSON.parse(Read(`${workDir}/state.json`));
|
const state = JSON.parse(Read(\`${workDir}/state.json\`));
|
||||||
console.log(`[Iteration ${iteration}] Status: ${state.status}`);
|
console.log(\`[Iteration ${iteration}] Status: ${state.status}\`);
|
||||||
|
|
||||||
// 2. 选择下一个动作
|
// 2. Select next action
|
||||||
const actionId = selectNextAction(state);
|
const actionId = selectNextAction(state);
|
||||||
|
|
||||||
if (!actionId) {
|
if (!actionId) {
|
||||||
@@ -102,14 +102,14 @@ async function runOrchestrator() {
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log(`[Iteration ${iteration}] Executing: ${actionId}`);
|
console.log(\`[Iteration ${iteration}] Executing: ${actionId}\`);
|
||||||
|
|
||||||
// 3. 更新状态:当前动作
|
// 3. Update state: current action
|
||||||
updateState({ current_action: actionId });
|
updateState({ current_action: actionId });
|
||||||
|
|
||||||
// 4. 执行动作
|
// 4. Execute action
|
||||||
try {
|
try {
|
||||||
const actionPrompt = Read(`phases/actions/${actionId}.md`);
|
const actionPrompt = Read(\`phases/actions/${actionId}.md\`);
|
||||||
|
|
||||||
const result = await Task({
|
const result = await Task({
|
||||||
subagent_type: 'universal-executor',
|
subagent_type: 'universal-executor',
|
||||||
@@ -128,7 +128,7 @@ Return JSON with stateUpdates field.
|
|||||||
|
|
||||||
const actionResult = JSON.parse(result);
|
const actionResult = JSON.parse(result);
|
||||||
|
|
||||||
// 5. 更新状态:动作完成
|
// 5. Update state: action completed
|
||||||
updateState({
|
updateState({
|
||||||
current_action: null,
|
current_action: null,
|
||||||
completed_actions: [...state.completed_actions, actionId],
|
completed_actions: [...state.completed_actions, actionId],
|
||||||
@@ -136,7 +136,7 @@ Return JSON with stateUpdates field.
|
|||||||
});
|
});
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// 错误处理
|
// Error handling
|
||||||
updateState({
|
updateState({
|
||||||
current_action: null,
|
current_action: null,
|
||||||
errors: [...state.errors, {
|
errors: [...state.errors, {
|
||||||
@@ -167,28 +167,28 @@ Return JSON with stateUpdates field.
|
|||||||
|
|
||||||
| Error Type | Recovery Strategy |
|
| 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
|
||||||
|
|
||||||
| 变量 | 说明 |
|
| Variable | Description |
|
||||||
|------|------|
|
|----------|-------------|
|
||||||
| `{{termination_checks}}` | 终止条件检查代码 |
|
| `{{termination_checks}}` | Termination condition check code |
|
||||||
| `{{action_selection_logic}}` | 动作选择逻辑代码 |
|
| `{{action_selection_logic}}` | Action selection logic code |
|
||||||
| `{{action_catalog_table}}` | 动作目录表格 |
|
| `{{action_catalog_table}}` | Action directory table |
|
||||||
| `{{termination_conditions_list}}` | 终止条件列表 |
|
| `{{termination_conditions_list}}` | List of termination conditions |
|
||||||
|
|
||||||
## 生成函数
|
## Generation Function
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
function generateOrchestrator(config) {
|
function generateOrchestrator(config) {
|
||||||
const actions = config.autonomous_config.actions;
|
const actions = config.autonomous_config.actions;
|
||||||
const terminations = config.autonomous_config.termination_conditions || [];
|
const terminations = config.autonomous_config.termination_conditions || [];
|
||||||
|
|
||||||
// 生成终止条件检查
|
// Generate termination checks
|
||||||
const terminationChecks = terminations.map(t => {
|
const terminationChecks = terminations.map(t => {
|
||||||
const checks = {
|
const checks = {
|
||||||
'user_exit': 'if (state.status === "user_exit") return null;',
|
'user_exit': 'if (state.status === "user_exit") return null;',
|
||||||
@@ -199,21 +199,21 @@ function generateOrchestrator(config) {
|
|||||||
return checks[t] || `if (state.${t}) return null;`;
|
return checks[t] || `if (state.${t}) return null;`;
|
||||||
}).join('\n ');
|
}).join('\n ');
|
||||||
|
|
||||||
// 生成动作选择逻辑
|
// Generate action selection logic
|
||||||
const actionSelectionLogic = actions.map(action => {
|
const actionSelectionLogic = actions.map(action => {
|
||||||
if (!action.preconditions?.length) {
|
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(' && ');
|
const conditions = action.preconditions.map(p => `state.${p}`).join(' && ');
|
||||||
return `if (${conditions}) return '${action.id}';`;
|
return `if (${conditions}) return '${action.id}';`;
|
||||||
}).join('\n ');
|
}).join('\n ');
|
||||||
|
|
||||||
// 生成动作目录表格
|
// Generate action catalog table
|
||||||
const actionCatalogTable = actions.map(a =>
|
const actionCatalogTable = actions.map(a =>
|
||||||
`| [${a.id}](actions/${a.id}.md) | ${a.description || a.name} | ${a.preconditions?.join(', ') || '-'} |`
|
`| [${a.id}](actions/${a.id}.md) | ${a.description || a.name} | ${a.preconditions?.join(', ') || '-'} |`
|
||||||
).join('\n');
|
).join('\n');
|
||||||
|
|
||||||
// 生成终止条件列表
|
// Generate termination conditions list
|
||||||
const terminationConditionsList = terminations.map(t => `- ${t}`).join('\n');
|
const terminationConditionsList = terminations.map(t => `- ${t}`).join('\n');
|
||||||
|
|
||||||
return template
|
return template
|
||||||
@@ -224,11 +224,11 @@ function generateOrchestrator(config) {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
## 编排策略
|
## Orchestration Strategies
|
||||||
|
|
||||||
### 1. 优先级策略
|
### 1. Priority Strategy
|
||||||
|
|
||||||
按预定义优先级选择动作:
|
Select action by predefined priority:
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
const PRIORITY = ['action-init', 'action-process', 'action-review', 'action-complete'];
|
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
|
```javascript
|
||||||
async function selectByUser(state, availableActions) {
|
async function selectByUser(state, availableActions) {
|
||||||
const response = await AskUserQuestion({
|
const response = await AskUserQuestion({
|
||||||
questions: [{
|
questions: [{
|
||||||
question: "选择下一个操作:",
|
question: "Select next operation:",
|
||||||
header: "操作",
|
header: "Operations",
|
||||||
multiSelect: false,
|
multiSelect: false,
|
||||||
options: availableActions.map(a => ({
|
options: availableActions.map(a => ({
|
||||||
label: a.name,
|
label: a.name,
|
||||||
@@ -261,31 +261,31 @@ 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
|
```javascript
|
||||||
function selectByState(state) {
|
function selectByState(state) {
|
||||||
// 初始化
|
// Initialization
|
||||||
if (state.status === 'pending') return 'action-init';
|
if (state.status === 'pending') return 'action-init';
|
||||||
|
|
||||||
// 有待处理项
|
// Has pending items
|
||||||
if (state.pending_items?.length > 0) return 'action-process';
|
if (state.pending_items?.length > 0) return 'action-process';
|
||||||
|
|
||||||
// 需要审核
|
// Needs review
|
||||||
if (state.needs_review) return 'action-review';
|
if (state.needs_review) return 'action-review';
|
||||||
|
|
||||||
// 完成
|
// Completed
|
||||||
return 'action-complete';
|
return 'action-complete';
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
## 状态机示例
|
## State Machine Example
|
||||||
|
|
||||||
```mermaid
|
```mermaid
|
||||||
stateDiagram-v2
|
stateDiagram-v2
|
||||||
|
|||||||
@@ -1,59 +1,59 @@
|
|||||||
# Code Analysis Action Template
|
# Code Analysis Action Template
|
||||||
|
|
||||||
代码分析动作模板,用于在 Skill 中集成代码探索和分析能力。
|
Code analysis action template for integrating code exploration and analysis capabilities into a Skill.
|
||||||
|
|
||||||
## Purpose
|
## 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
|
## Usage Context
|
||||||
|
|
||||||
| Phase | Usage |
|
| Phase | Usage |
|
||||||
|-------|-------|
|
|-------|-------|
|
||||||
| Optional | 当 Skill 需要代码探索和分析能力时使用 |
|
| Optional | Use when Skill requires code exploration and analysis capabilities |
|
||||||
| Generation Trigger | 用户选择添加 code-analysis 动作类型 |
|
| Generation Trigger | User selects to add code-analysis action type |
|
||||||
| Agent Types | Explore, cli-explore-agent, universal-executor |
|
| Agent Types | Explore, cli-explore-agent, universal-executor |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 配置结构
|
## Configuration Structure
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
interface CodeAnalysisActionConfig {
|
interface CodeAnalysisActionConfig {
|
||||||
id: string; // "analyze-structure", "explore-patterns"
|
id: string; // "analyze-structure", "explore-patterns"
|
||||||
name: string; // "Code Structure Analysis"
|
name: string; // "Code Structure Analysis"
|
||||||
type: 'code-analysis'; // 动作类型标识
|
type: 'code-analysis'; // Action type identifier
|
||||||
|
|
||||||
// 分析范围
|
// Analysis scope
|
||||||
scope: {
|
scope: {
|
||||||
paths: string[]; // 目标路径
|
paths: string[]; // Target paths
|
||||||
patterns: string[]; // Glob 模式
|
patterns: string[]; // Glob patterns
|
||||||
excludes?: string[]; // 排除模式
|
excludes?: string[]; // Exclude patterns
|
||||||
};
|
};
|
||||||
|
|
||||||
// 分析类型
|
// Analysis type
|
||||||
analysis_type: 'structure' | 'patterns' | 'dependencies' | 'quality' | 'security';
|
analysis_type: 'structure' | 'patterns' | 'dependencies' | 'quality' | 'security';
|
||||||
|
|
||||||
// Agent 配置
|
// Agent config
|
||||||
agent: {
|
agent: {
|
||||||
type: 'Explore' | 'cli-explore-agent' | 'universal-executor';
|
type: 'Explore' | 'cli-explore-agent' | 'universal-executor';
|
||||||
thoroughness: 'quick' | 'medium' | 'very thorough';
|
thoroughness: 'quick' | 'medium' | 'very thorough';
|
||||||
};
|
};
|
||||||
|
|
||||||
// 输出配置
|
// Output config
|
||||||
output: {
|
output: {
|
||||||
format: 'json' | 'markdown';
|
format: 'json' | 'markdown';
|
||||||
file: string;
|
file: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
// MCP 工具增强
|
// MCP tool enhancement
|
||||||
mcp_tools?: string[]; // ['mcp__ace-tool__search_context']
|
mcp_tools?: string[]; // ['mcp__ace-tool__search_context']
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 模板生成函数
|
## Template Generation Function
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
function generateCodeAnalysisAction(config) {
|
function generateCodeAnalysisAction(config) {
|
||||||
@@ -64,20 +64,20 @@ function generateCodeAnalysisAction(config) {
|
|||||||
|
|
||||||
## Action: ${id}
|
## Action: ${id}
|
||||||
|
|
||||||
### 分析范围
|
### Analysis Scope
|
||||||
|
|
||||||
- **路径**: ${scope.paths.join(', ')}
|
- **Paths**: ${scope.paths.join(', ')}
|
||||||
- **模式**: ${scope.patterns.join(', ')}
|
- **Patterns**: ${scope.patterns.join(', ')}
|
||||||
${scope.excludes ? `- **排除**: ${scope.excludes.join(', ')}` : ''}
|
${scope.excludes ? `- **Excludes**: ${scope.excludes.join(', ')}` : ''}
|
||||||
|
|
||||||
### 执行逻辑
|
### Execution Logic
|
||||||
|
|
||||||
\`\`\`javascript
|
\`\`\`javascript
|
||||||
async function execute${toPascalCase(id)}(context) {
|
async function execute${toPascalCase(id)}(context) {
|
||||||
const workDir = context.workDir;
|
const workDir = context.workDir;
|
||||||
const results = [];
|
const results = [];
|
||||||
|
|
||||||
// 1. 文件发现
|
// 1. File discovery
|
||||||
const files = await discoverFiles({
|
const files = await discoverFiles({
|
||||||
paths: ${JSON.stringify(scope.paths)},
|
paths: ${JSON.stringify(scope.paths)},
|
||||||
patterns: ${JSON.stringify(scope.patterns)},
|
patterns: ${JSON.stringify(scope.patterns)},
|
||||||
@@ -86,34 +86,34 @@ async function execute${toPascalCase(id)}(context) {
|
|||||||
|
|
||||||
console.log(\`Found \${files.length} files to analyze\`);
|
console.log(\`Found \${files.length} files to analyze\`);
|
||||||
|
|
||||||
// 2. 使用 MCP 工具进行语义搜索(如果配置)
|
// 2. Semantic search using MCP tools (if configured)
|
||||||
${mcp_tools.length > 0 ? `
|
${mcp_tools.length > 0 ? \`
|
||||||
const semanticResults = await mcp__ace_tool__search_context({
|
const semanticResults = await mcp__ace_tool__search_context({
|
||||||
project_root_path: context.projectRoot,
|
project_root_path: context.projectRoot,
|
||||||
query: '${getQueryForAnalysisType(analysis_type)}'
|
query: '\${getQueryForAnalysisType(analysis_type)}'
|
||||||
});
|
});
|
||||||
results.push({ type: 'semantic', data: semanticResults });
|
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({
|
const agentResult = await Task({
|
||||||
subagent_type: '${agent.type}',
|
subagent_type: '\${agent.type}',
|
||||||
prompt: \`
|
prompt: \`
|
||||||
${generateAgentPrompt(analysis_type, scope)}
|
\${generateAgentPrompt(analysis_type, scope)}
|
||||||
\`,
|
\`,
|
||||||
run_in_background: false
|
run_in_background: false
|
||||||
});
|
});
|
||||||
|
|
||||||
results.push({ type: 'agent', data: agentResult });
|
results.push({ type: 'agent', data: agentResult });
|
||||||
|
|
||||||
// 4. 汇总结果
|
// 4. Aggregate results
|
||||||
const summary = aggregateResults(results);
|
const summary = aggregateResults(results);
|
||||||
|
|
||||||
// 5. 输出结果
|
// 5. Output results
|
||||||
const outputPath = \`\${workDir}/${output.file}\`;
|
const outputPath = \`\${workDir}/${output.file}\`;
|
||||||
${output.format === 'json'
|
${output.format === 'json'
|
||||||
? `Write(outputPath, JSON.stringify(summary, null, 2));`
|
? \`Write(outputPath, JSON.stringify(summary, null, 2));\`
|
||||||
: `Write(outputPath, formatAsMarkdown(summary));`}
|
: \`Write(outputPath, formatAsMarkdown(summary));\`}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
@@ -122,8 +122,7 @@ ${generateAgentPrompt(analysis_type, scope)}
|
|||||||
analysis_type: '${analysis_type}'
|
analysis_type: '${analysis_type}'
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
\`\`\`
|
\`\`\`;
|
||||||
`;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function getQueryForAnalysisType(type) {
|
function getQueryForAnalysisType(type) {
|
||||||
@@ -139,101 +138,101 @@ function getQueryForAnalysisType(type) {
|
|||||||
|
|
||||||
function generateAgentPrompt(type, scope) {
|
function generateAgentPrompt(type, scope) {
|
||||||
const prompts = {
|
const prompts = {
|
||||||
structure: `分析以下路径的代码结构:
|
structure: \`Analyze code structure of the following paths:
|
||||||
${scope.paths.map(p => `- ${p}`).join('\\n')}
|
\${scope.paths.map(p => \`- \${p}\`).join('\\n')}
|
||||||
|
|
||||||
任务:
|
Tasks:
|
||||||
1. 识别主要模块和入口点
|
1. Identify main modules and entry points
|
||||||
2. 分析目录组织结构
|
2. Analyze directory organization structure
|
||||||
3. 提取模块间的导入导出关系
|
3. Extract module import/export relationships
|
||||||
4. 生成结构概览图 (Mermaid)
|
4. Generate structure overview diagram (Mermaid)
|
||||||
|
|
||||||
输出格式: JSON
|
Output format: JSON
|
||||||
{
|
{
|
||||||
"modules": [...],
|
"modules": [...],
|
||||||
"entry_points": [...],
|
"entry_points": [...],
|
||||||
"structure_diagram": "mermaid code"
|
"structure_diagram": "mermaid code"
|
||||||
}`,
|
}\`,
|
||||||
|
|
||||||
patterns: `分析以下路径的设计模式:
|
patterns: \`Analyze design patterns in the following paths:
|
||||||
${scope.paths.map(p => `- ${p}`).join('\\n')}
|
\${scope.paths.map(p => \`- \${p}\`).join('\\n')}
|
||||||
|
|
||||||
任务:
|
Tasks:
|
||||||
1. 识别使用的设计模式 (Factory, Strategy, Observer 等)
|
1. Identify design patterns used (Factory, Strategy, Observer, etc.)
|
||||||
2. 分析抽象层级
|
2. Analyze abstraction levels
|
||||||
3. 评估模式使用的恰当性
|
3. Evaluate appropriateness of pattern usage
|
||||||
4. 提取可复用的模式实例
|
4. Extract reusable pattern instances
|
||||||
|
|
||||||
输出格式: JSON
|
Output format: JSON
|
||||||
{
|
{
|
||||||
"patterns": [{ "name": "...", "location": "...", "usage": "..." }],
|
"patterns": [{ "name": "...", "location": "...", "usage": "..." }],
|
||||||
"abstractions": [...],
|
"abstractions": [...],
|
||||||
"reusable_components": [...]
|
"reusable_components": [...]
|
||||||
}`,
|
}\`,
|
||||||
|
|
||||||
dependencies: `分析以下路径的依赖关系:
|
dependencies: \`Analyze dependencies in the following paths:
|
||||||
${scope.paths.map(p => `- ${p}`).join('\\n')}
|
\${scope.paths.map(p => \`- \${p}\`).join('\\n')}
|
||||||
|
|
||||||
任务:
|
Tasks:
|
||||||
1. 提取内部模块依赖
|
1. Extract internal module dependencies
|
||||||
2. 识别外部包依赖
|
2. Identify external package dependencies
|
||||||
3. 分析耦合度
|
3. Analyze coupling degree
|
||||||
4. 检测循环依赖
|
4. Detect circular dependencies
|
||||||
|
|
||||||
输出格式: JSON
|
Output format: JSON
|
||||||
{
|
{
|
||||||
"internal_deps": [...],
|
"internal_deps": [...],
|
||||||
"external_deps": [...],
|
"external_deps": [...],
|
||||||
"coupling_score": 0-100,
|
"coupling_score": 0-100,
|
||||||
"circular_deps": [...]
|
"circular_deps": [...]
|
||||||
}`,
|
}\`,
|
||||||
|
|
||||||
quality: `分析以下路径的代码质量:
|
quality: \`Analyze code quality in the following paths:
|
||||||
${scope.paths.map(p => `- ${p}`).join('\\n')}
|
\${scope.paths.map(p => \`- \${p}\`).join('\\n')}
|
||||||
|
|
||||||
任务:
|
Tasks:
|
||||||
1. 评估代码复杂度
|
1. Assess code complexity
|
||||||
2. 检查测试覆盖率
|
2. Check test coverage
|
||||||
3. 分析文档完整性
|
3. Analyze documentation completeness
|
||||||
4. 识别技术债务
|
4. Identify technical debt
|
||||||
|
|
||||||
输出格式: JSON
|
Output format: JSON
|
||||||
{
|
{
|
||||||
"complexity": { "avg": 0, "max": 0, "hotspots": [...] },
|
"complexity": { "avg": 0, "max": 0, "hotspots": [...] },
|
||||||
"test_coverage": { "percentage": 0, "gaps": [...] },
|
"test_coverage": { "percentage": 0, "gaps": [...] },
|
||||||
"documentation": { "score": 0, "missing": [...] },
|
"documentation": { "score": 0, "missing": [...] },
|
||||||
"tech_debt": [...]
|
"tech_debt": [...]
|
||||||
}`,
|
}\`,
|
||||||
|
|
||||||
security: `分析以下路径的安全性:
|
security: \`Analyze security in the following paths:
|
||||||
${scope.paths.map(p => `- ${p}`).join('\\n')}
|
\${scope.paths.map(p => \`- \${p}\`).join('\\n')}
|
||||||
|
|
||||||
任务:
|
Tasks:
|
||||||
1. 检查认证授权实现
|
1. Check authentication/authorization implementation
|
||||||
2. 分析输入验证
|
2. Analyze input validation
|
||||||
3. 检测敏感数据处理
|
3. Detect sensitive data handling
|
||||||
4. 识别常见漏洞模式
|
4. Identify common vulnerability patterns
|
||||||
|
|
||||||
输出格式: JSON
|
Output format: JSON
|
||||||
{
|
{
|
||||||
"auth": { "methods": [...], "issues": [...] },
|
"auth": { "methods": [...], "issues": [...] },
|
||||||
"input_validation": { "coverage": 0, "gaps": [...] },
|
"input_validation": { "coverage": 0, "gaps": [...] },
|
||||||
"sensitive_data": { "found": [...], "protected": true/false },
|
"sensitive_data": { "found": [...], "protected": true/false },
|
||||||
"vulnerabilities": [{ "type": "...", "severity": "...", "location": "..." }]
|
"vulnerabilities": [{ "type": "...", "severity": "...", "location": "..." }]
|
||||||
}`
|
}\`
|
||||||
};
|
};
|
||||||
|
|
||||||
return prompts[type] || prompts.structure;
|
return prompts[type] || prompts.structure;
|
||||||
}
|
}
|
||||||
```
|
\`\`\`
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 预置代码分析动作
|
## Preset Code Analysis Actions
|
||||||
|
|
||||||
### 1. 项目结构分析
|
### 1. Project Structure Analysis
|
||||||
|
|
||||||
```yaml
|
\`\`\`yaml
|
||||||
id: analyze-project-structure
|
id: analyze-project-structure
|
||||||
name: Project Structure Analysis
|
name: Project Structure Analysis
|
||||||
type: code-analysis
|
type: code-analysis
|
||||||
@@ -255,11 +254,11 @@ output:
|
|||||||
file: structure-analysis.json
|
file: structure-analysis.json
|
||||||
mcp_tools:
|
mcp_tools:
|
||||||
- mcp__ace-tool__search_context
|
- mcp__ace-tool__search_context
|
||||||
```
|
\`\`\`
|
||||||
|
|
||||||
### 2. 设计模式提取
|
### 2. Design Pattern Extraction
|
||||||
|
|
||||||
```yaml
|
\`\`\`yaml
|
||||||
id: extract-design-patterns
|
id: extract-design-patterns
|
||||||
name: Design Pattern Extraction
|
name: Design Pattern Extraction
|
||||||
type: code-analysis
|
type: code-analysis
|
||||||
@@ -275,11 +274,11 @@ agent:
|
|||||||
output:
|
output:
|
||||||
format: markdown
|
format: markdown
|
||||||
file: patterns-report.md
|
file: patterns-report.md
|
||||||
```
|
\`\`\`
|
||||||
|
|
||||||
### 3. 依赖关系分析
|
### 3. Dependency Analysis
|
||||||
|
|
||||||
```yaml
|
\`\`\`yaml
|
||||||
id: analyze-dependencies
|
id: analyze-dependencies
|
||||||
name: Dependency Analysis
|
name: Dependency Analysis
|
||||||
type: code-analysis
|
type: code-analysis
|
||||||
@@ -297,11 +296,11 @@ agent:
|
|||||||
output:
|
output:
|
||||||
format: json
|
format: json
|
||||||
file: dependency-graph.json
|
file: dependency-graph.json
|
||||||
```
|
\`\`\`
|
||||||
|
|
||||||
### 4. 安全审计
|
### 4. Security Audit
|
||||||
|
|
||||||
```yaml
|
\`\`\`yaml
|
||||||
id: security-audit
|
id: security-audit
|
||||||
name: Security Audit
|
name: Security Audit
|
||||||
type: code-analysis
|
type: code-analysis
|
||||||
@@ -320,15 +319,15 @@ output:
|
|||||||
file: security-report.json
|
file: security-report.json
|
||||||
mcp_tools:
|
mcp_tools:
|
||||||
- mcp__ace-tool__search_context
|
- mcp__ace-tool__search_context
|
||||||
```
|
\`\`\`
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 使用示例
|
## Usage Examples
|
||||||
|
|
||||||
### 在 Phase 中使用
|
### Using in Phase
|
||||||
|
|
||||||
```javascript
|
\`\`\`javascript
|
||||||
// phases/01-code-exploration.md
|
// phases/01-code-exploration.md
|
||||||
|
|
||||||
const analysisConfig = {
|
const analysisConfig = {
|
||||||
@@ -351,14 +350,14 @@ const analysisConfig = {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// 执行
|
// Execute
|
||||||
const result = await executeCodeAnalysis(analysisConfig, context);
|
const result = await executeCodeAnalysis(analysisConfig, context);
|
||||||
```
|
\`\`\`
|
||||||
|
|
||||||
### 组合多种分析
|
### Combining Multiple Analyses
|
||||||
|
|
||||||
```javascript
|
\`\`\`javascript
|
||||||
// 串行执行多种分析
|
// Serial execution of multiple analyses
|
||||||
const analyses = [
|
const analyses = [
|
||||||
{ type: 'structure', file: 'structure.json' },
|
{ type: 'structure', file: 'structure.json' },
|
||||||
{ type: 'patterns', file: 'patterns.json' },
|
{ type: 'patterns', file: 'patterns.json' },
|
||||||
@@ -373,7 +372,7 @@ for (const analysis of analyses) {
|
|||||||
}, context);
|
}, context);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 并行执行(独立分析)
|
// Parallel execution (independent analyses)
|
||||||
const parallelResults = await Promise.all(
|
const parallelResults = await Promise.all(
|
||||||
analyses.map(a => executeCodeAnalysis({
|
analyses.map(a => executeCodeAnalysis({
|
||||||
...baseConfig,
|
...baseConfig,
|
||||||
@@ -381,51 +380,51 @@ const parallelResults = await Promise.all(
|
|||||||
output: { format: 'json', file: a.file }
|
output: { format: 'json', file: a.file }
|
||||||
}, context))
|
}, context))
|
||||||
);
|
);
|
||||||
```
|
\`\`\`
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Agent 选择指南
|
## Agent Selection Guide
|
||||||
|
|
||||||
| 分析类型 | 推荐 Agent | Thoroughness | 原因 |
|
| Analysis Type | Recommended Agent | Thoroughness | Reason |
|
||||||
|---------|-----------|--------------|------|
|
|-------------|-----------------|--------------|--------|
|
||||||
| structure | Explore | medium | 快速获取目录结构 |
|
| structure | Explore | medium | Quick directory structure retrieval |
|
||||||
| patterns | cli-explore-agent | very thorough | 需要深度代码理解 |
|
| patterns | cli-explore-agent | very thorough | Requires deep code understanding |
|
||||||
| dependencies | Explore | medium | 主要分析 import 语句 |
|
| dependencies | Explore | medium | Mainly analyzes import statements |
|
||||||
| quality | universal-executor | medium | 需要运行分析工具 |
|
| quality | universal-executor | medium | Requires running analysis tools |
|
||||||
| security | universal-executor | very thorough | 需要全面扫描 |
|
| security | universal-executor | very thorough | Requires comprehensive scanning |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## MCP 工具集成
|
## MCP Tool Integration
|
||||||
|
|
||||||
### 语义搜索增强
|
### Semantic Search Enhancement
|
||||||
|
|
||||||
```javascript
|
\`\`\`javascript
|
||||||
// 使用 ACE 工具进行语义搜索
|
// Use ACE tool for semantic search
|
||||||
const semanticContext = await mcp__ace_tool__search_context({
|
const semanticContext = await mcp__ace_tool__search_context({
|
||||||
project_root_path: projectRoot,
|
project_root_path: projectRoot,
|
||||||
query: 'authentication logic, user session management'
|
query: 'authentication logic, user session management'
|
||||||
});
|
});
|
||||||
|
|
||||||
// 将语义搜索结果作为 Agent 的输入上下文
|
// Use semantic search results as Agent input context
|
||||||
const agentResult = await Task({
|
const agentResult = await Task({
|
||||||
subagent_type: 'Explore',
|
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
|
run_in_background: false
|
||||||
});
|
});
|
||||||
```
|
\`\`\`
|
||||||
|
|
||||||
### smart_search 集成
|
### smart_search Integration
|
||||||
|
|
||||||
```javascript
|
\`\`\`javascript
|
||||||
// 使用 smart_search 进行精确搜索
|
// Use smart_search for exact matching
|
||||||
const exactMatches = await mcp__ccw_tools__smart_search({
|
const exactMatches = await mcp__ccw_tools__smart_search({
|
||||||
action: 'search',
|
action: 'search',
|
||||||
query: 'class.*Controller',
|
query: 'class.*Controller',
|
||||||
@@ -433,19 +432,19 @@ const exactMatches = await mcp__ccw_tools__smart_search({
|
|||||||
path: 'src/'
|
path: 'src/'
|
||||||
});
|
});
|
||||||
|
|
||||||
// 使用 find_files 发现文件
|
// Use find_files for file discovery
|
||||||
const configFiles = await mcp__ccw_tools__smart_search({
|
const configFiles = await mcp__ccw_tools__smart_search({
|
||||||
action: 'find_files',
|
action: 'find_files',
|
||||||
pattern: '**/*.config.ts',
|
pattern: '**/*.config.ts',
|
||||||
path: 'src/'
|
path: 'src/'
|
||||||
});
|
});
|
||||||
```
|
\`\`\`
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 结果聚合
|
## Results Aggregation
|
||||||
|
|
||||||
```javascript
|
\`\`\`javascript
|
||||||
function aggregateResults(results) {
|
function aggregateResults(results) {
|
||||||
const aggregated = {
|
const aggregated = {
|
||||||
timestamp: new Date().toISOString(),
|
timestamp: new Date().toISOString(),
|
||||||
@@ -478,38 +477,38 @@ function aggregateResults(results) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function extractKeyFindings(agentResult) {
|
function extractKeyFindings(agentResult) {
|
||||||
// 从 Agent 结果中提取关键发现
|
// Extract key findings from Agent result
|
||||||
// 实现取决于 Agent 的输出格式
|
// Implementation depends on Agent output format
|
||||||
return {
|
return {
|
||||||
modules: agentResult.modules?.length || 0,
|
modules: agentResult.modules?.length || 0,
|
||||||
patterns: agentResult.patterns?.length || 0,
|
patterns: agentResult.patterns?.length || 0,
|
||||||
issues: agentResult.issues?.length || 0
|
issues: agentResult.issues?.length || 0
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
```
|
\`\`\`
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 最佳实践
|
## Best Practices
|
||||||
|
|
||||||
1. **范围控制**
|
1. **Scope Control**
|
||||||
- 使用精确的 patterns 减少分析范围
|
- Use precise patterns to reduce analysis scope
|
||||||
- 配置 excludes 排除无关文件
|
- Configure excludes to ignore irrelevant files
|
||||||
|
|
||||||
2. **Agent 选择**
|
2. **Agent Selection**
|
||||||
- 快速探索用 Explore
|
- Use Explore for quick exploration
|
||||||
- 深度分析用 cli-explore-agent
|
- Use cli-explore-agent for in-depth analysis
|
||||||
- 需要执行操作用 universal-executor
|
- Use universal-executor when execution is required
|
||||||
|
|
||||||
3. **MCP 工具组合**
|
3. **MCP Tool Combination**
|
||||||
- 先用 mcp__ace-tool__search_context 获取语义上下文
|
- First use mcp__ace-tool__search_context for semantic context
|
||||||
- 再用 Agent 进行深度分析
|
- Then use Agent for in-depth analysis
|
||||||
- 最后用 smart_search 补充精确匹配
|
- Finally use smart_search for exact matching
|
||||||
|
|
||||||
4. **结果缓存**
|
4. **Result Caching**
|
||||||
- 将分析结果持久化到 workDir
|
- Persist analysis results to workDir
|
||||||
- 后续阶段可直接读取,避免重复分析
|
- Subsequent phases can read directly, avoiding re-analysis
|
||||||
|
|
||||||
5. **Brief Returns**
|
5. **Brief Returns**
|
||||||
- Agent 返回路径 + 摘要,而非完整内容
|
- Agent returns path + summary, not full content
|
||||||
- 避免上下文溢出
|
- Prevents context overflow
|
||||||
|
|||||||
@@ -1,56 +1,56 @@
|
|||||||
# LLM Action Template
|
# LLM Action Template
|
||||||
|
|
||||||
LLM 动作模板,用于在 Skill 中集成 LLM 调用能力。
|
LLM action template for integrating LLM call capabilities into a Skill.
|
||||||
|
|
||||||
## Purpose
|
## 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
|
## Usage Context
|
||||||
|
|
||||||
| Phase | Usage |
|
| Phase | Usage |
|
||||||
|-------|-------|
|
|-------|-------|
|
||||||
| Optional | 当 Skill 需要 LLM 能力时使用 |
|
| Optional | Use when Skill requires LLM capabilities |
|
||||||
| Generation Trigger | 用户选择添加 llm 动作类型 |
|
| Generation Trigger | User selects to add llm action type |
|
||||||
| Tools | gemini, qwen, codex (支持 fallback chain) |
|
| Tools | gemini, qwen, codex (supports fallback chain) |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 配置结构
|
## Configuration Structure
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
interface LLMActionConfig {
|
interface LLMActionConfig {
|
||||||
id: string; // "llm-analyze", "llm-generate"
|
id: string; // "llm-analyze", "llm-generate"
|
||||||
name: string; // "LLM Analysis"
|
name: string; // "LLM Analysis"
|
||||||
type: 'llm'; // 动作类型标识
|
type: 'llm'; // Action type identifier
|
||||||
|
|
||||||
// LLM 工具配置
|
// LLM tool config
|
||||||
tool: {
|
tool: {
|
||||||
primary: 'gemini' | 'qwen' | 'codex';
|
primary: 'gemini' | 'qwen' | 'codex';
|
||||||
fallback_chain: string[]; // ['gemini', 'qwen', 'codex']
|
fallback_chain: string[]; // ['gemini', 'qwen', 'codex']
|
||||||
};
|
};
|
||||||
|
|
||||||
// 执行模式
|
// Execution mode
|
||||||
mode: 'analysis' | 'write';
|
mode: 'analysis' | 'write';
|
||||||
|
|
||||||
// 提示词配置
|
// Prompt config
|
||||||
prompt: {
|
prompt: {
|
||||||
template: string; // 提示词模板路径或内联
|
template: string; // Prompt template path or inline
|
||||||
variables: string[]; // 需要替换的变量
|
variables: string[]; // Variables to replace
|
||||||
};
|
};
|
||||||
|
|
||||||
// 输入输出
|
// Input/Output
|
||||||
input: string[]; // 依赖的上下文文件
|
input: string[]; // Dependent context files
|
||||||
output: string; // 输出文件路径
|
output: string; // Output file path
|
||||||
|
|
||||||
// 超时配置
|
// Timeout config
|
||||||
timeout?: number; // 毫秒,默认 600000 (10min)
|
timeout?: number; // Milliseconds, default 600000 (10min)
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 模板生成函数
|
## Template Generation Function
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
function generateLLMAction(config) {
|
function generateLLMAction(config) {
|
||||||
@@ -61,25 +61,25 @@ function generateLLMAction(config) {
|
|||||||
|
|
||||||
## Action: ${id}
|
## Action: ${id}
|
||||||
|
|
||||||
### 执行逻辑
|
### Execution Logic
|
||||||
|
|
||||||
\`\`\`javascript
|
\`\`\`javascript
|
||||||
async function execute${toPascalCase(id)}(context) {
|
async function execute${toPascalCase(id)}(context) {
|
||||||
const workDir = context.workDir;
|
const workDir = context.workDir;
|
||||||
const state = context.state;
|
const state = context.state;
|
||||||
|
|
||||||
// 1. 收集输入上下文
|
// 1. Collect input context
|
||||||
const inputContext = ${JSON.stringify(input)}.map(f => {
|
const inputContext = ${JSON.stringify(input)}.map(f => {
|
||||||
const path = \`\${workDir}/\${f}\`;
|
const path = \`\${workDir}/\${f}\`;
|
||||||
return Read(path);
|
return Read(path);
|
||||||
}).join('\\n\\n---\\n\\n');
|
}).join('\\n\\n---\\n\\n');
|
||||||
|
|
||||||
// 2. 构建提示词
|
// 2. Build prompt
|
||||||
const promptTemplate = \`${prompt.template}\`;
|
const promptTemplate = \`${prompt.template}\`;
|
||||||
const finalPrompt = promptTemplate
|
const finalPrompt = promptTemplate
|
||||||
${prompt.variables.map(v => `.replace('{{${v}}}', context.${v} || '')`).join('\n ')};
|
${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(', ')}];
|
const tools = ['${tool.primary}', ${tool.fallback_chain.map(t => `'${t}'`).join(', ')}];
|
||||||
let result = null;
|
let result = null;
|
||||||
let usedTool = null;
|
let usedTool = null;
|
||||||
@@ -98,10 +98,10 @@ async function execute${toPascalCase(id)}(context) {
|
|||||||
throw new Error('All LLM tools failed');
|
throw new Error('All LLM tools failed');
|
||||||
}
|
}
|
||||||
|
|
||||||
// 4. 保存结果
|
// 4. Save result
|
||||||
Write(\`\${workDir}/${output}\`, result);
|
Write(\`\${workDir}/${output}\`, result);
|
||||||
|
|
||||||
// 5. 更新状态
|
// 5. Update state
|
||||||
state.llm_calls = (state.llm_calls || 0) + 1;
|
state.llm_calls = (state.llm_calls || 0) + 1;
|
||||||
state.last_llm_tool = usedTool;
|
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) {
|
async function callLLM(tool, prompt, mode, timeout) {
|
||||||
const modeFlag = mode === 'write' ? '--mode write' : '--mode analysis';
|
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 command = \`ccw cli -p "\${escapePrompt(prompt)}" --tool \${tool} \${modeFlag}\`;
|
||||||
|
|
||||||
const result = Bash({
|
const result = Bash({
|
||||||
command,
|
command,
|
||||||
timeout,
|
timeout,
|
||||||
run_in_background: true // 异步执行
|
run_in_background: true // Async execution
|
||||||
});
|
});
|
||||||
|
|
||||||
// 等待完成
|
// Wait for completion
|
||||||
return await waitForResult(result.task_id, timeout);
|
return await waitForResult(result.task_id, timeout);
|
||||||
}
|
}
|
||||||
|
|
||||||
function escapePrompt(prompt) {
|
function escapePrompt(prompt) {
|
||||||
// 转义双引号和特殊字符
|
// Escape double quotes and special characters
|
||||||
return prompt.replace(/"/g, '\\\\"').replace(/\$/g, '\\\\$');
|
return prompt.replace(/"/g, '\\\\"').replace(/\$/g, '\\\\$');
|
||||||
}
|
}
|
||||||
\`\`\`
|
\`\`\`
|
||||||
|
|
||||||
### Prompt 模板
|
### Prompt Template
|
||||||
|
|
||||||
\`\`\`
|
\`\`\`
|
||||||
${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
|
id: llm-code-analysis
|
||||||
name: LLM Code Analysis
|
name: LLM Code Analysis
|
||||||
type: llm
|
type: llm
|
||||||
@@ -168,15 +168,15 @@ tool:
|
|||||||
mode: analysis
|
mode: analysis
|
||||||
prompt:
|
prompt:
|
||||||
template: |
|
template: |
|
||||||
PURPOSE: 分析代码结构和模式,提取关键设计特征
|
PURPOSE: Analyze code structure and patterns, extract key design features
|
||||||
TASK:
|
TASK:
|
||||||
• 识别主要模块和组件
|
• Identify main modules and components
|
||||||
• 分析依赖关系
|
• Analyze dependencies
|
||||||
• 提取设计模式
|
• Extract design patterns
|
||||||
• 评估代码质量
|
• Evaluate code quality
|
||||||
MODE: analysis
|
MODE: analysis
|
||||||
CONTEXT: {{code_context}}
|
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)
|
RULES: $(cat ~/.claude/workflows/cli-templates/protocols/analysis-protocol.md)
|
||||||
variables:
|
variables:
|
||||||
- code_context
|
- code_context
|
||||||
@@ -184,11 +184,11 @@ input:
|
|||||||
- collected-code.md
|
- collected-code.md
|
||||||
output: analysis-report.json
|
output: analysis-report.json
|
||||||
timeout: 900000
|
timeout: 900000
|
||||||
```
|
\`\`\`
|
||||||
|
|
||||||
### 2. 文档生成动作
|
### 2. Documentation Generation Action
|
||||||
|
|
||||||
```yaml
|
\`\`\`yaml
|
||||||
id: llm-doc-generation
|
id: llm-doc-generation
|
||||||
name: LLM Documentation Generation
|
name: LLM Documentation Generation
|
||||||
type: llm
|
type: llm
|
||||||
@@ -198,15 +198,15 @@ tool:
|
|||||||
mode: write
|
mode: write
|
||||||
prompt:
|
prompt:
|
||||||
template: |
|
template: |
|
||||||
PURPOSE: 根据分析结果生成高质量文档
|
PURPOSE: Generate high-quality documentation based on analysis results
|
||||||
TASK:
|
TASK:
|
||||||
• 基于分析报告生成文档大纲
|
• Generate documentation outline based on analysis report
|
||||||
• 填充各章节内容
|
• Populate chapter content
|
||||||
• 添加代码示例和说明
|
• Add code examples and explanations
|
||||||
• 生成 Mermaid 图表
|
• Generate Mermaid diagrams
|
||||||
MODE: write
|
MODE: write
|
||||||
CONTEXT: {{analysis_report}}
|
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)
|
RULES: $(cat ~/.claude/workflows/cli-templates/protocols/write-protocol.md)
|
||||||
variables:
|
variables:
|
||||||
- analysis_report
|
- analysis_report
|
||||||
@@ -214,11 +214,11 @@ input:
|
|||||||
- analysis-report.json
|
- analysis-report.json
|
||||||
output: generated-doc.md
|
output: generated-doc.md
|
||||||
timeout: 1200000
|
timeout: 1200000
|
||||||
```
|
\`\`\`
|
||||||
|
|
||||||
### 3. 代码重构建议动作
|
### 3. Code Refactoring Suggestions Action
|
||||||
|
|
||||||
```yaml
|
\`\`\`yaml
|
||||||
id: llm-refactor-suggest
|
id: llm-refactor-suggest
|
||||||
name: LLM Refactoring Suggestions
|
name: LLM Refactoring Suggestions
|
||||||
type: llm
|
type: llm
|
||||||
@@ -228,15 +228,15 @@ tool:
|
|||||||
mode: analysis
|
mode: analysis
|
||||||
prompt:
|
prompt:
|
||||||
template: |
|
template: |
|
||||||
PURPOSE: 分析代码并提供重构建议
|
PURPOSE: Analyze code and provide refactoring suggestions
|
||||||
TASK:
|
TASK:
|
||||||
• 识别代码异味 (code smells)
|
• Identify code smells
|
||||||
• 评估复杂度热点
|
• Evaluate complexity hotspots
|
||||||
• 提出具体重构方案
|
• Propose specific refactoring plans
|
||||||
• 估算重构影响范围
|
• Estimate refactoring impact scope
|
||||||
MODE: analysis
|
MODE: analysis
|
||||||
CONTEXT: {{source_code}}
|
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)
|
RULES: $(cat ~/.claude/workflows/cli-templates/protocols/analysis-protocol.md)
|
||||||
variables:
|
variables:
|
||||||
- source_code
|
- source_code
|
||||||
@@ -244,15 +244,15 @@ input:
|
|||||||
- source-files.md
|
- source-files.md
|
||||||
output: refactor-suggestions.json
|
output: refactor-suggestions.json
|
||||||
timeout: 600000
|
timeout: 600000
|
||||||
```
|
\`\`\`
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 使用示例
|
## Usage Examples
|
||||||
|
|
||||||
### 在 Phase 中使用 LLM 动作
|
### Using LLM Actions in Phase
|
||||||
|
|
||||||
```javascript
|
\`\`\`javascript
|
||||||
// phases/02-llm-analysis.md
|
// phases/02-llm-analysis.md
|
||||||
|
|
||||||
const llmConfig = {
|
const llmConfig = {
|
||||||
@@ -265,39 +265,39 @@ const llmConfig = {
|
|||||||
},
|
},
|
||||||
mode: 'analysis',
|
mode: 'analysis',
|
||||||
prompt: {
|
prompt: {
|
||||||
template: `
|
template: \`
|
||||||
PURPOSE: 分析现有 Skill 的设计模式
|
PURPOSE: Analyze design patterns of existing Skills
|
||||||
TASK:
|
TASK:
|
||||||
• 提取 Skill 结构规范
|
• Extract Skill structure specification
|
||||||
• 识别 Phase 组织模式
|
• Identify Phase organization patterns
|
||||||
• 分析 Agent 调用模式
|
• Analyze Agent invocation patterns
|
||||||
MODE: analysis
|
MODE: analysis
|
||||||
CONTEXT: {{skill_source}}
|
CONTEXT: {{skill_source}}
|
||||||
EXPECTED: 结构化的设计模式分析
|
EXPECTED: Structured design pattern analysis
|
||||||
`,
|
\`,
|
||||||
variables: ['skill_source']
|
variables: ['skill_source']
|
||||||
},
|
},
|
||||||
input: ['collected-skills.md'],
|
input: ['collected-skills.md'],
|
||||||
output: 'skill-patterns.json'
|
output: 'skill-patterns.json'
|
||||||
};
|
};
|
||||||
|
|
||||||
// 执行
|
// Execute
|
||||||
const result = await executeLLMAction(llmConfig, {
|
const result = await executeLLMAction(llmConfig, {
|
||||||
workDir: '.workflow/.scratchpad/skill-gen-xxx',
|
workDir: '.workflow/.scratchpad/skill-gen-xxx',
|
||||||
skill_source: Read('.workflow/.scratchpad/skill-gen-xxx/collected-skills.md')
|
skill_source: Read('.workflow/.scratchpad/skill-gen-xxx/collected-skills.md')
|
||||||
});
|
});
|
||||||
```
|
\`\`\`
|
||||||
|
|
||||||
### 在 Orchestrator 中调度 LLM 动作
|
### Scheduling LLM Actions in Orchestrator
|
||||||
|
|
||||||
```javascript
|
\`\`\`javascript
|
||||||
// autonomous-orchestrator 中的 LLM 动作调度
|
// Schedule LLM actions in autonomous-orchestrator
|
||||||
|
|
||||||
const actions = [
|
const actions = [
|
||||||
{ type: 'collect', priority: 100 },
|
{ 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: 'process', priority: 80 },
|
||||||
{ type: 'llm', id: 'llm-generate', priority: 70 }, // LLM 生成
|
{ type: 'llm', id: 'llm-generate', priority: 70 }, // LLM generation
|
||||||
{ type: 'validate', priority: 60 }
|
{ type: 'validate', priority: 60 }
|
||||||
];
|
];
|
||||||
|
|
||||||
@@ -310,13 +310,13 @@ for (const action of sortByPriority(actions)) {
|
|||||||
context.state[action.id] = llmResult;
|
context.state[action.id] = llmResult;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
\`\`\`
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 错误处理
|
## Error Handling
|
||||||
|
|
||||||
```javascript
|
\`\`\`javascript
|
||||||
async function executeLLMActionWithRetry(config, context, maxRetries = 3) {
|
async function executeLLMActionWithRetry(config, context, maxRetries = 3) {
|
||||||
let lastError = null;
|
let lastError = null;
|
||||||
|
|
||||||
@@ -325,43 +325,43 @@ async function executeLLMActionWithRetry(config, context, maxRetries = 3) {
|
|||||||
return await executeLLMAction(config, context);
|
return await executeLLMAction(config, context);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
lastError = error;
|
lastError = error;
|
||||||
console.log(`Attempt ${attempt} failed: ${error.message}`);
|
console.log(\`Attempt ${attempt} failed: ${error.message}\`);
|
||||||
|
|
||||||
// 指数退避
|
// Exponential backoff
|
||||||
if (attempt < maxRetries) {
|
if (attempt < maxRetries) {
|
||||||
await sleep(Math.pow(2, attempt) * 1000);
|
await sleep(Math.pow(2, attempt) * 1000);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 所有重试失败
|
// All retries failed
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: lastError.message,
|
error: lastError.message,
|
||||||
fallback: 'manual_review_required'
|
fallback: 'manual_review_required'
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
```
|
\`\`\`
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 最佳实践
|
## Best Practices
|
||||||
|
|
||||||
1. **选择合适的工具**
|
1. **Select Appropriate Tool**
|
||||||
- 分析任务:Gemini(大上下文)> Qwen
|
- Analysis tasks: Gemini (large context) > Qwen
|
||||||
- 生成任务:Codex(自主执行)> Gemini > Qwen
|
- Generation tasks: Codex (autonomous execution) > Gemini > Qwen
|
||||||
- 代码修改:Codex > Gemini
|
- Code modification: Codex > Gemini
|
||||||
|
|
||||||
2. **配置 Fallback Chain**
|
2. **Configure Fallback Chain**
|
||||||
- 总是配置至少一个 fallback
|
- Always configure at least one fallback
|
||||||
- 考虑工具特性选择 fallback 顺序
|
- Consider tool characteristics when ordering fallbacks
|
||||||
|
|
||||||
3. **超时设置**
|
3. **Timeout Settings**
|
||||||
- 分析任务:10-15 分钟
|
- Analysis tasks: 10-15 minutes
|
||||||
- 生成任务:15-20 分钟
|
- Generation tasks: 15-20 minutes
|
||||||
- 复杂任务:20-60 分钟
|
- Complex tasks: 20-60 minutes
|
||||||
|
|
||||||
4. **提示词设计**
|
4. **Prompt Design**
|
||||||
- 使用 PURPOSE/TASK/MODE/CONTEXT/EXPECTED/RULES 结构
|
- Use PURPOSE/TASK/MODE/CONTEXT/EXPECTED/RULES structure
|
||||||
- 引用标准协议模板
|
- Reference standard protocol templates
|
||||||
- 明确输出格式要求
|
- Clearly specify output format requirements
|
||||||
|
|||||||
@@ -1,56 +1,56 @@
|
|||||||
# Script Template
|
# Script Template
|
||||||
|
|
||||||
统一的脚本模板,覆盖 Bash 和 Python 两种运行时。
|
Unified script template covering both Bash and Python runtimes.
|
||||||
|
|
||||||
## Usage Context
|
## Usage Context
|
||||||
|
|
||||||
| Phase | Usage |
|
| Phase | Usage |
|
||||||
|-------|-------|
|
|-------|-------|
|
||||||
| Optional | Phase/Action 中声明 `## Scripts` 时使用 |
|
| Optional | Use when declaring `## Scripts` in Phase/Action |
|
||||||
| Execution | 通过 `ExecuteScript('script-id', params)` 调用 |
|
| Execution | Invoke via `ExecuteScript('script-id', params)` |
|
||||||
| Output Location | `.claude/skills/{skill-name}/scripts/{script-id}.{ext}` |
|
| Output Location | `.claude/skills/{skill-name}/scripts/{script-id}.{ext}` |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 调用接口规范
|
## Invocation Interface Specification
|
||||||
|
|
||||||
所有脚本共享相同的调用约定:
|
All scripts share the same calling convention:
|
||||||
|
|
||||||
```
|
```
|
||||||
调用者
|
Caller
|
||||||
↓ ExecuteScript('script-id', { key: value })
|
| ExecuteScript('script-id', { key: value })
|
||||||
↓
|
|
|
||||||
脚本入口
|
Script Entry
|
||||||
├─ 参数解析 (--key value)
|
├─ Parameter parsing (--key value)
|
||||||
├─ 输入验证 (必需参数检查, 文件存在)
|
├─ Input validation (required parameter checks, file exists)
|
||||||
├─ 核心处理 (数据读取 → 转换 → 写入)
|
├─ Core processing (data read -> transform -> write)
|
||||||
└─ 输出结果 (最后一行: 单行 JSON → stdout)
|
└─ Output result (last line: single-line JSON -> stdout)
|
||||||
├─ 成功: {"status":"success", "output_file":"...", ...}
|
├─ Success: {"status":"success", "output_file":"...", ...}
|
||||||
└─ 失败: stderr 输出错误信息, exit 1
|
└─ Failure: stderr output error message, exit 1
|
||||||
```
|
```
|
||||||
|
|
||||||
### 返回格式
|
### Return Format
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
interface ScriptResult {
|
interface ScriptResult {
|
||||||
success: boolean; // exit code === 0
|
success: boolean; // exit code === 0
|
||||||
stdout: string; // 标准输出
|
stdout: string; // Standard output
|
||||||
stderr: string; // 标准错误
|
stderr: string; // Standard error
|
||||||
outputs: object; // 从 stdout 最后一行解析的 JSON
|
outputs: object; // JSON output parsed from stdout last line
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
### 参数约定
|
### Parameter Convention
|
||||||
|
|
||||||
| 参数 | 必需 | 说明 |
|
| Parameter | Required | Description |
|
||||||
|------|------|------|
|
|-----------|----------|-------------|
|
||||||
| `--input-path` | ✓ | 输入文件路径 |
|
| `--input-path` | Yes | Input file path |
|
||||||
| `--output-dir` | ✓ | 输出目录(由调用方指定) |
|
| `--output-dir` | Yes | Output directory (specified by caller) |
|
||||||
| 其他 | 按需 | 脚本特定参数 |
|
| Others | Optional | Script-specific parameters |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Bash 实现
|
## Bash Implementation
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
#!/bin/bash
|
#!/bin/bash
|
||||||
@@ -59,7 +59,7 @@ interface ScriptResult {
|
|||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
|
|
||||||
# ============================================================
|
# ============================================================
|
||||||
# 参数解析
|
# Parameter Parsing
|
||||||
# ============================================================
|
# ============================================================
|
||||||
|
|
||||||
INPUT_PATH=""
|
INPUT_PATH=""
|
||||||
@@ -70,11 +70,11 @@ while [[ "$#" -gt 0 ]]; do
|
|||||||
--input-path) INPUT_PATH="$2"; shift ;;
|
--input-path) INPUT_PATH="$2"; shift ;;
|
||||||
--output-dir) OUTPUT_DIR="$2"; shift ;;
|
--output-dir) OUTPUT_DIR="$2"; shift ;;
|
||||||
--help)
|
--help)
|
||||||
echo "用法: $0 --input-path <path> --output-dir <dir>"
|
echo "Usage: $0 --input-path <path> --output-dir <dir>"
|
||||||
exit 0
|
exit 0
|
||||||
;;
|
;;
|
||||||
*)
|
*)
|
||||||
echo "错误: 未知参数 $1" >&2
|
echo "Error: Unknown parameter $1" >&2
|
||||||
exit 1
|
exit 1
|
||||||
;;
|
;;
|
||||||
esac
|
esac
|
||||||
@@ -82,31 +82,31 @@ while [[ "$#" -gt 0 ]]; do
|
|||||||
done
|
done
|
||||||
|
|
||||||
# ============================================================
|
# ============================================================
|
||||||
# 参数验证
|
# Parameter Validation
|
||||||
# ============================================================
|
# ============================================================
|
||||||
|
|
||||||
[[ -z "$INPUT_PATH" ]] && { echo "错误: --input-path 是必需参数" >&2; exit 1; }
|
[[ -z "$INPUT_PATH" ]] && { echo "Error: --input-path is required parameter" >&2; exit 1; }
|
||||||
[[ -z "$OUTPUT_DIR" ]] && { echo "错误: --output-dir 是必需参数" >&2; exit 1; }
|
[[ -z "$OUTPUT_DIR" ]] && { echo "Error: --output-dir is required parameter" >&2; exit 1; }
|
||||||
[[ ! -f "$INPUT_PATH" ]] && { echo "错误: 输入文件不存在: $INPUT_PATH" >&2; exit 1; }
|
[[ ! -f "$INPUT_PATH" ]] && { echo "Error: Input file does not exist: $INPUT_PATH" >&2; exit 1; }
|
||||||
command -v jq &> /dev/null || { echo "错误: 需要安装 jq" >&2; exit 1; }
|
command -v jq &> /dev/null || { echo "Error: jq is required" >&2; exit 1; }
|
||||||
|
|
||||||
mkdir -p "$OUTPUT_DIR"
|
mkdir -p "$OUTPUT_DIR"
|
||||||
|
|
||||||
# ============================================================
|
# ============================================================
|
||||||
# 核心逻辑
|
# Core Logic
|
||||||
# ============================================================
|
# ============================================================
|
||||||
|
|
||||||
OUTPUT_FILE="$OUTPUT_DIR/result.txt"
|
OUTPUT_FILE="$OUTPUT_DIR/result.txt"
|
||||||
ITEMS_COUNT=0
|
ITEMS_COUNT=0
|
||||||
|
|
||||||
# TODO: 实现处理逻辑
|
# TODO: Implement processing logic
|
||||||
while IFS= read -r line; do
|
while IFS= read -r line; do
|
||||||
echo "$line" >> "$OUTPUT_FILE"
|
echo "$line" >> "$OUTPUT_FILE"
|
||||||
((ITEMS_COUNT++))
|
((ITEMS_COUNT++))
|
||||||
done < "$INPUT_PATH"
|
done < "$INPUT_PATH"
|
||||||
|
|
||||||
# ============================================================
|
# ============================================================
|
||||||
# 输出 JSON 结果(使用 jq 构建,避免转义问题)
|
# Output JSON Result (use jq to build, avoid escaping issues)
|
||||||
# ============================================================
|
# ============================================================
|
||||||
|
|
||||||
jq -n \
|
jq -n \
|
||||||
@@ -115,34 +115,34 @@ jq -n \
|
|||||||
'{output_file: $output_file, items_processed: $items_processed, status: "success"}'
|
'{output_file: $output_file, items_processed: $items_processed, status: "success"}'
|
||||||
```
|
```
|
||||||
|
|
||||||
### Bash 常用模式
|
### Bash Common Patterns
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# 文件遍历
|
# File iteration
|
||||||
for file in "$INPUT_DIR"/*.json; do
|
for file in "$INPUT_DIR"/*.json; do
|
||||||
[[ -f "$file" ]] || continue
|
[[ -f "$file" ]] || continue
|
||||||
# 处理逻辑...
|
# Processing logic...
|
||||||
done
|
done
|
||||||
|
|
||||||
# 临时文件 (自动清理)
|
# Temp file (auto cleanup)
|
||||||
TEMP_FILE=$(mktemp)
|
TEMP_FILE=$(mktemp)
|
||||||
trap "rm -f $TEMP_FILE" EXIT
|
trap "rm -f $TEMP_FILE" EXIT
|
||||||
|
|
||||||
# 工具依赖检查
|
# Tool dependency check
|
||||||
require_command() {
|
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
|
require_command jq
|
||||||
|
|
||||||
# jq 处理
|
# jq processing
|
||||||
VALUE=$(jq -r '.field' "$INPUT_PATH") # 读取字段
|
VALUE=$(jq -r '.field' "$INPUT_PATH") # Read field
|
||||||
jq '.field = "new"' input.json > output.json # 修改字段
|
jq '.field = "new"' input.json > output.json # Modify field
|
||||||
jq -s 'add' file1.json file2.json > merged.json # 合并文件
|
jq -s 'add' file1.json file2.json > merged.json # Merge files
|
||||||
```
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Python 实现
|
## Python Implementation
|
||||||
|
|
||||||
```python
|
```python
|
||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python3
|
||||||
@@ -158,33 +158,33 @@ from pathlib import Path
|
|||||||
|
|
||||||
def main():
|
def main():
|
||||||
parser = argparse.ArgumentParser(description='{{script_description}}')
|
parser = argparse.ArgumentParser(description='{{script_description}}')
|
||||||
parser.add_argument('--input-path', 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='输出目录')
|
parser.add_argument('--output-dir', type=str, required=True, help='Output directory')
|
||||||
args = parser.parse_args()
|
args = parser.parse_args()
|
||||||
|
|
||||||
# 验证输入
|
# Validate input
|
||||||
input_path = Path(args.input_path)
|
input_path = Path(args.input_path)
|
||||||
if not input_path.exists():
|
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)
|
sys.exit(1)
|
||||||
|
|
||||||
output_dir = Path(args.output_dir)
|
output_dir = Path(args.output_dir)
|
||||||
output_dir.mkdir(parents=True, exist_ok=True)
|
output_dir.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
# 执行处理
|
# Execute processing
|
||||||
try:
|
try:
|
||||||
result = process(input_path, output_dir)
|
result = process(input_path, output_dir)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"错误: {e}", file=sys.stderr)
|
print(f"Error: {e}", file=sys.stderr)
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
|
|
||||||
# 输出 JSON 结果
|
# Output JSON result
|
||||||
print(json.dumps(result))
|
print(json.dumps(result))
|
||||||
|
|
||||||
|
|
||||||
def process(input_path: Path, output_dir: Path) -> dict:
|
def process(input_path: Path, output_dir: Path) -> dict:
|
||||||
"""核心处理逻辑"""
|
"""Core processing logic"""
|
||||||
# TODO: 实现处理逻辑
|
# TODO: Implement processing logic
|
||||||
|
|
||||||
output_file = output_dir / 'result.json'
|
output_file = output_dir / 'result.json'
|
||||||
|
|
||||||
@@ -207,17 +207,17 @@ if __name__ == '__main__':
|
|||||||
main()
|
main()
|
||||||
```
|
```
|
||||||
|
|
||||||
### Python 常用模式
|
### Python Common Patterns
|
||||||
|
|
||||||
```python
|
```python
|
||||||
# 文件遍历
|
# File iteration
|
||||||
def process_files(input_dir: Path, pattern: str = '*.json') -> list:
|
def process_files(input_dir: Path, pattern: str = '*.json') -> list:
|
||||||
return [
|
return [
|
||||||
{'file': str(f), 'data': json.load(f.open())}
|
{'file': str(f), 'data': json.load(f.open())}
|
||||||
for f in input_dir.glob(pattern)
|
for f in input_dir.glob(pattern)
|
||||||
]
|
]
|
||||||
|
|
||||||
# 数据转换
|
# Data transformation
|
||||||
def transform(data: dict) -> dict:
|
def transform(data: dict) -> dict:
|
||||||
return {
|
return {
|
||||||
'id': data.get('id'),
|
'id': data.get('id'),
|
||||||
@@ -225,7 +225,7 @@ def transform(data: dict) -> dict:
|
|||||||
'timestamp': datetime.now().isoformat()
|
'timestamp': datetime.now().isoformat()
|
||||||
}
|
}
|
||||||
|
|
||||||
# 外部命令调用
|
# External command invocation
|
||||||
import subprocess
|
import subprocess
|
||||||
|
|
||||||
def run_command(cmd: list) -> str:
|
def run_command(cmd: list) -> str:
|
||||||
@@ -237,24 +237,24 @@ def run_command(cmd: list) -> str:
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 运行时选择指南
|
## Runtime Selection Guide
|
||||||
|
|
||||||
```
|
```
|
||||||
任务特征
|
Task Characteristics
|
||||||
↓
|
|
|
||||||
├─ 文件处理 / 系统命令 / 管道操作
|
├─ File processing / system commands / pipeline operations
|
||||||
│ └─ 选 Bash (.sh)
|
│ └─ Choose Bash (.sh)
|
||||||
│
|
│
|
||||||
├─ JSON 数据处理 / 复杂转换 / 数据分析
|
├─ JSON data processing / complex transformation / data analysis
|
||||||
│ └─ 选 Python (.py)
|
│ └─ Choose Python (.py)
|
||||||
│
|
│
|
||||||
└─ 简单读写 / 格式转换
|
└─ Simple read/write / format conversion
|
||||||
└─ 任选(Bash 更轻量)
|
└─ Either (Bash is lighter)
|
||||||
```
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 生成函数
|
## Generation Function
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
function generateScript(scriptConfig) {
|
function generateScript(scriptConfig) {
|
||||||
@@ -280,7 +280,7 @@ function generateBashScript(scriptConfig) {
|
|||||||
|
|
||||||
const paramValidation = inputs.filter(i => i.required).map(i => {
|
const paramValidation = inputs.filter(i => i.required).map(i => {
|
||||||
const VAR = i.name.toUpperCase().replace(/-/g, '_');
|
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');
|
}).join('\n');
|
||||||
|
|
||||||
return `#!/bin/bash
|
return `#!/bin/bash
|
||||||
@@ -293,16 +293,16 @@ ${paramDefs}
|
|||||||
while [[ "$#" -gt 0 ]]; do
|
while [[ "$#" -gt 0 ]]; do
|
||||||
case $1 in
|
case $1 in
|
||||||
${paramParse}
|
${paramParse}
|
||||||
*) echo "未知参数: $1" >&2; exit 1 ;;
|
*) echo "Unknown parameter: $1" >&2; exit 1 ;;
|
||||||
esac
|
esac
|
||||||
shift
|
shift
|
||||||
done
|
done
|
||||||
|
|
||||||
${paramValidation}
|
${paramValidation}
|
||||||
|
|
||||||
# TODO: 实现处理逻辑
|
# TODO: Implement processing logic
|
||||||
|
|
||||||
# 输出结果 (jq 构建)
|
# Output result (jq build)
|
||||||
jq -n ${outputs.map(o =>
|
jq -n ${outputs.map(o =>
|
||||||
`--arg ${o.name} "$${o.name.toUpperCase().replace(/-/g, '_')}"`
|
`--arg ${o.name} "$${o.name.toUpperCase().replace(/-/g, '_')}"`
|
||||||
).join(' \\\n ')} \
|
).join(' \\\n ')} \
|
||||||
@@ -339,7 +339,7 @@ def main():
|
|||||||
${argDefs}
|
${argDefs}
|
||||||
args = parser.parse_args()
|
args = parser.parse_args()
|
||||||
|
|
||||||
# TODO: 实现处理逻辑
|
# TODO: Implement processing logic
|
||||||
result = {
|
result = {
|
||||||
${resultFields}
|
${resultFields}
|
||||||
}
|
}
|
||||||
@@ -355,7 +355,7 @@ if __name__ == '__main__':
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 目录约定
|
## Directory Convention
|
||||||
|
|
||||||
```
|
```
|
||||||
scripts/
|
scripts/
|
||||||
@@ -364,5 +364,5 @@ scripts/
|
|||||||
└── transform.js # id: transform, runtime: node
|
└── transform.js # id: transform, runtime: node
|
||||||
```
|
```
|
||||||
|
|
||||||
- **命名即 ID**: 文件名(不含扩展名)= 脚本 ID
|
- **Name is ID**: Filename (without extension) = script ID
|
||||||
- **扩展名即运行时**: `.py` → python, `.sh` → bash, `.js` → node
|
- **Extension is runtime**: `.py` -> python, `.sh` -> bash, `.js` -> node
|
||||||
|
|||||||
@@ -1,31 +1,31 @@
|
|||||||
# Sequential Phase Template
|
# Sequential Phase Template
|
||||||
|
|
||||||
顺序模式 Phase 文件的模板。
|
Template for Phase files in Sequential execution mode.
|
||||||
|
|
||||||
## Purpose
|
## Purpose
|
||||||
|
|
||||||
生成 Sequential 执行模式的 Phase 文件,定义固定顺序的执行步骤。
|
Generate Phase files for Sequential execution mode, defining fixed-order execution steps.
|
||||||
|
|
||||||
## Usage Context
|
## Usage Context
|
||||||
|
|
||||||
| Phase | Usage |
|
| Phase | Usage |
|
||||||
|-------|-------|
|
|-------|-------|
|
||||||
| Phase 3 (Phase Generation) | `config.execution_mode === 'sequential'` 时生成 |
|
| Phase 3 (Phase Generation) | Generated when `config.execution_mode === 'sequential'` |
|
||||||
| Generation Trigger | 为每个 `config.sequential_config.phases` 生成一个 phase 文件 |
|
| Generation Trigger | Generate one phase file for each `config.sequential_config.phases` |
|
||||||
| Output Location | `.claude/skills/{skill-name}/phases/{phase-id}.md` |
|
| 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 时,需要确保:
|
> When generating Sequential Phase, ensure:
|
||||||
> 1. SKILL.md 中已包含 Phase 0 规范研读步骤
|
> 1. Phase 0 specification review step is included in SKILL.md
|
||||||
> 2. 每个 Phase 文件都引用相关的规范文档
|
> 2. Each Phase file references related specification documents
|
||||||
> 3. 执行流程明确标注 Phase 0 为禁止跳过的前置步骤
|
> 3. Execution flow clearly marks Phase 0 as non-skippable prerequisite
|
||||||
|
|
||||||
## 模板结构
|
## Template Structure
|
||||||
|
|
||||||
```markdown
|
```markdown
|
||||||
# Phase {{phase_number}}: {{phase_name}}
|
# Phase {{phase_number}}: {{phase_name}}
|
||||||
@@ -38,14 +38,14 @@
|
|||||||
|
|
||||||
## Input
|
## Input
|
||||||
|
|
||||||
- 依赖: `{{input_dependency}}`
|
- Dependency: `{{input_dependency}}`
|
||||||
- 配置: `{workDir}/skill-config.json`
|
- Config: `{workDir}/skill-config.json`
|
||||||
|
|
||||||
## Scripts
|
## Scripts
|
||||||
|
|
||||||
\`\`\`yaml
|
\`\`\`yaml
|
||||||
# 声明本阶段使用的脚本(可选)
|
# Declare scripts used in this phase (optional)
|
||||||
# - script-id # 对应 scripts/script-id.py 或 .sh
|
# - script-id # Corresponds to scripts/script-id.py or .sh
|
||||||
\`\`\`
|
\`\`\`
|
||||||
|
|
||||||
## Execution Steps
|
## Execution Steps
|
||||||
@@ -62,10 +62,10 @@
|
|||||||
{{step_2_code}}
|
{{step_2_code}}
|
||||||
\`\`\`
|
\`\`\`
|
||||||
|
|
||||||
### Step 3: 执行脚本(可选)
|
### Step 3: Execute Script (Optional)
|
||||||
|
|
||||||
\`\`\`javascript
|
\`\`\`javascript
|
||||||
// 调用脚本示例
|
// Script execution example
|
||||||
// const result = await ExecuteScript('script-id', { input_path: `${workDir}/data.json` });
|
// const result = await ExecuteScript('script-id', { input_path: `${workDir}/data.json` });
|
||||||
// if (!result.success) throw new Error(result.stderr);
|
// if (!result.success) throw new Error(result.stderr);
|
||||||
// console.log(result.outputs.output_file);
|
// console.log(result.outputs.output_file);
|
||||||
@@ -85,25 +85,25 @@
|
|||||||
{{next_phase_link}}
|
{{next_phase_link}}
|
||||||
```
|
```
|
||||||
|
|
||||||
## 变量说明
|
## Variable Descriptions
|
||||||
|
|
||||||
| 变量 | 说明 |
|
| Variable | Description |
|
||||||
|------|------|
|
|----------|-------------|
|
||||||
| `{{phase_number}}` | 阶段序号 (1, 2, 3...) |
|
| `{{phase_number}}` | Phase number (1, 2, 3...) |
|
||||||
| `{{phase_name}}` | 阶段名称 |
|
| `{{phase_name}}` | Phase name |
|
||||||
| `{{phase_description}}` | 一句话描述 |
|
| `{{phase_description}}` | One-line description |
|
||||||
| `{{objectives}}` | 目标列表 |
|
| `{{objectives}}` | List of objectives |
|
||||||
| `{{input_dependency}}` | 输入依赖文件 |
|
| `{{input_dependency}}` | Input dependency file |
|
||||||
| `{{step_N_name}}` | 步骤名称 |
|
| `{{step_N_name}}` | Step name |
|
||||||
| `{{step_N_code}}` | 步骤代码 |
|
| `{{step_N_code}}` | Step code |
|
||||||
| `{{output_file}}` | 输出文件名 |
|
| `{{output_file}}` | Output filename |
|
||||||
| `{{output_format}}` | 输出格式 |
|
| `{{output_format}}` | Output format |
|
||||||
| `{{quality_checklist}}` | 质量检查项 |
|
| `{{quality_checklist}}` | Quality checklist items |
|
||||||
| `{{next_phase_link}}` | 下一阶段链接 |
|
| `{{next_phase_link}}` | Next phase link |
|
||||||
|
|
||||||
## 脚本调用说明
|
## Script Invocation Guide
|
||||||
|
|
||||||
### 目录约定
|
### Directory Convention
|
||||||
|
|
||||||
```
|
```
|
||||||
scripts/
|
scripts/
|
||||||
@@ -112,154 +112,154 @@ scripts/
|
|||||||
└── transform.js # id: transform, runtime: node
|
└── transform.js # id: transform, runtime: node
|
||||||
```
|
```
|
||||||
|
|
||||||
- **命名即 ID**:文件名(不含扩展名)= 脚本 ID
|
- **Name is ID**: Filename (without extension) = script ID
|
||||||
- **扩展名即运行时**:`.py` → python, `.sh` → bash, `.js` → node
|
- **Extension is runtime**: `.py` → python, `.sh` → bash, `.js` → node
|
||||||
|
|
||||||
### 调用语法
|
### Invocation Syntax
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
// 一行调用
|
// Single-line invocation
|
||||||
const result = await ExecuteScript('script-id', { key: value });
|
const result = await ExecuteScript('script-id', { key: value });
|
||||||
|
|
||||||
// 检查结果
|
// Check result
|
||||||
if (!result.success) throw new Error(result.stderr);
|
if (!result.success) throw new Error(result.stderr);
|
||||||
|
|
||||||
// 获取输出
|
// Get output
|
||||||
const { output_file } = result.outputs;
|
const { output_file } = result.outputs;
|
||||||
```
|
```
|
||||||
|
|
||||||
### 返回格式
|
### Return Format
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
interface ScriptResult {
|
interface ScriptResult {
|
||||||
success: boolean; // exit code === 0
|
success: boolean; // exit code === 0
|
||||||
stdout: string; // 标准输出
|
stdout: string; // Standard output
|
||||||
stderr: string; // 标准错误
|
stderr: string; // Standard error
|
||||||
outputs: object; // 从 stdout 解析的 JSON 输出
|
outputs: object; // JSON output parsed from stdout
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
## Phase 类型模板
|
## Phase Type Templates
|
||||||
|
|
||||||
### 1. 收集型 Phase (Collection)
|
### 1. Collection Phase
|
||||||
|
|
||||||
```markdown
|
```markdown
|
||||||
# Phase 1: Requirements Collection
|
# Phase 1: Requirements Collection
|
||||||
|
|
||||||
收集用户需求和项目配置。
|
Collect user requirements and project configuration.
|
||||||
|
|
||||||
## Objective
|
## Objective
|
||||||
|
|
||||||
- 收集用户输入
|
- Collect user input
|
||||||
- 自动检测项目信息
|
- Auto-detect project information
|
||||||
- 生成配置文件
|
- Generate configuration file
|
||||||
|
|
||||||
## Execution Steps
|
## Execution Steps
|
||||||
|
|
||||||
### Step 1: 用户交互
|
### Step 1: User Interaction
|
||||||
|
|
||||||
\`\`\`javascript
|
\`\`\`javascript
|
||||||
const userInput = await AskUserQuestion({
|
const userInput = await AskUserQuestion({
|
||||||
questions: [
|
questions: [
|
||||||
{
|
{
|
||||||
question: "请选择...",
|
question: "Please select...",
|
||||||
header: "选项",
|
header: "Option",
|
||||||
multiSelect: false,
|
multiSelect: false,
|
||||||
options: [
|
options: [
|
||||||
{ label: "选项A", description: "..." },
|
{ label: "Option A", description: "..." },
|
||||||
{ label: "选项B", description: "..." }
|
{ label: "Option B", description: "..." }
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
});
|
});
|
||||||
\`\`\`
|
\`\`\`
|
||||||
|
|
||||||
### Step 2: 自动检测
|
### Step 2: Auto-detection
|
||||||
|
|
||||||
\`\`\`javascript
|
\`\`\`javascript
|
||||||
// 检测项目信息
|
// Detect project information
|
||||||
const packageJson = JSON.parse(Read('package.json'));
|
const packageJson = JSON.parse(Read('package.json'));
|
||||||
const projectName = packageJson.name;
|
const projectName = packageJson.name;
|
||||||
\`\`\`
|
\`\`\`
|
||||||
|
|
||||||
### Step 3: 生成配置
|
### Step 3: Generate Configuration
|
||||||
|
|
||||||
\`\`\`javascript
|
\`\`\`javascript
|
||||||
const config = {
|
const config = {
|
||||||
name: projectName,
|
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
|
## Output
|
||||||
|
|
||||||
- **File**: `config.json`
|
- **File**: \`config.json\`
|
||||||
- **Format**: JSON
|
- **Format**: JSON
|
||||||
```
|
```
|
||||||
|
|
||||||
### 2. 分析型 Phase (Analysis)
|
### 2. Analysis Phase
|
||||||
|
|
||||||
```markdown
|
```markdown
|
||||||
# Phase 2: Deep Analysis
|
# Phase 2: Deep Analysis
|
||||||
|
|
||||||
深度分析代码结构。
|
Analyze code structure in depth.
|
||||||
|
|
||||||
## Objective
|
## Objective
|
||||||
|
|
||||||
- 扫描代码文件
|
- Scan code files
|
||||||
- 提取关键信息
|
- Extract key information
|
||||||
- 生成分析报告
|
- Generate analysis report
|
||||||
|
|
||||||
## Execution Steps
|
## Execution Steps
|
||||||
|
|
||||||
### Step 1: 文件扫描
|
### Step 1: File Scanning
|
||||||
|
|
||||||
\`\`\`javascript
|
\`\`\`javascript
|
||||||
const files = Glob('src/**/*.ts');
|
const files = Glob('src/**/*.ts');
|
||||||
\`\`\`
|
\`\`\`
|
||||||
|
|
||||||
### Step 2: 内容分析
|
### Step 2: Content Analysis
|
||||||
|
|
||||||
\`\`\`javascript
|
\`\`\`javascript
|
||||||
const analysisResults = [];
|
const analysisResults = [];
|
||||||
for (const file of files) {
|
for (const file of files) {
|
||||||
const content = Read(file);
|
const content = Read(file);
|
||||||
// 分析逻辑
|
// Analysis logic
|
||||||
analysisResults.push({ file, /* 分析结果 */ });
|
analysisResults.push({ file, /* analysis results */ });
|
||||||
}
|
}
|
||||||
\`\`\`
|
\`\`\`
|
||||||
|
|
||||||
### Step 3: 生成报告
|
### Step 3: Generate Report
|
||||||
|
|
||||||
\`\`\`javascript
|
\`\`\`javascript
|
||||||
Write(`${workDir}/analysis.json`, JSON.stringify(analysisResults, null, 2));
|
Write(\`${workDir}/analysis.json\`, JSON.stringify(analysisResults, null, 2));
|
||||||
\`\`\`
|
\`\`\`
|
||||||
|
|
||||||
## Output
|
## Output
|
||||||
|
|
||||||
- **File**: `analysis.json`
|
- **File**: \`analysis.json\`
|
||||||
- **Format**: JSON
|
- **Format**: JSON
|
||||||
```
|
```
|
||||||
|
|
||||||
### 3. 并行型 Phase (Parallel)
|
### 3. Parallel Phase
|
||||||
|
|
||||||
```markdown
|
```markdown
|
||||||
# Phase 3: Parallel Processing
|
# Phase 3: Parallel Processing
|
||||||
|
|
||||||
并行处理多个子任务。
|
Process multiple subtasks in parallel.
|
||||||
|
|
||||||
## Objective
|
## Objective
|
||||||
|
|
||||||
- 启动多个 Agent 并行执行
|
- Launch multiple agents for parallel execution
|
||||||
- 收集各 Agent 结果
|
- Collect results from each agent
|
||||||
- 合并输出
|
- Merge outputs
|
||||||
|
|
||||||
## Execution Steps
|
## Execution Steps
|
||||||
|
|
||||||
### Step 1: 准备任务
|
### Step 1: Prepare Tasks
|
||||||
|
|
||||||
\`\`\`javascript
|
\`\`\`javascript
|
||||||
const tasks = [
|
const tasks = [
|
||||||
@@ -269,7 +269,7 @@ const tasks = [
|
|||||||
];
|
];
|
||||||
\`\`\`
|
\`\`\`
|
||||||
|
|
||||||
### Step 2: 并行执行
|
### Step 2: Parallel Execution
|
||||||
|
|
||||||
\`\`\`javascript
|
\`\`\`javascript
|
||||||
const results = await Promise.all(
|
const results = await Promise.all(
|
||||||
@@ -283,7 +283,7 @@ const results = await Promise.all(
|
|||||||
);
|
);
|
||||||
\`\`\`
|
\`\`\`
|
||||||
|
|
||||||
### Step 3: 合并结果
|
### Step 3: Merge Results
|
||||||
|
|
||||||
\`\`\`javascript
|
\`\`\`javascript
|
||||||
const merged = results.map((r, i) => ({
|
const merged = results.map((r, i) => ({
|
||||||
@@ -291,83 +291,83 @@ const merged = results.map((r, i) => ({
|
|||||||
result: JSON.parse(r)
|
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
|
## Output
|
||||||
|
|
||||||
- **File**: `parallel-results.json`
|
- **File**: \`parallel-results.json\`
|
||||||
- **Format**: JSON
|
- **Format**: JSON
|
||||||
```
|
```
|
||||||
|
|
||||||
### 4. 组装型 Phase (Assembly)
|
### 4. Assembly Phase
|
||||||
|
|
||||||
```markdown
|
```markdown
|
||||||
# Phase 4: Document Assembly
|
# Phase 4: Document Assembly
|
||||||
|
|
||||||
组装最终输出文档。
|
Assemble final output documents.
|
||||||
|
|
||||||
## Objective
|
## Objective
|
||||||
|
|
||||||
- 读取各阶段产出
|
- Read outputs from each phase
|
||||||
- 合并内容
|
- Merge content
|
||||||
- 生成最终文档
|
- Generate final document
|
||||||
|
|
||||||
## Execution Steps
|
## Execution Steps
|
||||||
|
|
||||||
### Step 1: 读取产出
|
### Step 1: Read Outputs
|
||||||
|
|
||||||
\`\`\`javascript
|
\`\`\`javascript
|
||||||
const config = JSON.parse(Read(`${workDir}/config.json`));
|
const config = JSON.parse(Read(\`${workDir}/config.json\`));
|
||||||
const analysis = JSON.parse(Read(`${workDir}/analysis.json`));
|
const analysis = JSON.parse(Read(\`${workDir}/analysis.json\`));
|
||||||
const sections = Glob(`${workDir}/sections/*.md`).map(f => Read(f));
|
const sections = Glob(\`${workDir}/sections/*.md\`).map(f => Read(f));
|
||||||
\`\`\`
|
\`\`\`
|
||||||
|
|
||||||
### Step 2: 组装内容
|
### Step 2: Assemble Content
|
||||||
|
|
||||||
\`\`\`javascript
|
\`\`\`javascript
|
||||||
const document = \`
|
const document = \`
|
||||||
# \${config.name}
|
# \${config.name}
|
||||||
|
|
||||||
## 概述
|
## Overview
|
||||||
\${config.description}
|
\${config.description}
|
||||||
|
|
||||||
## 详细内容
|
## Detailed Content
|
||||||
\${sections.join('\\n\\n')}
|
\${sections.join('\\n\\n')}
|
||||||
\`;
|
\`;
|
||||||
\`\`\`
|
\`\`\`
|
||||||
|
|
||||||
### Step 3: 写入文件
|
### Step 3: Write File
|
||||||
|
|
||||||
\`\`\`javascript
|
\`\`\`javascript
|
||||||
Write(`${workDir}/${config.name}-output.md`, document);
|
Write(\`${workDir}/\${config.name}-output.md\`, document);
|
||||||
\`\`\`
|
\`\`\`
|
||||||
|
|
||||||
## Output
|
## Output
|
||||||
|
|
||||||
- **File**: `{name}-output.md`
|
- **File**: \`{name}-output.md\`
|
||||||
- **Format**: Markdown
|
- **Format**: Markdown
|
||||||
```
|
```
|
||||||
|
|
||||||
### 5. 验证型 Phase (Validation)
|
### 5. Validation Phase
|
||||||
|
|
||||||
```markdown
|
```markdown
|
||||||
# Phase 5: Validation
|
# Phase 5: Validation
|
||||||
|
|
||||||
验证输出质量。
|
Verify output quality.
|
||||||
|
|
||||||
## Objective
|
## Objective
|
||||||
|
|
||||||
- 检查输出完整性
|
- Check output completeness
|
||||||
- 验证内容质量
|
- Verify content quality
|
||||||
- 生成验证报告
|
- Generate validation report
|
||||||
|
|
||||||
## Execution Steps
|
## Execution Steps
|
||||||
|
|
||||||
### Step 1: 完整性检查
|
### Step 1: Completeness Check
|
||||||
|
|
||||||
\`\`\`javascript
|
\`\`\`javascript
|
||||||
const outputFile = `${workDir}/${config.name}-output.md`;
|
const outputFile = \`${workDir}/\${config.name}-output.md\`;
|
||||||
const content = Read(outputFile);
|
const content = Read(outputFile);
|
||||||
const completeness = {
|
const completeness = {
|
||||||
hasTitle: content.includes('# '),
|
hasTitle: content.includes('# '),
|
||||||
@@ -376,16 +376,16 @@ const completeness = {
|
|||||||
};
|
};
|
||||||
\`\`\`
|
\`\`\`
|
||||||
|
|
||||||
### Step 2: 质量评估
|
### Step 2: Quality Assessment
|
||||||
|
|
||||||
\`\`\`javascript
|
\`\`\`javascript
|
||||||
const quality = {
|
const quality = {
|
||||||
completeness: Object.values(completeness).filter(v => v).length / 3 * 100,
|
completeness: Object.values(completeness).filter(v => v).length / 3 * 100,
|
||||||
// 其他维度...
|
// Other dimensions...
|
||||||
};
|
};
|
||||||
\`\`\`
|
\`\`\`
|
||||||
|
|
||||||
### Step 3: 生成报告
|
### Step 3: Generate Report
|
||||||
|
|
||||||
\`\`\`javascript
|
\`\`\`javascript
|
||||||
const report = {
|
const report = {
|
||||||
@@ -394,16 +394,16 @@ const report = {
|
|||||||
issues: []
|
issues: []
|
||||||
};
|
};
|
||||||
|
|
||||||
Write(`${workDir}/validation-report.json`, JSON.stringify(report, null, 2));
|
Write(\`${workDir}/validation-report.json\`, JSON.stringify(report, null, 2));
|
||||||
\`\`\`
|
\`\`\`
|
||||||
|
|
||||||
## Output
|
## Output
|
||||||
|
|
||||||
- **File**: `validation-report.json`
|
- **File**: \`validation-report.json\`
|
||||||
- **Format**: JSON
|
- **Format**: JSON
|
||||||
```
|
```
|
||||||
|
|
||||||
## 生成函数
|
## Generation Function
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
function generateSequentialPhase(phaseConfig, index, phases, skillConfig) {
|
function generateSequentialPhase(phaseConfig, index, phases, skillConfig) {
|
||||||
@@ -412,37 +412,37 @@ function generateSequentialPhase(phaseConfig, index, phases, skillConfig) {
|
|||||||
|
|
||||||
return `# Phase ${index + 1}: ${phaseConfig.name}
|
return `# Phase ${index + 1}: ${phaseConfig.name}
|
||||||
|
|
||||||
${phaseConfig.description || `执行 ${phaseConfig.name}`}
|
${phaseConfig.description || `Execute ${phaseConfig.name}`}
|
||||||
|
|
||||||
## Objective
|
## Objective
|
||||||
|
|
||||||
- ${phaseConfig.objectives?.join('\n- ') || 'TODO: 定义目标'}
|
- ${phaseConfig.objectives?.join('\n- ') || 'TODO: Define objectives'}
|
||||||
|
|
||||||
## Input
|
## Input
|
||||||
|
|
||||||
- 依赖: \`${prevPhase ? prevPhase.output : 'user input'}\`
|
- Dependency: \`${prevPhase ? prevPhase.output : 'user input'}\`
|
||||||
- 配置: \`{workDir}/skill-config.json\`
|
- Config: \`{workDir}/skill-config.json\`
|
||||||
|
|
||||||
## Execution Steps
|
## Execution Steps
|
||||||
|
|
||||||
### Step 1: 准备
|
### Step 1: Preparation
|
||||||
|
|
||||||
\`\`\`javascript
|
\`\`\`javascript
|
||||||
${prevPhase ?
|
${prevPhase ?
|
||||||
`const prevOutput = JSON.parse(Read(\`\${workDir}/${prevPhase.output}\`));` :
|
`const prevOutput = JSON.parse(Read(\`${workDir}/${prevPhase.output}\`));` :
|
||||||
'// 首阶段,从配置开始'}
|
'// First phase, start from configuration'}
|
||||||
\`\`\`
|
\`\`\`
|
||||||
|
|
||||||
### Step 2: 处理
|
### Step 2: Processing
|
||||||
|
|
||||||
\`\`\`javascript
|
\`\`\`javascript
|
||||||
// TODO: 实现核心逻辑
|
// TODO: Implement core logic
|
||||||
\`\`\`
|
\`\`\`
|
||||||
|
|
||||||
### Step 3: 输出
|
### Step 3: Output
|
||||||
|
|
||||||
\`\`\`javascript
|
\`\`\`javascript
|
||||||
Write(\`\${workDir}/${phaseConfig.output}\`, JSON.stringify(result, null, 2));
|
Write(\`${workDir}/${phaseConfig.output}\`, JSON.stringify(result, null, 2));
|
||||||
\`\`\`
|
\`\`\`
|
||||||
|
|
||||||
## Output
|
## Output
|
||||||
@@ -452,13 +452,13 @@ Write(\`\${workDir}/${phaseConfig.output}\`, JSON.stringify(result, null, 2));
|
|||||||
|
|
||||||
## Quality Checklist
|
## 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)` :
|
`## 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.md Template
|
||||||
|
|
||||||
用于生成新 Skill 入口文件的模板。
|
Template for generating new Skill entry files.
|
||||||
|
|
||||||
## Purpose
|
## 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
|
## Usage Context
|
||||||
|
|
||||||
| Phase | Usage |
|
| Phase | Usage |
|
||||||
|-------|-------|
|
|-------|-------|
|
||||||
| Phase 2 (Structure Generation) | 创建 SKILL.md 入口文件 |
|
| Phase 2 (Structure Generation) | Create SKILL.md entry file |
|
||||||
| Generation Trigger | `config.execution_mode` 决定架构图样式 |
|
| Generation Trigger | `config.execution_mode` determines architecture diagram style |
|
||||||
| Output Location | `.claude/skills/{skill-name}/SKILL.md` |
|
| 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.
|
||||||
>
|
>
|
||||||
> **禁止**使用以下格式:
|
> **Do NOT use** the following formats:
|
||||||
> - `# Title` 然后 `## Metadata` + yaml 代码块 ❌
|
> - `# 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}}
|
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}}
|
{{mandatory_prerequisites}}
|
||||||
|
|
||||||
@@ -82,31 +82,31 @@ Bash(\`mkdir -p "\${workDir}"\`);
|
|||||||
|
|
||||||
## Reference Documents by Phase
|
## 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}}
|
{{reference_table}}
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 变量说明
|
## Variable Descriptions
|
||||||
|
|
||||||
| 变量 | 类型 | 来源 |
|
| Variable | Type | Source |
|
||||||
|------|------|------|
|
|----------|------|--------|
|
||||||
| `{{skill_name}}` | string | config.skill_name |
|
| `{{skill_name}}` | string | config.skill_name |
|
||||||
| `{{display_name}}` | string | config.display_name |
|
| `{{display_name}}` | string | config.display_name |
|
||||||
| `{{description}}` | string | config.description |
|
| `{{description}}` | string | config.description |
|
||||||
| `{{triggers}}` | string | config.triggers.join(", ") |
|
| `{{triggers}}` | string | config.triggers.join(", ") |
|
||||||
| `{{allowed_tools}}` | string | config.allowed_tools.join(", ") |
|
| `{{allowed_tools}}` | string | config.allowed_tools.join(", ") |
|
||||||
| `{{architecture_diagram}}` | string | 根据 execution_mode 生成 (包含 Phase 0) |
|
| `{{architecture_diagram}}` | string | Generated based on execution_mode (includes Phase 0) |
|
||||||
| `{{design_principles}}` | string | 根据 execution_mode 生成 |
|
| `{{design_principles}}` | string | Generated based on execution_mode |
|
||||||
| `{{mandatory_prerequisites}}` | string | 强制前置阅读文档列表 (specs + templates) |
|
| `{{mandatory_prerequisites}}` | string | List of mandatory prerequisite reading documents (specs + templates) |
|
||||||
| `{{execution_flow}}` | string | 根据 phases/actions 生成 (Phase 0 在最前) |
|
| `{{execution_flow}}` | string | Generated from phases/actions (Phase 0 first) |
|
||||||
| `{{output_location}}` | string | config.output.location |
|
| `{{output_location}}` | string | config.output.location |
|
||||||
| `{{additional_dirs}}` | string | 根据 execution_mode 生成 |
|
| `{{additional_dirs}}` | string | Generated based on execution_mode |
|
||||||
| `{{output_structure}}` | string | 根据配置生成 |
|
| `{{output_structure}}` | string | Generated based on configuration |
|
||||||
| `{{reference_table}}` | string | 根据文件列表生成 |
|
| `{{reference_table}}` | string | Generated from file list |
|
||||||
|
|
||||||
## 生成函数
|
## Generation Function
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
function generateSkillMd(config) {
|
function generateSkillMd(config) {
|
||||||
@@ -118,32 +118,32 @@ function generateSkillMd(config) {
|
|||||||
.replace(/\{\{description\}\}/g, config.description)
|
.replace(/\{\{description\}\}/g, config.description)
|
||||||
.replace(/\{\{triggers\}\}/g, config.triggers.map(t => `"${t}"`).join(", "))
|
.replace(/\{\{triggers\}\}/g, config.triggers.map(t => `"${t}"`).join(", "))
|
||||||
.replace(/\{\{allowed_tools\}\}/g, config.allowed_tools.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(/\{\{design_principles\}\}/g, generatePrinciples(config))
|
||||||
.replace(/\{\{mandatory_prerequisites\}\}/g, generatePrerequisites(config)) // 强制前置条件
|
.replace(/\{\{mandatory_prerequisites\}\}/g, generatePrerequisites(config)) // Mandatory prerequisites
|
||||||
.replace(/\{\{execution_flow\}\}/g, generateFlow(config)) // Phase 0 在最前
|
.replace(/\{\{execution_flow\}\}/g, generateFlow(config)) // Phase 0 first
|
||||||
.replace(/\{\{output_location\}\}/g, config.output.location)
|
.replace(/\{\{output_location\}\}/g, config.output.location)
|
||||||
.replace(/\{\{additional_dirs\}\}/g, generateAdditionalDirs(config))
|
.replace(/\{\{additional_dirs\}\}/g, generateAdditionalDirs(config))
|
||||||
.replace(/\{\{output_structure\}\}/g, generateOutputStructure(config))
|
.replace(/\{\{output_structure\}\}/g, generateOutputStructure(config))
|
||||||
.replace(/\{\{reference_table\}\}/g, generateReferenceTable(config));
|
.replace(/\{\{reference_table\}\}/g, generateReferenceTable(config));
|
||||||
}
|
}
|
||||||
|
|
||||||
// 生成强制前置条件表格
|
// Generate mandatory prerequisites table
|
||||||
function generatePrerequisites(config) {
|
function generatePrerequisites(config) {
|
||||||
const specs = config.specs || [];
|
const specs = config.specs || [];
|
||||||
const templates = config.templates || [];
|
const templates = config.templates || [];
|
||||||
|
|
||||||
let result = '### 规范文档 (必读)\n\n';
|
let result = '### Specification Documents (Required Reading)\n\n';
|
||||||
result += '| Document | Purpose | When |\n';
|
result += '| Document | Purpose | When |\n';
|
||||||
result += '|----------|---------|------|\n';
|
result += '|----------|---------|------|\n';
|
||||||
|
|
||||||
specs.forEach((spec, index) => {
|
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`;
|
result += `| [${spec.path}](${spec.path}) | ${spec.purpose} | ${when} |\n`;
|
||||||
});
|
});
|
||||||
|
|
||||||
if (templates.length > 0) {
|
if (templates.length > 0) {
|
||||||
result += '\n### 模板文件 (生成前必读)\n\n';
|
result += '\n### Template Files (Must read before generation)\n\n';
|
||||||
result += '| Document | Purpose |\n';
|
result += '| Document | Purpose |\n';
|
||||||
result += '|----------|---------|\n';
|
result += '|----------|---------|\n';
|
||||||
templates.forEach(tmpl => {
|
templates.forEach(tmpl => {
|
||||||
@@ -154,7 +154,7 @@ function generatePrerequisites(config) {
|
|||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
// ⭐ 新增:生成分阶段参考文档指南
|
// Generate phase-by-phase reference document guide
|
||||||
function generateReferenceTable(config) {
|
function generateReferenceTable(config) {
|
||||||
const phases = config.phases || config.actions || [];
|
const phases = config.phases || config.actions || [];
|
||||||
const specs = config.specs || [];
|
const specs = config.specs || [];
|
||||||
@@ -162,65 +162,53 @@ function generateReferenceTable(config) {
|
|||||||
|
|
||||||
let result = '';
|
let result = '';
|
||||||
|
|
||||||
// 为每个执行阶段生成文档导航
|
// Generate document navigation for each execution phase
|
||||||
phases.forEach((phase, index) => {
|
phases.forEach((phase, index) => {
|
||||||
const phaseNum = index + 1;
|
const phaseNum = index + 1;
|
||||||
const phaseEmoji = getPhaseEmoji(phase.type || 'default');
|
|
||||||
const phaseTitle = phase.display_name || phase.name;
|
const phaseTitle = phase.display_name || phase.name;
|
||||||
|
|
||||||
result += `### ${phaseEmoji} Phase ${phaseNum}: ${phaseTitle}\n`;
|
result += `### Phase ${phaseNum}: ${phaseTitle}\n`;
|
||||||
result += `执行Phase ${phaseNum}时查阅的文档\n\n`;
|
result += `Documents to reference when executing Phase ${phaseNum}\n\n`;
|
||||||
|
|
||||||
// 列出该阶段相关的文档
|
// List documents related to this phase
|
||||||
const relatedDocs = filterDocsByPhase(specs, phase, index);
|
const relatedDocs = filterDocsByPhase(specs, phase, index);
|
||||||
if (relatedDocs.length > 0) {
|
if (relatedDocs.length > 0) {
|
||||||
result += '| Document | Purpose | When to Use |\n';
|
result += '| Document | Purpose | When to Use |\n';
|
||||||
result += '|----------|---------|-------------|\n';
|
result += '|----------|---------|-------------|\n';
|
||||||
relatedDocs.forEach(doc => {
|
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 += '\n';
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// 问题排查部分
|
// Troubleshooting section
|
||||||
result += '### 🔍 Debugging & Troubleshooting (问题排查)\n';
|
result += '### Debugging & Troubleshooting\n';
|
||||||
result += '遇到问题时查阅的文档\n\n';
|
result += 'Documents to reference when encountering issues\n\n';
|
||||||
result += '| Issue | Solution Document |\n';
|
result += '| Issue | Solution Document |\n';
|
||||||
result += '|-------|-------------------|\n';
|
result += '|-------|-------------------|\n';
|
||||||
result += `| Phase执行失败 | 查阅相应Phase的文档 |\n`;
|
result += `| Phase execution failed | Refer to the relevant Phase documentation |\n`;
|
||||||
result += `| 输出不符合预期 | [specs/quality-standards.md](specs/quality-standards.md) - 验证质量标准 |\n`;
|
result += `| Output does not meet expectations | [specs/quality-standards.md](specs/quality-standards.md) - Verify quality standards |\n`;
|
||||||
result += '\n';
|
result += '\n';
|
||||||
|
|
||||||
// 深度学习参考
|
// In-depth learning reference
|
||||||
result += '### 📚 Reference & Background (深度学习)\n';
|
result += '### Reference & Background\n';
|
||||||
result += '用于理解原始实现和设计决策\n\n';
|
result += 'For understanding the original implementation and design decisions\n\n';
|
||||||
result += '| Document | Purpose | Notes |\n';
|
result += '| Document | Purpose | Notes |\n';
|
||||||
result += '|----------|---------|-------|\n';
|
result += '|----------|---------|-------|\n';
|
||||||
templates.forEach(tmpl => {
|
templates.forEach(tmpl => {
|
||||||
result += `| [${tmpl.path}](${tmpl.path}) | ${tmpl.purpose} | 生成时参考 |\n`;
|
result += `| [${tmpl.path}](${tmpl.path}) | ${tmpl.purpose} | Reference during generation |\n`;
|
||||||
});
|
});
|
||||||
|
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 辅助函数:获取Phase表情符号
|
// Helper function: Get Phase emoji (removed)
|
||||||
function getPhaseEmoji(phaseType) {
|
// Note: Emoji support has been removed. Consider using Phase numbers instead.
|
||||||
const emojiMap = {
|
|
||||||
'discovery': '📋',
|
|
||||||
'generation': '🔧',
|
|
||||||
'analysis': '🔍',
|
|
||||||
'implementation': '⚙️',
|
|
||||||
'validation': '✅',
|
|
||||||
'completion': '🏁',
|
|
||||||
'default': '📌'
|
|
||||||
};
|
|
||||||
return emojiMap[phaseType] || emojiMap['default'];
|
|
||||||
}
|
|
||||||
|
|
||||||
// 辅助函数:根据Phase过滤文档
|
// Helper function: Filter documents by Phase
|
||||||
function filterDocsByPhase(specs, phase, phaseIndex) {
|
function filterDocsByPhase(specs, phase, phaseIndex) {
|
||||||
// 简单过滤逻辑:匹配phase名称关键词
|
// Simple filtering logic: match phase name keywords
|
||||||
const keywords = phase.name.toLowerCase().split('-');
|
const keywords = phase.name.toLowerCase().split('-');
|
||||||
return specs.filter(spec => {
|
return specs.filter(spec => {
|
||||||
const specName = spec.path.toLowerCase();
|
const specName = spec.path.toLowerCase();
|
||||||
@@ -229,7 +217,7 @@ function filterDocsByPhase(specs, phase, phaseIndex) {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
## Sequential 模式示例
|
## Sequential Mode Example
|
||||||
|
|
||||||
```markdown
|
```markdown
|
||||||
---
|
---
|
||||||
@@ -245,36 +233,33 @@ Generate API documentation from source code.
|
|||||||
## Architecture Overview
|
## Architecture Overview
|
||||||
|
|
||||||
\`\`\`
|
\`\`\`
|
||||||
┌─────────────────────────────────────────────────────────────────┐
|
Phase 0: Specification Study (Mandatory prerequisite - Read and understand design specifications)
|
||||||
│ ⚠️ Phase 0: Specification → 阅读并理解设计规范 (强制前置) │
|
↓
|
||||||
│ Study │
|
Phase 1: Scanning → endpoints.json
|
||||||
│ ↓ │
|
↓
|
||||||
│ Phase 1: Scanning → endpoints.json │
|
Phase 2: Parsing → schemas.json
|
||||||
│ ↓ │
|
↓
|
||||||
│ Phase 2: Parsing → schemas.json │
|
Phase 3: Generation → api-docs.md
|
||||||
│ ↓ │
|
|
||||||
│ 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 |
|
| 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 |
|
| 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
|
```markdown
|
||||||
---
|
---
|
||||||
@@ -290,36 +275,34 @@ Interactive task management with CRUD operations.
|
|||||||
## Architecture Overview
|
## Architecture Overview
|
||||||
|
|
||||||
\`\`\`
|
\`\`\`
|
||||||
┌─────────────────────────────────────────────────────────────────┐
|
Phase 0: Specification Study (Mandatory prerequisite)
|
||||||
│ ⚠️ Phase 0: Specification Study (强制前置) │
|
|
||||||
└───────────────┬─────────────────────────────────────────────────┘
|
|
||||||
↓
|
↓
|
||||||
┌─────────────────────────────────────────────────────────────────┐
|
┌────────────────────────────────────────┐
|
||||||
│ Orchestrator (状态驱动决策) │
|
│ Orchestrator (State-driven decision) │
|
||||||
└───────────────┬─────────────────────────────────────────────────┘
|
└────────────┬───────────────────────────┘
|
||||||
│
|
│
|
||||||
┌───────────┼───────────┬───────────┐
|
┌────────┼────────┬────────┐
|
||||||
↓ ↓ ↓ ↓
|
↓ ↓ ↓ ↓
|
||||||
┌───────┐ ┌───────┐ ┌───────┐ ┌───────┐
|
┌────────┐ ┌────────┐ ┌────────┐ ┌────────┐
|
||||||
│ List │ │Create │ │ Edit │ │Delete │
|
│ 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 |
|
| Document | Purpose | Priority |
|
||||||
|----------|---------|----------|
|
|----------|---------|----------|
|
||||||
| [specs/task-schema.md](specs/task-schema.md) | 任务数据结构规范 | **P0 - 最高** |
|
| [specs/task-schema.md](specs/task-schema.md) | Task data structure specification | **P0 - Highest** |
|
||||||
| [specs/action-catalog.md](specs/action-catalog.md) | 动作目录 | P1 |
|
| [specs/action-catalog.md](specs/action-catalog.md) | Action catalog | P1 |
|
||||||
|
|
||||||
### 模板文件 (生成前必读)
|
### Template Files (Must read before generation)
|
||||||
|
|
||||||
| Document | Purpose |
|
| Document | Purpose |
|
||||||
|----------|---------|
|
|----------|---------|
|
||||||
| [templates/orchestrator-base.md](templates/orchestrator-base.md) | 编排器模板 |
|
| [templates/orchestrator-base.md](templates/orchestrator-base.md) | Orchestrator template |
|
||||||
| [templates/action-base.md](templates/action-base.md) | 动作模板 |
|
| [templates/action-base.md](templates/action-base.md) | Action template |
|
||||||
```
|
```
|
||||||
|
|||||||
Reference in New Issue
Block a user