# Skill Chain Generator

> Skill Chain Generator

- Skill: `napoler/skill-chain-generator` (Agent Skill, multi-file: 16 files)
- Install (CLI): `npx skillmds@latest add napoler/skill-chain-generator`
- Raw SKILL.md: https://api.skillmd.com/api/skills/napoler/skill-chain-generator/raw
- Safety review: pending
- Works with: Claude Code, Claude.ai, OpenAI Codex
- Category: Coding & Dev Tools
- Author: napoler (https://skillmd.com/u/napoler)
- Updated: 2026-09-17
- Page: https://skillmd.com/skills/napoler/skill-chain-generator

---

# Skill Chain Generator

Create declarative multi-skill workflows using YAML definitions. Automatically generates production-ready SKILL.md files with state machines, routing logic, and best practices inspired by /comet and /plan.

## Core Concept

**What is a Skill Chain?**
A skill chain is a coordinated multi-skill workflow where one master skill routes through multiple sub-skills based on state, user decisions, and workflow progress. Examples: `/comet` (open → design → build → verify → archive), `/plan` (planning with files pattern).

**Why Declarative?**
Instead of manually writing hundreds of lines of routing/state logic, define your chain in YAML and let this generator produce the complete SKILL.md template.

**Comet Compatibility:**
This generator supports full Comet-style chains: `.comet.yaml` state fields (phase/build_mode/tdd_mode/review_mode/verify_mode/isolation/verify_failures), preset escalation (hotfix→tweak→full), Node Contracts (Skill Binding / Required Skill Call / Output Schema / Guardrail / Handoff), subagent dispatch contract (DONE/DONE_WITH_CONCERNS/BLOCKED/NEEDS_CONTEXT), and workflow kind distinction (`comet-five-phase-overlay` vs `workflow-kernel`).

---

## Comet Compatibility Mode

When generating chains for Comet-style workflows, use these extended fields:

### Extended State Fields
```yaml
states:
  - id: build
    name: "实施构建"
    skill: "openspec-apply-change"
    model: opus                    # Per-state model override
    build_mode: subagent-driven-development  # subagent-driven-development | executing-plans | direct
    tdd_mode: tdd                  # tdd | direct
    review_mode: standard          # off | standard | thorough
    isolation: branch              # current | branch | worktree
```

### Preset Escalation
```yaml
preset_escalation:
  - from: hotfix
    to: full
    signal: "scope_expansion_detected"
  - from: tweak
    to: full
    signal: "complexity_exceeds_tweak"
```

### Node Contract
```yaml
nodes:
  execute:
    required_skill_calls:
      - skill: "openspec-apply-change"
        reason: "Implement tasks from change"
    output_schema:
      - "tests pass"
      - "commits made"
    guardrail: "block if tests fail"
    handoff: "implemented_files + test_results"
```

### Subagent Dispatch Contract
Generated skills must define agent return states: `DONE | DONE_WITH_CONCERNS | BLOCKED | NEEDS_CONTEXT`. Risk signals (cross-module changes, auth, concurrency, schema migration, public API) must be checked and reported by implementer agents.

### Workflow Kind
```yaml
chain:
  kind: comet-five-phase-overlay  # preserves .comet.yaml state | workflow-kernel for custom
```

---

## Quick Start

### 1. Discover Existing Skills (Avoid Reinventing)

Before defining your chain, **check what's already available**:

```bash
# Query installed skills
bash ~/.claude/skills/skill-chain-generator/scripts/discover.js --local

# Search for mature solutions online (optional)
bash ~/.claude/skills/skill-chain-generator/scripts/discover.js --web "workflow automation skill chain"
```

The discover script will:
- List all installed skills with their descriptions
- Match your needed functionality (e.g., "brainstorming", "code-review")
- Suggest reuse instead of creating new skills
- Provide installation commands for missing skills

**Best Practice**: Always discover first → reuse existing → only create new when necessary.

### 2. Define Your Chain

Create a `chain.yaml`:

```yaml
chain:
  name: "feature-workflow"
  description: "Add new feature workflow"
  model: "z.ai/glm-5.2"
  
  states:
    - id: explore
      name: "探索需求"
      skill: "research-assistant"  # ← Use discovered skill name
      next: design
      
    - id: design
      name: "设计方案"
      skill: "superpowers:brainstorming"
      next: build
      decision_point:
        question: "设计方案是否可行？"
        options: ["继续", "重新设计"]
        
    - id: build
      name: "实施构建"
      skill: "superpowers:writing-plans"
      next: verify
      
    - id: verify
      name: "验证测试"
      skill: "code-reviewer"
      next: [archive, build]  # 条件分支
      conditions:
        - if: "review_result == 'pass'"
          then: archive
        - if: "review_result == 'fail'"
          then: build
          
    - id: archive
      name: "归档"
      skill: "comet-archive"
      end: true
```

**Tip**: Use skill names from `discover.js` output. Format: `skill-name` or `group:skill`.

### 3. Generate SKILL.md (with Reuse Analysis)

```bash
bash ~/.claude/skills/skill-chain-generator/scripts/generate.js chain.yaml --check-reuse
```

The `--check-reuse` flag will:
- Verify each referenced skill exists locally
- Suggest alternatives if a skill is missing
- Generate a **reuse report** (`reuse_report.json`) showing:
  - `installed_skills`: Already available
  - `missing_skills`: Need to create or find
  - `suggested_alternatives`: Closest matches from local skills
  - `reuse_rate`: Percentage of skills you can reuse

### 4. Find Missing Skills Online (Optional)

If you have missing skills, use `--online-search` to get search suggestions:

```bash
bash ~/.claude/skills/skill-chain-generator/scripts/generate.js chain.yaml --check-reuse --online-search
```

This will print commands like:
```
/skill-find "brainstorming agent skill github"
```

Run those commands to search GitHub for public skills. Install any that match your needs.

### 5. Create Only What's Missing

Use `/skill-creator` **only for skills that cannot be found online**.
For skills with good online candidates, review, install, and adapt instead of building from scratch.

---

## Tool Reference

### discover.js

Skill discovery utility.

```bash
# List all locally installed skills
bash ~/.claude/skills/skill-chain-generator/scripts/discover.js --local

# Output as JSON (for scripts)
bash ~/.claude/skills/skill-chain-generator/scripts/discover.js --local --format json
```

### generate.js

Chain generation utility.

```bash
# Basic generation
bash generate.js chain.yaml [output-dir]

# With reuse check
bash generate.js chain.yaml . --check-reuse

# With online search suggestions
bash generate.js chain.yaml . --check-reuse --online-search
```

---

## YAML Schema Reference

### Top-Level Fields

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `chain.name` | string | ✅ | Skill chain identifier (kebab-case) |
| `chain.description` | string | ✅ | Frontmatter description |
| `chain.model` | string | ❌ | Default model (inherit if omitted) |
| `chain.states` | array | ✅ | State definitions |
| `chain.preset_detection` | array | ❌ | Preset routing logic |
| `chain.decision_points` | array | ❌ | Global decision points |
| `chain.reuse_check` | bool | ❌ | Enable skill existence check (default: true) |
| `chain.kind` | string | ❌ | `comet-five-phase-overlay` (preserves .comet.yaml) or `workflow-kernel` (custom) |

### State Definition

```yaml
states:
  - id: open                # Unique state ID
    name: "开启"            # Human-readable name
    skill: "comet-open"     # Skill to invoke (format: "skill-name" or "group:skill")
    next: design            # Next state ID (single)
    # OR conditional branching:
    next:                  # Conditional next states
      - condition: "verify_result == 'pass'"
        state: archive
      - condition: "verify_result == 'fail'"
        state: build
    decision_point:         # Optional user decision at this state
      question: "继续吗？"
      options: ["是", "否"]
    end: false             # Mark as terminal state (default: false)
    model: opus            # Per-state model override (optional)
    build_mode: subagent-driven-development  # subagent-driven-development | executing-plans | direct
    tdd_mode: tdd          # tdd | direct
    review_mode: standard  # off | standard | thorough
    isolation: branch      # current | branch | worktree
```

### Preset Detection

```yaml
preset_detection:
  - if: "user_intent == 'hotfix' && file_count < 3"
    then: "hotfix-chain"      # Use a different chain variant
  - if: "user_intent == 'tweak' && file_count < 5"
    then: "tweak-chain"
```

Presets allow you to define shortcut workflows (like comet-hotfix / comet-tweak).

### Preset Escalation

Define conditions where a preset should upgrade to a more comprehensive workflow:

```yaml
preset_escalation:
  - from: hotfix
    to: full
    signal: scope_expansion_detected
    condition: "file_count > 3 || cross_module_change"
  - from: tweak
    to: full
    signal: complexity_exceeds_tweak
    condition: "design_doc_required || schema_change"
```

Use `comet state transition <name> preset-escalate` to execute escalation after user confirmation.

### Decision Points

Two ways to define decisions:

**1. Inline (per-state)**:
```yaml
- id: design
  decision_point:
    question: "设计方案是否满意？"
    options: ["满意，继续", "需要修改"]
```

**2. Global**:
```yaml
decision_points:
  - at: verify
    question: "验证结果如何？"
    options: ["通过", "失败"]
```

### Skill Reuse & Discovery

Set `chain.reuse_check: true` (default) to enable automatic skill discovery:

```yaml
chain:
  name: "my-workflow"
  reuse_check: true  # Check for existing skills before generating
```

The generator will:
1. Query local skill registry (`~/.claude/skills/*/SKILL.md`)
2. For missing skills, search known marketplaces
3. Generate a **reuse report** with install suggestions
4. Flag skills that need to be created from scratch

---

## Generated SKILL.md Structure

The generator produces a complete SKILL.md following the Comet pattern:

```markdown
---
name: <chain.name>
model: <chain.model>
description: <chain.description>
---

# <chain.name>

## 决策核心

### 状态管理
- State file: `<workflow>/<change>/.<chain>.yaml`
- Comet fields: phase, build_mode, tdd_mode, review_mode, isolation, verify_mode, verify_failures, verify_result, workflow, language, base_ref, design_doc, plan

### 阶段自动检测
<generated routing logic>

### 预设检测 (Optional)
<generated preset detection>
- `comet state transition <name> preset-escalate` for preset upgrades

### 决策点 (Optional)
<generated decision point handlers>

### 子代理派发契约
Implementer agent return states: `DONE | DONE_WITH_CONCERNS | BLOCKED | NEEDS_CONTEXT`
Risk signals: cross-module, auth, concurrency, schema migration, public API change

### 节点合约 (Node Contract)
Each node declares: Skill Binding, Required Skill Call, Output Schema, Guardrail, Handoff

### 错误处理速查
<generated error handling table>

### 阶段衔接
<generated transition rules>
- Exit gate: must pass 36+2 quality standards before transition

## 子命令速查
| 阶段 | 技能 | 说明 |
|------|------|------|

## 参考附录
- 文件结构
- 最佳实践
- 验证与归档

---

## Scripts

Auto-generated helper scripts:
- `scripts/<chain>-state.js` - State transitions
- `scripts/<chain>-guard.js` - Phase verification
- `scripts/<chain>-handoff.js` - Context handoff
```

---

## Advanced Patterns

### Conditional Branching

Use `conditions` for multi-way transitions:

```yaml
- id: verify
  conditions:
    - if: "tests_pass && lint_clean"
      then: archive
    - if: "tests_pass && !lint_clean"
      then: fix-lint
    - if: "!tests_pass"
      then: debug
```

### Preset Variants

Define multiple chain variants for different scenarios:

```yaml
chain:
  name: "deploy-workflow"
  # ... states (full workflow)
  
presets:
  hotfix:
    skip_states: [design]
    conditions: "file_count < 3 && bug_fix"
  emergency:
    skip_states: [design, verify]
    conditions: "production_down"
```

### Model Selection per State

Override model for specific states:

```yaml
states:
  - id: brainstorm
    skill: "superpowers:brainstorming"
    model: "z.ai/glm-5.2"  # Force advanced model for design
    next: plan
```

---

## Examples

See `examples/` directory for complete working templates:

- `simple-linear.yaml` - Basic 5-state linear workflow
- `comet-lite.yaml` - Simplified Comet pattern
- `preset-workflow.yaml` - With hotfix/tweak variants
- `conditional-workflow.yaml` - Complex branching logic

---

## Best Practices

1. **Keep chains focused** - 5-7 states maximum per chain
2. **Use descriptive state IDs** - `design-doc-approved` not just `design`
3. **Mark terminal states** - Set `end: true` for archive/completion
4. **Document decision points** - Explain why users need to decide
5. **Include error handling** - Define what happens on failure
6. **Test each path** - Ensure all conditional branches reachable
7. **Leverage presets** - Define hotfix/tweak variants for speed
8. **Inherit model** - Set model at chain level, avoid per-state overrides

---

## Integration with Other Skills

**Skill-creator**: Create individual sub-skills first, then reference them in your chain.

**Plan**: Use `/plan` to design the chain structure before writing YAML.

**Comet**: Analyze existing `/comet` chains by reading its SKILL.md and templates.

**Skill-fix**: If a chain skill has defects (missing state fields, incorrect routing, preset misconfiguration), call `/skill-fix` to diagnose and repair.

---

## Troubleshooting

| Issue | Solution |
|-------|----------|
| "Skill not found" error | Check skill name format: use "skill-name" or "group:skill" |
| Circular dependency | Ensure no state loops back to itself without exit |
| Missing decision point | Decision points require `AskUserQuestion` in generated code |
| Preset not triggering | Check condition syntax - must be valid Python expression |

---

## Implementation Details

**Frontmatter**:
- `name`: from `chain.name`
- `model`: from `chain.model` (or omit to use default)
- `description`: from `chain.description`

**Code Generation**:
- Uses Jinja2 templates in `templates/`
- Main template: `skill.md.j2`
- Helper templates: `state-router.j2`, `decision-points.j2`, `guard.j2`

**Validation**:
- YAML syntax check
- State ID uniqueness
- Skill existence verification (optional)
- Circular dependency detection

---

## Future Enhancements

- [ ] Visual chain editor (web UI)
- [ ] JSON Schema validation for YAML
- [ ] Automatic dependency graph generation
- [ ] Cost estimation based on skill invocations
- [ ] Multi-chain composition (chain-of-chains)
- [ ] Export to PlantUML / Graphviz

---

**Inspired by**: Comet (OpenSpec + Superpowers), Plan (Manus pattern)  
**Pattern**: State Machine + Skill Routing  
**Target**: Complex, multi-phase, collaborative development workflows

