
Skill Generator
- 159 installs
- 2.1k repo stars
- Updated June 18, 2026
- catlog22/claude-code-workflow
Support for skill-generator
About
Provides workflow support for skill-generator. Solo builders use this to streamline development.
- skill-generator
Skill Generator by the numbers
- 159 all-time installs (skills.sh)
- Ranked #1,146 of 3,282 Productivity & Planning skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/catlog22/claude-code-workflow --skill skill-generatorAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 159 |
|---|---|
| repo stars | ★ 2.1k |
| Last updated | June 18, 2026 |
| Repository | catlog22/claude-code-workflow ↗ |
What it does
Support for skill-generator
Files
Skill Generator
Meta-skill for creating new Claude Code skills with configurable execution modes.
Architecture Overview
┌─────────────────────────────────────────────────────────────────┐
│ Skill Generator │
│ │
│ Input: User Request (skill name, purpose, mode) │
│ ↓ │
│ ┌─────────────────────────────────────────────────────────┐ │
│ │ Phase 0-5: Sequential Pipeline │ │
│ │ ┌────┐ ┌────┐ ┌────┐ ┌────┐ ┌────┐ ┌────┐ │ │
│ │ │ P0 │→│ P1 │→│ P2 │→│ P3 │→│ P4 │→│ P5 │ │ │
│ │ │Spec│ │Req │ │Dir │ │Gen │ │Spec│ │Val │ │ │
│ │ └────┘ └────┘ └────┘ └─┬──┘ └────┘ └────┘ │ │
│ │ │ │ │
│ │ ┌────┴────┐ │ │
│ │ ↓ ↓ │ │
│ │ Sequential Autonomous │ │
│ │ (phases/) (actions/) │ │
│ └─────────────────────────────────────────────────────────┘ │
│ ↓ │
│ Output: .claude/skills/{skill-name}/ (complete package) │
│ │
└─────────────────────────────────────────────────────────────────┘Execution Modes
Mode 1: Sequential (Fixed Order)
Traditional linear execution model, phases execute in numeric prefix order.
Phase 01 -> Phase 02 -> Phase 03 -> ... -> Phase NUse Cases:
- Pipeline tasks (collect -> analyze -> generate)
- Strong dependencies between phases
- Fixed output structure
Examples: software-manual, copyright-docs
Mode 2: Autonomous (Stateless Auto-Select)
Intelligent routing model, dynamically selects execution path based on context.
---------------------------------------------------
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
Examples: issue-manage, workflow-debug
Key Design Principles
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
---
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 | Universal design spec - defines structure, naming, quality standards for all Skills | P0 - Critical |
| 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 | SKILL.md entry file template |
| templates/sequential-phase.md | Sequential Phase template |
| templates/autonomous-orchestrator.md | Autonomous Orchestrator template |
| templates/autonomous-action.md | Autonomous Action template |
| templates/code-analysis-action.md | Code Analysis Action template |
| templates/llm-action.md | LLM Action template |
| templates/script-template.md | Unified Script Template (Bash + Python) |
Specification Documents (Read as Needed)
| Document | Purpose |
|---|---|
| specs/execution-modes.md | Execution Modes Specification |
| specs/skill-requirements.md | Skill Requirements Specification |
| specs/cli-integration.md | CLI Integration Specification |
| specs/scripting-integration.md | Script Integration Specification |
Phase Execution Guides (Reference During Execution)
| Document | Purpose |
|---|---|
| phases/01-requirements-discovery.md | Collect Skill Requirements |
| phases/02-structure-generation.md | Generate Directory Structure |
| phases/03-phase-generation.md | Generate Phase Files |
| phases/04-specs-templates.md | Generate Specs and Templates |
| phases/05-validation.md | Validation and Documentation |
---
Execution Flow
Input Parsing:
└─ Convert user request to structured format (skill-name/purpose/mode)
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
- 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
Phase 3: Phase/Action Generation
- 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)
- 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 documentationExecution Protocol:
// Phase 0: Read specifications (in-memory)
Read('.claude/skills/_shared/SKILL-DESIGN-SPEC.md');
Read('.claude/skills/skill-generator/templates/*.md'); // All templates
// Phase 1: Gather requirements
const answers = AskUserQuestion({
questions: [
{ question: "Skill name?", header: "Name", options: [...] },
{ question: "Execution mode?", header: "Mode", options: ["Sequential", "Autonomous"] }
]
});
const config = generateConfig(answers);
const workDir = `.workflow/.scratchpad/skill-gen-${timestamp}`;
Write(`${workDir}/skill-config.json`, JSON.stringify(config));
// Phase 2: Create structure
const skillDir = `.claude/skills/${config.skill_name}`;
Bash(`mkdir -p "${skillDir}/phases" "${skillDir}/specs" "${skillDir}/templates"`);
Write(`${skillDir}/SKILL.md`, generateSkillEntry(config));
// Phase 3: Generate phases (mode-dependent)
if (config.execution_mode === 'sequential') {
Write(`${skillDir}/phases/_orchestrator.md`, generateOrchestrator(config));
Write(`${skillDir}/workflow.json`, generateWorkflowDef(config));
config.sequential_config.phases.forEach(phase => {
Write(`${skillDir}/phases/${phase.id}.md`, generatePhase(phase, config));
});
} else {
Write(`${skillDir}/phases/orchestrator.md`, generateAutonomousOrchestrator(config));
Write(`${skillDir}/phases/state-schema.md`, generateStateSchema(config));
config.autonomous_config.actions.forEach(action => {
Write(`${skillDir}/phases/actions/${action.id}.md`, generateAction(action, config));
});
}
// Phase 4: Generate specs
Write(`${skillDir}/specs/${config.skill_name}-requirements.md`, generateRequirements(config));
Write(`${skillDir}/specs/quality-standards.md`, generateQualityStandards(config));
// Phase 5: Validate & Document
const validation = validateStructure(skillDir);
Write(`${skillDir}/validation-report.json`, JSON.stringify(validation));
Write(`${skillDir}/README.md`, generateReadme(config, validation));---
Reference Documents by Phase
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 for details.
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 | Universal Skill design specification | Understand Skill structure and naming conventions - REQUIRED |
| specs/reference-docs-spec.md | Reference document generation specification | Ensure Reference Documents have proper phase-based organization - REQUIRED |
Phase 1: Requirements Discovery
Collect Skill requirements and configuration
| Document | Purpose | When to Use |
|---|---|---|
| phases/01-requirements-discovery.md | Phase 1 execution guide | Understand how to collect user requirements and generate configuration |
| specs/skill-requirements.md | Skill requirements specification | Understand what information a Skill should contain |
Phase 2: Structure Generation
Generate directory structure and entry file
| Document | Purpose | When to Use |
|---|---|---|
| phases/02-structure-generation.md | Phase 2 execution guide | Understand how to generate directory structure |
| templates/skill-md.md | SKILL.md template | Learn how to generate the entry file |
Phase 3: Phase/Action Generation
Generate specific phase or action files based on execution mode
| Document | Purpose | When to Use |
|---|---|---|
| phases/03-phase-generation.md | Phase 3 execution guide | Understand Sequential vs Autonomous generation logic |
| templates/sequential-phase.md | Sequential Phase template | Generate phase files for Sequential mode |
| templates/autonomous-orchestrator.md | Orchestrator template | Generate orchestrator for Autonomous mode |
| templates/autonomous-action.md | Action template | Generate action files for Autonomous mode |
Phase 4: Specs & Templates
Generate domain-specific specifications and templates
| Document | Purpose | When to Use |
|---|---|---|
| phases/04-specs-templates.md | Phase 4 execution guide | Understand how to generate domain-specific documentation |
| specs/reference-docs-spec.md | Reference document specification | IMPORTANT: Follow this spec when generating Specs |
Phase 5: Validation & Documentation
Verify results and generate final documentation
| Document | Purpose | When to Use |
|---|---|---|
| phases/05-validation.md | Phase 5 execution guide | Understand how to verify generated Skill completeness |
Debugging & Troubleshooting
Reference documents when encountering issues
| Issue | Solution Document |
|---|---|
| Generated Skill missing Reference Documents | specs/reference-docs-spec.md - verify phase-based organization is followed |
| Reference document organization unclear | specs/reference-docs-spec.md - Core Principles section |
| Generated documentation does not meet quality standards | ../_shared/SKILL-DESIGN-SPEC.md |
Reference & Background
Documents for deep learning and design decisions
| Document | Purpose | Notes |
|---|---|---|
| specs/execution-modes.md | Detailed execution modes specification | Comparison and use cases for Sequential vs Autonomous |
| specs/cli-integration.md | CLI integration specification | How generated Skills integrate with CLI |
| specs/scripting-integration.md | Script integration specification | How to use scripts in Phases |
| templates/script-template.md | Script template | Unified Bash + Python template |
---
Output Structure
Sequential Mode
.claude/skills/{skill-name}/
├── SKILL.md # Entry file
├── phases/
│ ├── _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
├── templates/
│ └── agent-base.md
├── scripts/
└── README.mdAutonomous Mode
.claude/skills/{skill-name}/
├── SKILL.md # Entry file
├── phases/
│ ├── orchestrator.md # Orchestrator (state-driven)
│ ├── state-schema.md # State schema definition
│ └── actions/
│ ├── action-init.md
│ ├── action-create.md
│ └── action-list.md
├── specs/
│ ├── {skill-name}-requirements.md
│ ├── action-catalog.md
│ └── quality-standards.md
├── templates/
│ ├── orchestrator-base.md
│ └── action-base.md
├── scripts/
└── README.md---
Reference Documents by Phase
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 for details.
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 | Universal Skill design specification | Understand Skill structure and naming conventions - REQUIRED |
| specs/reference-docs-spec.md | Reference document generation specification | Ensure Reference Documents have proper phase-based organization - REQUIRED |
Phase 1: Requirements Discovery
Collect Skill requirements and configuration
| Document | Purpose | When to Use |
|---|---|---|
| phases/01-requirements-discovery.md | Phase 1 execution guide | Understand how to collect user requirements and generate configuration |
| specs/skill-requirements.md | Skill requirements specification | Understand what information a Skill should contain |
Phase 2: Structure Generation
Generate directory structure and entry file
| Document | Purpose | When to Use |
|---|---|---|
| phases/02-structure-generation.md | Phase 2 execution guide | Understand how to generate directory structure |
| templates/skill-md.md | SKILL.md template | Learn how to generate the entry file |
Phase 3: Phase/Action Generation
Generate specific phase or action files based on execution mode
| Document | Purpose | When to Use |
|---|---|---|
| phases/03-phase-generation.md | Phase 3 execution guide | Understand Sequential vs Autonomous generation logic |
| templates/sequential-phase.md | Sequential Phase template | Generate phase files for Sequential mode |
| templates/autonomous-orchestrator.md | Orchestrator template | Generate orchestrator for Autonomous mode |
| templates/autonomous-action.md | Action template | Generate action files for Autonomous mode |
Phase 4: Specs & Templates
Generate domain-specific specifications and templates
| Document | Purpose | When to Use |
|---|---|---|
| phases/04-specs-templates.md | Phase 4 execution guide | Understand how to generate domain-specific documentation |
| specs/reference-docs-spec.md | Reference document specification | IMPORTANT: Follow this spec when generating Specs |
Phase 5: Validation & Documentation
Verify results and generate final documentation
| Document | Purpose | When to Use |
|---|---|---|
| phases/05-validation.md | Phase 5 execution guide | Understand how to verify generated Skill completeness |
Debugging & Troubleshooting
Reference documents when encountering issues
| Issue | Solution Document |
|---|---|
| Generated Skill missing Reference Documents | specs/reference-docs-spec.md - verify phase-based organization is followed |
| Reference document organization unclear | specs/reference-docs-spec.md - Core Principles section |
| Generated documentation does not meet quality standards | ../_shared/SKILL-DESIGN-SPEC.md |
Reference & Background
Documents for deep learning and design decisions
| Document | Purpose | Notes |
|---|---|---|
| specs/execution-modes.md | Detailed execution modes specification | Comparison and use cases for Sequential vs Autonomous |
| specs/cli-integration.md | CLI integration specification | How generated Skills integrate with CLI |
| specs/scripting-integration.md | Script integration specification | How to use scripts in Phases |
| templates/script-template.md | Script template | Unified Bash + Python template |
Phase 1: Requirements Discovery
Collect basic skill information, configuration, and execution mode based on user input.
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
const basicInfo = await AskUserQuestion({
questions: [
{
question: "What is the name of the new Skill? (English, lowercase with hyphens, e.g., 'api-docs')",
header: "Skill Name",
multiSelect: false,
options: [
{ label: "Auto-generate", description: "Generate name automatically based on description" },
{ label: "Manual Input", description: "Enter custom name now" }
]
},
{
question: "What is the primary purpose of the Skill?",
header: "Purpose Type",
multiSelect: false,
options: [
{ 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 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 = {
"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: Execution Mode Selection
const modeInfo = await AskUserQuestion({
questions: [
{
question: "Select execution mode:",
header: "Execution Mode",
multiSelect: false,
options: [
{
label: "Sequential (Sequential Mode)",
description: "Phases execute in fixed order (collect→analyze→generate), suitable for pipeline tasks (recommended)"
},
{
label: "Autonomous (Autonomous Mode)",
description: "Dynamically select execution path, suitable for interactive tasks (e.g., Issue management)"
},
{
label: "Hybrid (Hybrid Mode)",
description: "Fixed initialization and finalization, flexible interaction in the middle"
}
]
}
]
});
const executionMode = modeInfo["Execution Mode"].includes("Sequential") ? "sequential" :
modeInfo["Execution Mode"].includes("Autonomous") ? "autonomous" : "hybrid";Step 3: Phase/Action Definition
Sequential Mode
if (executionMode === "sequential") {
const phaseInfo = await AskUserQuestion({
questions: [
{
question: "How many execution phases are needed?",
header: "Phase Count",
multiSelect: false,
options: [
{ 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 Phases": [
{ id: "01-collection", name: "Data Collection" },
{ id: "02-processing", name: "Processing" },
{ id: "03-output", name: "Output Generation" }
],
"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 Phases": [
{ id: "01-collection", name: "Requirements Collection" },
{ id: "02-exploration", name: "Project Exploration" },
{ id: "03-parallel", name: "Parallel Analysis" },
{ id: "03.5-consolidation", name: "Consolidation" },
{ id: "04-assembly", name: "Document Assembly" },
{ id: "05-refinement", name: "Iterative Refinement" },
{ id: "06-output", name: "Final Output" }
]
};
}Autonomous Mode
if (executionMode === "autonomous") {
const actionInfo = await AskUserQuestion({
questions: [
{
question: "What are the core actions? (Multiple selection allowed)",
header: "Action Definition",
multiSelect: true,
options: [
{ 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" }
]
}
]
});
}Step 4: Tool and Output Configuration
const toolsInfo = await AskUserQuestion({
questions: [
{
question: "Which special tools are needed? (Basic tools are included by default)",
header: "Tool Selection",
multiSelect: true,
options: [
{ 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: "What is the output format?",
header: "Output Format",
multiSelect: false,
options: [
{ 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: Generate Configuration File
const config = {
skill_name: skillName,
display_name: displayName,
description: description,
triggers: triggers,
execution_mode: executionMode,
// Mode-specific configuration
...(executionMode === "sequential" ? {
sequential_config: { phases: phases }
} : {
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
Data Flow to Phase 2:
- skill-config.json with all configuration parameters
- Execution mode decision drives directory structure creation
Phase 2: Structure Generation
Create Skill directory structure and entry file based on configuration.
Objective
- Create standard directory structure
- Generate SKILL.md entry file
- Create corresponding subdirectories based on execution mode
Execution Steps
Step 1: Read Configuration
const config = JSON.parse(Read(`${workDir}/skill-config.json`));
const skillDir = `.claude/skills/${config.skill_name}`;Step 2: Create Directory Structure
Base Directories (All Modes)
// Base infrastructure
Bash(`mkdir -p "${skillDir}/{phases,specs,templates,scripts}"`);Execution Mode-Specific Directories
config.execution_mode
↓
├─ "sequential"
│ ↓ Creates:
│ └─ phases/ (base directory already included)
│ ├─ _orchestrator.md
│ └─ workflow.json
│
└─ "autonomous" | "hybrid"
↓ Creates:
└─ phases/actions/
├─ state-schema.md
└─ *.md (action files)// Additional directories for Autonomous/Hybrid mode
if (config.execution_mode === 'autonomous' || config.execution_mode === 'hybrid') {
Bash(`mkdir -p "${skillDir}/phases/actions"`);
}Context Strategy-Specific Directories (P0 Enhancement)
// ========== 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"
);
}
// Memory strategy does not require directory creation (in-memory only)Directory Tree View:
Sequential + File Strategy:
.claude/skills/{skill-name}/
├── phases/
│ ├── _orchestrator.md
│ ├── workflow.json
│ ├── 01-*.md
│ └── 02-*.md
├── .scratchpad-template/
│ └── context/ <- File strategy persistent storage
└── specs/
Autonomous + Memory Strategy:
.claude/skills/{skill-name}/
├── phases/
│ ├── orchestrator.md
│ ├── state-schema.md
│ └── actions/
│ └── *.md
└── specs/Step 3: Generate SKILL.md
const skillMdTemplate = `---
name: ${config.skill_name}
description: ${config.description}. Triggers on ${config.triggers.map(t => `"${t}"`).join(", ")}.
allowed-tools: ${config.allowed_tools.join(", ")}
---
# ${config.display_name}
${config.description}
## Architecture Overview
\`\`\`
${generateArchitectureDiagram(config)}
\`\`\`
## Key Design Principles
${generateDesignPrinciples(config)}
## Execution Flow
${generateExecutionFlow(config)}
## Directory Setup
\`\`\`javascript
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"\`);` :
`Bash(\`mkdir -p "\${workDir}/state"\`);`}
\`\`\`
## Output Structure
\`\`\`
${generateOutputStructure(config)}
\`\`\`
## Reference Documents
${generateReferenceTable(config)}
`;
Write(`${skillDir}/SKILL.md`, skillMdTemplate);Step 4: Architecture Diagram Generation Functions
function generateArchitectureDiagram(config) {
if (config.execution_mode === 'sequential') {
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 (State-driven decision-making) │
└───────────────┬─────────────────────────────────────────────────┘
│
┌───────────┼───────────┐
↓ ↓ ↓
${config.autonomous_config.actions.slice(0, 3).map(a =>
`┌─────────┐ `).join('')}
${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 =>
`└─────────┘ `).join('')}`;
}
}
function generateDesignPrinciples(config) {
const common = [
"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. **Phase Isolation**: Each phase is independently testable",
"4. **Chained Output**: Phase output becomes next phase input"
].join('\n');
} else {
return [...common,
"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) =>
`├─ Phase ${i+1}: ${p.name}\n│ → Output: ${p.output || 'output.json'}`
).join('\n') + '\n```';
} else {
return `\`\`\`
┌─────────────────────────────────────────────────────────────────┐
│ Orchestrator Loop │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
│ │ Read │────▶│ Select │────▶│ Execute │ │
│ │ State │ │ Action │ │ Action │ │
│ └──────────┘ └──────────┘ └──────────┘ │
│ ▲ │ │
│ └──────────── Update State ◀───────┘ │
└─────────────────────────────────────────────────────────────────┘
\`\`\``;
}
}
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 =>
`│ └── ${p.output || 'section-' + p.id + '.md'}`
).join('\n') + `\n└── ${config.output.filename_pattern}`;
} else {
return base + `
├── actions-log.json
└── ${config.output.filename_pattern}`;
}
}
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) | 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) | Domain Requirements |`);
rows.push(`| [specs/quality-standards.md](specs/quality-standards.md) | Quality Standards |`);
return `| Document | Purpose |\n|----------|---------||\n` + rows.join('\n');
}Next Phase
→ Phase 3: Phase Generation
Data Flow to Phase 3:
- Complete directory structure in .claude/skills/{skill-name}/
- SKILL.md entry file ready for phase/action generation
- skill-config.json for template population
Phase 3: Phase Generation
Generate Phase files based on execution mode, including declarative workflow orchestration and context strategy support.
Objective
- 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)
Generate different context management code based on config.context_strategy:
| Strategy | Use Case | Advantages | Disadvantages |
|---|---|---|---|
file | Complex multi-phase tasks | Persistence, debuggable, recoverable | I/O overhead |
memory | Simple linear tasks | Fast speed | Not recoverable, hard to debug |
const CONTEXT_STRATEGIES = {
file: {
read: (key) => `JSON.parse(Read(\`\${workDir}/context/${key}.json\`))`,
write: (key, data) => `Write(\`\${workDir}/context/${key}.json\`, JSON.stringify(${data}, null, 2))`,
init: `Bash(\`mkdir -p "\${workDir}/context"\`)`
},
memory: {
read: (key) => `state.context.${key}`,
write: (key, data) => `state.context.${key} = ${data}`,
init: `state.context = {}`
}
};Execution Steps
Step 1: Load Configuration and Templates
const config = JSON.parse(Read(`${workDir}/skill-config.json`));
const skillDir = `.claude/skills/${config.skill_name}`;
const contextStrategy = config.context_strategy || 'file'; // Default file strategy
// Load templates
const skillRoot = '.claude/skills/skill-generator';Step 2: Sequential Mode - Generate Phase Files + Declarative Orchestrator
if (config.execution_mode === 'sequential') {
const phases = config.sequential_config.phases;
// ========== P0 Enhancement: Generate declarative orchestrator ==========
const workflowOrchestrator = generateSequentialOrchestrator(config, phases);
Write(`${skillDir}/phases/_orchestrator.md`, workflowOrchestrator);
// ========== P0 Enhancement: Generate workflow definition ==========
const workflowDef = generateWorkflowDefinition(config, phases);
Write(`${skillDir}/workflow.json`, JSON.stringify(workflowDef, null, 2));
// ========== 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;
const nextPhase = i < phases.length - 1 ? phases[i+1] : null;
const content = generateSequentialPhase({
phaseNumber: i + 1,
phaseId: phase.id,
phaseName: phase.name,
phaseDescription: phase.description || `Execute ${phase.name}`,
input: prevPhase ? prevPhase.output : "phase 0 output", // Phase 0 as first input source
output: phase.output,
nextPhase: nextPhase ? nextPhase.id : null,
config: config,
contextStrategy: contextStrategy
});
Write(`${skillDir}/phases/${phase.id}.md`, content);
}
}
// ========== P0 Enhancement: Declarative workflow definition ==========
function generateWorkflowDefinition(config, phases) {
// ========== 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',
parallel: false,
condition: null,
agent: {
type: 'universal-executor',
run_in_background: false
}
};
return {
skill_name: config.skill_name,
version: "1.0.0",
execution_mode: "sequential",
context_strategy: config.context_strategy || "file",
// ========== P0: Phase 0 placed first ==========
phases_to_run: ['00-spec-study', ...phases.map(p => p.id)],
// ========== 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, // First phase depends on Phase 0
output: p.output,
parallel: p.parallel || false,
condition: p.condition || null,
// Agent configuration (supports LLM integration)
agent: p.agent || (config.llm_integration?.enabled ? {
type: "llm",
tool: config.llm_integration.default_tool,
mode: config.llm_integration.mode || "analysis",
fallback_chain: config.llm_integration.fallback_chain || [],
run_in_background: false
} : {
type: "universal-executor",
run_in_background: false
})
}))
],
// Termination conditions
termination: {
on_success: "all_phases_completed",
on_error: "stop_and_report",
max_retries: 3
}
};
}
// ========== P0 Enhancement: Declarative orchestrator ==========
function generateSequentialOrchestrator(config, phases) {
return `# Sequential Orchestrator
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;
// 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) {
console.log(\`[Orchestrator] Skipping \${phaseId} (condition not met)\`);
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\`);
// Use Task to invoke Agent
const result = await Agent({
subagent_type: phaseConfig.agent?.type || 'universal-executor',
run_in_background: phaseConfig.agent?.run_in_background || false,
prompt: \`
[PHASE] \${phaseId}
[WORK_DIR] \${workDir}
[INPUT] \${phaseConfig.input ? \`\${workDir}/\${phaseConfig.input}\` : 'None'}
[OUTPUT] \${workDir}/\${phaseConfig.output}
\${phasePrompt}
\`
});
return JSON.parse(result);
}
\`\`\`
## Phase Execution Plan
**Execution Flow**:
\`\`\`
START
↓
Phase 0: Specification Study
↓ Output: spec-study-complete.flag
↓
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')}
↓
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'} |\`
).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}\`));`,
writeResult: `Write(\`\${workDir}/${params.output}\`, JSON.stringify(result, null, 2));`,
readContext: (key) => `JSON.parse(Read(\`\${workDir}/context/${key}.json\`))`,
writeContext: (key) => `Write(\`\${workDir}/context/${key}.json\`, JSON.stringify(data, null, 2))`
} : {
readPrev: `const prevOutput = state.context.prevPhaseOutput;`,
writeResult: `state.context.${params.phaseId.replace(/-/g, '_')}_output = result;`,
readContext: (key) => `state.context.${key}`,
writeContext: (key) => `state.context.${key} = data`
};
return `# Phase ${params.phaseNumber}: ${params.phaseName}
${params.phaseDescription}
## Objective
- Primary objective description
- Specific task list
## Input
- Dependency: \`${params.input}\`
- Configuration: \`{workDir}/skill-config.json\`
- Context Strategy: \`${params.contextStrategy}\`
## Execution Steps
### Step 1: Read Input
\`\`\`javascript
// Context strategy: ${params.contextStrategy}
${params.phaseNumber > 1 ? contextCode.readPrev : '// First phase, start directly from config'}
\`\`\`
### Step 2: Core Processing
\`\`\`javascript
// TODO: Implement core logic
const result = {
status: 'completed',
data: {
// Processing results
},
metadata: {
phase: '${params.phaseId}',
timestamp: new Date().toISOString()
}
};
\`\`\`
### Step 3: Output Results
\`\`\`javascript
// Write phase output (context strategy: ${params.contextStrategy})
${contextCode.writeResult}
// Return summary information to orchestrator
return {
status: 'completed',
output_file: '${params.output}',
summary: 'Phase ${params.phaseNumber} completed'
};
\`\`\`
## Output
- **File**: \`${params.output}\`
- **Format**: ${params.output.endsWith('.json') ? 'JSON' : 'Markdown'}
- **Context Strategy**: ${params.contextStrategy}
## 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\nThis is the final phase, produce final deliverables.`}
`;
}Step 3: Autonomous Mode - Generate Enhanced Orchestrator
if (config.execution_mode === 'autonomous' || config.execution_mode === 'hybrid') {
const contextStrategy = config.context_strategy || 'file';
// 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
- **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 => ({
id: a.id,
name: a.name,
preconditions: a.preconditions || [],
effects: a.effects || [],
priority: a.priority || 0
})), null, 2)};
\`\`\`
## Context Management (${contextStrategy} Strategy)
\`\`\`javascript
const ContextManager = {
${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. Check termination conditions
${config.autonomous_config.termination_conditions?.map(c =>
\` if (\${getTerminationCheck(c)}) return null;\`
).join('\n') || ' if (state.status === "completed") return null;'}
// 2. Check error limit
if (state.error_count >= 3) return 'action-abort';
// 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. 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);
}
return state[cond] === true;
});
}
\`\`\`
## 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. Read state
const state = ContextManager.readState(workDir);
console.log(\`[Iteration \${iteration}] Status: \${state.status}, Completed: \${state.completed_actions.length}\`);
// 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. Update current action
state.current_action = actionId;
ContextManager.writeState(workDir, state);
// 4. Execute action
try {
const actionPrompt = Read(\`\${skillDir}/phases/actions/\${actionId}.md\`);
const result = await Agent({
subagent_type: 'universal-executor',
run_in_background: false,
prompt: \`
[STATE]
\${JSON.stringify(state, null, 2)}
[WORK_DIR]
\${workDir}
[CONTEXT_STRATEGY]
${contextStrategy}
[ACTION]
\${actionPrompt}
[RETURN FORMAT]
Return JSON: { "status": "completed"|"failed", "stateUpdates": {...}, "summary": "..." }
\`
});
const actionResult = JSON.parse(result);
// 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({
action: actionId,
message: error.message,
timestamp: new Date().toISOString()
});
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(', ') || '-'} |\`
).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'}\`);
console.log(\`Completed actions: \${state.completed_actions.join(', ')}\`);
return runOrchestrator(workDir);
}
// Retry failed action
async function retryFailedAction(workDir) {
const state = ContextManager.readState(workDir);
if (state.errors.length > 0) {
const lastError = state.errors[state.errors.length - 1];
console.log(\`Retrying: \${lastError.action}\`);
state.error_count = Math.max(0, state.error_count - 1);
ContextManager.writeState(workDir, state);
return runOrchestrator(workDir);
}
}
\`\`\`
`;
}
// Enhanced action generation
function generateEnhancedAction(action, config, contextStrategy) {
return `# Action: ${action.name}
${action.description || 'Execute ' + action.name + ' operation'}
## Purpose
${action.description || 'TODO: Describe the purpose of this action'}
## Preconditions
${action.preconditions?.map(p => \`- [ ] \\\`${p}\\\`\`).join('\n') || '- [ ] No special preconditions'}
## Context Access (${contextStrategy} Strategy)
\`\`\`javascript
// Read shared context
${contextStrategy === 'file' ?
\`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;\`}
\`\`\`
## Execution
\`\`\`javascript
async function execute(state, workDir) {
// 1. Read necessary data
${contextStrategy === 'file' ?
\`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. Save results (${contextStrategy} strategy)
${contextStrategy === 'file' ?
\`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 }\` : '// File strategy: results saved to file'}
},
summary: '${action.name} completed'
};
}
\`\`\`
## State Updates
\`\`\`javascript
return {
status: 'completed',
stateUpdates: {
completed_actions: [...state.completed_actions, '${action.id}'],
${action.effects?.map(e => \` // Effect: ${e}\`).join('\n') || ' // No additional effects'}
}
};
\`\`\`
## Error Handling
| 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)
- 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
Available action catalog for ${config.display_name} (declarative).
## Action Definition
\`\`\`json
${JSON.stringify(actions.map(a => ({
id: a.id,
name: a.name,
description: a.description,
preconditions: a.preconditions || [],
effects: a.effects || [],
priority: a.priority || 0
})), null, 2)}
\`\`\`
## Action Dependency Graph
\`\`\`mermaid
graph TD
${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}]\`;
} else if (deps.length > 0) {
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} |\`
).join('\n')}
`;
}Step 4: Helper Functions
// ========== P0: Phase 0 generation function ==========
function generatePhase0Spec(config) {
const skillRoot = '.claude/skills/skill-generator';
const specsToRead = [
'../_shared/SKILL-DESIGN-SPEC.md',
`${skillRoot}/templates/*.md`
];
return `# Phase 0: Specification Study
MANDATORY PREREQUISITE - This phase cannot be skipped
## Objective
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 - Core Design Specification
\`\`\`javascript
// Universal design standards (MUST READ)
const designSpec = Read('.claude/skills/_shared/SKILL-DESIGN-SPEC.md');
// Key content checkpoints:
const checkpoints = {
structure: 'Directory structure conventions',
naming: 'Naming standards',
quality: 'Quality standards',
output: 'Output format requirements'
};
\`\`\`
### P1 - Template Files (Must read before generation)
\`\`\`javascript
// Load corresponding templates based on execution mode
const templates = {
all: [
'templates/skill-md.md' // SKILL.md entry file template
],
sequential: [
'templates/sequential-phase.md'
],
autonomous: [
'templates/autonomous-orchestrator.md',
'templates/autonomous-action.md'
]
};
const mode = '${config.execution_mode}';
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. Design specification (P0)
specs.push({
file: '../_shared/SKILL-DESIGN-SPEC.md',
content: Read('.claude/skills/_shared/SKILL-DESIGN-SPEC.md'),
priority: 'P0'
});
// 2. Template files (P1)
const templateFiles = Glob('.claude/skills/skill-generator/templates/*.md');
templateFiles.forEach(file => {
specs.push({
file: file,
content: Read(file),
priority: 'P1'
});
});
// ========== 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,
timestamp: new Date().toISOString()
};
Write(\`\${workDir}/spec-study-complete.flag\`, JSON.stringify(result, null, 2));
\`\`\`
## Output
- **Flag File**: \`spec-study-complete.flag\` (proves reading completion)
- **Side Effect**: Internalize specification knowledge, subsequent phases follow standards
## Success Criteria
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)
**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('');
}
function getDefaultValue(type) {
if (type.endsWith('[]')) return '[]';
if (type === 'number') return '0';
if (type === 'boolean') return 'false';
if (type === 'string') return '""';
return '{}';
}
function getTerminationCheck(condition) {
const checks = {
'user_exit': 'state.status === "user_exit"',
'error_limit': 'state.error_count >= 3',
'task_completed': 'state.status === "completed"',
'max_iterations': 'iteration >= MAX_ITERATIONS'
};
return checks[condition] || `state.${condition}`;
}
function getPreconditionCheck(action) {
if (!action.preconditions?.length) return 'true';
return action.preconditions.map(p => `state.${p}`).join(' && ');
}Next Phase
→ Phase 4: Specifications & Templates
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
Phase 4: Specifications & Templates Generation
Generate domain requirements, quality standards, agent templates, and action catalogs.
Objective
Generate comprehensive specifications and templates:
- Domain requirements document with validation function
- Quality standards with automated check system
- Agent base template with prompt structure
- Action catalog for autonomous mode (conditional)
Input
File Dependencies:
skill-config.json(from Phase 1).claude/skills/{skill-name}/directory (from Phase 2)- Generated phase/action files (from Phase 3)
Required Information:
- Skill name, display name, description
- Execution mode (determines if action-catalog.md is generated)
- Output format and location
- Phase/action definitions
Output
Generated Files:
| File | Purpose | Generation Condition |
|---|---|---|
specs/{skill-name}-requirements.md | Domain requirements with validation | Always |
specs/quality-standards.md | Quality evaluation criteria | Always |
templates/agent-base.md | Agent prompt template | Always |
specs/action-catalog.md | Action dependency graph and selection priority | Autonomous/Hybrid mode only |
File Structure:
Domain Requirements (specs/{skill-name}-requirements.md):
# {display_name} Requirements
- When to Use (phase/action reference table)
- Domain Requirements (Functional requirements, Output requirements, Quality requirements)
- Validation Function (JavaScript code)
- Error Handling (recovery strategies)Quality Standards (specs/quality-standards.md):
# Quality Standards
- Quality Dimensions (Completeness 25%, Consistency 25%, Accuracy 25%, Usability 25%)
- Quality Gates (Pass ≥80%, Review 60-79%, Fail <60%)
- Issue Classification (Errors, Warnings, Info)
- Automated Checks (runQualityChecks function)Agent Base (templates/agent-base.md):
# Agent Base Template
- 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):
# Action Catalog
- Available Actions (table with Purpose, Preconditions, Effects)
- Action Dependencies (Mermaid diagram)
- State Transitions (state machine table)
- Selection Priority (ordered action list)Decision Logic
Decision (execution_mode check):
├─ mode === 'sequential' → Generate 3 files only
│ └─ Files: requirements.md, quality-standards.md, agent-base.md
│
├─ mode === 'autonomous' → Generate 4 files
│ ├─ Files: requirements.md, quality-standards.md, agent-base.md
│ └─ Additional: action-catalog.md (with action dependencies)
│
└─ mode === 'hybrid' → Generate 4 files
├─ Files: requirements.md, quality-standards.md, agent-base.md
└─ Additional: action-catalog.md (with hybrid logic)Execution Protocol
// Phase 4: Generate Specifications & Templates
// Reference: phases/04-specs-templates.md
// Load config and setup
const config = JSON.parse(Read(`${workDir}/skill-config.json`));
const skillDir = `.claude/skills/${config.skill_name}`;
// Ensure specs and templates directories exist (created in Phase 2)
// skillDir structure: phases/, specs/, templates/
// Step 1: Generate domain requirements
const domainRequirements = `# ${config.display_name} Requirements
${config.description}
## When to Use
| Phase | Usage | Reference |
|-------|-------|-----------|
${config.execution_mode === 'sequential' ?
config.sequential_config.phases.map((p, i) =>
`| Phase ${i+1} | ${p.name} | ${p.id}.md |`
).join('\n') :
`| Orchestrator | Action selection | orchestrator.md |
| Actions | Action execution | actions/*.md |`}
---
## Domain Requirements
### Functional Requirements
- [ ] Requirement 1: TODO
- [ ] Requirement 2: TODO
- [ ] Requirement 3: TODO
### Output Requirements
- [ ] 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: Add validation rules
{ name: "Format correct", pass: output.format === "${config.output.format}" },
{ name: "Content complete", pass: output.content?.length > 0 }
];
return {
passed: checks.filter(c => c.pass).length,
total: checks.length,
details: checks
};
}
\`\`\`
## Error Handling
| 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);
// Step 2: Generate quality standards
const qualityStandards = `# Quality Standards
Quality assessment standards for ${config.display_name}.
## Quality Dimensions
### 1. Completeness (Completeness) - 25%
| 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 (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 (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 (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% | 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
\`\`\`javascript
function runQualityChecks(workDir) {
const results = {
completeness: checkCompleteness(workDir),
consistency: checkConsistency(workDir),
accuracy: checkAccuracy(workDir),
usability: checkUsability(workDir)
};
results.overall = (
results.completeness * 0.25 +
results.consistency * 0.25 +
results.accuracy * 0.25 +
results.usability * 0.25
);
return {
score: results.overall,
gate: results.overall >= 80 ? 'pass' :
results.overall >= 60 ? 'review' : 'fail',
details: results
};
}
\`\`\`
`;
Write(`${skillDir}/specs/quality-standards.md`, qualityStandards);
// Step 3: Generate agent base template
const agentBase = `# Agent Base Template
Agent base template for ${config.display_name}.
## Universal Prompt Structure
\`\`\`
[ROLE] You are {role}, focused on {responsibility}.
[PROJECT CONTEXT]
Skill: ${config.skill_name}
Objective: ${config.description}
[TASK]
{task description}
- Output: {output_path}
- Format: ${config.output.format}
[CONSTRAINTS]
- Constraint 1
- Constraint 2
[OUTPUT_FORMAT]
1. Execute task
2. Return JSON summary information
[QUALITY_CHECKLIST]
- [ ] Output format correct
- [ ] Content complete without omission
- [ ] No placeholder remnants
\`\`\`
## Variable Description
| 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 {
status: "completed" | "partial" | "failed";
output_file: string;
summary: string; // Max 50 chars
stats?: {
items_processed?: number;
errors?: number;
};
}
\`\`\`
## Role Definition Reference
${config.execution_mode === 'sequential' ?
config.sequential_config.phases.map((p, i) =>
`- **Phase ${i+1} Agent**: ${p.name} Expert`
).join('\n') :
config.autonomous_config.actions.map(a =>
`- **${a.name} Agent**: ${a.description || a.name + ' Executor'}`
).join('\n')}
`;
Write(`${skillDir}/templates/agent-base.md`, agentBase);
// Step 4: Conditional - Generate action catalog for autonomous/hybrid mode
if (config.execution_mode === 'autonomous' || config.execution_mode === 'hybrid') {
const actionCatalog = `# Action Catalog
Available action catalog for ${config.display_name}.
## Available Actions
| Action | Purpose | Preconditions | Effects |
|--------|---------|---------------|---------|
${config.autonomous_config.actions.map(a =>
`| [${a.id}](../phases/actions/${a.id}.md) | ${a.description || a.name} | ${a.preconditions?.join(', ') || '-'} | ${a.effects?.join(', ') || '-'} |`
).join('\n')}
## Action Dependencies
\`\`\`mermaid
graph TD
${config.autonomous_config.actions.map((a, i, arr) => {
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}]\`;
}).join('\n')}
\`\`\`
## State Transitions
| From State | Action | To State |
|------------|--------|----------|
| pending | action-init | running |
${config.autonomous_config.actions.slice(1).map(a =>
`| running | ${a.id} | running |`
).join('\n')}
| running | action-complete | completed |
| running | action-abort | failed |
## 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}\`
).join('\n')}
`;
Write(`${skillDir}/specs/action-catalog.md`, actionCatalog);
}
// Helper function
function toPascalCase(str) {
return str.split('-').map(s => s.charAt(0).toUpperCase() + s.slice(1)).join('');
}
// Phase output summary
console.log('Phase 4 complete: Generated specs and templates');Next Phase
→ Phase 5: Validation
Data Flow to Phase 5:
- All generated files in
specs/andtemplates/ - skill-config.json for validation reference
- Complete skill directory structure ready for final validation
Phase 5: Validation & Documentation
Verify generated skill completeness and generate user documentation.
Objective
Comprehensive validation and documentation:
- Verify all required files exist
- Check file content quality and completeness
- Generate validation report with issues and recommendations
- Generate README.md usage documentation
- Output final status and next steps
Input
File Dependencies:
skill-config.json(from Phase 1).claude/skills/{skill-name}/directory (from Phase 2)- All generated phase/action files (from Phase 3)
- All generated specs/templates files (from Phase 4)
Required Information:
- Skill name, display name, description
- Execution mode
- Trigger words
- Output configuration
- Complete skill directory structure
Output
Generated Files:
| File | Purpose | Content |
|---|---|---|
validation-report.json (workDir) | Validation report with detailed checks | File completeness, content quality, issues, recommendations |
README.md (skillDir) | User documentation | Quick Start, Usage, Output, Directory Structure, Customization |
Validation Report Structure (validation-report.json):
{
"skill_name": "...",
"execution_mode": "sequential|autonomous",
"generated_at": "ISO timestamp",
"file_checks": {
"total": N,
"existing": N,
"with_content": N,
"with_todos": N,
"details": [...]
},
"content_checks": {
"files_checked": N,
"all_passed": true|false,
"details": [...]
},
"summary": {
"status": "PASS|REVIEW|FAIL",
"issues": [...],
"recommendations": [...]
}
}README Structure (README.md):
# {display_name}
- Quick Start (Triggers, Execution Mode)
- Usage (Examples)
- Output (Format, Location, Filename)
- Directory Structure (Tree view)
- Customization (How to modify)
- Related Documents (Links)Validation Status Gates:
| Status | Condition | Meaning |
|---|---|---|
| PASS | All files exist + All content checks passed | Ready for use |
| REVIEW | All files exist + Some content checks failed | Needs refinement |
| FAIL | Missing files | Incomplete generation |
Decision Logic
Decision (Validation Flow):
├─ File Completeness Check
│ ├─ All files exist → Continue to content checks
│ └─ Missing files → Status = FAIL, collect missing file errors
│
├─ Content Quality Check
│ ├─ Sequential mode → Check phase files for structure
│ ├─ Autonomous mode → Check orchestrator + action files
│ └─ Common → Check SKILL.md, specs/, templates/
│
├─ Status Calculation
│ ├─ All files exist + All checks pass → Status = PASS
│ ├─ All files exist + Some checks fail → Status = REVIEW
│ └─ Missing files → Status = FAIL
│
└─ Generate Report & README
├─ validation-report.json (with issues and recommendations)
└─ README.md (with usage documentation)Execution Protocol
// Phase 5: Validation & Documentation
// Reference: phases/05-validation.md
// Load config and setup
const config = JSON.parse(Read(`${workDir}/skill-config.json`));
const skillDir = `.claude/skills/${config.skill_name}`;
// Step 1: File completeness check
const requiredFiles = {
common: [
'SKILL.md',
`specs/${config.skill_name}-requirements.md`,
'specs/quality-standards.md',
'templates/agent-base.md'
],
sequential: config.sequential_config?.phases?.map(p => `phases/${p.id}.md`) || [],
autonomous: [
'phases/orchestrator.md',
'phases/state-schema.md',
'specs/action-catalog.md',
...(config.autonomous_config?.actions?.map(a => `phases/actions/${a.id}.md`) || [])
]
};
const filesToCheck = [
...requiredFiles.common,
...(config.execution_mode === 'sequential' ? requiredFiles.sequential : requiredFiles.autonomous)
];
const fileCheckResults = filesToCheck.map(file => {
const fullPath = `${skillDir}/${file}`;
try {
const content = Read(fullPath);
return {
file: file,
exists: true,
size: content.length,
hasContent: content.length > 100,
hasTodo: content.includes('TODO')
};
} catch (e) {
return {
file: file,
exists: false,
size: 0,
hasContent: false,
hasTodo: false
};
}
});
// Step 2: Content quality check
const contentChecks = [];
// Check SKILL.md structure
const skillMd = Read(`${skillDir}/SKILL.md`);
contentChecks.push({
file: 'SKILL.md',
checks: [
{ name: 'Front Matter', pass: skillMd.startsWith('---') },
{ name: 'Architecture', pass: skillMd.includes('## Architecture') },
{ name: 'Execution Flow', pass: skillMd.includes('## Execution Flow') },
{ name: 'References', pass: skillMd.includes('## Reference Documents') }
]
});
// Check phase files
const phaseFiles = Glob(`${skillDir}/phases/*.md`);
for (const phaseFile of phaseFiles) {
if (phaseFile.includes('/actions/')) continue; // Check separately
const content = Read(phaseFile);
contentChecks.push({
file: phaseFile.replace(skillDir + '/', ''),
checks: [
{ name: 'Objective', pass: content.includes('## Objective') },
{ name: 'Execution', pass: content.includes('## Execution') || content.includes('## Execution Steps') },
{ name: 'Output', pass: content.includes('## Output') },
{ name: 'Code Blocks', pass: content.includes('```') }
]
});
}
// Check specs files
const specFiles = Glob(`${skillDir}/specs/*.md`);
for (const specFile of specFiles) {
const content = Read(specFile);
contentChecks.push({
file: specFile.replace(skillDir + '/', ''),
checks: [
{ name: 'Has Content', pass: content.length > 200 },
{ name: 'Has Structure', pass: content.includes('##') },
{ name: 'No Empty Sections', pass: !content.match(/##[^#]+\n\n##/) }
]
});
}
// Step 3: Generate validation report
const report = {
skill_name: config.skill_name,
execution_mode: config.execution_mode,
generated_at: new Date().toISOString(),
file_checks: {
total: fileCheckResults.length,
existing: fileCheckResults.filter(f => f.exists).length,
with_content: fileCheckResults.filter(f => f.hasContent).length,
with_todos: fileCheckResults.filter(f => f.hasTodo).length,
details: fileCheckResults
},
content_checks: {
files_checked: contentChecks.length,
all_passed: contentChecks.every(c => c.checks.every(ch => ch.pass)),
details: contentChecks
},
summary: {
status: calculateOverallStatus(fileCheckResults, contentChecks),
issues: collectIssues(fileCheckResults, contentChecks),
recommendations: generateRecommendations(fileCheckResults, contentChecks)
}
};
Write(`${workDir}/validation-report.json`, JSON.stringify(report, null, 2));
// Helper functions
function calculateOverallStatus(fileResults, contentResults) {
const allFilesExist = fileResults.every(f => f.exists);
const allContentPassed = contentResults.every(c => c.checks.every(ch => ch.pass));
if (allFilesExist && allContentPassed) return 'PASS';
if (allFilesExist) return 'REVIEW';
return 'FAIL';
}
function collectIssues(fileResults, contentResults) {
const issues = [];
fileResults.filter(f => !f.exists).forEach(f => {
issues.push({ type: 'ERROR', message: `Missing file: ${f.file}` });
});
fileResults.filter(f => f.hasTodo).forEach(f => {
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}: Missing ${ch.name}` });
});
});
return issues;
}
function generateRecommendations(fileResults, contentResults) {
const recommendations = [];
if (fileResults.some(f => f.hasTodo)) {
recommendations.push('Replace all TODO placeholders with actual content');
}
contentResults.forEach(c => {
if (c.checks.some(ch => !ch.pass)) {
recommendations.push(`Improve structure of ${c.file}`);
}
});
return recommendations;
}
// Step 4: Generate README.md
const readme = `# ${config.display_name}
${config.description}
## Quick Start
### Trigger Words
${config.triggers.map(t => `- "${t}"`).join('\n')}
### Execution Mode
**${config.execution_mode === 'sequential' ? 'Sequential (Sequential)' : 'Autonomous (Autonomous)'}**
${config.execution_mode === 'sequential' ?
\`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
\`\`\`
# Direct trigger
User: ${config.triggers[0]}
# Or use Skill name
User: /skill ${config.skill_name}
\`\`\`
## Output
- **Format**: ${config.output.format}
- **Location**: \`${config.output.location}\`
- **Filename**: \`${config.output.filename_pattern}\`
## Directory Structure
\`\`\`
.claude/skills/${config.skill_name}/
├── SKILL.md # Entry file
├── phases/ # Execution phases
${config.execution_mode === 'sequential' ?
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/ # Specification files
│ ├── ${config.skill_name}-requirements.md
│ ├── quality-standards.md
${config.execution_mode === 'autonomous' ? '│ └── action-catalog.md' : ''}
└── templates/ # Template files
└── agent-base.md
\`\`\`
## Customization
### Modify Execution Logic
Edit phase files in the \`phases/\` directory.
### Adjust Quality Standards
Edit \`specs/quality-standards.md\`.
### Add New ${config.execution_mode === 'sequential' ? 'Phase' : 'Action'}
${config.execution_mode === 'sequential' ?
\`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
- [Design Specification](../_shared/SKILL-DESIGN-SPEC.md)
- [Execution Modes Specification](specs/../../../skill-generator/specs/execution-modes.md)
---
*Generated by skill-generator v1.0*
`;
Write(`${skillDir}/README.md`, readme);
// Step 5: Output final result
const finalResult = {
skill_name: config.skill_name,
skill_path: skillDir,
execution_mode: config.execution_mode,
generated_files: [
'SKILL.md',
'README.md',
...filesToCheck
],
validation: report.summary,
next_steps: [
'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 Generation Complete ===');
console.log(\`Path: \${skillDir}\`);
console.log(\`Mode: \${config.execution_mode}\`);
console.log(\`Status: \${report.summary.status}\`);
console.log('');
console.log('Next Steps:');
finalResult.next_steps.forEach(s => console.log(s));Workflow Completion
Final Status: Skill generation pipeline complete
Generated Artifacts:
- Complete skill directory structure in
.claude/skills/{skill-name}/ - Validation report in
{workDir}/validation-report.json - User documentation in
{skillDir}/README.md
Next Steps: 1. Review validation report for any issues or recommendations 2. Replace TODO placeholders with actual implementation 3. Test skill execution with trigger words 4. Customize phase logic based on specific requirements 5. Update triggers and descriptions as needed
CLI Integration Specification
CCW CLI integration specification that defines how to properly call external CLI tools within Skills.
---
Execution Modes
1. Synchronous Execution (Blocking)
Suitable for scenarios that need immediate results.
// Agent call - synchronous
const result = Agent({
subagent_type: 'universal-executor',
prompt: 'Execute task...',
run_in_background: false // Key: synchronous execution
});
// Result immediately available
console.log(result);2. Asynchronous Execution (Background)
Suitable for long-running CLI commands.
// CLI call - asynchronous
const task = Bash({
command: 'ccw cli -p "..." --tool gemini --mode analysis',
run_in_background: true // Key: background execution
});
// Returns immediately without waiting for result
// task.task_id available for later queries---
CCW CLI Call Specification
Basic Command Structure
ccw cli -p "<PROMPT>" --tool <gemini|qwen|codex> --mode <analysis|write>Parameter Description
| Parameter | Required | Description |
|---|---|---|
-p "<prompt>" | Yes | Prompt text (use double quotes) |
--tool <tool> | Yes | Tool selection: gemini, qwen, codex |
--mode <mode> | Yes | Execution mode: analysis, write |
--cd <path> | - | Working directory |
--includeDirs <dirs> | - | Additional directories (comma-separated) |
--resume [id] | - | Resume session |
Mode Selection
- Analysis/Documentation tasks?
→ --mode analysis (read-only)
- Implementation/Modification tasks?
→ --mode write (read-write)---
Agent Types and Selection
universal-executor
General-purpose executor, the most commonly used agent type.
Agent({
subagent_type: 'universal-executor',
prompt: `
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
Code exploration agent for quick codebase understanding.
Agent({
subagent_type: 'Explore',
prompt: `
Explore src/ directory:
- Identify main modules
- Understand directory structure
- Find entry points
Thoroughness: medium
`,
run_in_background: false
});Applicable Scenarios:
- Codebase exploration
- File discovery
- Structure understanding
cli-explore-agent
Deep code analysis agent.
Agent({
subagent_type: 'cli-explore-agent',
prompt: `
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
// Save session ID
const session = Bash({
command: 'ccw cli -p "Initial analysis..." --tool gemini --mode analysis',
run_in_background: true
});
// Resume later
const continuation = Bash({
command: `ccw cli -p "Continue analysis..." --tool gemini --mode analysis --resume ${session.id}`,
run_in_background: true
});Multi-Session Merge
// Merge context from multiple sessions
const merged = Bash({
command: `ccw cli -p "Aggregate analysis..." --tool gemini --mode analysis --resume ${id1},${id2}`,
run_in_background: true
});---
CLI Integration Patterns in Skills
Pattern 1: Single Call
Simple tasks completed in one call.
// Phase execution
async function executePhase(context) {
const result = Bash({
command: `ccw cli -p "
PURPOSE: Analyze project structure
TASK: Identify modules, dependencies, entry points
MODE: analysis
CONTEXT: @src/**/*
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);
}Pattern 2: Chained Calls
Multi-step tasks where each step depends on previous results.
async function executeChain(context) {
// Step 1: Collect
const collectId = await runCLI('collect', context);
// Step 2: Analyze (depends on Step 1)
const analyzeId = await runCLI('analyze', context, `--resume ${collectId}`);
// Step 3: Generate (depends on Step 2)
const generateId = await runCLI('generate', context, `--resume ${analyzeId}`);
return generateId;
}
async function runCLI(step, context, resumeFlag = '') {
const prompts = {
collect: 'PURPOSE: Collect code files...',
analyze: 'PURPOSE: Analyze code patterns...',
generate: 'PURPOSE: Generate documentation...'
};
const result = Bash({
command: `ccw cli -p "${prompts[step]}" --tool gemini --mode analysis ${resumeFlag}`,
run_in_background: true
});
return await waitForCompletion(result.task_id);
}Pattern 3: Parallel Calls
Independent tasks executed in parallel.
async function executeParallel(context) {
const tasks = [
{ type: 'structure', tool: 'gemini' },
{ type: 'dependencies', tool: 'gemini' },
{ type: 'patterns', tool: 'qwen' }
];
// Start tasks in parallel
const taskIds = tasks.map(task =>
Bash({
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))
);
return results;
}Pattern 4: Fallback Chain
Automatically switch tools on failure.
async function executeWithFallback(context) {
const tools = ['gemini', 'qwen', 'codex'];
let result = null;
for (const tool of tools) {
try {
result = await runWithTool(tool, context);
if (result.success) break;
} catch (error) {
console.log(`${tool} failed, trying next...`);
}
}
if (!result?.success) {
throw new Error('All tools failed');
}
return result;
}
async function runWithTool(tool, context) {
const task = Bash({
command: `ccw cli -p "..." --tool ${tool} --mode analysis`,
run_in_background: true,
timeout: 600000
});
return await waitForCompletion(task.task_id);
}---
Prompt Template Integration
Reference Protocol Templates
# Analysis mode - use --rule to auto-load protocol and template (appended to prompt)
ccw cli -p "
CONSTRAINTS: ...
..." --tool gemini --mode analysis --rule analysis-code-patterns
# Write mode - use --rule to auto-load protocol and template (appended to prompt)
ccw cli -p "
CONSTRAINTS: ...
..." --tool codex --mode write --rule development-featureDynamic Template Building
function buildPrompt(config) {
const { purpose, task, mode, context, expected, constraints } = config;
return `
PURPOSE: ${purpose}
TASK: ${task.map(t => `• ${t}`).join('\n')}
MODE: ${mode}
CONTEXT: ${context}
EXPECTED: ${expected}
CONSTRAINTS: ${constraints || ''}
`; // Use --rule option to auto-append protocol + template
}---
Timeout Configuration
Recommended Timeout Values
| 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 |
Special Codex Handling
Codex requires longer timeout (recommend 3x).
const timeout = tool === 'codex' ? baseTimeout * 3 : baseTimeout;
Bash({
command: `ccw cli -p "..." --tool ${tool} --mode write`,
run_in_background: true,
timeout: timeout
});---
Error Handling
Common Errors
| 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
async function executeWithRetry(command, maxRetries = 3) {
let lastError = null;
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
const task = Bash({
command,
run_in_background: true,
timeout: 600000
});
return await waitForCompletion(task.task_id);
} catch (error) {
lastError = error;
console.log(`Attempt ${attempt} failed: ${error.message}`);
// Exponential backoff
if (attempt < maxRetries) {
await sleep(Math.pow(2, attempt) * 1000);
}
}
}
throw lastError;
}---
Best Practices
1. run_in_background Rule
Agent calls (Task):
run_in_background: false → Synchronous, get result immediately
CLI calls (Bash + ccw cli):
run_in_background: true → Asynchronous, run in background2. Tool Selection
Analysis tasks: gemini > qwen
Generation tasks: codex > gemini > qwen
Code modification: codex > gemini3. Session Management
- Use
--resumefor related tasks to maintain context - Do not use
--resumefor independent tasks
4. Prompt Specification
- Always use PURPOSE/TASK/MODE/CONTEXT/EXPECTED/CONSTRAINTS structure
- Use
--rule <template>to auto-append protocol + template to prompt - Template name format:
category-function(e.g.,analysis-code-patterns)
5. Result Processing
- Persist important results to workDir
- Brief returns: path + summary, avoid context overflow
- JSON format convenient for downstream processing
Execution Modes Specification
Detailed specification definitions for two Skill execution modes.
---
Mode Overview
| Feature | Sequential (Fixed Order) | Autonomous (Dynamic) |
|---|---|---|
| Execution Order | Fixed (numeric prefix) | Dynamic (orchestrator decision) |
| Phase Dependencies | Strong dependencies | Weak/no dependencies |
| State Management | Implicit (phase output) | Explicit (state file) |
| Use Cases | Pipeline tasks | Interactive tasks |
| Complexity | Low | Medium-High |
| Extensibility | Insert sub-phases | Add new actions |
---
Mode 1: Sequential (Fixed Order Mode)
Definition
Phases execute linearly in fixed order, with each phase's output serving as input to the next phase.
Directory Structure
phases/
├── 01-{first-step}.md
├── 02-{second-step}.md
├── 02.5-{sub-step}.md # Optional: sub-phase
├── 03-{third-step}.md
└── ...Execution Flow
┌─────────┐ ┌─────────┐ ┌─────────┐
│Phase 01 │────▶│Phase 02 │────▶│Phase 03 │────▶ ...
└─────────┘ └─────────┘ └─────────┘
│ │ │
▼ ▼ ▼
output1.json output2.md output3.mdPhase File Specification
# Phase N: {Phase Name}
{One-sentence description}
## Objective
{Detailed objective}
## Input
- Dependencies: {Previous phase output}
- Configuration: {Configuration file}
## Execution Steps
### Step 1: {Step}
{Execution code or description}
### Step 2: {Step}
{Execution code or description}
## Output
- **File**: `{Output file}`
- **Format**: {JSON/Markdown}
## Next Phase
→ [Phase N+1: xxx](0N+1-xxx.md)Applicable Scenarios
- Document Generation: Collect → Analyze → Assemble → Optimize
- Code Analysis: Scan → Parse → Report
- Data Processing: Extract → Transform → Load
Advantages
- Clear logic, easy to understand
- Simple debugging, can validate phase by phase
- Predictable output
Disadvantages
- Low flexibility
- Difficult to handle branching logic
- Limited user interaction
---
Mode 2: Autonomous (Dynamic Mode)
Definition
No fixed execution order. The orchestrator dynamically selects the next action based on current state.
Directory Structure
phases/
├── orchestrator.md # Orchestrator: core decision logic
├── state-schema.md # State structure definition
└── actions/ # Independent actions (no order)
├── action-{a}.md
├── action-{b}.md
├── action-{c}.md
└── ...Core Components
1. Orchestrator
# Orchestrator
## Role
Select and execute the next action based on current state.
## State Reading
Read state file: `{workDir}/state.json`
## Decision Logic
function selectNextAction(state) { // 1. Check termination conditions if (state.status === 'completed') return null; if (state.error_count > MAX_RETRIES) return 'action-abort';
// 2. Select action based on state if (!state.initialized) return 'action-init'; if (state.pending_items.length > 0) return 'action-process'; if (state.needs_review) return 'action-review';
// 3. Default action return 'action-complete'; }
## Execution Loop
while (true) { state = readState(); action = selectNextAction(state); if (!action) break;
result = executeAction(action, state); updateState(result); }
2. State Schema
# State Schema
## State File
Location: `{workDir}/state.json`
## Structure Definition
interface SkillState { // Metadata skill_name: string; started_at: string; updated_at: string;
// Execution state status: 'pending' | 'running' | 'completed' | 'failed'; current_action: string | null; completed_actions: string[];
// Business data context: Record<string, any>; pending_items: any[]; results: Record<string, any>;
// Error tracking errors: Array<{ action: string; message: string; timestamp: string; }>; error_count: number; }
## Initial State
{ "skill_name": "{skill-name}", "started_at": "{ISO8601}", "updated_at": "{ISO8601}", "status": "pending", "current_action": null, "completed_actions": [], "context": {}, "pending_items": [], "results": {}, "errors": [], "error_count": 0 }
3. Action
# Action: {action-name}
## Purpose
{Action purpose}
## Preconditions
- [ ] Condition 1
- [ ] Condition 2
## Execution
{Execution logic}
## State Updates
return { completed_actions: [...state.completed_actions, 'action-name'], results: { ...state.results, action_name: { / result / } }, // Other state updates };
## Next Actions (Hints)
- On success: `action-{next}`
- On failure: `action-retry` or `action-abort`Execution Flow
┌─────────────────────────────────────────────────────────────────┐
│ Orchestrator Loop │
│ ┌─────────────────────────────────────────────────────────┐ │
│ │ │ │
│ │ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ │
│ │ │ Read │────▶│ Select │────▶│ Execute │ │ │
│ │ │ State │ │ Action │ │ Action │ │ │
│ │ └──────────┘ └──────────┘ └──────────┘ │ │
│ │ ▲ │ │ │
│ │ │ ▼ │ │
│ │ │ ┌──────────┐ │ │
│ │ └───────────│ Update │◀────────────────────────┘ │
│ │ │ State │ │
│ │ └──────────┘ │
│ │ │ │
│ └─────────────────────────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌──────────────────┐ │
│ │ Termination? │ │
│ │ - completed │ │
│ │ - max_retries │ │
│ │ - user_abort │ │
│ └──────────────────┘ │
└─────────────────────────────────────────────────────────────────┘Action Catalog
Defined in specs/action-catalog.md:
# Action Catalog
## Available Actions
| Action | Purpose | Preconditions | Effects |
|--------|---------|---------------|---------|
| action-init | Initialize state | status=pending | status=running |
| action-process | Process pending items | pending_items.length>0 | pending_items-- |
| action-review | User review | needs_review=true | needs_review=false |
| action-complete | Complete task | pending_items.length=0 | status=completed |
| action-abort | Abort task | error_count>MAX | status=failed |
## Action Dependencies Graph
graph TD INIT[action-init] --> PROCESS[action-process] PROCESS --> PROCESS PROCESS --> REVIEW[action-review] REVIEW --> PROCESS REVIEW --> COMPLETE[action-complete] PROCESS --> ABORT[action-abort]
Applicable Scenarios
- Interactive Tasks: Q&A, dialog, form filling
- State Machine Tasks: Issue management, workflow approval
- Exploratory Tasks: Debugging, diagnosis, search
Advantages
- Highly flexible, adapts to dynamic requirements
- Supports complex branching logic
- Easy to extend with new actions
Disadvantages
- High complexity
- State management overhead
- Large debugging difficulty
---
Mode Selection Guide
Decision Flow
Analyze user requirements
│
▼
┌────────────────────────────┐
│ Are there strong │
│ dependencies between │
│ phases? │
└────────────────────────────┘
│
├── Yes → Sequential
│
└── No → Continue decision
│
▼
┌────────────────────────────┐
│ Do you need dynamic │
│ response to user intent? │
└────────────────────────────┘
│
├── Yes → Autonomous
│
└── No → SequentialQuick Decision Table
| Question | Sequential | Autonomous |
|---|---|---|
| Is output structure fixed? | Yes | No |
| Do you need multi-turn user interaction? | No | Yes |
| Can phases be skipped/repeated? | No | Yes |
| Is there complex branching logic? | No | Yes |
| Should debugging be simple? | Yes | No |
---
Hybrid Mode
Some complex Skills may need to use both modes in combination:
phases/
├── 01-init.md # Sequential: initialization
├── 02-orchestrator.md # Autonomous: core interaction loop
│ └── actions/
│ ├── action-a.md
│ └── action-b.md
└── 03-finalize.md # Sequential: finalizationApplicable Scenarios:
- Initialization and finalization are fixed, middle interaction is flexible
- Multi-phase tasks where certain phases need dynamic decisions
Reference Documents Generation Specification
IMPORTANT: This specification defines how to organize and present reference documents in generated skills to avoid duplication issues.
Core Principles
1. Phase-Based Organization
Reference documents must be organized by skill execution phases, not as a flat list.
Wrong Approach (Flat List):
## Reference Documents
| Document | Purpose |
|----------|---------|
| doc1.md | ... |
| doc2.md | ... |
| doc3.md | ... |Correct Approach (Phase-Based Navigation):
## Reference Documents by Phase
### Phase 1: Analysis
Documents to refer to when executing Phase 1
| Document | Purpose | When to Use |
|----------|---------|-------------|
| doc1.md | ... | Understand concept x |
### Phase 2: Implementation
Documents to refer to when executing Phase 2
| Document | Purpose | When to Use |
|----------|---------|-------------|
| doc2.md | ... | Implement feature y |2. Four Standard Groupings
Reference documents must be divided into the following four groupings:
| Grouping | When to Use | Content |
|---|---|---|
| Phase N: [Name] | When executing this phase | All documents related to this phase |
| Debugging | When encountering problems | Issue to documentation mapping table |
| Reference | When learning in depth | Templates, original implementations, best practices |
| (Optional) Quick Links | Quick navigation | Most frequently consulted 5-7 documents |
3. Each Document Entry Must Include
| [path](path) | Purpose | When to Use |When to Use Column Requirements:
- Clear explanation of usage scenarios
- Describe what problem is solved
- Do not simply say "refer to" or "learn about"
Good Examples:
- "Understand issue data structure"
- "Learn about the Planning Agent role"
- "Check if implementation meets quality standards"
- "Quickly locate the reason for status anomalies"
Poor Examples:
- "Reference document"
- "More information"
- "Background knowledge"
4. Embedding Document Guidance in Execution Flow
In the "Execution Flow" section, each Phase description should include "Refer to" hints:
### Phase 2: Planning Pipeline
→ **Refer to**: action-plan.md, subagent-roles.md
→ Detailed flow description...5. Quick Troubleshooting Reference Table
Should contain common issue to documentation mapping:
### Debugging & Troubleshooting
| Issue | Solution Document |
|-------|------------------|
| Phase execution failed | Refer to corresponding phase documentation |
| Output format incorrect | specs/quality-standards.md |
| Data validation failed | specs/schema-validation.md |---
Generation Rules
Rule 1: Document Classification Recognition
Automatically generate groupings based on skill phases:
const phaseEmojis = {
'discovery': '📋', // Collection, exploration
'generation': '🔧', // Generation, creation
'analysis': '🔍', // Analysis, review
'implementation': '⚙️', // Implementation, execution
'validation': '✅', // Validation, testing
'completion': '🏁', // Completion, wrap-up
};
// Generate a section for each phase
phases.forEach((phase, index) => {
const emoji = phaseEmojis[phase.type] || '📌';
const title = `### ${emoji} Phase ${index + 1}: ${phase.name}`;
// List all documents related to this phase
});Rule 2: Document to Phase Mapping
In config, specs and templates should be annotated with their belonging phases:
{
"specs": [
{
"path": "specs/issue-handling.md",
"purpose": "Issue data specification",
"phases": ["phase-2", "phase-3"], // Which phases this spec is related to
"context": "Understand issue structure and validation rules"
}
]
}Rule 3: Priority and Mandatory Reading
Use visual symbols to distinguish document importance:
| Document | When | Notes |
|----------|------|-------|
| spec.md | **Must Read Before Execution** | Mandatory prerequisite |
| action.md | Refer to during execution | Operation guide |
| template.md | Reference for learning | Optional in-depth |Rule 4: Avoid Duplication
- Mandatory Prerequisites section: List mandatory P0 specifications
- Reference Documents by Phase section: List all documents (including mandatory prerequisites)
- Documents in both sections can overlap, but their purposes differ:
- Prerequisites: Emphasize "must read first"
- Reference: Provide "complete navigation"
---
Implementation Example
Sequential Skill Example
## Mandatory Prerequisites
| Document | Purpose | When |
|----------|---------|------|
| [specs/issue-handling.md](specs/issue-handling.md) | Issue data specification | **Must Read Before Execution** |
| [specs/solution-schema.md](specs/solution-schema.md) | Solution structure | **Must Read Before Execution** |
---
## Reference Documents by Phase
### Phase 1: Issue Collection
Documents to refer to when executing Phase 1
| Document | Purpose | When to Use |
|----------|---------|-------------|
| [phases/actions/action-list.md](phases/actions/action-list.md) | Issue loading logic | Understand how to collect issues |
| [specs/issue-handling.md](specs/issue-handling.md) | Issue data specification | Verify issue format **Required Reading** |
### Phase 2: Planning
Documents to refer to when executing Phase 2
| Document | Purpose | When to Use |
|----------|---------|-------------|
| [phases/actions/action-plan.md](phases/actions/action-plan.md) | Planning process | Understand issue to solution transformation |
| [specs/solution-schema.md](specs/solution-schema.md) | Solution structure | Verify solution JSON format **Required Reading** |
### Debugging & Troubleshooting
| Issue | Solution Document |
|-------|------------------|
| Phase 1 failed | [phases/actions/action-list.md](phases/actions/action-list.md) |
| Planning output incorrect | [phases/actions/action-plan.md](phases/actions/action-plan.md) + [specs/solution-schema.md](specs/solution-schema.md) |
| Data validation failed | [specs/issue-handling.md](specs/issue-handling.md) |
### Reference & Background
| Document | Purpose | Notes |
|----------|---------|-------|
| [../issue-plan.md](../../.codex/prompts/issue-plan.md) | Original implementation | Planning Agent system prompt |---
Generation Algorithm
function generateReferenceDocuments(config) {
let result = '## Reference Documents by Phase\n\n';
// Generate a section for each phase
const phases = config.phases || config.actions || [];
phases.forEach((phase, index) => {
const phaseNum = index + 1;
const emoji = getPhaseEmoji(phase.type);
const title = phase.display_name || phase.name;
result += `### ${emoji} Phase ${phaseNum}: ${title}\n`;
result += `Documents to refer to when executing Phase ${phaseNum}\n\n`;
// Find all documents related to this phase
const docs = config.specs.filter(spec =>
(spec.phases || []).includes(`phase-${phaseNum}`) ||
matchesByName(spec.path, phase.name)
);
if (docs.length > 0) {
result += '| Document | Purpose | When to Use |\n';
result += '|----------|---------|-------------|\n';
docs.forEach(doc => {
const required = doc.phases && doc.phases[0] === `phase-${phaseNum}` ? ' **Required Reading**' : '';
result += `| [${doc.path}](${doc.path}) | ${doc.purpose} | ${doc.context}${required} |\n`;
});
result += '\n';
}
});
// Troubleshooting section
result += '### Debugging & Troubleshooting\n\n';
result += generateDebuggingTable(config);
// In-depth reference learning
result += '### Reference & Background\n\n';
result += generateReferenceTable(config);
return result;
}---
Checklist
When generating skill's SKILL.md, the reference documents section should satisfy:
- [ ] Has clear "## Reference Documents by Phase" heading
- [ ] Each phase has a corresponding section (identified with symbols)
- [ ] Each document entry includes "When to Use" column
- [ ] Includes "Debugging & Troubleshooting" section
- [ ] Includes "Reference & Background" section
- [ ] Mandatory reading documents are marked with bold text
- [ ] Execution Flow section includes "→ Refer to: ..." guidance
- [ ] Avoid overly long document lists (maximum 5-8 documents per phase)
Scripting Integration Specification
Skill scripting integration specification that defines how to use external scripts for deterministic task execution.
Core Principles
1. Convention over configuration: Naming is ID, file extension is runtime 2. Minimal invocation: Complete script call in one line 3. Standard input/output: Command-line parameters as input, JSON as standard output
Directory Structure
.claude/skills/<skill-name>/
├── scripts/ # Scripts directory
│ ├── process-data.py # id: process-data
│ ├── validate-output.sh # id: validate-output
│ └── transform-json.js # id: transform-json
├── phases/
└── specs/Naming Conventions
| Extension | Runtime | Execution Command |
|---|---|---|
.py | python | python scripts/{id}.py |
.sh | bash | bash scripts/{id}.sh |
.js | node | node scripts/{id}.js |
Declaration Format
Declare in the ## Scripts section of Phase or Action files:
## Scripts
- process-data
- validate-outputInvocation Syntax
Basic Call
const result = await ExecuteScript('script-id', { key: value });Parameter Name Conversion
Keys in the JS object are automatically converted to kebab-case command-line parameters:
| JS Key Name | Converted Parameter |
|---|---|
input_path | --input-path |
output_dir | --output-dir |
max_count | --max-count |
Use --input-path in scripts, pass input_path when calling.
Complete Call (with Error Handling)
const result = await ExecuteScript('process-data', {
input_path: `${workDir}/data.json`,
threshold: 0.9
});
if (!result.success) {
throw new Error(`Script execution failed: ${result.stderr}`);
}
const { output_file, count } = result.outputs;Return Format
interface ScriptResult {
success: boolean; // exit code === 0
stdout: string; // Complete standard output
stderr: string; // Complete standard error
outputs: { // JSON parsed from last line of stdout
[key: string]: any;
};
}Script Writing Specification
Input: Command-line Parameters
# Python: argparse
--input-path /path/to/file --threshold 0.9
# Bash: manual parsing
--input-path /path/to/fileOutput: Standard Output JSON
Script must print single-line JSON on last line:
{"output_file": "/tmp/result.json", "count": 42}Python Template
import argparse
import json
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--input-path', required=True)
parser.add_argument('--threshold', type=float, default=0.9)
args = parser.parse_args()
# Execution logic...
result_path = "/tmp/result.json"
# Output JSON
print(json.dumps({
"output_file": result_path,
"items_processed": 100
}))
if __name__ == '__main__':
main()Bash Template
#!/bin/bash
# Parse parameters
while [[ "$#" -gt 0 ]]; do
case $1 in
--input-path) INPUT_PATH="$2"; shift ;;
*) echo "Unknown: $1" >&2; exit 1 ;;
esac
shift
done
# Execution logic...
LOG_FILE="/tmp/process.log"
echo "Processing $INPUT_PATH" > "$LOG_FILE"
# Output JSON
echo "{\"log_file\": \"$LOG_FILE\", \"status\": \"done\"}"ExecuteScript Implementation
async function ExecuteScript(scriptId, inputs = {}) {
const skillDir = GetSkillDir();
// Find script file
const extensions = ['.py', '.sh', '.js'];
let scriptPath, runtime;
for (const ext of extensions) {
const path = `${skillDir}/scripts/${scriptId}${ext}`;
if (FileExists(path)) {
scriptPath = path;
runtime = ext === '.py' ? 'python' : ext === '.sh' ? 'bash' : 'node';
break;
}
}
if (!scriptPath) {
throw new Error(`Script not found: ${scriptId}`);
}
// Build command-line parameters
const args = Object.entries(inputs)
.map(([k, v]) => `--${k.replace(/_/g, '-')} "${v}"`)
.join(' ');
// Execute script
const cmd = `${runtime} "${scriptPath}" ${args}`;
const { stdout, stderr, exitCode } = await Bash(cmd);
// Parse output
let outputs = {};
try {
const lastLine = stdout.trim().split('\n').pop();
outputs = JSON.parse(lastLine);
} catch (e) {
// Unable to parse JSON, keep empty object
}
return {
success: exitCode === 0,
stdout,
stderr,
outputs
};
}Use Cases
Suitable for Scripting
- Data processing and transformation
- File format conversion
- Batch file operations
- Complex calculation logic
- Call external tools/libraries
Not Suitable for Scripting
- Tasks requiring user interaction
- Tasks needing access to Claude tools
- Simple file read/write
- Tasks requiring dynamic decision-making
Path Conventions
Script Path
Script paths are relative to the directory containing SKILL.md (skill root directory):
.claude/skills/<skill-name>/ # Skill root directory (SKILL.md location)
├── SKILL.md
├── scripts/ # Scripts directory
│ └── process-data.py # Relative path: scripts/process-data.py
└── phases/ExecuteScript automatically finds scripts from skill root directory:
// Actually executes: python .claude/skills/<skill-name>/scripts/process-data.py
await ExecuteScript('process-data', { ... });Output Directory
Recommended: Pass output directory from caller, not hardcode in script to /tmp:
// Specify output directory when calling (in workflow working directory)
const result = await ExecuteScript('process-data', {
input_path: `${workDir}/data.json`,
output_dir: `${workDir}/output` // Explicitly specify output location
});Scripts should accept --output-dir parameter instead of hardcoding output paths.
Best Practices
1. Single Responsibility: Each script does one thing 2. No Side Effects: Scripts should not modify global state 3. Idempotence: Same input produces same output 4. Clear Errors: Error messages to stderr, normal output to stdout 5. Fail Fast: Exit immediately on parameter validation failure 6. Parameterized Paths: Output paths specified by caller, not hardcoded