diff --git a/.claude/skills/skill-generator/SKILL.md b/.claude/skills/skill-generator/SKILL.md index ad2b70ea..5410bcc0 100644 --- a/.claude/skills/skill-generator/SKILL.md +++ b/.claude/skills/skill-generator/SKILL.md @@ -1,6 +1,6 @@ --- 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 --- @@ -36,96 +36,94 @@ Meta-skill for creating new Claude Code skills with configurable 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 │ -│ (读取状态 → 选择 Phase → 执行 → 更新) │ -└───────────────┬─────────────────────────┘ - │ - ┌───────────┼───────────┐ - ↓ ↓ ↓ -┌───────┐ ┌───────┐ ┌───────┐ -│Phase A│ │Phase B│ │Phase C│ -│(独立) │ │(独立) │ │(独立) │ -└───────┘ └───────┘ └───────┘ +--------------------------------------------------- + Orchestrator Agent + (Read state -> Select Phase -> Execute -> Update) +--------------------------------------------------- + | + ---------+----------+---------- + | | | + 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 -1. **模式感知**: 根据任务特性自动推荐执行模式 -2. **骨架生成**: 生成完整目录结构和文件骨架 -3. **规范遵循**: 严格遵循 `_shared/SKILL-DESIGN-SPEC.md` -4. **可扩展性**: 生成的 Skill 易于扩展和修改 +1. **Mode Awareness**: Automatically recommend execution mode based on task characteristics +2. **Skeleton Generation**: Generate complete directory structure and file skeletons +3. **Standards Compliance**: Strictly follow `_shared/SKILL-DESIGN-SPEC.md` +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 | |----------|---------|----------| -| [../_shared/SKILL-DESIGN-SPEC.md](../_shared/SKILL-DESIGN-SPEC.md) | 通用设计规范 - 定义所有 Skill 的结构、命名、质量标准 | **P0 - 最高** | -| [specs/reference-docs-spec.md](specs/reference-docs-spec.md) | **参考文档生成规范** - 确保生成的skill中Reference Documents部分有正确的分阶段组织和使用时机指引 | **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) | 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 | |----------|---------| -| [templates/skill-md.md](templates/skill-md.md) | SKILL.md 入口文件模板 | -| [templates/sequential-phase.md](templates/sequential-phase.md) | Sequential Phase 模板 | -| [templates/autonomous-orchestrator.md](templates/autonomous-orchestrator.md) | Autonomous 编排器模板 | -| [templates/autonomous-action.md](templates/autonomous-action.md) | Autonomous Action 模板 | -| [templates/code-analysis-action.md](templates/code-analysis-action.md) | 代码分析 Action 模板 | -| [templates/llm-action.md](templates/llm-action.md) | LLM Action 模板 | -| [templates/script-template.md](templates/script-template.md) | 统一脚本模板 (Bash + Python) | +| [templates/skill-md.md](templates/skill-md.md) | SKILL.md entry file template | +| [templates/sequential-phase.md](templates/sequential-phase.md) | Sequential Phase template | +| [templates/autonomous-orchestrator.md](templates/autonomous-orchestrator.md) | Autonomous Orchestrator template | +| [templates/autonomous-action.md](templates/autonomous-action.md) | Autonomous Action template | +| [templates/code-analysis-action.md](templates/code-analysis-action.md) | Code Analysis Action template | +| [templates/llm-action.md](templates/llm-action.md) | LLM Action template | +| [templates/script-template.md](templates/script-template.md) | Unified Script Template (Bash + Python) | -### 规范文档 (按需阅读) +### Specification Documents (Read as Needed) | Document | Purpose | |----------|---------| -| [specs/execution-modes.md](specs/execution-modes.md) | 执行模式规范 | -| [specs/skill-requirements.md](specs/skill-requirements.md) | Skill 需求规范 | -| [specs/cli-integration.md](specs/cli-integration.md) | CLI 集成规范 | -| [specs/scripting-integration.md](specs/scripting-integration.md) | 脚本集成规范 | +| [specs/execution-modes.md](specs/execution-modes.md) | Execution Modes Specification | +| [specs/skill-requirements.md](specs/skill-requirements.md) | Skill Requirements Specification | +| [specs/cli-integration.md](specs/cli-integration.md) | CLI Integration Specification | +| [specs/scripting-integration.md](specs/scripting-integration.md) | Script Integration Specification | -### Phase 执行指南 (执行时参考) +### Phase Execution Guides (Reference During Execution) | Document | Purpose | |----------|---------| -| [phases/01-requirements-discovery.md](phases/01-requirements-discovery.md) | 收集 Skill 需求 | -| [phases/02-structure-generation.md](phases/02-structure-generation.md) | 生成目录结构 | -| [phases/03-phase-generation.md](phases/03-phase-generation.md) | 生成 Phase 文件 | -| [phases/04-specs-templates.md](phases/04-specs-templates.md) | 生成规范和模板 | -| [phases/05-validation.md](phases/05-validation.md) | 验证和文档 | +| [phases/01-requirements-discovery.md](phases/01-requirements-discovery.md) | Collect Skill Requirements | +| [phases/02-structure-generation.md](phases/02-structure-generation.md) | Generate Directory Structure | +| [phases/03-phase-generation.md](phases/03-phase-generation.md) | Generate Phase Files | +| [phases/04-specs-templates.md](phases/04-specs-templates.md) | Generate Specs and Templates | +| [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: └─ Convert user request to structured format (skill-name/purpose/mode) -Phase 0: Specification Study (⚠️ MANDATORY - 禁止跳过) - └─ Read specification documents - ├─ Load: ../_shared/SKILL-DESIGN-SPEC.md - ├─ Load: All templates/*.md files - ├─ Understand: Structure rules, naming conventions, quality standards - └─ Output: Internalized requirements (in-memory, no file output) - └─ Validation: ⛔ MUST complete before Phase 1 +Phase 0: Specification Study (MANDATORY - Must complete before proceeding) + - Read specification documents + - Load: ../_shared/SKILL-DESIGN-SPEC.md + - Load: All templates/*.md files + - Understand: Structure rules, naming conventions, quality standards + - Output: Internalized requirements (in-memory, no file output) + - Validation: MUST complete before Phase 1 Phase 1: Requirements Discovery - └─ Gather skill requirements via user interaction - ├─ Tool: AskUserQuestion - │ ├─ Prompt: Skill name, purpose, execution mode - │ ├─ Prompt: Phase/Action definition - │ └─ Prompt: Tool dependencies, output format - ├─ Process: Generate configuration object - └─ Output: skill-config.json → ${workDir}/ - ├─ skill_name: string - ├─ execution_mode: "sequential" | "autonomous" - ├─ phases/actions: array - └─ allowed_tools: array + - Gather skill requirements via user interaction + - Tool: AskUserQuestion + - Collect: Skill name, purpose, execution mode + - Collect: Phase/Action definition + - Collect: Tool dependencies, output format + - Process: Generate configuration object + - Output: skill-config.json + - Contains: skill_name, execution_mode, phases/actions, allowed_tools Phase 2: Structure Generation - └─ Create directory structure and entry file - ├─ Input: skill-config.json (from Phase 1) - ├─ Tool: Bash - │ └─ Execute: mkdir -p .claude/skills/{skill-name}/{phases,specs,templates,scripts} - ├─ Tool: Write - │ └─ Generate: SKILL.md (entry point with architecture diagram) - └─ 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/ + - Create directory structure and entry file + - Input: skill-config.json (from Phase 1) + - Tool: Bash + - Execute: mkdir -p .claude/skills/{skill-name}/{phases,specs,templates,scripts} + - Tool: Write + - Generate: SKILL.md (entry point with architecture diagram) + - Output: Complete directory structure Phase 3: Phase/Action Generation - └─ Decision (execution_mode check): - ├─ execution_mode === "sequential" → Generate Sequential Phases - │ ├─ Tool: Read (template: templates/sequential-phase.md) - │ ├─ Loop: For each phase in config.sequential_config.phases - │ │ ├─ Generate: phases/{phase-id}.md - │ │ └─ Link: Previous phase output → Current phase input - │ ├─ Tool: Write (orchestrator: phases/_orchestrator.md) - │ ├─ Tool: Write (workflow definition: workflow.json) - │ └─ Output: phases/01-{name}.md, phases/02-{name}.md, ... - │ - └─ execution_mode === "autonomous" → Generate Orchestrator + Actions - ├─ Tool: Read (template: templates/autonomous-orchestrator.md) - ├─ Tool: Write (state schema: phases/state-schema.md) - ├─ Tool: Write (orchestrator: phases/orchestrator.md) - ├─ Tool: Write (action catalog: specs/action-catalog.md) - ├─ Loop: For each action in config.autonomous_config.actions - │ ├─ Tool: Read (template: templates/autonomous-action.md) - │ └─ Generate: phases/actions/{action-id}.md - └─ Output: phases/orchestrator.md, phases/actions/*.md + - Decision (execution_mode check): + - IF execution_mode === "sequential": Generate Sequential Phases + - Read template: templates/sequential-phase.md + - Loop: For each phase in config.sequential_config.phases + - Generate: phases/{phase-id}.md + - Link: Previous phase output -> Current phase input + - Write: phases/_orchestrator.md + - Write: workflow.json + - Output: phases/01-{name}.md, phases/02-{name}.md, ... + + - ELSE IF execution_mode === "autonomous": Generate Orchestrator + Actions + - Read template: templates/autonomous-orchestrator.md + - Write: phases/state-schema.md + - Write: phases/orchestrator.md + - Write: specs/action-catalog.md + - Loop: For each action in config.autonomous_config.actions + - Read template: templates/autonomous-action.md + - Generate: phases/actions/{action-id}.md + - Output: phases/orchestrator.md, phases/actions/*.md Phase 4: Specs & Templates - └─ Generate domain specifications and templates - ├─ Input: skill-config.json (domain context) - ├─ ⚠️ 参考规范: [specs/reference-docs-spec.md](specs/reference-docs-spec.md) - 确保生成的参考文档有正确的分阶段组织 - ├─ Tool: Write - │ ├─ Generate: specs/{domain}-requirements.md - │ ├─ Generate: specs/quality-standards.md - │ └─ Generate: templates/agent-base.md (if needed) - └─ Output: Domain-specific documentation - ├─ specs/{skill-name}-requirements.md - ├─ specs/quality-standards.md - └─ templates/agent-base.md + - Generate domain specifications and templates + - Input: skill-config.json (domain context) + - Reference: [specs/reference-docs-spec.md](specs/reference-docs-spec.md) for document organization + - Tool: Write + - Generate: specs/{domain}-requirements.md + - Generate: specs/quality-standards.md + - Generate: templates/agent-base.md (if needed) + - Output: Domain-specific documentation Phase 5: Validation & Documentation - └─ Verify completeness and generate usage guide - ├─ Input: All generated files from previous phases - ├─ Tool: Glob + Read - │ └─ Check: Required files exist and contain proper structure - ├─ Tool: Write - │ ├─ Generate: README.md (usage instructions) - │ └─ Generate: validation-report.json (completeness check) - └─ 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" + - Verify completeness and generate usage guide + - Input: All generated files from previous phases + - Tool: Glob + Read + - Check: Required files exist and contain proper structure + - Tool: Write + - Generate: README.md (usage instructions) + - Generate: validation-report.json (completeness check) + - Output: Final documentation ``` **Execution Protocol**: @@ -278,83 +257,83 @@ Write(`${skillDir}/README.md`, generateReadme(config, validation)); ## 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 | |----------|---------|-------------| -| [../_shared/SKILL-DESIGN-SPEC.md](../_shared/SKILL-DESIGN-SPEC.md) | Skill设计通用规范 | 理解Skill结构和命名规范 ✅ **必读** | -| [specs/reference-docs-spec.md](specs/reference-docs-spec.md) | 参考文档生成规范 | 确保Reference Documents有正确的组织方式 ✅ **必读** | +| [../_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 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 | |----------|---------|-------------| -| [phases/01-requirements-discovery.md](phases/01-requirements-discovery.md) | Phase 1执行指南 | 理解如何收集用户需求和生成配置 | -| [specs/skill-requirements.md](specs/skill-requirements.md) | Skill需求规范 | 理解Skill应包含哪些信息 | +| [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 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 | |----------|---------|-------------| -| [phases/02-structure-generation.md](phases/02-structure-generation.md) | Phase 2执行指南 | 理解如何生成目录结构 | -| [templates/skill-md.md](templates/skill-md.md) | SKILL.md模板 | 了解如何生成入口文件 | +| [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 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 | |----------|---------|-------------| -| [phases/03-phase-generation.md](phases/03-phase-generation.md) | Phase 3执行指南 | 理解Sequential vs Autonomous生成逻辑 | -| [templates/sequential-phase.md](templates/sequential-phase.md) | Sequential Phase模板 | 生成Sequential模式的phase文件 | -| [templates/autonomous-orchestrator.md](templates/autonomous-orchestrator.md) | Orchestrator模板 | 生成Autonomous模式的编排器 | -| [templates/autonomous-action.md](templates/autonomous-action.md) | Action模板 | 生成Autonomous模式的action | +| [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 template | Generate phase files for Sequential mode | +| [templates/autonomous-orchestrator.md](templates/autonomous-orchestrator.md) | Orchestrator template | Generate orchestrator for Autonomous mode | +| [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 | |----------|---------|-------------| -| [phases/04-specs-templates.md](phases/04-specs-templates.md) | Phase 4执行指南 | 理解如何生成domain-specific文档 | -| [specs/reference-docs-spec.md](specs/reference-docs-spec.md) | 参考文档规范 | ⭐ 生成Specs时要遵循的规范 | +| [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) | 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 | |----------|---------|-------------| -| [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 | |-------|------------------| -| 生成的Skill缺少Reference Documents | [specs/reference-docs-spec.md](specs/reference-docs-spec.md) - 检查是否遵循分阶段组织 | -| 参考文档组织混乱 | [specs/reference-docs-spec.md](specs/reference-docs-spec.md) - 核心原则部分 | -| 生成的文档不符合质量标准 | [../_shared/SKILL-DESIGN-SPEC.md](../_shared/SKILL-DESIGN-SPEC.md) | +| Generated Skill missing Reference Documents | [specs/reference-docs-spec.md](specs/reference-docs-spec.md) - verify phase-based organization is followed | +| Reference document organization unclear | [specs/reference-docs-spec.md](specs/reference-docs-spec.md) - Core Principles section | +| 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 | |----------|---------|-------| -| [specs/execution-modes.md](specs/execution-modes.md) | 执行模式详细规范 | Sequential vs Autonomous的对比和适用场景 | -| [specs/cli-integration.md](specs/cli-integration.md) | CLI集成规范 | 生成的Skill如何与CLI集成 | -| [specs/scripting-integration.md](specs/scripting-integration.md) | 脚本集成规范 | Phase中如何使用脚本 | -| [templates/script-template.md](templates/script-template.md) | 脚本模板 | Bash + Python统一模板 | +| [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 integration specification | How generated Skills integrate with CLI | +| [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) | Script template | Unified Bash + Python template | --- @@ -364,13 +343,13 @@ Write(`${skillDir}/README.md`, generateReadme(config, validation)); ``` .claude/skills/{skill-name}/ -├── SKILL.md # 入口文件 +├── SKILL.md # Entry file ├── phases/ -│ ├── _orchestrator.md # 声明式编排器 -│ ├── workflow.json # 工作流定义 -│ ├── 01-{step-one}.md # 阶段 1 -│ ├── 02-{step-two}.md # 阶段 2 -│ └── 03-{step-three}.md # 阶段 3 +│ ├── _orchestrator.md # Declarative orchestrator +│ ├── workflow.json # Workflow definition +│ ├── 01-{step-one}.md # Phase 1 +│ ├── 02-{step-two}.md # Phase 2 +│ └── 03-{step-three}.md # Phase 3 ├── specs/ │ ├── {skill-name}-requirements.md │ └── quality-standards.md @@ -384,10 +363,10 @@ Write(`${skillDir}/README.md`, generateReadme(config, validation)); ``` .claude/skills/{skill-name}/ -├── SKILL.md # 入口文件 +├── SKILL.md # Entry file ├── phases/ -│ ├── orchestrator.md # 编排器 (状态驱动) -│ ├── state-schema.md # 状态结构定义 +│ ├── orchestrator.md # Orchestrator (state-driven) +│ ├── state-schema.md # State schema definition │ └── actions/ │ ├── action-init.md │ ├── action-create.md @@ -407,80 +386,80 @@ Write(`${skillDir}/README.md`, generateReadme(config, validation)); ## 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 | |----------|---------|-------------| -| [../_shared/SKILL-DESIGN-SPEC.md](../_shared/SKILL-DESIGN-SPEC.md) | Skill设计通用规范 | 理解Skill结构和命名规范 ✅ **必读** | -| [specs/reference-docs-spec.md](specs/reference-docs-spec.md) | 参考文档生成规范 | 确保Reference Documents有正确的组织方式 ✅ **必读** | +| [../_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 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 | |----------|---------|-------------| -| [phases/01-requirements-discovery.md](phases/01-requirements-discovery.md) | Phase 1执行指南 | 理解如何收集用户需求和生成配置 | -| [specs/skill-requirements.md](specs/skill-requirements.md) | Skill需求规范 | 理解Skill应包含哪些信息 | +| [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 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 | |----------|---------|-------------| -| [phases/02-structure-generation.md](phases/02-structure-generation.md) | Phase 2执行指南 | 理解如何生成目录结构 | -| [templates/skill-md.md](templates/skill-md.md) | SKILL.md模板 | 了解如何生成入口文件 | +| [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 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 | |----------|---------|-------------| -| [phases/03-phase-generation.md](phases/03-phase-generation.md) | Phase 3执行指南 | 理解Sequential vs Autonomous生成逻辑 | -| [templates/sequential-phase.md](templates/sequential-phase.md) | Sequential Phase模板 | 生成Sequential模式的phase文件 | -| [templates/autonomous-orchestrator.md](templates/autonomous-orchestrator.md) | Orchestrator模板 | 生成Autonomous模式的编排器 | -| [templates/autonomous-action.md](templates/autonomous-action.md) | Action模板 | 生成Autonomous模式的action | +| [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 template | Generate phase files for Sequential mode | +| [templates/autonomous-orchestrator.md](templates/autonomous-orchestrator.md) | Orchestrator template | Generate orchestrator for Autonomous mode | +| [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 | |----------|---------|-------------| -| [phases/04-specs-templates.md](phases/04-specs-templates.md) | Phase 4执行指南 | 理解如何生成domain-specific文档 | -| [specs/reference-docs-spec.md](specs/reference-docs-spec.md) | 参考文档规范 | ⭐ 生成Specs时要遵循的规范 | +| [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) | 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 | |----------|---------|-------------| -| [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 | |-------|------------------| -| 生成的Skill缺少Reference Documents | [specs/reference-docs-spec.md](specs/reference-docs-spec.md) - 检查是否遵循分阶段组织 | -| 参考文档组织混乱 | [specs/reference-docs-spec.md](specs/reference-docs-spec.md) - 核心原则部分 | -| 生成的文档不符合质量标准 | [../_shared/SKILL-DESIGN-SPEC.md](../_shared/SKILL-DESIGN-SPEC.md) | +| Generated Skill missing Reference Documents | [specs/reference-docs-spec.md](specs/reference-docs-spec.md) - verify phase-based organization is followed | +| Reference document organization unclear | [specs/reference-docs-spec.md](specs/reference-docs-spec.md) - Core Principles section | +| 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 | |----------|---------|-------| -| [specs/execution-modes.md](specs/execution-modes.md) | 执行模式详细规范 | Sequential vs Autonomous的对比和适用场景 | -| [specs/cli-integration.md](specs/cli-integration.md) | CLI集成规范 | 生成的Skill如何与CLI集成 | -| [specs/scripting-integration.md](specs/scripting-integration.md) | 脚本集成规范 | Phase中如何使用脚本 | -| [templates/script-template.md](templates/script-template.md) | 脚本模板 | Bash + Python统一模板 | \ No newline at end of file +| [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 integration specification | How generated Skills integrate with CLI | +| [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) | Script template | Unified Bash + Python template | \ No newline at end of file diff --git a/.claude/skills/skill-generator/phases/01-requirements-discovery.md b/.claude/skills/skill-generator/phases/01-requirements-discovery.md index b54b69c2..e218deb3 100644 --- a/.claude/skills/skill-generator/phases/01-requirements-discovery.md +++ b/.claude/skills/skill-generator/phases/01-requirements-discovery.md @@ -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 const basicInfo = await AskUserQuestion({ questions: [ { - question: "新 Skill 的名称是什么?(英文,小写-连字符格式,如 'api-docs')", - header: "Skill 名称", + question: "What is the name of the new Skill? (English, lowercase with hyphens, e.g., 'api-docs')", + header: "Skill Name", multiSelect: false, options: [ - { label: "自动生成", description: "根据后续描述自动生成名称" }, - { label: "手动输入", description: "现在输入自定义名称" } + { label: "Auto-generate", description: "Generate name automatically based on description" }, + { label: "Manual Input", description: "Enter custom name now" } ] }, { - question: "Skill 的主要用途是什么?", - header: "用途类型", + question: "What is the primary purpose of the Skill?", + header: "Purpose Type", multiSelect: false, options: [ - { label: "文档生成", description: "生成 Markdown/HTML 文档(如手册、报告)" }, - { label: "代码分析", description: "分析代码结构、质量、安全性" }, - { label: "交互管理", description: "管理 Issue、任务、工作流(CRUD 操作)" }, - { label: "数据处理", description: "ETL、格式转换、报告生成" } + { label: "Document Generation", description: "Generate Markdown/HTML documents (manuals, reports)" }, + { label: "Code Analysis", description: "Analyze code structure, quality, security" }, + { label: "Interactive Management", description: "Manage Issues, tasks, workflows (CRUD operations)" }, + { label: "Data Processing", description: "ETL, format conversion, report generation" } ] } ] }); -// 如果选择手动输入,进一步询问 -if (basicInfo["Skill 名称"] === "手动输入") { - // 用户会在 "Other" 中输入 +// If manual input is selected, prompt further +if (basicInfo["Skill Name"] === "Manual Input") { + // User will input in "Other" } -// 根据用途类型推断描述模板 +// Infer description template based on purpose type const purposeTemplates = { - "文档生成": "Generate {type} documents from {source}", - "代码分析": "Analyze {target} for {purpose}", - "交互管理": "Manage {entity} with interactive operations", - "数据处理": "Process {data} and generate {output}" + "Document Generation": "Generate {type} documents from {source}", + "Code Analysis": "Analyze {target} for {purpose}", + "Interactive Management": "Manage {entity} with interactive operations", + "Data Processing": "Process {data} and generate {output}" }; ``` -### Step 2: 执行模式选择 +### Step 2: Execution Mode Selection ```javascript const modeInfo = await AskUserQuestion({ questions: [ { - question: "选择执行模式:", - header: "执行模式", + question: "Select execution mode:", + header: "Execution Mode", multiSelect: false, options: [ - { - label: "Sequential (顺序模式)", - description: "阶段按固定顺序执行(收集→分析→生成),适合流水线任务(推荐)" + { + label: "Sequential (Sequential Mode)", + description: "Phases execute in fixed order (collect→analyze→generate), suitable for pipeline tasks (recommended)" }, - { - label: "Autonomous (自主模式)", - description: "动态选择执行路径,适合交互式任务(如 Issue 管理)" + { + label: "Autonomous (Autonomous Mode)", + description: "Dynamically select execution path, suitable for interactive tasks (e.g., Issue management)" }, - { - label: "Hybrid (混合模式)", - description: "初始化和收尾固定,中间交互灵活" + { + label: "Hybrid (Hybrid Mode)", + description: "Fixed initialization and finalization, flexible interaction in the middle" } ] } ] }); -const executionMode = modeInfo["执行模式"].includes("Sequential") ? "sequential" : - modeInfo["执行模式"].includes("Autonomous") ? "autonomous" : "hybrid"; +const executionMode = modeInfo["Execution Mode"].includes("Sequential") ? "sequential" : + modeInfo["Execution Mode"].includes("Autonomous") ? "autonomous" : "hybrid"; ``` -### Step 3: 阶段/动作定义 +### Step 3: Phase/Action Definition -#### Sequential 模式 +#### Sequential Mode ```javascript if (executionMode === "sequential") { const phaseInfo = await AskUserQuestion({ questions: [ { - question: "需要多少个执行阶段?", - header: "阶段数量", + question: "How many execution phases are needed?", + header: "Phase Count", multiSelect: false, options: [ - { label: "3 阶段(简单)", description: "收集 → 处理 → 输出" }, - { label: "5 阶段(标准)", description: "收集 → 探索 → 分析 → 组装 → 验证" }, - { label: "7 阶段(完整)", description: "含并行处理、汇总、迭代优化" } + { label: "3 Phases (Simple)", description: "Collection → Processing → Output" }, + { label: "5 Phases (Standard)", description: "Collection → Exploration → Analysis → Assembly → Validation" }, + { label: "7 Phases (Complete)", description: "Includes parallel processing, consolidation, iterative optimization" } ] } ] }); - - // 根据选择生成阶段定义 + + // Generate phase definitions based on selection const phaseTemplates = { - "3 阶段": [ + "3 Phases": [ { id: "01-collection", name: "Data Collection" }, { id: "02-processing", name: "Processing" }, { id: "03-output", name: "Output Generation" } ], - "5 阶段": [ + "5 Phases": [ { id: "01-collection", name: "Requirements Collection" }, { id: "02-exploration", name: "Project Exploration" }, { id: "03-analysis", name: "Deep Analysis" }, { id: "04-assembly", name: "Document Assembly" }, { id: "05-validation", name: "Validation" } ], - "7 阶段": [ + "7 Phases": [ { id: "01-collection", name: "Requirements Collection" }, { id: "02-exploration", name: "Project Exploration" }, { id: "03-parallel", name: "Parallel Analysis" }, @@ -121,23 +132,23 @@ if (executionMode === "sequential") { } ``` -#### Autonomous 模式 +#### Autonomous Mode ```javascript if (executionMode === "autonomous") { const actionInfo = await AskUserQuestion({ questions: [ { - question: "核心动作有哪些?(可多选)", - header: "动作定义", + question: "What are the core actions? (Multiple selection allowed)", + header: "Action Definition", multiSelect: true, options: [ - { label: "初始化 (init)", description: "设置初始状态" }, - { label: "列表 (list)", description: "显示当前项目列表" }, - { label: "创建 (create)", description: "创建新项目" }, - { label: "编辑 (edit)", description: "修改现有项目" }, - { label: "删除 (delete)", description: "删除项目" }, - { label: "搜索 (search)", description: "搜索/过滤项目" } + { label: "Initialize (init)", description: "Set initial state" }, + { label: "List (list)", description: "Display current item list" }, + { label: "Create (create)", description: "Create new item" }, + { label: "Edit (edit)", description: "Modify existing item" }, + { label: "Delete (delete)", description: "Delete item" }, + { label: "Search (search)", description: "Search/filter items" } ] } ] @@ -145,37 +156,37 @@ if (executionMode === "autonomous") { } ``` -### Step 4: 工具和输出配置 +### Step 4: Tool and Output Configuration ```javascript const toolsInfo = await AskUserQuestion({ questions: [ { - question: "需要哪些特殊工具?(基础工具已默认包含)", - header: "工具选择", + question: "Which special tools are needed? (Basic tools are included by default)", + header: "Tool Selection", multiSelect: true, options: [ - { label: "用户交互 (AskUserQuestion)", description: "需要与用户对话" }, - { label: "Chrome 截图 (mcp__chrome__*)", description: "需要网页截图" }, - { label: "外部搜索 (mcp__exa__search)", description: "需要搜索外部信息" }, - { label: "无特殊需求", description: "仅使用基础工具" } + { label: "User Interaction (AskUserQuestion)", description: "Need to dialog with user" }, + { label: "Chrome Screenshot (mcp__chrome__*)", description: "Need web page screenshots" }, + { label: "External Search (mcp__exa__search)", description: "Need to search external information" }, + { label: "No Special Requirements", description: "Use basic tools only" } ] }, { - question: "输出格式是什么?", - header: "输出格式", + question: "What is the output format?", + header: "Output Format", multiSelect: false, options: [ - { label: "Markdown", description: "适合文档和报告" }, - { label: "HTML", description: "适合交互式文档" }, - { label: "JSON", description: "适合数据和配置" } + { label: "Markdown", description: "Suitable for documents and reports" }, + { label: "HTML", description: "Suitable for interactive documents" }, + { label: "JSON", description: "Suitable for data and configuration" } ] } ] }); ``` -### Step 5: 生成配置文件 +### Step 5: Generate Configuration File ```javascript const config = { @@ -184,41 +195,40 @@ const config = { description: description, triggers: triggers, execution_mode: executionMode, - - // 模式特定配置 + + // Mode-specific configuration ...(executionMode === "sequential" ? { sequential_config: { phases: phases } } : { - autonomous_config: { + autonomous_config: { state_schema: stateSchema, actions: actions, termination_conditions: ["user_exit", "error_limit", "task_completed"] } }), - + allowed_tools: [ "Task", "Read", "Write", "Glob", "Grep", "Bash", ...selectedTools ], - + output: { format: outputFormat.toLowerCase(), location: `.workflow/.scratchpad/${skillName}-{timestamp}`, filename_pattern: `{name}-output.${outputFormat === "HTML" ? "html" : outputFormat === "JSON" ? "json" : "md"}` }, - + created_at: new Date().toISOString(), version: "1.0.0" }; -// 写入配置文件 +// Write configuration file const workDir = `.workflow/.scratchpad/skill-gen-${timestamp}`; Bash(`mkdir -p "${workDir}"`); Write(`${workDir}/skill-config.json`, JSON.stringify(config, null, 2)); ``` - ## Next Phase → [Phase 2: Structure Generation](02-structure-generation.md) diff --git a/.claude/skills/skill-generator/phases/02-structure-generation.md b/.claude/skills/skill-generator/phases/02-structure-generation.md index 65d6007b..cf6b7879 100644 --- a/.claude/skills/skill-generator/phases/02-structure-generation.md +++ b/.claude/skills/skill-generator/phases/02-structure-generation.md @@ -1,41 +1,40 @@ # Phase 2: Structure Generation -根据配置创建 Skill 目录结构和入口文件。 +Create Skill directory structure and entry file based on configuration. ## Objective -- 创建标准目录结构 -- 生成 SKILL.md 入口文件 -- 根据执行模式创建对应的子目录 - +- Create standard directory structure +- Generate SKILL.md entry file +- Create corresponding subdirectories based on execution mode ## Execution Steps -### Step 1: 读取配置 +### Step 1: Read Configuration ```javascript const config = JSON.parse(Read(`${workDir}/skill-config.json`)); const skillDir = `.claude/skills/${config.skill_name}`; ``` -### Step 2: 创建目录结构 +### Step 2: Create Directory Structure -#### 基础目录(所有模式) +#### Base Directories (All Modes) ```javascript -// 基础架构 +// Base infrastructure Bash(`mkdir -p "${skillDir}/{phases,specs,templates,scripts}"`); ``` -#### 执行模式特定目录 +#### Execution Mode-Specific Directories ``` config.execution_mode ↓ ├─ "sequential" │ ↓ Creates: - │ └─ phases/ (基础目录已包含) + │ └─ phases/ (base directory already included) │ ├─ _orchestrator.md │ └─ workflow.json │ @@ -43,36 +42,36 @@ config.execution_mode ↓ Creates: └─ phases/actions/ ├─ state-schema.md - └─ *.md (动作文件) + └─ *.md (action files) ``` ```javascript -// Autonomous/Hybrid 模式额外目录 +// Additional directories for Autonomous/Hybrid mode if (config.execution_mode === 'autonomous' || config.execution_mode === 'hybrid') { Bash(`mkdir -p "${skillDir}/phases/actions"`); } ``` -#### Context Strategy 特定目录 (P0 增强) +#### Context Strategy-Specific Directories (P0 Enhancement) ```javascript -// ========== P0: 根据上下文策略创建目录 ========== +// ========== P0: Create directories based on context strategy ========== const contextStrategy = config.context_strategy || 'file'; if (contextStrategy === 'file') { - // 文件策略:创建上下文持久化目录 + // File strategy: Create persistent context directory Bash(`mkdir -p "${skillDir}/.scratchpad-template/context"`); - // 创建上下文模板文件 + // Create context template file Write( `${skillDir}/.scratchpad-template/context/.gitkeep`, "# 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: @@ -83,7 +82,7 @@ Sequential + File Strategy: │ ├── 01-*.md │ └── 02-*.md ├── .scratchpad-template/ - │ └── context/ ← File strategy persistent storage + │ └── context/ <- File strategy persistent storage └── specs/ Autonomous + Memory Strategy: @@ -96,7 +95,7 @@ Autonomous + Memory Strategy: └── specs/ ``` -### Step 3: 生成 SKILL.md +### Step 3: Generate SKILL.md ```javascript const skillMdTemplate = `--- @@ -130,8 +129,8 @@ const timestamp = new Date().toISOString().slice(0,19).replace(/[-:T]/g, ''); const workDir = \`${config.output.location.replace('{timestamp}', '${timestamp}')}\`; Bash(\`mkdir -p "\${workDir}"\`); -${config.execution_mode === 'sequential' ? - `Bash(\`mkdir -p "\${workDir}/sections"\`);` : +${config.execution_mode === 'sequential' ? + `Bash(\`mkdir -p "\${workDir}/sections"\`);` : `Bash(\`mkdir -p "\${workDir}/state"\`);`} \`\`\` @@ -149,53 +148,53 @@ ${generateReferenceTable(config)} Write(`${skillDir}/SKILL.md`, skillMdTemplate); ``` -### Step 4: 架构图生成函数 +### Step 4: Architecture Diagram Generation Functions ```javascript function generateArchitectureDiagram(config) { if (config.execution_mode === 'sequential') { - return config.sequential_config.phases.map((p, i) => + return config.sequential_config.phases.map((p, i) => `│ Phase ${i+1}: ${p.name.padEnd(15)} → ${p.output || 'output-' + (i+1) + '.json'}${' '.repeat(10)}│` ).join('\n│ ↓' + ' '.repeat(45) + '│\n'); } else { return ` ┌─────────────────────────────────────────────────────────────────┐ -│ Orchestrator (状态驱动决策) │ +│ Orchestrator (State-driven decision-making) │ └───────────────┬─────────────────────────────────────────────────┘ │ ┌───────────┼───────────┐ ↓ ↓ ↓ -${config.autonomous_config.actions.slice(0, 3).map(a => +${config.autonomous_config.actions.slice(0, 3).map(a => `┌─────────┐ `).join('')} -${config.autonomous_config.actions.slice(0, 3).map(a => +${config.autonomous_config.actions.slice(0, 3).map(a => `│${a.name.slice(0, 7).padEnd(7)}│ `).join('')} -${config.autonomous_config.actions.slice(0, 3).map(a => +${config.autonomous_config.actions.slice(0, 3).map(a => `└─────────┘ `).join('')}`; } } function generateDesignPrinciples(config) { const common = [ - "1. **规范遵循**: 严格遵循 `_shared/SKILL-DESIGN-SPEC.md`", - "2. **简要返回**: Agent 返回路径+摘要,避免上下文溢出" + "1. **Specification Compliance**: Strictly follow `_shared/SKILL-DESIGN-SPEC.md`", + "2. **Brief Return**: Agent returns path+summary, avoiding context overflow" ]; - + if (config.execution_mode === 'sequential') { return [...common, - "3. **阶段隔离**: 每个阶段独立可测", - "4. **链式输出**: 阶段产出作为下阶段输入" + "3. **Phase Isolation**: Each phase is independently testable", + "4. **Chained Output**: Phase output becomes next phase input" ].join('\n'); } else { return [...common, - "3. **状态驱动**: 显式状态管理,动态决策", - "4. **动作独立**: 每个动作无副作用依赖" + "3. **State-driven**: Explicit state management, dynamic decision-making", + "4. **Action Independence**: Each action has no side-effect dependencies" ].join('\n'); } } function generateExecutionFlow(config) { if (config.execution_mode === 'sequential') { - return '```\n' + config.sequential_config.phases.map((p, i) => + return '```\n' + config.sequential_config.phases.map((p, i) => `├─ Phase ${i+1}: ${p.name}\n│ → Output: ${p.output || 'output.json'}` ).join('\n') + '\n```'; } else { @@ -216,9 +215,9 @@ function generateExecutionFlow(config) { function generateOutputStructure(config) { const base = `${config.output.location}/ ├── ${config.execution_mode === 'sequential' ? 'sections/' : 'state.json'}`; - + if (config.execution_mode === 'sequential') { - return base + '\n' + config.sequential_config.phases.map(p => + return base + '\n' + config.sequential_config.phases.map(p => `│ └── ${p.output || 'section-' + p.id + '.md'}` ).join('\n') + `\n└── ${config.output.filename_pattern}`; } else { @@ -230,22 +229,22 @@ function generateOutputStructure(config) { function generateReferenceTable(config) { const rows = []; - + if (config.execution_mode === 'sequential') { config.sequential_config.phases.forEach(p => { rows.push(`| [phases/${p.id}.md](phases/${p.id}.md) | ${p.name} |`); }); } else { - rows.push(`| [phases/orchestrator.md](phases/orchestrator.md) | 编排器 |`); - rows.push(`| [phases/state-schema.md](phases/state-schema.md) | 状态定义 |`); + rows.push(`| [phases/orchestrator.md](phases/orchestrator.md) | Orchestrator |`); + rows.push(`| [phases/state-schema.md](phases/state-schema.md) | State Definition |`); config.autonomous_config.actions.forEach(a => { 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/quality-standards.md](specs/quality-standards.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) | Quality Standards |`); + return `| Document | Purpose |\n|----------|---------||\n` + rows.join('\n'); } ``` diff --git a/.claude/skills/skill-generator/phases/03-phase-generation.md b/.claude/skills/skill-generator/phases/03-phase-generation.md index e8f2c5ca..a9ec7624 100644 --- a/.claude/skills/skill-generator/phases/03-phase-generation.md +++ b/.claude/skills/skill-generator/phases/03-phase-generation.md @@ -1,23 +1,22 @@ # Phase 3: Phase Generation -根据执行模式生成 Phase 文件,包含声明式工作流编排和上下文策略支持。 +Generate Phase files based on execution mode, including declarative workflow orchestration and context strategy support. ## Objective -- Sequential 模式:生成顺序 Phase 文件 + **声明式编排器** -- Autonomous 模式:生成编排器和动作文件 -- 支持 **文件上下文** 和 **内存上下文** 两种策略 +- Sequential Mode: Generate sequential Phase files + **declarative orchestrator** +- 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` 生成不同的上下文管理代码: - -| 策略 | 适用场景 | 优点 | 缺点 | -|------|----------|------|------| -| `file` | 复杂多阶段任务 | 持久化、可调试、可恢复 | IO 开销 | -| `memory` | 简单线性任务 | 速度快 | 无法恢复、调试困难 | +| 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 | ```javascript const CONTEXT_STRATEGIES = { @@ -36,36 +35,36 @@ const CONTEXT_STRATEGIES = { ## Execution Steps -### Step 1: 读取配置和模板 +### Step 1: Load Configuration and Templates ```javascript const config = JSON.parse(Read(`${workDir}/skill-config.json`)); 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'; ``` -### Step 2: Sequential 模式 - 生成阶段文件 + 声明式编排器 +### Step 2: Sequential Mode - Generate Phase Files + Declarative Orchestrator ```javascript if (config.execution_mode === 'sequential') { const phases = config.sequential_config.phases; - // ========== P0 增强: 生成声明式编排器 ========== + // ========== P0 Enhancement: Generate declarative orchestrator ========== const workflowOrchestrator = generateSequentialOrchestrator(config, phases); Write(`${skillDir}/phases/_orchestrator.md`, workflowOrchestrator); - // ========== P0 增强: 生成工作流定义 ========== + // ========== P0 Enhancement: Generate workflow definition ========== const workflowDef = generateWorkflowDefinition(config, phases); Write(`${skillDir}/workflow.json`, JSON.stringify(workflowDef, null, 2)); - // ========== P0 增强: 生成 Phase 0 (强制规范研读) ========== + // ========== P0 Enhancement: Generate Phase 0 (mandatory specification study) ========== const phase0Content = generatePhase0Spec(config); Write(`${skillDir}/phases/00-spec-study.md`, phase0Content); - // ========== 生成用户定义的各阶段文件 ========== + // ========== Generate user-defined phase files ========== for (let i = 0; i < phases.length; i++) { const phase = phases[i]; const prevPhase = i > 0 ? phases[i-1] : null; @@ -76,7 +75,7 @@ if (config.execution_mode === 'sequential') { phaseId: phase.id, phaseName: 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, nextPhase: nextPhase ? nextPhase.id : null, config: config, @@ -87,16 +86,16 @@ if (config.execution_mode === 'sequential') { } } -// ========== P0 增强: 声明式工作流定义 ========== +// ========== P0 Enhancement: Declarative workflow definition ========== function generateWorkflowDefinition(config, phases) { - // ========== P0: 添加强制 Phase 0 ========== + // ========== P0: Add mandatory Phase 0 ========== const phase0 = { id: '00-spec-study', name: 'Specification Study', order: 0, input: null, output: 'spec-study-complete.flag', - description: '⚠️ MANDATORY: Read all specification documents before execution', + description: 'MANDATORY: Read all specification documents before execution', parallel: false, condition: null, agent: { @@ -111,21 +110,21 @@ function generateWorkflowDefinition(config, phases) { execution_mode: "sequential", 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)], - // ========== P0: Phase 0 + 用户定义阶段 ========== + // ========== P0: Phase 0 + user-defined phases ========== phases: [ phase0, ...phases.map((p, i) => ({ id: p.id, name: p.name, 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, parallel: p.parallel || false, condition: p.condition || null, - // Agent 配置 (支持 LLM 集成) + // Agent configuration (supports LLM integration) agent: p.agent || (config.llm_integration?.enabled ? { type: "llm", tool: config.llm_integration.default_tool, @@ -139,7 +138,7 @@ function generateWorkflowDefinition(config, phases) { })) ], - // 终止条件 + // Termination conditions termination: { on_success: "all_phases_completed", on_error: "stop_and_report", @@ -148,52 +147,52 @@ function generateWorkflowDefinition(config, phases) { }; } -// ========== P0 增强: 声明式编排器 ========== +// ========== P0 Enhancement: Declarative orchestrator ========== function generateSequentialOrchestrator(config, phases) { return `# Sequential Orchestrator -声明式工作流编排器,按 \`workflow.json\` 定义顺序执行阶段。 +Declarative workflow orchestrator that executes phases in order defined by \`workflow.json\`. -## 工作流定义 +## Workflow Definition \`\`\`javascript const workflow = JSON.parse(Read(\`\${skillDir}/workflow.json\`)); \`\`\` -## 编排逻辑 +## Orchestration Logic \`\`\`javascript async function runSequentialWorkflow(workDir) { const workflow = JSON.parse(Read(\`\${skillDir}/workflow.json\`)); const contextStrategy = workflow.context_strategy; - - // 初始化上下文 - ${config.context_strategy === 'file' ? + + // Initialize context + ${config.context_strategy === 'file' ? `Bash(\`mkdir -p "\${workDir}/context"\`);` : `const state = { context: {} };`} - - // 执行状态追踪 + + // Execution state tracking const execution = { started_at: new Date().toISOString(), phases_completed: [], current_phase: null, errors: [] }; - + Write(\`\${workDir}/execution-state.json\`, JSON.stringify(execution, null, 2)); - - // 按声明顺序执行阶段 + + // Execute phases in declared order for (const phaseId of workflow.phases_to_run) { const phaseConfig = workflow.phases.find(p => p.id === phaseId); - - // 更新执行状态 + + // Update execution state execution.current_phase = phaseId; Write(\`\${workDir}/execution-state.json\`, JSON.stringify(execution, null, 2)); - + console.log(\`[Orchestrator] Executing: \${phaseId}\`); - + try { - // 检查条件执行 + // Check conditional execution if (phaseConfig.condition) { const shouldRun = evaluateCondition(phaseConfig.condition, execution); if (!shouldRun) { @@ -201,46 +200,46 @@ async function runSequentialWorkflow(workDir) { continue; } } - - // 执行阶段 + + // Execute phase const result = await executePhase(phaseId, phaseConfig, workDir); - - // 记录完成 + + // Record completion execution.phases_completed.push({ id: phaseId, completed_at: new Date().toISOString(), output: phaseConfig.output }); - + } catch (error) { execution.errors.push({ phase: phaseId, message: error.message, timestamp: new Date().toISOString() }); - - // 错误处理策略 + + // Error handling strategy if (workflow.termination.on_error === 'stop_and_report') { console.error(\`[Orchestrator] Failed at \${phaseId}: \${error.message}\`); break; } } - + Write(\`\${workDir}/execution-state.json\`, JSON.stringify(execution, null, 2)); } - - // 完成 + + // Complete execution.current_phase = null; execution.completed_at = new Date().toISOString(); Write(\`\${workDir}/execution-state.json\`, JSON.stringify(execution, null, 2)); - + return execution; } async function executePhase(phaseId, phaseConfig, workDir) { const phasePrompt = Read(\`\${skillDir}/phases/\${phaseId}.md\`); - - // 使用 Task 调用 Agent + + // Use Task to invoke Agent const result = await Task({ subagent_type: phaseConfig.agent?.type || 'universal-executor', run_in_background: phaseConfig.agent?.run_in_background || false, @@ -253,14 +252,14 @@ async function executePhase(phaseId, phaseConfig, workDir) { \${phasePrompt} \` }); - + return JSON.parse(result); } \`\`\` -## 阶段执行计划 +## Phase Execution Plan -**执行流程**: +**Execution Flow**: \`\`\` START @@ -270,43 +269,43 @@ Phase 0: Specification Study ↓ Phase 1: ${phases[0]?.name || 'First Phase'} ↓ Output: ${phases[0]?.output || 'phase-1.json'} -${phases.slice(1).map((p, i) => ` ↓ -Phase ${i+2}: ${p.name} - ↓ Output: ${p.output}`).join('\n')} +${phases.slice(1).map((p, i) => \` ↓ +Phase \${i+2}: \${p.name} + ↓ Output: \${p.output}\`).join('\n')} ↓ COMPLETE \`\`\` -**阶段列表**: +**Phase List**: | Order | Phase | Input | Output | Agent | |-------|-------|-------|--------|-------| | 0 | 00-spec-study | - | spec-study-complete.flag | universal-executor | ${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')} -## 错误恢复 +## Error Recovery \`\`\`javascript -// 从指定阶段恢复执行 +// Resume execution from specified phase async function resumeFromPhase(phaseId, workDir) { const workflow = JSON.parse(Read(\`\${skillDir}/workflow.json\`)); const startIndex = workflow.phases_to_run.indexOf(phaseId); - + if (startIndex === -1) { throw new Error(\`Phase not found: \${phaseId}\`); } - - // 从指定阶段开始执行 + + // Continue execution from specified phase const remainingPhases = workflow.phases_to_run.slice(startIndex); - // ...继续执行 + // ...continue execution } \`\`\` `; } -// 生成阶段文件(增强上下文策略支持) +// Generate phase files (enhanced context strategy support) function generateSequentialPhase(params) { const contextCode = params.contextStrategy === 'file' ? { readPrev: `const prevOutput = JSON.parse(Read(\`\${workDir}/${params.input}\`));`, @@ -326,32 +325,32 @@ ${params.phaseDescription} ## Objective -- 主要目标描述 -- 具体任务列表 +- Primary objective description +- Specific task list ## Input -- 依赖: \`${params.input}\` -- 配置: \`{workDir}/skill-config.json\` -- 上下文策略: \`${params.contextStrategy}\` +- Dependency: \`${params.input}\` +- Configuration: \`{workDir}/skill-config.json\` +- Context Strategy: \`${params.contextStrategy}\` ## Execution Steps -### Step 1: 读取输入 +### Step 1: Read Input \`\`\`javascript -// 上下文策略: ${params.contextStrategy} -${params.phaseNumber > 1 ? contextCode.readPrev : '// 首阶段,直接从配置开始'} +// Context strategy: ${params.contextStrategy} +${params.phaseNumber > 1 ? contextCode.readPrev : '// First phase, start directly from config'} \`\`\` -### Step 2: 核心处理 +### Step 2: Core Processing \`\`\`javascript -// TODO: 实现核心逻辑 +// TODO: Implement core logic const result = { status: 'completed', data: { - // 处理结果 + // Processing results }, metadata: { phase: '${params.phaseId}', @@ -360,17 +359,17 @@ const result = { }; \`\`\` -### Step 3: 输出结果 +### Step 3: Output Results \`\`\`javascript -// 写入阶段产出 (上下文策略: ${params.contextStrategy}) +// Write phase output (context strategy: ${params.contextStrategy}) ${contextCode.writeResult} -// 返回简要信息给编排器 +// Return summary information to orchestrator return { status: 'completed', output_file: '${params.output}', - summary: '阶段 ${params.phaseNumber} 完成' + summary: 'Phase ${params.phaseNumber} completed' }; \`\`\` @@ -382,57 +381,57 @@ return { ## Quality Checklist -- [ ] 输入数据验证通过 -- [ ] 核心逻辑执行成功 -- [ ] 输出格式正确 -- [ ] 上下文正确保存 +- [ ] Input data validation passed +- [ ] Core logic executed successfully +- [ ] Output format correct +- [ ] Context saved correctly -${params.nextPhase ? - `## Next Phase\n\n→ [Phase ${params.phaseNumber + 1}: ${params.nextPhase}](${params.nextPhase}.md)` : - `## Completion\n\n此为最后阶段,输出最终产物。`} +${params.nextPhase ? + `## Next Phase\n\n→ [Phase ${params.phaseNumber + 1}: ${params.nextPhase}](${params.nextPhase}.md)` : + `## Completion\n\nThis is the final phase, produce final deliverables.`} `; } ``` -### Step 3: Autonomous 模式 - 生成编排器 (增强版) +### Step 3: Autonomous Mode - Generate Enhanced Orchestrator ```javascript if (config.execution_mode === 'autonomous' || config.execution_mode === 'hybrid') { const contextStrategy = config.context_strategy || 'file'; - - // 生成状态 Schema (增强文件策略支持) + + // Generate state schema (enhanced file strategy support) const stateSchema = generateStateSchema(config, contextStrategy); Write(`${skillDir}/phases/state-schema.md`, stateSchema); - - // 生成编排器 (增强版) + + // Generate enhanced orchestrator const orchestrator = generateEnhancedOrchestrator(config, contextStrategy); Write(`${skillDir}/phases/orchestrator.md`, orchestrator); - - // 生成动作目录 + + // Generate action catalog const actionCatalog = generateActionCatalog(config); Write(`${skillDir}/specs/action-catalog.md`, actionCatalog); - - // 生成动作文件 + + // Generate action files for (const action of config.autonomous_config.actions) { const actionContent = generateEnhancedAction(action, config, contextStrategy); Write(`${skillDir}/phases/actions/${action.id}.md`, actionContent); } } -// 增强版编排器生成 +// Enhanced orchestrator generation function generateEnhancedOrchestrator(config, contextStrategy) { const actions = config.autonomous_config.actions; - + return `# Orchestrator (Enhanced) -增强版编排器,支持声明式动作调度和文件上下文策略。 +Enhanced orchestrator supporting declarative action scheduling and file-based context strategy. -## 配置 +## Configuration -- **上下文策略**: ${contextStrategy} -- **终止条件**: ${config.autonomous_config.termination_conditions?.join(', ') || 'task_completed'} +- **Context Strategy**: ${contextStrategy} +- **Termination Conditions**: ${config.autonomous_config.termination_conditions?.join(', ') || 'task_completed'} -## 声明式动作目录 +## Declarative Action Catalog \`\`\`javascript const ACTION_CATALOG = ${JSON.stringify(actions.map(a => ({ @@ -444,87 +443,87 @@ const ACTION_CATALOG = ${JSON.stringify(actions.map(a => ({ })), null, 2)}; \`\`\` -## 上下文管理 (${contextStrategy} 策略) +## Context Management (${contextStrategy} Strategy) \`\`\`javascript const ContextManager = { - ${contextStrategy === 'file' ? ` - // 文件策略: 持久化到 .scratchpad + ${contextStrategy === 'file' ? \` + // File strategy: persist to .scratchpad init: (workDir) => { Bash(\`mkdir -p "\${workDir}/context"\`); Write(\`\${workDir}/state.json\`, JSON.stringify(initialState, null, 2)); }, - + readState: (workDir) => JSON.parse(Read(\`\${workDir}/state.json\`)), - + writeState: (workDir, state) => { state.updated_at = new Date().toISOString(); Write(\`\${workDir}/state.json\`, JSON.stringify(state, null, 2)); }, - + readContext: (workDir, key) => { try { return JSON.parse(Read(\`\${workDir}/context/\${key}.json\`)); } catch { return null; } }, - + writeContext: (workDir, key, data) => { Write(\`\${workDir}/context/\${key}.json\`, JSON.stringify(data, null, 2)); - }` : ` - // 内存策略: 仅在运行时保持 + }\` : \` + // Memory strategy: maintain only at runtime state: null, context: {}, - + init: (workDir) => { ContextManager.state = { ...initialState }; ContextManager.context = {}; }, - + readState: () => ContextManager.state, - + writeState: (workDir, state) => { state.updated_at = new Date().toISOString(); ContextManager.state = state; }, - + readContext: (workDir, key) => ContextManager.context[key], - + writeContext: (workDir, key, data) => { ContextManager.context[key] = data; - }`} + }\`} }; \`\`\` -## 决策逻辑 +## Decision Logic \`\`\`javascript function selectNextAction(state) { - // 1. 终止条件检查 -${config.autonomous_config.termination_conditions?.map(c => - ` if (${getTerminationCheck(c)}) return null;` + // 1. Check termination conditions +${config.autonomous_config.termination_conditions?.map(c => + \` if (\${getTerminationCheck(c)}) return null;\` ).join('\n') || ' if (state.status === "completed") return null;'} - - // 2. 错误限制检查 + + // 2. Check error limit if (state.error_count >= 3) return 'action-abort'; - - // 3. 按优先级选择满足前置条件的动作 + + // 3. Select actions that meet preconditions, sorted by priority const availableActions = ACTION_CATALOG .filter(a => checkPreconditions(a.preconditions, state)) .filter(a => !state.completed_actions.includes(a.id)) .sort((a, b) => b.priority - a.priority); - + if (availableActions.length > 0) { return availableActions[0].id; } - - // 4. 默认完成 + + // 4. Default complete return 'action-complete'; } function checkPreconditions(conditions, state) { if (!conditions || conditions.length === 0) return true; return conditions.every(cond => { - // 支持多种条件格式 + // Support multiple condition formats if (cond.includes('===')) { const [left, right] = cond.split('===').map(s => s.trim()); return eval(\`state.\${left}\`) === eval(right); @@ -534,46 +533,46 @@ function checkPreconditions(conditions, state) { } \`\`\` -## 执行循环 (增强版) +## Execution Loop (Enhanced) \`\`\`javascript async function runOrchestrator(workDir) { console.log('=== Orchestrator Started ==='); console.log(\`Context Strategy: ${contextStrategy}\`); - - // 初始化 + + // Initialize ContextManager.init(workDir); - + let iteration = 0; const MAX_ITERATIONS = 100; - + while (iteration < MAX_ITERATIONS) { iteration++; - - // 1. 读取状态 + + // 1. Read state const state = ContextManager.readState(workDir); console.log(\`[Iteration \${iteration}] Status: \${state.status}, Completed: \${state.completed_actions.length}\`); - - // 2. 选择动作 + + // 2. Select action const actionId = selectNextAction(state); - + if (!actionId) { console.log('=== All actions completed ==='); state.status = 'completed'; ContextManager.writeState(workDir, state); break; } - + console.log(\`[Iteration \${iteration}] Executing: \${actionId}\`); - - // 3. 更新当前动作 + + // 3. Update current action state.current_action = actionId; ContextManager.writeState(workDir, state); - - // 4. 执行动作 + + // 4. Execute action try { const actionPrompt = Read(\`\${skillDir}/phases/actions/\${actionId}.md\`); - + const result = await Task({ subagent_type: 'universal-executor', run_in_background: false, @@ -594,16 +593,16 @@ ${contextStrategy} Return JSON: { "status": "completed"|"failed", "stateUpdates": {...}, "summary": "..." } \` }); - + const actionResult = JSON.parse(result); - - // 5. 更新状态 + + // 5. Update state state.completed_actions.push(actionId); state.current_action = null; Object.assign(state, actionResult.stateUpdates || {}); - + console.log(\`[Iteration \${iteration}] Completed: \${actionResult.summary || actionId}\`); - + } catch (error) { console.error(\`[Iteration \${iteration}] Error: \${error.message}\`); state.errors.push({ @@ -614,27 +613,27 @@ Return JSON: { "status": "completed"|"failed", "stateUpdates": {...}, "summary": state.error_count++; state.current_action = null; } - + ContextManager.writeState(workDir, state); } - + console.log('=== Orchestrator Finished ==='); return ContextManager.readState(workDir); } \`\`\` -## 动作目录 +## Action Catalog | Action | Priority | Preconditions | Effects | |--------|----------|---------------|---------| -${actions.map(a => - `| [${a.id}](actions/${a.id}.md) | ${a.priority || 0} | ${a.preconditions?.join(', ') || '-'} | ${a.effects?.join(', ') || '-'} |` +${actions.map(a => + \`| [${a.id}](actions/${a.id}.md) | ${a.priority || 0} | ${a.preconditions?.join(', ') || '-'} | ${a.effects?.join(', ') || '-'} |\` ).join('\n')} -## 调试与恢复 +## Debugging and Recovery \`\`\`javascript -// 从特定状态恢复 +// Resume from specific state async function resumeFromState(workDir) { const state = ContextManager.readState(workDir); console.log(\`Resuming from: \${state.current_action || 'start'}\`); @@ -642,7 +641,7 @@ async function resumeFromState(workDir) { return runOrchestrator(workDir); } -// 重试失败的动作 +// Retry failed action async function retryFailedAction(workDir) { const state = ContextManager.readState(workDir); if (state.errors.length > 0) { @@ -657,62 +656,62 @@ async function retryFailedAction(workDir) { `; } -// 增强版动作生成 +// Enhanced action generation function generateEnhancedAction(action, config, contextStrategy) { return `# Action: ${action.name} -${action.description || '执行 ' + action.name + ' 操作'} +${action.description || 'Execute ' + action.name + ' operation'} ## Purpose -${action.description || 'TODO: 描述此动作的目的'} +${action.description || 'TODO: Describe the purpose of this action'} ## 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 -// 读取共享上下文 +// Read shared context ${contextStrategy === 'file' ? - `const sharedData = JSON.parse(Read(\`\${workDir}/context/shared.json\`));` : - `const sharedData = state.context.shared || {};`} + \`const sharedData = JSON.parse(Read(\\\`\${workDir}/context/shared.json\\\`));\` : + \`const sharedData = state.context.shared || {};\`} -// 写入共享上下文 +// Write shared context ${contextStrategy === 'file' ? - `Write(\`\${workDir}/context/shared.json\`, JSON.stringify(updatedData, null, 2));` : - `state.context.shared = updatedData;`} + \`Write(\\\`\${workDir}/context/shared.json\\\`, JSON.stringify(updatedData, null, 2));\` : + \`state.context.shared = updatedData;\`} \`\`\` ## Execution \`\`\`javascript async function execute(state, workDir) { - // 1. 读取必要数据 + // 1. Read necessary data ${contextStrategy === 'file' ? - `const input = JSON.parse(Read(\`\${workDir}/context/input.json\`));` : - `const input = state.context.input || {};`} - - // 2. 执行核心逻辑 - // TODO: 实现动作逻辑 + \`const input = JSON.parse(Read(\\\`\${workDir}/context/input.json\\\`));\` : + \`const input = state.context.input || {};\`} + + // 2. Execute core logic + // TODO: Implement action logic const result = { - // 处理结果 + // Processing results }; - - // 3. 保存结果 (${contextStrategy} 策略) + + // 3. Save results (${contextStrategy} strategy) ${contextStrategy === 'file' ? - `Write(\`\${workDir}/context/${action.id.replace(/-/g, '_')}_result.json\`, JSON.stringify(result, null, 2));` : - `// 结果通过 stateUpdates 返回`} - - // 4. 返回状态更新 + \`Write(\\\`\${workDir}/context/${action.id.replace(/-/g, '_')}_result.json\\\`, JSON.stringify(result, null, 2));\` : + \`// Results returned via stateUpdates\`} + + // 4. Return state updates return { status: 'completed', stateUpdates: { 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', stateUpdates: { 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_count | -| 上下文读取失败 | 使用默认值或跳过 | +| Error Type | Handling | +|------------|----------| +| Data validation failure | Return error, do not update state | +| Execution exception | Log error, increment error_count | +| Context read failure | Use default value or skip | ## Next Actions (Hints) -- 成功: 由编排器根据 \`ACTION_CATALOG\` 优先级决定 -- 失败: 重试或 \`action-abort\` +- Success: Determined by orchestrator based on \`ACTION_CATALOG\` priority +- Failure: Retry or \`action-abort\` `; } -// 生成动作目录 +// Generate action catalog function generateActionCatalog(config) { const actions = config.autonomous_config.actions; - + return `# Action Catalog -${config.display_name} 的可用动作目录(声明式)。 +Available action catalog for ${config.display_name} (declarative). -## 动作定义 +## Action Definition \`\`\`json ${JSON.stringify(actions.map(a => ({ @@ -765,7 +764,7 @@ ${JSON.stringify(actions.map(a => ({ })), null, 2)} \`\`\` -## 动作依赖图 +## Action Dependency Graph \`\`\`mermaid graph TD @@ -773,32 +772,32 @@ ${actions.map((a, i) => { const deps = a.preconditions?.filter(p => p.startsWith('completed_actions.includes')) .map(p => p.match(/'([^']+)'/)?.[1]) .filter(Boolean) || []; - + 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) { - 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 ''; }).filter(Boolean).join('\n')} ${actions[actions.length-1]?.id.replace(/-/g, '_') || 'last'} --> END((End)) \`\`\` -## 选择优先级 +## Selection Priority | Priority | Action | Description | |----------|--------|-------------| -${actions.sort((a, b) => (b.priority || 0) - (a.priority || 0)).map(a => - `| ${a.priority || 0} | ${a.id} | ${a.description || a.name} |` +${actions.sort((a, b) => (b.priority || 0) - (a.priority || 0)).map(a => + \`| ${a.priority || 0} | ${a.id} | ${a.description || a.name} |\` ).join('\n')} `; } ``` -### Step 4: 辅助函数 +### Step 4: Helper Functions ```javascript -// ========== P0: Phase 0 生成函数 ========== +// ========== P0: Phase 0 generation function ========== function generatePhase0Spec(config) { const skillRoot = '.claude/skills/skill-generator'; const specsToRead = [ @@ -808,54 +807,54 @@ function generatePhase0Spec(config) { return `# Phase 0: Specification Study -⚠️ **MANDATORY PREREQUISITE** - 此阶段不可跳过 +MANDATORY PREREQUISITE - This phase cannot be skipped ## Objective -在生成任何文件前,完整阅读所有规范文档,理解 Skill 设计标准。 +Complete reading of all specification documents before generating any files, understand Skill design standards. ## 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 -### P0 - 核心设计规范 +### P0 - Core Design Specification \`\`\`javascript -// 通用设计标准 (MUST READ) +// Universal design standards (MUST READ) const designSpec = Read('.claude/skills/_shared/SKILL-DESIGN-SPEC.md'); -// 关键内容检查点: +// Key content checkpoints: const checkpoints = { - structure: '目录结构约定', - naming: '命名规范', - quality: '质量标准', - output: '输出格式要求' + structure: 'Directory structure conventions', + naming: 'Naming standards', + quality: 'Quality standards', + output: 'Output format requirements' }; \`\`\` -### P1 - 模板文件 (生成前必读) +### P1 - Template Files (Must read before generation) \`\`\`javascript -// 根据执行模式加载对应模板 +// Load corresponding templates based on execution mode const templates = { all: [ - 'templates/skill-md.md' // SKILL.md 入口文件模板 + 'templates/skill-md.md' // SKILL.md entry file template ], sequential: [ 'templates/sequential-phase.md' @@ -871,24 +870,24 @@ const requiredTemplates = [...templates.all, ...templates[mode]]; requiredTemplates.forEach(template => { const content = Read(\`.claude/skills/skill-generator/\${template}\`); - // 理解模板结构、变量位置、生成规则 + // Understand template structure, variable positions, generation rules }); \`\`\` ## Execution \`\`\`javascript -// ========== 加载规范 ========== +// ========== Load specifications ========== const specs = []; -// 1. 设计规范 (P0) +// 1. Design specification (P0) specs.push({ file: '../_shared/SKILL-DESIGN-SPEC.md', content: Read('.claude/skills/_shared/SKILL-DESIGN-SPEC.md'), priority: 'P0' }); -// 2. 模板文件 (P1) +// 2. Template files (P1) const templateFiles = Glob('.claude/skills/skill-generator/templates/*.md'); templateFiles.forEach(file => { specs.push({ @@ -898,14 +897,14 @@ templateFiles.forEach(file => { }); }); -// ========== 内化规范 ========== -console.log('📖 Reading specifications...'); +// ========== Internalize specifications ========== +console.log('Reading specifications...'); specs.forEach(spec => { console.log(\` [\${spec.priority}] \${spec.file}\`); - // 理解内容(无需生成文件,仅内存处理) + // Understand content (no need to generate files, only memory processing) }); -// ========== 生成完成标记 ========== +// ========== Generate completion flag ========== const result = { status: 'completed', specs_loaded: specs.length, @@ -917,27 +916,27 @@ Write(\`\${workDir}/spec-study-complete.flag\`, JSON.stringify(result, null, 2)) ## 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 -✅ **通过标准**: -- [ ] 已阅读 SKILL-DESIGN-SPEC.md -- [ ] 已阅读执行模式对应的模板文件 -- [ ] 理解目录结构约定 -- [ ] 理解命名规范 -- [ ] 理解质量标准 +Completion criteria: +- [ ] Read SKILL-DESIGN-SPEC.md +- [ ] Read execution mode corresponding template files +- [ ] Understand directory structure conventions +- [ ] Understand naming standards +- [ ] Understand quality standards ## Next Phase → [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) { 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 diff --git a/.claude/skills/skill-generator/phases/04-specs-templates.md b/.claude/skills/skill-generator/phases/04-specs-templates.md index 6870bed0..876ac616 100644 --- a/.claude/skills/skill-generator/phases/04-specs-templates.md +++ b/.claude/skills/skill-generator/phases/04-specs-templates.md @@ -40,7 +40,7 @@ Generate comprehensive specifications and templates: ```markdown # {display_name} Requirements - When to Use (phase/action reference table) -- Domain Requirements (功能要求, 输出要求, 质量要求) +- Domain Requirements (Functional requirements, Output requirements, Quality requirements) - Validation Function (JavaScript code) - Error Handling (recovery strategies) ``` @@ -57,10 +57,10 @@ Generate comprehensive specifications and templates: **Agent Base** (`templates/agent-base.md`): ```markdown # Agent Base Template -- 通用 Prompt 结构 (ROLE, PROJECT CONTEXT, TASK, CONSTRAINTS, OUTPUT_FORMAT, QUALITY_CHECKLIST) -- 变量说明 (workDir, output_path) -- 返回格式 (AgentReturn interface) -- 角色定义参考 (phase/action specific agents) +- Universal Prompt Structure (ROLE, PROJECT CONTEXT, TASK, CONSTRAINTS, OUTPUT_FORMAT, QUALITY_CHECKLIST) +- Variable Description (workDir, output_path) +- Return Format (AgentReturn interface) +- Role Definition Reference (phase/action specific agents) ``` **Action Catalog** (`specs/action-catalog.md`, Autonomous/Hybrid only): @@ -114,39 +114,39 @@ ${config.execution_mode === 'sequential' ? config.sequential_config.phases.map((p, i) => `| Phase ${i+1} | ${p.name} | ${p.id}.md |` ).join('\n') : - `| Orchestrator | 动作选择 | orchestrator.md | -| Actions | 动作执行 | actions/*.md |`} + `| Orchestrator | Action selection | orchestrator.md | +| Actions | Action execution | actions/*.md |`} --- ## Domain Requirements -### 功能要求 +### Functional Requirements -- [ ] 要求1: TODO -- [ ] 要求2: TODO -- [ ] 要求3: TODO +- [ ] Requirement 1: TODO +- [ ] Requirement 2: TODO +- [ ] Requirement 3: TODO -### 输出要求 +### Output Requirements -- [ ] 格式: ${config.output.format} -- [ ] 位置: ${config.output.location} -- [ ] 命名: ${config.output.filename_pattern} +- [ ] Format: ${config.output.format} +- [ ] Location: ${config.output.location} +- [ ] 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 \`\`\`javascript function validate${toPascalCase(config.skill_name)}(output) { const checks = [ - // TODO: 添加验证规则 - { name: "格式正确", pass: output.format === "${config.output.format}" }, - { name: "内容完整", pass: output.content?.length > 0 } + // TODO: Add validation rules + { name: "Format correct", pass: output.format === "${config.output.format}" }, + { name: "Content complete", pass: output.content?.length > 0 } ]; return { @@ -161,9 +161,9 @@ function validate${toPascalCase(config.skill_name)}(output) { | 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); @@ -171,68 +171,68 @@ Write(`${skillDir}/specs/${config.skill_name}-requirements.md`, domainRequiremen // Step 2: Generate quality standards const qualityStandards = `# Quality Standards -${config.display_name} 的质量评估标准。 +Quality assessment standards for ${config.display_name}. ## Quality Dimensions -### 1. Completeness (完整性) - 25% +### 1. Completeness (Completeness) - 25% -| 要求 | 权重 | 检查方式 | -|------|------|----------| -| 所有必需输出存在 | 10 | 文件检查 | -| 内容覆盖完整 | 10 | 内容分析 | -| 无占位符残留 | 5 | 文本搜索 | +| Requirement | Weight | Validation Method | +|------------|--------|-----------------| +| All necessary outputs exist | 10 | File check | +| Content coverage complete | 10 | Content analysis | +| 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 | Gate | Threshold | Action | |------|-----------|--------| -| Pass | ≥ 80% | 输出最终产物 | -| Review | 60-79% | 处理警告后继续 | -| Fail | < 60% | 必须修复 | +| Pass | >= 80% | Output final deliverables | +| Review | 60-79% | Process warnings then continue | +| Fail | < 60% | Must fix | ## Issue Classification ### Errors (Must Fix) -- 必需输出缺失 -- 数据错误 -- 代码不可运行 +- Necessary output missing +- Data error +- Code not runnable ### Warnings (Should Fix) -- 格式不一致 -- 内容深度不足 -- 缺少示例 +- Format inconsistency +- Content depth insufficient +- Missing examples ### Info (Nice to Have) -- 优化建议 -- 增强机会 +- Optimization suggestions +- Enhancement opportunities ## Automated Checks @@ -267,44 +267,44 @@ Write(`${skillDir}/specs/quality-standards.md`, qualityStandards); // Step 3: Generate 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] Skill: ${config.skill_name} -目标: ${config.description} +Objective: ${config.description} [TASK] -{任务描述} -- 输出: {output_path} -- 格式: ${config.output.format} +{task description} +- Output: {output_path} +- Format: ${config.output.format} [CONSTRAINTS] -- 约束1 -- 约束2 +- Constraint 1 +- Constraint 2 [OUTPUT_FORMAT] -1. 执行任务 -2. 返回 JSON 简要信息 +1. Execute task +2. Return JSON summary information [QUALITY_CHECKLIST] -- [ ] 输出格式正确 -- [ ] 内容完整无遗漏 -- [ ] 无占位符残留 +- [ ] Output format correct +- [ ] Content complete without omission +- [ ] No placeholder remnants \`\`\` -## 变量说明 +## Variable Description -| 变量 | 来源 | 示例 | -|------|------|------| -| {workDir} | 运行时 | .workflow/.scratchpad/${config.skill_name}-xxx | -| {output_path} | 配置 | ${config.output.location}/${config.output.filename_pattern} | +| Variable | Source | Example | +|----------|--------|---------| +| {workDir} | Runtime | .workflow/.scratchpad/${config.skill_name}-xxx | +| {output_path} | Configuration | ${config.output.location}/${config.output.filename_pattern} | -## 返回格式 +## Return Format \`\`\`typescript interface AgentReturn { @@ -318,14 +318,14 @@ interface AgentReturn { } \`\`\` -## 角色定义参考 +## Role Definition Reference ${config.execution_mode === 'sequential' ? config.sequential_config.phases.map((p, i) => - `- **Phase ${i+1} Agent**: ${p.name} 专家` + `- **Phase ${i+1} Agent**: ${p.name} Expert` ).join('\n') : config.autonomous_config.actions.map(a => - `- **${a.name} Agent**: ${a.description || a.name + ' 执行者'}` + `- **${a.name} Agent**: ${a.description || a.name + ' Executor'}` ).join('\n')} `; @@ -335,7 +335,7 @@ Write(`${skillDir}/templates/agent-base.md`, agentBase); if (config.execution_mode === 'autonomous' || config.execution_mode === 'hybrid') { const actionCatalog = `# Action Catalog -${config.display_name} 的可用动作目录。 +Available action catalog for ${config.display_name}. ## Available Actions @@ -350,9 +350,9 @@ ${config.autonomous_config.actions.map(a => \`\`\`mermaid graph TD ${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]; - return ` ${prev.id.replace(/-/g, '_')} --> ${a.id.replace(/-/g, '_')}[${a.name}]`; + return \` ${prev.id.replace(/-/g, '_')} --> ${a.id.replace(/-/g, '_')}[${a.name}]\`; }).join('\n')} \`\`\` @@ -369,10 +369,10 @@ ${config.autonomous_config.actions.slice(1).map(a => ## Selection Priority -当多个动作的前置条件都满足时,按以下优先级选择: +When multiple actions' preconditions are met, select based on the following priority: ${config.autonomous_config.actions.map((a, i) => - `${i + 1}. \`${a.id}\` - ${a.name}` + \`${i + 1}. \\\`${a.id}\\\` - ${a.name}\` ).join('\n')} `; diff --git a/.claude/skills/skill-generator/phases/05-validation.md b/.claude/skills/skill-generator/phases/05-validation.md index 2d90e1ef..8462dd0b 100644 --- a/.claude/skills/skill-generator/phases/05-validation.md +++ b/.claude/skills/skill-generator/phases/05-validation.md @@ -246,16 +246,16 @@ function collectIssues(fileResults, contentResults) { const issues = []; 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 => { - issues.push({ type: 'WARNING', message: `包含 TODO: ${f.file}` }); + issues.push({ type: 'WARNING', message: `Contains TODO: ${f.file}` }); }); contentResults.forEach(c => { 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 = []; if (fileResults.some(f => f.hasTodo)) { - recommendations.push('替换所有 TODO 占位符为实际内容'); + recommendations.push('Replace all TODO placeholders with actual content'); } contentResults.forEach(c => { 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 -### 触发词 +### Trigger Words ${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' ? - `阶段按固定顺序执行:\n${config.sequential_config.phases.map((p, i) => - `${i + 1}. ${p.name}` - ).join('\n')}` : - `动作由编排器动态选择:\n${config.autonomous_config.actions.map(a => - `- ${a.name}: ${a.description || ''}` - ).join('\n')}`} + \`Phases execute in fixed order:\n\${config.sequential_config.phases.map((p, i) => + \`\${i + 1}. \${p.name}\` + ).join('\n')}\` : + \`Actions selected dynamically by orchestrator:\n\${config.autonomous_config.actions.map(a => + \`- \${a.name}: \${a.description || ''}\` + ).join('\n')}\`} ## Usage \`\`\` -# 直接触发 -用户: ${config.triggers[0]} +# Direct trigger +User: ${config.triggers[0]} -# 或使用 Skill 名称 -用户: /skill ${config.skill_name} +# Or use Skill name +User: /skill ${config.skill_name} \`\`\` ## Output -- **格式**: ${config.output.format} -- **位置**: \`${config.output.location}\` -- **文件名**: \`${config.output.filename_pattern}\` +- **Format**: ${config.output.format} +- **Location**: \`${config.output.location}\` +- **Filename**: \`${config.output.filename_pattern}\` ## Directory Structure \`\`\` .claude/skills/${config.skill_name}/ -├── SKILL.md # 入口文件 -├── phases/ # 执行阶段 +├── SKILL.md # Entry file +├── phases/ # Execution phases ${config.execution_mode === 'sequential' ? - config.sequential_config.phases.map(p => `│ ├── ${p.id}.md`).join('\n') : - `│ ├── orchestrator.md + config.sequential_config.phases.map(p => \`│ ├── \${p.id}.md\`).join('\n') : + \`│ ├── orchestrator.md │ ├── state-schema.md │ └── actions/ -${config.autonomous_config.actions.map(a => `│ ├── ${a.id}.md`).join('\n')}`} -├── specs/ # 规范文件 +\${config.autonomous_config.actions.map(a => \`│ ├── \${a.id}.md\`).join('\n')}\`} +├── specs/ # Specification files │ ├── ${config.skill_name}-requirements.md │ ├── quality-standards.md ${config.execution_mode === 'autonomous' ? '│ └── action-catalog.md' : ''} -└── templates/ # 模板文件 +└── templates/ # Template files └── agent-base.md \`\`\` ## 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' ? - `1. 在 \`phases/\` 创建新的阶段文件 (如 \`03.5-new-step.md\`) -2. 更新 SKILL.md 的执行流程` : - `1. 在 \`phases/actions/\` 创建新的动作文件 -2. 更新 \`specs/action-catalog.md\` -3. 在 \`phases/orchestrator.md\` 添加选择逻辑`} + \`1. Create new phase file in \`phases/\` (e.g., \`03.5-new-step.md\`) +2. Update execution flow in SKILL.md\` : + \`1. Create new action file in \`phases/actions/\` +2. Update \`specs/action-catalog.md\` +3. Add selection logic in \`phases/orchestrator.md\`\`} ## Related Documents -- [设计规范](../_shared/SKILL-DESIGN-SPEC.md) -- [执行模式规范](specs/../../../skill-generator/specs/execution-modes.md) +- [Design Specification](../_shared/SKILL-DESIGN-SPEC.md) +- [Execution Modes Specification](specs/../../../skill-generator/specs/execution-modes.md) --- @@ -383,20 +383,20 @@ const finalResult = { validation: report.summary, next_steps: [ - '1. 审阅生成的文件结构', - '2. 替换 TODO 占位符', - '3. 根据实际需求调整阶段逻辑', - '4. 测试 Skill 执行流程', - '5. 更新触发词和描述' + '1. Review generated file structure', + '2. Replace TODO placeholders', + '3. Adjust phase logic based on actual requirements', + '4. Test Skill execution flow', + '5. Update trigger words and descriptions' ] }; -console.log('=== Skill 生成完成 ==='); -console.log(`路径: ${skillDir}`); -console.log(`模式: ${config.execution_mode}`); -console.log(`状态: ${report.summary.status}`); +console.log('=== Skill Generation Complete ==='); +console.log(\`Path: \${skillDir}\`); +console.log(\`Mode: \${config.execution_mode}\`); +console.log(\`Status: \${report.summary.status}\`); console.log(''); -console.log('下一步:'); +console.log('Next Steps:'); finalResult.next_steps.forEach(s => console.log(s)); ``` diff --git a/.claude/skills/skill-generator/specs/cli-integration.md b/.claude/skills/skill-generator/specs/cli-integration.md index d002c591..6d57954f 100644 --- a/.claude/skills/skill-generator/specs/cli-integration.md +++ b/.claude/skills/skill-generator/specs/cli-integration.md @@ -1,111 +1,111 @@ # 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 -// Agent 调用 - 同步 +// Agent call - synchronous const result = Task({ subagent_type: 'universal-executor', - prompt: '执行任务...', - run_in_background: false // 关键: 同步执行 + prompt: 'Execute task...', + run_in_background: false // Key: synchronous execution }); -// 结果立即可用 +// Result immediately available console.log(result); ``` -### 2. 异步执行 (Background) +### 2. Asynchronous Execution (Background) -适用于长时间运行的 CLI 命令。 +Suitable for long-running CLI commands. ```javascript -// CLI 调用 - 异步 +// CLI call - asynchronous const task = Bash({ command: 'ccw cli -p "..." --tool gemini --mode analysis', - run_in_background: true // 关键: 后台执行 + run_in_background: true // Key: background execution }); -// 立即返回,不等待结果 -// task.task_id 可用于后续查询 +// Returns immediately without waiting for result +// task.task_id available for later queries ``` --- -## CCW CLI 调用规范 +## CCW CLI Call Specification -### 基础命令结构 +### Basic Command Structure ```bash ccw cli -p "" --tool --mode ``` -### 参数说明 +### Parameter Description -| 参数 | 必需 | 说明 | -|------|------|------| -| `-p ""` | ✓ | 提示词(使用双引号) | -| `--tool ` | ✓ | 工具选择: gemini, qwen, codex | -| `--mode ` | ✓ | 执行模式: analysis, write | -| `--cd ` | - | 工作目录 | -| `--includeDirs ` | - | 包含额外目录(逗号分隔) | -| `--resume [id]` | - | 恢复会话 | +| Parameter | Required | Description | +|-----------|----------|-------------| +| `-p ""` | Yes | Prompt text (use double quotes) | +| `--tool ` | Yes | Tool selection: gemini, qwen, codex | +| `--mode ` | Yes | Execution mode: analysis, write | +| `--cd ` | - | Working directory | +| `--includeDirs ` | - | Additional directories (comma-separated) | +| `--resume [id]` | - | Resume session | -### 模式选择 +### Mode Selection ``` -┌─ 分析/文档任务? -│ └─→ --mode analysis (只读) -│ -└─ 实现/修改任务? - └─→ --mode write (读写) +- Analysis/Documentation tasks? + → --mode analysis (read-only) + +- Implementation/Modification tasks? + → --mode write (read-write) ``` --- -## Agent 类型与选择 +## Agent Types and Selection ### universal-executor -通用执行器,最常用的 Agent 类型。 +General-purpose executor, the most commonly used agent type. ```javascript Task({ subagent_type: 'universal-executor', prompt: ` -执行任务: -1. 读取配置文件 -2. 分析依赖关系 -3. 生成报告到 ${outputPath} +Execute task: +1. Read configuration file +2. Analyze dependencies +3. Generate report to ${outputPath} `, run_in_background: false }); ``` -**适用场景**: -- 多步骤任务执行 -- 文件操作(读/写/编辑) -- 需要工具调用的任务 +**Applicable Scenarios**: +- Multi-step task execution +- File operations (read/write/edit) +- Tasks that require tool invocation ### Explore -代码探索 Agent,快速理解代码库。 +Code exploration agent for quick codebase understanding. ```javascript Task({ subagent_type: 'Explore', prompt: ` -探索 src/ 目录: -- 识别主要模块 -- 理解目录结构 -- 找到入口点 +Explore src/ directory: +- Identify main modules +- Understand directory structure +- Find entry points Thoroughness: medium `, @@ -113,104 +113,104 @@ Thoroughness: medium }); ``` -**适用场景**: -- 代码库探索 -- 文件发现 -- 结构理解 +**Applicable Scenarios**: +- Codebase exploration +- File discovery +- Structure understanding ### cli-explore-agent -深度代码分析 Agent。 +Deep code analysis agent. ```javascript Task({ subagent_type: 'cli-explore-agent', prompt: ` -深度分析 src/auth/ 模块: -- 认证流程 -- 会话管理 -- 安全机制 +Deep analysis of src/auth/ module: +- Authentication flow +- Session management +- Security mechanisms `, run_in_background: false }); ``` -**适用场景**: -- 深度代码理解 -- 设计模式识别 -- 复杂逻辑分析 +**Applicable Scenarios**: +- Deep code understanding +- Design pattern identification +- Complex logic analysis --- -## 会话管理 +## Session Management -### 会话恢复 +### Session Recovery ```javascript -// 保存会话 ID +// Save session ID 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 }); -// 后续恢复 +// Resume later 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 }); ``` -### 多会话合并 +### Multi-Session Merge ```javascript -// 合并多个会话的上下文 +// Merge context from multiple sessions 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 }); ``` --- -## Skill 中的 CLI 集成模式 +## CLI Integration Patterns in Skills -### 模式 1: 单次调用 +### Pattern 1: Single Call -简单任务,一次调用完成。 +Simple tasks completed in one call. ```javascript -// Phase 执行 +// Phase execution async function executePhase(context) { const result = Bash({ command: `ccw cli -p " -PURPOSE: 分析项目结构 -TASK: 识别模块、依赖、入口点 +PURPOSE: Analyze project structure +TASK: Identify modules, dependencies, entry points MODE: analysis CONTEXT: @src/**/* -EXPECTED: JSON 格式的结构报告 +EXPECTED: JSON format structure report " --tool gemini --mode analysis --cd ${context.projectRoot}`, run_in_background: true, timeout: 600000 }); - // 等待完成 + // Wait for completion return await waitForCompletion(result.task_id); } ``` -### 模式 2: 链式调用 +### Pattern 2: Chained Calls -多步骤任务,每步依赖前一步结果。 +Multi-step tasks where each step depends on previous results. ```javascript async function executeChain(context) { - // Step 1: 收集 + // Step 1: Collect 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}`); - // Step 3: 生成 (依赖 Step 2) + // Step 3: Generate (depends on Step 2) const generateId = await runCLI('generate', context, `--resume ${analyzeId}`); return generateId; @@ -218,9 +218,9 @@ async function executeChain(context) { async function runCLI(step, context, resumeFlag = '') { const prompts = { - collect: 'PURPOSE: 收集代码文件...', - analyze: 'PURPOSE: 分析代码模式...', - generate: 'PURPOSE: 生成文档...' + collect: 'PURPOSE: Collect code files...', + analyze: 'PURPOSE: Analyze code patterns...', + generate: 'PURPOSE: Generate documentation...' }; const result = Bash({ @@ -232,9 +232,9 @@ async function runCLI(step, context, resumeFlag = '') { } ``` -### 模式 3: 并行调用 +### Pattern 3: Parallel Calls -独立任务并行执行。 +Independent tasks executed in parallel. ```javascript async function executeParallel(context) { @@ -244,15 +244,15 @@ async function executeParallel(context) { { type: 'patterns', tool: 'qwen' } ]; - // 并行启动 + // Start tasks in parallel const taskIds = tasks.map(task => 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 }).task_id ); - // 等待全部完成 + // Wait for all to complete const results = await Promise.all( 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 async function executeWithFallback(context) { @@ -299,9 +299,9 @@ async function runWithTool(tool, context) { --- -## 提示词模板集成 +## Prompt Template Integration -### 引用协议模板 +### Reference Protocol Templates ```bash # 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 ``` -### 动态模板构建 +### Dynamic Template Building ```javascript function buildPrompt(config) { @@ -334,21 +334,21 @@ CONSTRAINTS: ${constraints || ''} --- -## 超时配置 +## Timeout Configuration -### 推荐超时值 +### Recommended Timeout Values -| 任务类型 | 超时 (ms) | 说明 | -|---------|----------|------| -| 快速分析 | 300000 | 5 分钟 | -| 标准分析 | 600000 | 10 分钟 | -| 深度分析 | 1200000 | 20 分钟 | -| 代码生成 | 1800000 | 30 分钟 | -| 复杂任务 | 3600000 | 60 分钟 | +| Task Type | Timeout (ms) | Description | +|-----------|--------------|-------------| +| Quick analysis | 300000 | 5 minutes | +| Standard analysis | 600000 | 10 minutes | +| Deep analysis | 1200000 | 20 minutes | +| Code generation | 1800000 | 30 minutes | +| Complex tasks | 3600000 | 60 minutes | -### Codex 特殊处理 +### Special Codex Handling -Codex 需要更长的超时时间(建议 3x)。 +Codex requires longer timeout (recommend 3x). ```javascript const timeout = tool === 'codex' ? baseTimeout * 3 : baseTimeout; @@ -362,17 +362,17 @@ Bash({ --- -## 错误处理 +## Error Handling -### 常见错误 +### Common Errors -| 错误 | 原因 | 处理 | -|------|------|------| -| ETIMEDOUT | 网络超时 | 重试或切换工具 | -| Exit code 1 | 命令执行失败 | 检查参数,切换工具 | -| Context overflow | 上下文过大 | 减少输入范围 | +| Error | Cause | Handler | +|-------|-------|---------| +| ETIMEDOUT | Network timeout | Retry or switch tool | +| Exit code 1 | Command execution failed | Check parameters, switch tool | +| Context overflow | Input context too large | Reduce input scope | -### 重试策略 +### Retry Strategy ```javascript async function executeWithRetry(command, maxRetries = 3) { @@ -391,7 +391,7 @@ async function executeWithRetry(command, maxRetries = 3) { lastError = error; console.log(`Attempt ${attempt} failed: ${error.message}`); - // 指数退避 + // Exponential backoff if (attempt < maxRetries) { 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): - run_in_background: false → 同步,立即获取结果 +Agent calls (Task): + run_in_background: false → Synchronous, get result immediately -CLI 调用 (Bash + ccw cli): - run_in_background: true → 异步,后台执行 +CLI calls (Bash + ccw cli): + run_in_background: true → Asynchronous, run in background ``` -### 2. 工具选择 +### 2. Tool Selection ``` -分析任务: gemini > qwen -生成任务: codex > gemini > qwen -代码修改: codex > gemini +Analysis tasks: gemini > qwen +Generation tasks: codex > gemini > qwen +Code modification: codex > gemini ``` -### 3. 会话管理 +### 3. Session Management -- 相关任务使用 `--resume` 保持上下文 -- 独立任务不使用 `--resume` +- Use `--resume` for related tasks to maintain context +- Do not use `--resume` for independent tasks ### 4. Prompt Specification @@ -435,8 +435,8 @@ CLI 调用 (Bash + ccw cli): - Use `--rule