---
name: skill-generator
description: Auto-generate reusable Artifex skills from completed workflow traces or manual specifications. Use this skill when the user wants to extract a repeatable workflow into a skill, detect patterns in implementation traces, generate skill scaffolding, or create a blank skill template.
---

# Skill Generator

**For Claude Code AI Assistant**

This skill analyzes implementation traces to detect repeatable patterns and generates complete, installable Artifex skills. It is the meta-skill: a skill that creates other skills.

## Modes

Parse the user's `/afx-skill-gen` command to determine the mode and arguments, then follow the corresponding section below.

---

## Mode 1: Detect (`/afx-skill-gen detect <ticket_id>`)

Analyze a completed ticket trace to identify whether it contains a repeatable workflow pattern worth extracting as a skill.

### Steps

1. **Read the trace file:**
   ```bash
   cat .artifex/traces/<ticket_id>.json
   ```
   If the file does not exist, inform the user and suggest running `/afx-trace list` to see available traces.

2. **Parse the trace entries.** For each entry, extract:
   - `event_type` (file_read, file_write, file_edit, decision, test_run, correction, error, review_comment)
   - `phase` (pre-implementation, implementation, post-implementation, finalization)
   - `details` (file paths, commands, rationale)

3. **Identify the workflow pattern.** Look for:
   - **Sequence:** The ordered list of actions taken (read X, transform, write Y, validate)
   - **File types involved:** What kinds of files were read and produced?
   - **Transformations:** What changed between input and output files?
   - **Validation steps:** Were tests run? What assertions were checked?
   - **Decision points:** What choices were made, and are they parameterizable?

4. **Assess extractability.** A pattern is worth extracting if it meets ALL of these criteria:
   - **Non-trivial:** More than 5 meaningful steps (exclude simple file reads for context)
   - **Repeatable:** The steps follow a logical sequence that would apply to similar inputs
   - **Parameterizable:** Specific file paths, ticket IDs, and names can be replaced with variables
   - **Self-contained:** The pattern does not depend heavily on unique project context

5. **Present the findings.** Report to the user:

   ```
   Pattern Detection: Ticket <ticket_id>

   Detected Pattern: <one-line description>

   Steps identified:
     1. <step description>
     2. <step description>
     ...

   Input:  <what the pattern reads/consumes>
   Output: <what the pattern produces>

   Extractability Assessment:
     Steps:          <count> (threshold: >5)
     Repeatable:     Yes/No - <reason>
     Parameterizable: Yes/No - <reason>
     Self-contained: Yes/No - <reason>

   Recommendation: <EXTRACT / SKIP>
   Reason: <explanation>

   To generate this skill:
     /afx-skill-gen create <suggested-name> from-ticket <ticket_id>
   ```

---

## Mode 2: Create (`/afx-skill-gen create <name> [from-ticket <ticket_id>]`)

Generate a complete Artifex skill with all required files.

### Branch A: From a Ticket Trace

If `from-ticket <ticket_id>` is provided:

1. **Read the trace** (same as Detect mode step 1).

2. **Extract the pattern** (same as Detect mode steps 2-3).

3. **Parameterize the pattern.** Replace specifics with variables:
   - Specific file paths become `<input_file>`, `<output_file>`, or descriptive placeholders
   - Ticket IDs become `<ticket_id>`
   - Project-specific names become `<project_name>` or `<component_name>`
   - Specific values in decisions become documented choices with defaults

4. **Generate skill files.** Create the following files:

   **a) `skills/<name>/skill.yaml`**
   ```yaml
   name: <name>
   description: <derived from pattern analysis>
   version: 1.0.0
   category: <inferred from pattern type>
   author: Artifex

   provides:
     - <capability_1>
     - <capability_2>

   commands:
     - name: <primary_command>
       description: <what it does>
       usage: "<how to invoke>"

   # Model routing convention (Phase 14): classify the skill's primary work and
   # pick a default. Always include this block; pick by these rules:
   #   - Extraction / retrieval / data shaping / mechanical transforms → claude-haiku-4-5
   #   - Synthesis / code review / architecture / domain reasoning      → claude-sonnet-4-6
   #   - High-stakes specialist work (legal, security, multi-doc reasoning) → claude-opus-4-7
   # The fallback should be one tier more capable than the default.
   model_preference:
     default: <classified-model>
     fallback: <one-tier-up>
     rationale: <one-line reason — e.g., "mostly extraction; speed and cost matter">

   dependencies:
     - <any tools the pattern used>
   ```

   **b) `skills/<name>/SKILL.md`**

   Structure the SKILL.md with:
   - YAML frontmatter with `name` and `description` (for skill discovery)
   - Title and purpose section
   - "When to Use" section listing trigger conditions
   - Step-by-step instructions extracted from the trace pattern, written as Claude Code directives
   - Input/output specifications
   - Example invocations
   - Error handling guidance
   - Related commands/skills

   The instructions must be written as directives to Claude Code (e.g., "Read the file at...", "Generate a file containing...", "Run the following command..."). They should NOT be descriptions of what happened -- they must be reusable instructions.

   **c) `skills/<name>/USAGE.md`**

   Structure the USAGE.md with:
   - Brief description of what the skill does
   - "How to Use It" section with common actions
   - "What It Does" section explaining the workflow
   - "Typical Workflow" numbered list
   - Tips and troubleshooting

   **d) Optional: `skills/<name>/<name>.sh`**

   Generate a shell script ONLY if the trace shows mechanical operations that benefit from scripting:
   - File system operations (mkdir, cp, mv)
   - Repeated command invocations with different arguments
   - JSON/YAML manipulation with jq/yq
   - Validation checks that can be automated

   The script must:
   - Start with `#!/bin/bash` and `set -euo pipefail`
   - Accept subcommands as the first argument
   - Include a `usage()` function
   - Use functions for each subcommand
   - Exit with non-zero status on errors

5. **Verify the output.** After generating files:
   - Confirm all required files exist: `skill.yaml`, `SKILL.md`, `USAGE.md`
   - Check that the SKILL.md contains actionable directives, not just descriptions
   - Ensure the skill.yaml `commands` section matches the SKILL.md sections
   - Report what was created:
     ```
     Skill generated: <name>

     Files created:
       skills/<name>/skill.yaml   - Metadata
       skills/<name>/SKILL.md     - Skill definition
       skills/<name>/USAGE.md     - Usage documentation
       [skills/<name>/<name>.sh   - Shell script (if generated)]

     Next steps:
       1. Review the generated files and adjust as needed
       2. Run the installer to register: ./install.sh --mode=full
       3. Test with: /afx-skill-gen template shows a blank version for comparison
     ```

### Branch B: Manual Creation (no from-ticket)

If no `from-ticket` argument is provided, interview the user:

1. **Gather information.** Ask the user these questions one at a time (do not dump all questions at once):
   - "What does this skill do? Describe the workflow in a sentence or two."
   - "What triggers this skill? When should someone use it?"
   - "Walk me through the steps. What happens first, then next, etc.?"
   - "What inputs does it need? (files, arguments, configuration)"
   - "What does it produce? (files, output, side effects)"
   - "Does it need any external tools? (jq, sqlite3, curl, etc.)"
   - "What category fits best? (project_management, quality_improvement, observability, code_generation, documentation, meta)"

2. **Synthesize and confirm.** Present a summary of the skill design and ask for confirmation before generating files.

3. **Generate files.** Follow the same file generation process as Branch A, step 4.

4. **Verify and report.** Follow the same verification as Branch A, step 5.

---

## Mode 3: Suggest (`/afx-skill-gen suggest`)

Scan all traces to find patterns that repeat across multiple tickets, then suggest skill extractions.

### Steps

1. **List available traces:**
   ```bash
   ls .artifex/traces/*.json 2>/dev/null
   ```
   If no traces exist, inform the user:
   ```
   No traces found in .artifex/traces/. Complete some ticket implementations
   with tracing enabled (/afx-trace start <id>) to use pattern suggestion.
   ```

2. **Read all trace files.** For each trace JSON, extract the sequence of event types and the associated file patterns.

3. **Build pattern fingerprints.** For each trace, create a fingerprint:
   - Ordered list of event_type values
   - File extensions involved (e.g., .ts, .yaml, .md)
   - Phases used and their relative duration
   - Decision categories (from decision event details)

4. **Find recurring patterns.** Compare fingerprints across traces:
   - **Exact matches:** Two or more traces with the same event_type sequence
   - **Fuzzy matches:** Traces with >70% overlap in event_type sequence (same steps in mostly the same order, with minor variations)
   - **Structural matches:** Traces that read the same types of files and produce the same types of outputs, even if specific steps differ

5. **Rank patterns.** Score each recurring pattern by:
   - **Frequency:** How many traces contain this pattern (higher = better)
   - **Complexity:** Number of steps in the pattern (more complex = more value in extraction)
   - **Distinctiveness:** How different is this from existing skills? (more distinct = more valuable)

6. **Present the top 3 suggestions:**

   ```
   Skill Extraction Suggestions
   (Based on <N> traces analyzed)

   1. <Suggested Skill Name> (found in <count> traces)
      Pattern: <description>
      Steps: <count>
      Source tickets: <ticket_id_1>, <ticket_id_2>, ...
      Confidence: High/Medium/Low

      To extract: /afx-skill-gen create <name> from-ticket <best_ticket_id>

   2. <Suggested Skill Name> (found in <count> traces)
      ...

   3. <Suggested Skill Name> (found in <count> traces)
      ...

   No further patterns met the extraction threshold
   (minimum: 2 occurrences, 5+ steps).
   ```

   If fewer than 3 patterns are found, report only those found. If none are found, say so and explain why (e.g., "Only 2 traces available, need more implementation history").

---

## Mode 4: Template (`/afx-skill-gen template <name>`)

Generate a blank skill template that can be filled in manually.

### Steps

1. **Create the skill directory:**
   ```bash
   mkdir -p skills/<name>
   ```

2. **Generate `skills/<name>/skill.yaml`:**
   ```yaml
   name: <name>
   description: TODO - Describe what this skill does
   version: 1.0.0
   category: TODO - One of: project_management, quality_improvement, observability, code_generation, documentation, meta
   author: Artifex

   provides:
     - TODO_capability_1
     - TODO_capability_2

   commands:
     - name: TODO_command
       description: TODO - What this command does
       usage: "TODO - How to invoke"

   # Optional but recommended (Phase 14 convention): declare the optimal model.
   # Drop this block if the skill is pure-bash with no LLM calls.
   model_preference:
     default: claude-haiku-4-5    # TODO - haiku for mechanical, sonnet for synthesis, opus for high-stakes
     fallback: claude-sonnet-4-6
     rationale: TODO - one-line reason

   dependencies: []
   ```

3. **Generate `skills/<name>/SKILL.md`:**
   ```markdown
   ---
   name: <name>
   description: TODO - Describe what this skill does. Include trigger conditions so Claude Code knows when to activate this skill.
   ---

   # <Name> Skill

   **For Claude Code AI Assistant**

   TODO - Describe the purpose of this skill.

   ## When to Use

   Use this skill when:
   - TODO - Trigger condition 1
   - TODO - Trigger condition 2

   ## Instructions

   ### Step 1: TODO

   TODO - First action Claude should take.

   ### Step 2: TODO

   TODO - Next action.

   ## Input

   - TODO - What this skill needs as input

   ## Output

   - TODO - What this skill produces

   ## Error Handling

   - TODO - What to do when things go wrong

   ## Related Skills

   - TODO - Related skills or commands
   ```

4. **Generate `skills/<name>/USAGE.md`:**
   ```markdown
   # <Name> - Usage Guide

   TODO - Brief description of the skill.

   ## How to Use It

   **TODO - Primary action:**
   ```
   /TODO-command argument
   ```

   ## What It Does

   TODO - Explain the workflow.

   ## Typical Workflow

   1. TODO - First step
   2. TODO - Second step
   3. TODO - Third step

   ## Tips

   - TODO - Helpful tip 1
   - TODO - Helpful tip 2

   ## Troubleshooting

   ### TODO - Common issue

   TODO - Resolution.
   ```

5. **Report what was created:**
   ```
   Skill template generated: <name>

   Files created:
     skills/<name>/skill.yaml   - Metadata (fill in TODOs)
     skills/<name>/SKILL.md     - Skill definition (fill in TODOs)
     skills/<name>/USAGE.md     - Usage documentation (fill in TODOs)

   Next steps:
     1. Fill in all TODO placeholders in the generated files
     2. Optionally add a <name>.sh script for mechanical operations
     3. Run the installer to register: ./install.sh --mode=full
   ```

---

## Skill File Conventions

When generating skills, follow these Artifex conventions:

### skill.yaml
- `name`: lowercase, hyphenated (e.g., `my-skill`)
- `version`: semver starting at `1.0.0`
- `category`: one of `project_management`, `quality_improvement`, `observability`, `code_generation`, `documentation`, `meta`
- `provides`: list of snake_case capability identifiers
- `commands`: each has `name`, `description`, `usage`
- `dependencies`: list of required CLI tools

### SKILL.md
- YAML frontmatter with `name` and `description`
- Description must include trigger conditions for skill discovery
- Written as directives to Claude Code (imperative mood)
- Sections for each command/mode with numbered steps
- Shell commands use `~/.claude/skills/<name>/` prefix for script invocations
- Include example output formats where applicable

### USAGE.md
- Title format: `# <Name> - Usage Guide`
- Sections: How to Use It, What It Does, Typical Workflow, Tips, Troubleshooting
- Show slash command examples, not script invocations
- Keep it conversational and user-focused

### Shell Scripts (optional)
- `#!/bin/bash` with `set -euo pipefail`
- Subcommand routing via `case` on `$1`
- `usage()` function for help
- Functions for each subcommand
- Non-zero exit on errors
- Quote all variables

---

## Parameterization Rules

When converting a specific trace into a reusable pattern:

| Specific Value | Replacement | Example |
|---|---|---|
| File paths | `<input_file>`, `<output_dir>` | `src/api.ts` -> `<source_file>` |
| Ticket IDs | `<ticket_id>` | `2.3` -> `<ticket_id>` |
| Project names | `<project_name>` | `my-app` -> `<project_name>` |
| Branch names | `<branch_name>` | `feat/auth` -> `<branch_name>` |
| URLs | `<url>` | `https://api.example.com` -> `<api_url>` |
| Specific counts/sizes | documented defaults | `120 lines` -> configurable with default |
| Tool-specific flags | preserved as-is | `--strict` stays `--strict` |

---

## Quality Checks

Before presenting a generated skill, verify:

1. **Completeness:** All three required files exist (skill.yaml, SKILL.md, USAGE.md)
2. **Consistency:** Commands in skill.yaml match sections in SKILL.md
3. **Actionability:** SKILL.md contains directives, not descriptions
4. **Parameterization:** No hardcoded ticket IDs, file paths, or project names remain
5. **Convention compliance:** File formats match the conventions documented above
