Skip to main content

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

.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

Skill Lifecycle

1

SessionStart: Index Skills

skill_indexer.py hook scans .claude/skills/ and generates SKILL-INDEX.json:
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
2

Extract Metadata

For each SKILL.md, extract header metadata:
> **Auto-Trigger:** When user mentions creating agents
> **Keywords:** agent, criar agente, novo agent
> **Prioridade:** ALTA
3

UserPromptSubmit: Match Keywords

skill_router.py compares user prompt against keyword map:
prompt_lower = prompt.lower()
for keyword, skill_list in keyword_map.items():
    if keyword in prompt_lower:
        matches.append(skill_list[0])
4

Inject Context

If match found, inject skill instructions into context:
[
  "continue": true,
  "feedback": "[SKILL AUTO-ACTIVATED: agent-creation]\nKeyword: 'agent'\n\n=== INSTRUCTIONS ===\n..."
]

SKILL.md Format

Every skill must have a SKILL.md file with this structure:
# 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
The header metadata (Auto-Trigger, Keywords, Prioridade) is required for auto-detection.

Keyword Matching

Matching Algorithm

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

Keywords match as substrings (case-insensitive):
KeywordMatches
"agent"”create agent”, “agent creation”, “novo agent”
"doc"”documentation”, “docs”, “write doc”
"pipeline"”run pipeline”, “pipeline process”
Short keywords (1-2 chars) may cause false positives. Use multi-word keywords when possible.
When multiple skills match, priority determines activation order:
PriorityUse CaseActivation
ALTACore operations (agents, pipeline, docs)Always first
MÉDIADomain-specific (finance, sales)After ALTA
BAIXAUtilities and helpersLast 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)
Skills can have multiple keywords for better coverage:
> **Keywords:** criar agente, novo agent, agent creation, agente novo
All keywords are indexed independently:
[
  "keyword_map": [
    "criar agente": [["name": "agent-creation", "priority": "ALTA"]],
    "novo agent": [["name": "agent-creation", "priority": "ALTA"]],
    "agent creation": [["name": "agent-creation", "priority": "ALTA"]]
  ]
]

Naming Convention

Mega Brain uses a HYBRID naming convention:
Numbered for guaranteed load order:
NumberSkillPurpose
00SKILL-CREATORCreate new skills
01DOCS-MEGABRAINDocumentation
02PYTHON-MEGABRAINPython scripts
03AGENT-CREATIONCreate agents
04KNOWLEDGE-EXTRACTIONExtract insights
05PIPELINE-JARVISPipeline processing
06BRAINSTORMINGIdeation
07DISPATCHING-PARALLELParallel agents
08EXECUTING-PLANSExecute plans
09WRITING-PLANSWrite plans
10VERIFICATIONValidation
11USING-SUPERPOWERSAdvanced features
Core skills (00-11) are loaded in numerical order for predictable precedence.

Creating Skills

Quick Start

1

Create Skill Directory

mkdir -p .claude/skills/my-skill-name
cd .claude/skills/my-skill-name
2

Create SKILL.md

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
3

Test Activation

Restart Claude and use a keyword:
User: "Can you help with keyword1?"
→ [SKILL AUTO-ACTIVATED: my-skill-name]

Skill Template

Use the template from .claude/skills/_TEMPLATES/SKILL-WRITER-GUIDE.md:
# [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]`

Skill Best Practices

  • ✅ Always test skills before deployment
  • ❌ Never hard-code file paths
  • Keywords are specific and unique
  • Auto-trigger conditions are clear
  • Skill activates on test prompts
Problem: Skill not activating Solution: Check keyword matching in SKILL-INDEX.json and ensure priority is set

Skill Registry

Active Skills

Mega Brain ships with 37 active skills (12 core + 25 domain):
#SkillKeywordsPriority
00SKILL-CREATORcriar skill, nova skillALTA
01DOCS-MEGABRAINdocumentar, md, playbookALTA
02PYTHON-MEGABRAINpython, script, codigoALTA
03AGENT-CREATIONcriar agente, novo agentALTA
04KNOWLEDGE-EXTRACTIONextrair, insight, chunkALTA
05PIPELINE-JARVISprocessar, pipeline, jarvisALTA
06BRAINSTORMINGbrainstorm, ideiasMEDIA
07DISPATCHING-PARALLELparalelo, dispatch, batchALTA
08EXECUTING-PLANSexecutar, planoALTA
09WRITING-PLANSplano, planejamentoMEDIA
10VERIFICATIONverificar, validar, checklistALTA
11USING-SUPERPOWERSsuperpower, avancadoMEDIA
SkillKeywordsPriority
chroniclerbriefing, handoff, logALTA
github-workflowgithub, issue, PRALTA
jarvisjarvis, orquestradorALTA
jarvis-briefingbriefing, statusALTA
verify-6-levelsverificar, 6 levelsALTA
ask-companycompany, empresaMEDIA
executorexecutar, tarefaMEDIA
savesave, salvarMEDIA
resumeresume, retomarMEDIA
(20 more…)MEDIA

Detection Protocol

From DETECTION-PROTOCOL.md:
## 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:
.claude/jarvis/sub-agents/
├── my-sub-agent/
   ├── AGENT.md      # Required: Agent instructions
   └── SOUL.md       # Optional: Personality
Sub-agents vs Skills:
FeatureSkillsSub-Agents
FileSKILL.mdAGENT.md + SOUL.md
PurposeInstructionsFull agent persona
Location.claude/skills/.claude/jarvis/sub-agents/
Type"skill""sub-agent"
HierarchyStandaloneReports to JARVIS

Dependencies

Skills can declare dependencies:
## 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

1

Check Skill Index

Verify skill was indexed:
cat .claude/mission-control/SKILL-INDEX.json | jq '.skills'
2

Test Keywords

Check keyword map:
cat .claude/mission-control/SKILL-INDEX.json | jq '.keyword_map'
3

Run skill_router.py Directly

Test matching logic:
python3 .claude/hooks/skill_router.py --test
4

Validate SKILL.md

Check header format:
head -20 .claude/skills/my-skill/SKILL.md

Common Issues

Problem: Skill exists but doesn’t activateSolutions:
  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
Problem: Different skill activates than expectedSolutions:
  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
Problem: SKILL-INDEX.json is empty or missingSolutions:
  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

Hooks System

Learn about the hook system that powers skill routing

Agent Creation

Create agents that work with the skill system

Validation

Validate skill structure and content

Writing Skills

Complete guide to writing new skills

Build docs developers (and LLMs) love