> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/thiagofinch/mega-brain/llms.txt
> Use this file to discover all available pages before exploring further.

# Skills Routing

> Understand Mega Brain's intelligent skill system with keyword-based auto-routing and dynamic skill activation.

# Skills Routing

Mega Brain's skills system provides **automatic skill activation** based on keyword detection in user prompts. Skills are modular instruction sets that enhance Claude's capabilities for specific tasks.

## Overview

The skills routing system consists of three components:

```
┌─────────────────────────────────────────────────────────────────────────────┐
│  SKILL DETECTION PIPELINE                                                    │
│                                                                              │
│  1. SCAN      → List folders in .claude/skills/                             │
│  2. DETECT    → For each folder, check if SKILL.md exists                   │
│  3. EXTRACT   → Read header: Auto-Trigger, Keywords, Priority               │
│  4. INDEX     → Build keyword map in SKILL-INDEX.json                       │
│  5. MATCH     → Compare user input with triggers                            │
└─────────────────────────────────────────────────────────────────────────────┘
```

## Architecture

### Directory Structure

<CodeGroup>
  ```bash Project Skills theme={null}
  .claude/skills/
  ├── _TEMPLATES/              # Templates (ignored)
  ├── 00-SKILL-CREATOR/        # Core: Skill creation
  │   └── SKILL.md
  ├── 01-SKILL-DOCS-MEGABRAIN/ # Core: Documentation
  │   └── SKILL.md
  ├── 03-SKILL-AGENT-CREATION/ # Core: Agent creation
  │   └── SKILL.md
  └── agent-creation/          # Domain: Create agents
      └── SKILL.md
  ```

  ```json Skill Index (Generated) theme={null}
  [
    "version": "2.0.0",
    "skills_count": 12,
    "subagents_count": 0,
    "total_count": 12,
    "skills": [
      "00-SKILL-CREATOR": [
        "name": "00-SKILL-CREATOR",
        "type": "skill",
        "auto_trigger": "When user wants to create new skill",
        "keywords": ["criar skill", "nova skill", "skill"],
        "priority": "ALTA"
      ]
    ],
    "keyword_map": [
      "skill": [
        [
          "name": "00-SKILL-CREATOR",
          "type": "skill",
          "priority": "ALTA"
        ]
      ]
    ]
  ]
  ```
</CodeGroup>

### Skill Lifecycle

<Steps>
  <Step title="SessionStart: Index Skills">
    `skill_indexer.py` hook scans `.claude/skills/` and generates `SKILL-INDEX.json`:

    ```python theme={null}
    def scan_skills() -> List[Path]:
        skills = []
        for item in SKILLS_PATH.iterdir():
            if item.is_dir() and not item.name.startswith('_'):
                skill_md = item / "SKILL.md"
                if skill_md.exists():
                    skills.append(item)
        return skills
    ```
  </Step>

  <Step title="Extract Metadata">
    For each SKILL.md, extract header metadata:

    ```markdown theme={null}
    > **Auto-Trigger:** When user mentions creating agents
    > **Keywords:** agent, criar agente, novo agent
    > **Prioridade:** ALTA
    ```
  </Step>

  <Step title="UserPromptSubmit: Match Keywords">
    `skill_router.py` compares user prompt against keyword map:

    ```python theme={null}
    prompt_lower = prompt.lower()
    for keyword, skill_list in keyword_map.items():
        if keyword in prompt_lower:
            matches.append(skill_list[0])
    ```
  </Step>

  <Step title="Inject Context">
    If match found, inject skill instructions into context:

    ```json theme={null}
    [
      "continue": true,
      "feedback": "[SKILL AUTO-ACTIVATED: agent-creation]\nKeyword: 'agent'\n\n=== INSTRUCTIONS ===\n..."
    ]
    ```
  </Step>
</Steps>

## SKILL.md Format

Every skill must have a `SKILL.md` file with this structure:

<CodeGroup>
  ````markdown Minimal SKILL.md theme={null}
  # SKILL-NAME
  ## Brief description

  > **Auto-Trigger:** When this skill should activate
  > **Keywords:** keyword1, keyword2, keyword3
  > **Prioridade:** ALTA | MÉDIA | BAIXA

  ---

  ## INSTRUCTIONS

  1. Step-by-step instructions for Claude
  2. What to do when skill is activated
  3. Expected outputs and validation

  ## EXAMPLES

  ```bash
  Example commands or code
  ````

  ## RULES

  * Rule 1: Never do X
  * Rule 2: Always do Y

  ````

  ```markdown Full Example
  # SKILL-AGENT-CREATION
  ## Create new AI agents with DNA profiles

  > **Auto-Trigger:** When user wants to create a new agent
  > **Keywords:** criar agente, novo agent, agent creation, agent
  > **Prioridade:** ALTA

  ---

  ## DETECTION

  This skill activates when:
  - User mentions "criar agente" or "create agent"
  - User asks to generate a new AI agent
  - User references agent templates

  ## INSTRUCTIONS

  1. Ask user for agent details:
     - Agent name (e.g., "AGENT-CFO")
     - Role/purpose (e.g., "Chief Financial Officer")
     - Category (e.g., "Finance", "Sales", "Operations")

  2. Use template from `agents/_templates/TEMPLATE-AGENT-MD-ULTRA-ROBUSTO-V3.md`

  3. Create agent structure:
  ````

  agents/cargo/AGENT-NAME/
  ├── AGENT.md      # Main instructions
  ├── SOUL.md       # Personality (optional)
  ├── MEMORY.md     # Knowledge base (optional)
  └── DNA-CONFIG.yaml  # DNA weights

  ```

  4. Populate sections:
  - WHO I AM (Quem Sou)
  - MY FORMATION (Minha Formação)
  - HOW I SPEAK (Como Falo)
  - WHAT I KNOW (O Que Sei)

  5. Update `AGENT-INDEX.yaml` with new agent

  ## VALIDATION

  - [ ] AGENT.md exists and has all required sections
  - [ ] Agent name follows convention (AGENT-[NAME])
  - [ ] Category is valid (Sales, Finance, Ops, etc.)
  - [ ] AGENT-INDEX.yaml updated

  ## OUTPUTS

  - `agents/cargo/[AGENT-NAME]/AGENT.md`
  - `agents/cargo/[AGENT-NAME]/SOUL.md` (if personality defined)
  - Updated `AGENT-INDEX.yaml`
  ```
</CodeGroup>

<Note>
  The header metadata (Auto-Trigger, Keywords, Prioridade) is **required** for auto-detection.
</Note>

## Keyword Matching

### Matching Algorithm

```python theme={null}
def match_prompt(prompt: str, index: Dict) -> List[Dict]:
    """
    Matches keywords from prompt against skill index.
    Returns sorted list by priority (ALTA > MÉDIA > BAIXA).
    """
    prompt_lower = prompt.lower()
    matches = []
    seen_skills = set()
    
    priority_order = ["ALTA": 0, "MÉDIA": 1, "BAIXA": 2]
    
    for keyword, skill_list in index.get("keyword_map", []).items():
        # Match by substring (keyword in prompt)
        if keyword in prompt_lower:
            for skill_info in skill_list:
                skill_name = skill_info["name"]
                if skill_name not in seen_skills:
                    seen_skills.add(skill_name)
                    matches.append([
                        "name": skill_name,
                        "type": skill_info["type"],
                        "priority": skill_info["priority"],
                        "matched_keyword": keyword
                    ])
    
    # Sort by priority
    matches.sort(key=lambda x: priority_order.get(x["priority"], 1))
    return matches
```

### Matching Rules

<Accordion title="Substring Matching">
  Keywords match as **substrings** (case-insensitive):

  | Keyword      | Matches                                        |
  | ------------ | ---------------------------------------------- |
  | `"agent"`    | "create agent", "agent creation", "novo agent" |
  | `"doc"`      | "documentation", "docs", "write doc"           |
  | `"pipeline"` | "run pipeline", "pipeline process"             |

  <Warning>
    Short keywords (1-2 chars) may cause false positives. Use multi-word keywords when possible.
  </Warning>
</Accordion>

<Accordion title="Priority Ordering">
  When multiple skills match, priority determines activation order:

  | Priority  | Use Case                                 | Activation   |
  | --------- | ---------------------------------------- | ------------ |
  | **ALTA**  | Core operations (agents, pipeline, docs) | Always first |
  | **MÉDIA** | Domain-specific (finance, sales)         | After ALTA   |
  | **BAIXA** | Utilities and helpers                    | Last resort  |

  **Example:**

  ```
  User: "Create an agent for finance"

  Matches:
  1. agent-creation (ALTA, keyword: "agent")
  2. finance-agent (MÉDIA, keyword: "finance")

  → Activates: agent-creation (ALTA wins)
  ```
</Accordion>

<Accordion title="Multiple Keywords">
  Skills can have **multiple keywords** for better coverage:

  ```markdown theme={null}
  > **Keywords:** criar agente, novo agent, agent creation, agente novo
  ```

  All keywords are indexed independently:

  ```json theme={null}
  [
    "keyword_map": [
      "criar agente": [["name": "agent-creation", "priority": "ALTA"]],
      "novo agent": [["name": "agent-creation", "priority": "ALTA"]],
      "agent creation": [["name": "agent-creation", "priority": "ALTA"]]
    ]
  ]
  ```
</Accordion>

## Naming Convention

Mega Brain uses a **HYBRID naming convention**:

<Tabs>
  <Tab title="Core Skills (00-11)">
    **Numbered** for guaranteed load order:

    | Number | Skill                | Purpose             |
    | ------ | -------------------- | ------------------- |
    | 00     | SKILL-CREATOR        | Create new skills   |
    | 01     | DOCS-MEGABRAIN       | Documentation       |
    | 02     | PYTHON-MEGABRAIN     | Python scripts      |
    | 03     | AGENT-CREATION       | Create agents       |
    | 04     | KNOWLEDGE-EXTRACTION | Extract insights    |
    | 05     | PIPELINE-JARVIS      | Pipeline processing |
    | 06     | BRAINSTORMING        | Ideation            |
    | 07     | DISPATCHING-PARALLEL | Parallel agents     |
    | 08     | EXECUTING-PLANS      | Execute plans       |
    | 09     | WRITING-PLANS        | Write plans         |
    | 10     | VERIFICATION         | Validation          |
    | 11     | USING-SUPERPOWERS    | Advanced features   |

    <Note>
      Core skills (00-11) are loaded in numerical order for predictable precedence.
    </Note>
  </Tab>

  <Tab title="Domain Skills (Semantic)">
    **Semantic names** for clarity:

    | Skill                  | Category    | Purpose           |
    | ---------------------- | ----------- | ----------------- |
    | `agent-creation`       | System      | Create agents     |
    | `chronicler`           | System      | Session logs      |
    | `github-workflow`      | Integration | GitHub ops        |
    | `jarvis`               | System      | Orchestrator      |
    | `jarvis-briefing`      | System      | Status reports    |
    | `knowledge-extraction` | Pipeline    | Extract knowledge |
    | `save`                 | System      | Save sessions     |
    | `resume`               | System      | Resume sessions   |
    | `verify`               | Quality     | Validation        |

    <Tip>
      Use kebab-case for semantic skill names (e.g., `my-skill-name`).
    </Tip>
  </Tab>
</Tabs>

## Creating Skills

### Quick Start

<Steps>
  <Step title="Create Skill Directory">
    ```bash theme={null}
    mkdir -p .claude/skills/my-skill-name
    cd .claude/skills/my-skill-name
    ```
  </Step>

  <Step title="Create SKILL.md">
    ```bash theme={null}
    cat > SKILL.md << 'EOF'
    # MY-SKILL-NAME
    ## Brief description of what this skill does

    > **Auto-Trigger:** When user mentions X or Y
    > **Keywords:** keyword1, keyword2, keyword3
    > **Prioridade:** MÉDIA

    ---

    ## INSTRUCTIONS

    1. First do this
    2. Then do that
    3. Finally validate
    EOF
    ```
  </Step>

  <Step title="Test Activation">
    Restart Claude and use a keyword:

    ```
    User: "Can you help with keyword1?"
    → [SKILL AUTO-ACTIVATED: my-skill-name]
    ```
  </Step>
</Steps>

### Skill Template

Use the template from `.claude/skills/_TEMPLATES/SKILL-WRITER-GUIDE.md`:

<CodeGroup>
  ```markdown Basic Skill theme={null}
  # [SKILL-NAME]
  ## [One-line description]

  > **Auto-Trigger:** [When to activate]
  > **Keywords:** [comma, separated, keywords]
  > **Prioridade:** [ALTA|MÉDIA|BAIXA]

  ---

  ## DETECTION

  This skill activates when:
  - [Condition 1]
  - [Condition 2]

  ## INSTRUCTIONS

  1. [Step 1]
  2. [Step 2]
  3. [Step 3]

  ## VALIDATION

  - [ ] [Check 1]
  - [ ] [Check 2]

  ## OUTPUTS

  - `[file path]`
  - `[another file]`
  ```

  ````markdown Advanced Skill theme={null}
  # [SKILL-NAME]
  ## [One-line description]

  > **Auto-Trigger:** [When to activate]
  > **Keywords:** [comma, separated, keywords]
  > **Prioridade:** [ALTA|MÉDIA|BAIXA]
  > **Dependencies:** [skill1, skill2]

  ---

  ## DEPENDENCIES

  | Type | Path |
  |------|------|
  | READS | `path/to/source` |
  | WRITES | `path/to/output` |
  | DEPENDS_ON | Other Skill Name |

  ## DETECTION

  Activates when:
  - [Condition]

  ## INSTRUCTIONS

  ### Phase 1: [Name]
  1. [Step]

  ### Phase 2: [Name]
  1. [Step]

  ## EXAMPLES

  ```bash
  # Example command
  command --flag value
  ````
</CodeGroup>

## Skill Best Practices

<Accordion title="Rules">
  * ✅ Always test skills before deployment
  * ❌ Never hard-code file paths
</Accordion>

<Accordion title="Validation Checklist">
  * [ ] Keywords are specific and unique
  * [ ] Auto-trigger conditions are clear
  * [ ] Skill activates on test prompts
</Accordion>

<Accordion title="Troubleshooting">
  **Problem:** Skill not activating
  **Solution:** Check keyword matching in SKILL-INDEX.json and ensure priority is set
</Accordion>

## Skill Registry

### Active Skills

Mega Brain ships with **37 active skills** (12 core + 25 domain):

<Accordion title="Core Skills (00-11)">
  | #  | Skill                | Keywords                      | Priority |
  | -- | -------------------- | ----------------------------- | -------- |
  | 00 | SKILL-CREATOR        | criar skill, nova skill       | ALTA     |
  | 01 | DOCS-MEGABRAIN       | documentar, md, playbook      | ALTA     |
  | 02 | PYTHON-MEGABRAIN     | python, script, codigo        | ALTA     |
  | 03 | AGENT-CREATION       | criar agente, novo agent      | ALTA     |
  | 04 | KNOWLEDGE-EXTRACTION | extrair, insight, chunk       | ALTA     |
  | 05 | PIPELINE-JARVIS      | processar, pipeline, jarvis   | ALTA     |
  | 06 | BRAINSTORMING        | brainstorm, ideias            | MEDIA    |
  | 07 | DISPATCHING-PARALLEL | paralelo, dispatch, batch     | ALTA     |
  | 08 | EXECUTING-PLANS      | executar, plano               | ALTA     |
  | 09 | WRITING-PLANS        | plano, planejamento           | MEDIA    |
  | 10 | VERIFICATION         | verificar, validar, checklist | ALTA     |
  | 11 | USING-SUPERPOWERS    | superpower, avancado          | MEDIA    |
</Accordion>

<Accordion title="Domain Skills (25)">
  | Skill           | Keywords               | Priority |
  | --------------- | ---------------------- | -------- |
  | chronicler      | briefing, handoff, log | ALTA     |
  | github-workflow | github, issue, PR      | ALTA     |
  | jarvis          | jarvis, orquestrador   | ALTA     |
  | jarvis-briefing | briefing, status       | ALTA     |
  | verify-6-levels | verificar, 6 levels    | ALTA     |
  | ask-company     | company, empresa       | MEDIA    |
  | executor        | executar, tarefa       | MEDIA    |
  | save            | save, salvar           | MEDIA    |
  | resume          | resume, retomar        | MEDIA    |
  | (20 more...)    | ...                    | MEDIA    |
</Accordion>

### Detection Protocol

From `DETECTION-PROTOCOL.md`:

```markdown theme={null}
## PROTOCOL

1. **Scan Phase** (SessionStart)
   - List all folders in .claude/skills/
   - Ignore folders starting with _
   - Check for SKILL.md in each folder

2. **Extract Phase**
   - Parse SKILL.md header
   - Extract: Auto-Trigger, Keywords, Prioridade
   - Build keyword map

3. **Index Phase**
   - Write SKILL-INDEX.json
   - Generate reverse keyword map
   - Sort by priority

4. **Match Phase** (UserPromptSubmit)
   - Compare prompt against keyword map
   - Find all matching skills
   - Sort by priority (ALTA > MÉDIA > BAIXA)

5. **Inject Phase**
   - Load top match SKILL.md
   - Inject instructions into context
   - Return feedback to user
```

## Advanced Features

### Sub-Agents

Skills v2.0 supports **sub-agents** in addition to skills:

<CodeGroup>
  ```bash Sub-Agent Structure theme={null}
  .claude/jarvis/sub-agents/
  ├── my-sub-agent/
  │   ├── AGENT.md      # Required: Agent instructions
  │   └── SOUL.md       # Optional: Personality
  ```

  ```python Detection theme={null}
  def scan_skills() -> List[Tuple[Path, str]]:
      items = []
      
      # Scan skills
      for item in SKILLS_PATH.iterdir():
          if item.is_dir() and (item / "SKILL.md").exists():
              items.append((item, "skill"))
      
      # Scan sub-agents
      for item in SUBAGENTS_PATH.iterdir():
          if item.is_dir() and (item / "AGENT.md").exists():
              items.append((item, "sub-agent"))
      
      return items
  ```
</CodeGroup>

**Sub-agents vs Skills:**

| Feature   | Skills            | Sub-Agents                   |
| --------- | ----------------- | ---------------------------- |
| File      | `SKILL.md`        | `AGENT.md` + `SOUL.md`       |
| Purpose   | Instructions      | Full agent persona           |
| Location  | `.claude/skills/` | `.claude/jarvis/sub-agents/` |
| Type      | `"skill"`         | `"sub-agent"`                |
| Hierarchy | Standalone        | Reports to JARVIS            |

### Dependencies

Skills can declare dependencies:

```markdown theme={null}
## DEPENDENCIES

| Type | Path |
|------|------|
| READS | `knowledge/dna/` |
| WRITES | `agents/cargo/[AGENT]/` |
| DEPENDS_ON | SKILL-DOCS-MEGABRAIN |
```

### Skill Graph

From `SKILL-REGISTRY.md`:

```
SKILL-CREATOR (meta-skill, root)
    │
    ├── SKILL-DOCS-MEGABRAIN
    │       │
    │       ├── SKILL-AGENT-CREATION
    │       │
    │       └── SKILL-KNOWLEDGE-EXTRACTION
    │               │
    │               └── SKILL-PIPELINE-JARVIS
    │
    └── SKILL-PYTHON-MEGABRAIN
```

## Debugging Skills

<Steps>
  <Step title="Check Skill Index">
    Verify skill was indexed:

    ```bash theme={null}
    cat .claude/mission-control/SKILL-INDEX.json | jq '.skills'
    ```
  </Step>

  <Step title="Test Keywords">
    Check keyword map:

    ```bash theme={null}
    cat .claude/mission-control/SKILL-INDEX.json | jq '.keyword_map'
    ```
  </Step>

  <Step title="Run skill_router.py Directly">
    Test matching logic:

    ```bash theme={null}
    python3 .claude/hooks/skill_router.py --test
    ```
  </Step>

  <Step title="Validate SKILL.md">
    Check header format:

    ```bash theme={null}
    head -20 .claude/skills/my-skill/SKILL.md
    ```
  </Step>
</Steps>

### Common Issues

<Accordion title="Skill Not Detected">
  **Problem:** Skill exists but doesn't activate

  **Solutions:**

  1. Verify SKILL.md header has all required fields
  2. Check keyword spelling (case-insensitive but must match)
  3. Ensure folder doesn't start with `_`
  4. Restart Claude to rebuild index
  5. Check `.claude/mission-control/SKILL-INDEX.json`
</Accordion>

<Accordion title="Wrong Skill Activates">
  **Problem:** Different skill activates than expected

  **Solutions:**

  1. Check keyword conflicts in `SKILL-INDEX.json`
  2. Adjust priority (ALTA > MÉDIA > BAIXA)
  3. Use more specific keywords
  4. Use multi-word keywords to reduce false positives
</Accordion>

<Accordion title="Skill Index Empty">
  **Problem:** `SKILL-INDEX.json` is empty or missing

  **Solutions:**

  1. Check if `skill_indexer.py` ran (SessionStart hook)
  2. Verify `.claude/skills/` exists and has folders
  3. Run manually: `python3 .claude/hooks/skill_indexer.py`
  4. Check for Python errors in hook logs
</Accordion>

## Related Documentation

<CardGroup cols={2}>
  <Card title="Hooks System" icon="webhook" href="/advanced/hooks-system">
    Learn about the hook system that powers skill routing
  </Card>

  <Card title="Agent Creation" icon="robot" href="/advanced/agent-creation">
    Create agents that work with the skill system
  </Card>

  <Card title="Validation" icon="check" href="/advanced/validation">
    Validate skill structure and content
  </Card>

  <Card title="Writing Skills" icon="pen" href="/advanced/skills-routing">
    Complete guide to writing new skills
  </Card>
</CardGroup>
