---
name: video-generator-orchestrator
description: Orchestrate 6 specialized agents to transform children's stories into MidJourney video prompts. Sequential workflow with human approval gates. Trigger when user asks to generate video from story, create MidJourney prompts from narrative, or says "genera video para esta historia".
---

# Video Generator Orchestrator

Transform children's stories (ages 2-10) into structured MidJourney video prompts through a 7-phase agent workflow with human validation at each step.

## Workflow Overview

```
Story Input → Style Selection → [Human Review] → Character Agent → [Human Review] →
Dialogue Agent → [Human Review] → Scenography Agent → [Human Review] →
Cinematography Agent → [Human Review] → Scriptwriter Agent → [Human Review] →
Prompt Engineer Agent → [Human Review] → MidJourney Prompts (Final Output)
```

**Core Principle**: STOP after each phase and WAIT for explicit human approval before proceeding to next phase.

**Dual Persistence**: All phases saved to both:
- **Engram**: Topic keys `video-gen/{story-slug}/phase-{N}` for session recovery
- **Files**: `specs/workflows/{story-slug}/{NN}-{phase-name}.md` for Git versioning

## Orchestrator Instructions

### Initialization

When user provides a story:

1. **Validate story suitability**:
   - Target age range mentioned or inferable (2-10 years)
   - Has narrative structure (characters, setting, conflict/resolution)
   - Appropriate content for children (no violence, mature themes)
   
2. **Create identifiers**:
   - Engram topic key: `video-gen/{story-slug}/{timestamp}`
   - File path: `specs/workflows/{story-slug}/`

3. **Show workflow preview with style selection**:
   ```
   Voy a procesar tu historia en 7 fases:
   
   0. Style Selection → Elegís el estilo visual general
   1. Character Agent → Descripciones de personajes
   2. Dialogue Agent → Diálogos apropiados para edad
   3. Scenography Agent → Escenografías y locaciones
   4. Cinematography Agent → Ángulos de cámara y composición
   5. Scriptwriter Agent → Guion completo ensamblado
   6. Prompt Engineer Agent → Prompts MidJourney listos
   
   Después de cada fase te pido aprobación antes de continuar.
   
   Arrancamos con Style Selection: ¿Qué estilo visual preferís para este video?
   
   **Opciones**:
   1. **Disney 3D** — Render realista, personajes expresivos, iluminación cálida (ej: Frozen, Moana)
   2. **Pixar 3D Animation** — Stylized, colores vibrantes, texturas suaves (ej: Coco, Inside Out)
   3. **Studio Ghibli / Anime** — Dibujo a mano, detalles delicados, fondos pintados (ej: Totoro, Spirited Away)
   4. **2D Traditional Animation** — Disney clásico, líneas limpias, cel shading (ej: Lion King, Aladdin)
   5. **Stop Motion / Clay Animation** — Texturas táctiles, look artesanal (ej: Coraline, Kubo)
   6. **Children's Book Illustration** — Acuarela o gouache, estilo pictórico (ej: The Gruffalo)
   7. **Otro** — Describí el estilo que tenés en mente
   
   Elegí un número (1-7) o describí tu estilo preferido.
   ```

4. **Wait for style selection** — do NOT proceed until user selects style

### Phase Execution Pattern

For EACH of the 7 phases (0-6):

1. **Launch sub-agent** (or present options for Phase 0) with:
   - Phase-specific instructions (see Agent Definitions below)
   - Relevant skills injected (compact rules from registry)
   - Previous phase outputs as context
   - **Selected style** (from Phase 0) as context for all subsequent phases
   - Story input

2. **Present results**:
   ```
   ## Fase {N}: {Agent Name} — Resultados
   
   {Agent output formatted clearly}
   
   ¿Aprobás este resultado o querés cambios?
   - "apruebo" / "sí" / "continúa" → procedo a siguiente fase
   - Feedback específico → re-ejecuto este agente con tus ajustes
   ```

3. **Save to dual persistence** (after approval):
   
   **A) Engram** (session recovery):
   ```python
   mcp_engram_mem_save(
       title=f"video-gen/{story-slug}/phase-{N}-{agent-name}",
       topic_key=f"video-gen/{story-slug}/phase-{N}",
       type="decision",
       project="kogi-kids",
       content=f"""
       ## Phase {N}: {Agent Name}
       
       **Story**: {story_title}
       **Status**: Approved
       **Output**: {agent_output}
       **User Feedback**: {feedback if any}
       """
   )
   ```
   
   **B) File system** (Git versioning):
   ```python
   create_file(
       filePath=f"specs/workflows/{story-slug}/{N:02d}-{phase-name}.md",
       content=f"""
       # Fase {N}: {Agent Name} — {Story Title}
       
       **Workflow**: video-generator-orchestrator
       **Story**: {story_title}
       **Target Age**: {age_range}
       **Date**: {current_date}
       **Status**: ✅ Approved
       
       ---
       
       {agent_output_formatted_as_markdown}
       
       ---
       
       ## User Feedback
       
       **User Response**: "{user_response}"
       **Changes Requested**: {changes_if_any}
       **Date Approved**: {current_date}
       
       ---
       
       ## Next Phase
       
       ✅ {Phase Name} approved → Proceed to **Phase {N+1}: {Next Agent Name}**
       """
   )
   ```

4. **Wait for approval** — do NOT proceed to next phase until user explicitly approves

### Recovery from Interruption

If conversation is compacted or user returns later:

1. Search Engram: `mcp_engram_mem_search(query="video-gen/{story-slug}", project="kogi-kids")`
2. Find latest completed phase
3. Offer to resume: "Veo que llegamos hasta {phase N}. ¿Continuamos con {phase N+1}?"

## Agent Definitions

### 0. Style Selection (No sub-agent needed)

**Goal**: Define visual style direction for entire video before generating any content

**Orchestrator Action**: Present style options directly to user (no sub-agent launch needed)

**Options to Present**:

1. **Disney 3D** 
   - Realistic render, expressive characters, warm lighting
   - Examples: Frozen, Moana, Encanto
   - MidJourney style tags: `disney 3d render, pixar quality, warm lighting, detailed textures`
   - Best for: Stories with emotional depth, magical realism

2. **Pixar 3D Animation** 
   - Stylized, vibrant colors, soft textures, exaggerated proportions
   - Examples: Coco, Inside Out, Toy Story
   - MidJourney style tags: `pixar animation style, vibrant colors, soft lighting, stylized characters`
   - Best for: Whimsical stories, character-driven narratives

3. **Studio Ghibli / Anime** 
   - Hand-drawn look, delicate details, painted backgrounds, watercolor feel
   - Examples: My Neighbor Totoro, Spirited Away, Ponyo
   - MidJourney style tags: `studio ghibli style, hand drawn animation, watercolor backgrounds, anime`
   - Best for: Nature-focused stories, gentle pacing, emotional journeys

4. **2D Traditional Animation** 
   - Disney classic, clean lines, cel shading, bold colors
   - Examples: The Lion King, Aladdin, Mulan
   - MidJourney style tags: `traditional 2d animation, disney classic style, cel shading, clean lines`
   - Best for: Epic adventures, classic storytelling

5. **Stop Motion / Clay Animation** 
   - Tactile textures, handcrafted look, imperfect charm
   - Examples: Coraline, Kubo and the Two Strings, Wallace & Gromit
   - MidJourney style tags: `stop motion animation, clay animation, textured surfaces, handcrafted look`
   - Best for: Quirky stories, tactile worlds, unique aesthetics

6. **Children's Book Illustration** 
   - Watercolor or gouache, painterly, soft edges, storybook feel
   - Examples: The Gruffalo, Where the Wild Things Are, The Very Hungry Caterpillar
   - MidJourney style tags: `children's book illustration, watercolor painting, gouache, soft edges, storybook art`
   - Best for: Gentle stories, bedtime tales, educational content

7. **Other / Custom**
   - User describes their preferred style
   - Orchestrator translates to MidJourney style tags

**User Selection Process**:
```
¿Qué estilo visual preferís para este video?

1. Disney 3D (Frozen, Moana)
2. Pixar 3D (Coco, Inside Out)
3. Studio Ghibli / Anime (Totoro, Spirited Away)
4. 2D Traditional Animation (Lion King, Aladdin)
5. Stop Motion / Clay (Coraline, Kubo)
6. Children's Book Illustration (The Gruffalo)
7. Otro (describí tu estilo)

Elegí un número (1-7) o describí el estilo.
```

**Output Format**:
```json
{
  "style_choice": "Pixar 3D Animation",
  "midjourney_style_tags": "pixar animation style, vibrant colors, soft lighting, stylized characters",
  "art_direction_notes": "Focus on exaggerated expressions, round shapes, warm color palette. Characters should have large expressive eyes and simplified but appealing designs.",
  "reference_films": ["Coco", "Inside Out", "Toy Story"],
  "color_palette_guidance": "Vibrant but not oversaturated, warm tones preferred, magical lighting"
}
```

**Save to File**: `specs/workflows/{story-slug}/00-style-selection.md`

**Pass to All Subsequent Agents**: Style selection context MUST be included in prompts for Character, Scenography, Cinematography, and Prompt Engineer agents.

---

### 1. Character Agent

**Goal**: Extract and describe all characters with visual consistency for MidJourney

**Sub-agent prompt**:
```
Analyze this children's story and generate character descriptions suitable for MidJourney image generation (ages {age_range}):

{story_input}

For EACH character, provide:

1. **Name & Role**: Main character, sidekick, antagonist, etc.
2. **Age**: Specific age or age range
3. **Physical Traits**: 
   - Ethnicity / skin tone (use neutral descriptive terms)
   - Hair (color, style, length)
   - Body type (slim, chubby, tall, short)
   - Distinguishing features (freckles, glasses, dimples)
4. **Wardrobe**: Typical outfit they wear throughout the story (color palette, style)
5. **Personality Archetype**: Brave, curious, shy, mischievous (affects facial expressions)
6. **MidJourney Consistency Tags**: Suggest style tags for visual consistency (e.g., "pixar style", "Studio Ghibli", "watercolor illustration")

**Output Format**: JSON array per character

Apply character-design-sheet skill patterns for turnaround consistency.
```

**Skills to inject**: `character-design-sheet`, `kids-book-writer` (age-appropriate traits)

**Expected output**: JSON array of 2-8 character descriptions

---

### 2. Dialogue Agent

**Goal**: Write age-appropriate dialogue with pacing suitable for video

**Sub-agent prompt**:
```
Given these character descriptions:

{character_descriptions}

And this story:

{story_input}

Generate dialogue script with:

1. **Scene breakdown**: Divide story into 5-10 scenes (each = 15-30 seconds for ages 2-4, 30-60 seconds for ages 5-10)
2. **Dialogue per scene**:
   - Character name
   - Spoken line (age-appropriate vocabulary — see kids-book-writer skill for word counts)
   - Emotion/tone (excited, worried, curious)
   - Duration estimate (seconds)
3. **Narration** (if needed): Voice-over text for scene transitions or exposition
4. **Pacing notes**: Identify moments that need visual focus (no dialogue, just action/music)

**Constraints**:
- Ages 2-3: Max 50 words total per scene, simple sentences (3-5 words)
- Ages 4-5: Max 100 words per scene, compound sentences OK
- Ages 6-7: Max 150 words per scene, some complex sentences
- Ages 8-10: Max 200 words per scene, narrative complexity allowed

Apply kids-book-writer skill for vocabulary and storytelling skill for pacing.
```

**Skills to inject**: `kids-book-writer`, `storytelling`

**Expected output**: JSON array of scenes with dialogue objects

---

### 3. Scenography Agent

**Goal**: Describe settings, locations, and atmosphere for each scene

**Sub-agent prompt**:
```
Given this dialogue script:

{dialogue_script}

And these characters:

{character_descriptions}

Generate scenography descriptions for each scene:

1. **Location**: Beach, forest, bedroom, spaceship, etc.
2. **Time of Day**: Morning, afternoon, sunset, night
3. **Weather/Atmosphere**: Sunny, rainy, foggy, magical glow
4. **Key Props**: Objects important to the scene (treasure chest, magic wand, bicycle)
5. **Color Palette**: Dominant colors for mood (warm pastels, cool blues, vibrant primary)
6. **Mood/Tone**: Cozy, adventurous, mysterious, playful
7. **MidJourney Scene Tags**: Environment descriptors (e.g., "whimsical forest --ar 16:9", "cozy bedroom interior")

**Output Format**: JSON array per scene matching dialogue script

Apply storytelling skill for SCAR framework (setup scenes vs conflict scenes).
```

**Skills to inject**: `storytelling`, `character-design-sheet` (color palette consistency)

**Expected output**: JSON array of scene descriptions (1 per dialogue scene)

---

### 4. Cinematography Agent

**Goal**: Define camera angles, framing, and shot composition

**Sub-agent prompt**:
```
Given:
- Dialogue script: {dialogue_script}
- Scene descriptions: {scene_descriptions}
- Target age: {age_range}

Generate shot list for each scene:

1. **Shot Number**: Sequential (e.g., Shot 1.1, 1.2 for scene 1)
2. **Shot Type**:
   - Establishing shot (wide, shows full location)
   - Medium shot (character from waist up)
   - Close-up (face, shows emotion)
   - Over-the-shoulder (dialogue between characters)
   - POV (point of view shot)
   - Detail shot (prop, object focus)
3. **Camera Angle**: Eye-level, low angle (heroic), high angle (vulnerable), dutch tilt
4. **Camera Movement**: Static, pan, zoom in/out, tracking
5. **Duration**: Seconds per shot (shorter for younger ages — 2-3 sec ages 2-4, 4-6 sec ages 5-10)
6. **Framing Notes**: Rule of thirds, centered, symmetrical
7. **Transition**: Cut, fade, dissolve to next shot

**Age Guidelines**:
- Ages 2-4: Prefer static medium/close shots, minimal camera movement, bright clear framing
- Ages 5-7: Mix of shot types OK, some movement, dynamic angles for excitement
- Ages 8-10: Full cinematic range, faster cuts, complex compositions

**Output Format**: JSON array of shots per scene

Apply cinematography principles: 3-point lighting assumptions, rule of thirds, eye-line match for dialogue.
```

**Skills to inject**: `storytelling` (visual pacing), `prompt-engineering-patterns` (structured output)

**Expected output**: JSON array of 20-50 shots total (depends on story length)

---

### 5. Scriptwriter Agent

**Goal**: Assemble complete script with all elements synchronized

**Sub-agent prompt**:
```
Given:
- Characters: {character_descriptions}
- Dialogue: {dialogue_script}
- Scenography: {scene_descriptions}
- Shot list: {shot_list}

Generate unified script in professional format:

For EACH scene:

```
SCENE {N}: {LOCATION} - {TIME OF DAY}

SCENOGRAPHY:
{Atmosphere, color palette, key props}

[SHOT {N}.1 - {SHOT TYPE} - {ANGLE} - {DURATION}sec]

CHARACTER NAME (emotion)
Dialogue line here.

NARRATION (if applicable):
Voice-over text.

ACTION:
[Visual action description: Character does X while Y happens]

[SHOT {N}.2 - {SHOT TYPE} - {ANGLE} - {DURATION}sec]
...
```

**Synchronization checks**:
- Every dialogue line has corresponding shot
- Shot durations match dialogue duration estimates
- Scene transitions are clear
- Character descriptions consistent across scenes
- Props mentioned in dialogue appear in scenography

Apply mockumentary-screenplay skill for Fountain-like formatting (adapted for animation).
```

**Skills to inject**: `mockumentary-screenplay` (script structure), `storytelling` (narrative flow)

**Expected output**: Full text script (plain text or Markdown formatted)

---

### 6. Prompt Engineer Agent

**Goal**: Transform script into MidJourney V7 prompts ready for generation

**Sub-agent prompt**:
```
Given this complete script:

{full_script}

Generate MidJourney V7 prompts for EACH shot:

**Prompt Structure**:
```
[Shot {N}] {Character descriptions} in {location}, {action}, {shot type}, {camera angle}, {lighting}, {color palette}, {art style} --ar 16:9 --style {style_code} --v 7
```

**Requirements**:
1. **Character Consistency**: Use SAME character descriptors across all shots (from Character Agent output)
2. **Art Style Consistency**: Choose ONE style for entire video:
   - Pixar 3D animation
   - Studio Ghibli watercolor
   - Disney 2D animation classic
   - Childrens book illustration (gouache)
   - Clay animation (stop motion)
3. **Shot-specific details**:
   - Camera angle (low angle shot, birds eye view, close up on face)
   - Action/emotion (character jumping with joy, character looking worried)
   - Lighting (soft morning light, dramatic sunset, magical glow)
4. **Parameters**:
   - `--ar 16:9` (video aspect ratio) for all shots
   - `--style raw` or custom style code for consistency
   - `--v 7` (MidJourney version 7)
   - Optional: `--chaos {0-50}` for variety (lower = more consistent)

5. **Quality scoring**: For each prompt, provide 7-dimension score (see midjourney-prompt-engineering skill)

**Output Format**:
```json
{
  "style_choice": "Pixar 3D animation",
  "consistency_tags": ["red-haired girl with freckles", "blue overalls", "curious expression"],
  "prompts": [
    {
      "shot_number": "1.1",
      "prompt": "full MidJourney prompt here",
      "parameters": "--ar 16:9 --style raw --v 7",
      "estimated_quality_score": {7-dimension object},
      "notes": "Establishing shot, introduces main character"
    },
    ...
  ]
}
```

Apply midjourney-prompt-engineering skill patterns for V7 syntax, style refs, and scoring.
```

**Skills to inject**: `midjourney-prompt-engineering`, `prompt-engineering-patterns` (few-shot examples), `character-design-sheet` (consistency tags)

**Expected output**: JSON object with 20-50 prompts (1 per shot) + metadata

---

## Final Deliverable

After Phase 6 approved:

```markdown
# Video Generation Complete — {Story Title}

## Prompts Listos para MidJourney

**Style**: {chosen_style}  
**Total Shots**: {N}  
**Estimated Duration**: {X} minutes  

### Character Consistency Tags (use in ALL prompts)
- {tag1}
- {tag2}
- ...

### Shot Prompts

**Scene 1: {Location}**

1. Shot 1.1 ({duration}sec)
   ```
   {full MidJourney prompt}
   ```
   
2. Shot 1.2 ({duration}sec)
   ```
   {full MidJourney prompt}
   ```

...

## Next Steps

1. Copy prompts to MidJourney (Discord bot or web app)
2. Generate images for each shot
3. Download all images
4. Assemble in video editor (order by shot number)
5. Add dialogue voice-over + music
6. Export final video

## Engram Archive

All phases saved to: `video-gen/{story-slug}/*`
- Phase 1: Character descriptions
- Phase 2: Dialogue script
- Phase 3: Scene descriptions
- Phase 4: Shot list
- Phase 5: Full script
- Phase 6: MidJourney prompts

Retrieve with: `mem_search(query="video-gen/{story-slug}", project="kogi-kids")`
```

Save final deliverable to Engram as `video-gen/{story-slug}/final-output`.

## Error Handling

### User Requests Changes Mid-Phase

- **Scenario**: User approves Phase 1-3, but wants to change character hair color in Phase 4
- **Action**: 
  1. Note the change request
  2. Re-run Character Agent with updated constraints
  3. Propagate changes to subsequent phases (Dialogue likely unchanged, Scenography may need color palette update, Cinematography unchanged, Scriptwriter needs character description update, Prompt Engineer needs consistency tags update)
  4. Ask user: "El cambio afecta {N} fases. ¿Re-ejecuto desde Character Agent o solo actualizo Prompt Engineer?"

### User Abandons Mid-Workflow

- **Scenario**: User stops responding after Phase 3
- **Action**: Save current state to Engram with status "paused"
- **Recovery**: Next session, search Engram, offer to resume

### Agent Fails (LLM error, timeout, etc.)

- **Scenario**: Sub-agent returns error or malformed output
- **Action**:
  1. Show error to user: "Phase {N} falló: {error message}"
  2. Offer options:
     - Retry same phase
     - Skip phase (proceed with placeholder)
     - Abort workflow
  3. Log error to Engram for debugging

## Compact Rules (for Registry Injection)

```
# video-generator-orchestrator compact rules

1. Orchestrate 7 sequential phases: Style Selection → Character → Dialogue → Scenography → Cinematography → Scriptwriter → Prompt Engineer
2. Phase 0 (Style Selection): Present 6 visual style options (Disney 3D, Pixar, Ghibli/Anime, 2D Traditional, Stop Motion, Book Illustration), wait for user choice
3. STOP after each phase, show results, WAIT for explicit approval ("apruebo", "sí", "continúa") before proceeding
4. Dual persistence: Save to Engram (topic_key = "video-gen/{story-slug}/phase-{N}") AND file (specs/workflows/{story-slug}/{NN}-{phase}.md)
5. Pass selected style context to ALL subsequent agents (Phase 1-6) as art direction constraint
6. If user gives feedback → re-run current agent with constraints, don't proceed to next
7. Character Agent: JSON array of characters with physical traits + MidJourney consistency tags matching selected style (use character-design-sheet skill)
8. Dialogue Agent: JSON array of scenes with dialogue, duration, age-appropriate vocabulary (use kids-book-writer skill for word limits)
9. Scenography Agent: JSON array of scene descriptions with location, mood, color palette, props matching selected style (use storytelling skill)
10. Cinematography Agent: JSON array of shots with type, angle, movement, duration adapted to selected animation style
11. Scriptwriter Agent: Unified text script synchronizing all elements (use mockumentary-screenplay for structure)
12. Prompt Engineer Agent: MidJourney V7 prompts per shot with --ar 16:9, selected style tags, character consistency tags (use midjourney-prompt-engineering skill)
13. Recovery: Search Engram "video-gen/{story-slug}" OR read specs/workflows/{story-slug}/*.md, find latest phase, offer to resume
14. Final output: Markdown document with all prompts + character consistency tags + style notes + Engram/file archive references
```

---

## MCP Agent Discovery (NEW — Migration to MCP Protocol)

### Feature Flag

The orchestrator supports TWO execution modes controlled by `USE_MCP_AGENTS` environment variable:

- **`USE_MCP_AGENTS=true`**: Load agents from `agents/` directory via MCP protocol (NEW)
- **`USE_MCP_AGENTS=false`** (default): Use legacy inline agent definitions from SKILL.md.legacy

**Graceful Degradation**: If MCP mode fails for ANY reason (missing agent, corrupt schema, filesystem error), orchestrator logs warning and falls back to legacy mode. Workflow NEVER breaks due to MCP issues.

### Discovery Algorithm

When `USE_MCP_AGENTS=true`, orchestrator discovers agents at workflow initialization:

```python
def discover_agents(agents_dir: Path = Path("agents")) -> dict[str, AgentConfig]:
    """
    Scan agents/ directory for MCP-compliant agents.
    
    Returns:
        dict mapping phase names to AgentConfig objects
        Example: {"character-agent": AgentConfig(...), "dialogue-agent": AgentConfig(...)}
    
    Raises:
        NoAgentsFoundError: If agents/ directory empty or no valid agents
        InvalidMCPSchemaError: If any agent.json fails validation (fail-fast)
    """
    agents = {}
    
    # Scan agents/*/agent.json files
    for agent_path in agents_dir.glob("*/agent.json"):
        try:
            config = json.loads(agent_path.read_text(encoding='utf-8'))
            
            # Validate MCP schema (fail-fast on first error)
            validate_mcp_schema(config, agent_path)
            
            # Build agent config
            agent_name = config["name"]
            agents[agent_name] = AgentConfig(
                name=agent_name,
                config=config,
                prompt_path=agent_path.parent / "prompt.md"
            )
            
        except Exception as e:
            # Fail-fast: don't partially load agents
            raise InvalidAgentError(
                f"Agent {agent_path.parent.name} invalid: {e}\n"
                f"Path: {agent_path}"
            )
    
    if not agents:
        raise NoAgentsFoundError(
            f"No valid MCP agents found in {agents_dir}\n"
            f"Ensure agents/ directory contains subdirectories with agent.json files"
        )
    
    logger.info(f"✅ Discovered {len(agents)} MCP agents: {list(agents.keys())}")
    return agents
```

### Schema Validation

```python
def validate_mcp_schema(config: dict, path: Path):
    """
    Validate MCP 2024-11-05 schema compliance.
    
    Raises:
        InvalidMCPSchemaError: If required fields missing or invalid
    """
    # Required top-level fields
    required_fields = ["name", "version", "runtime", "protocol_version", "capabilities", 
                       "inputs", "outputs", "dependencies"]
    missing = [field for field in required_fields if field not in config]
    
    if missing:
        raise InvalidMCPSchemaError(
            f"Missing required fields: {missing}\n"
            f"Path: {path}\n"
            f"Required: {required_fields}"
        )
    
    # Validate protocol version
    if config["protocol_version"] != "2024-11-05":
        raise InvalidMCPSchemaError(
            f"Unsupported protocol version: {config['protocol_version']}\n"
            f"Expected: 2024-11-05\n"
            f"Path: {path}"
        )
    
    # Validate runtime
    if config["runtime"] != "mcp":
        raise InvalidMCPSchemaError(
            f"Invalid runtime: {config['runtime']}\n"
            f"Expected: 'mcp'\n"
            f"Path: {path}"
        )
    
    # Validate capabilities structure
    if not isinstance(config["capabilities"], dict):
        raise InvalidMCPSchemaError(
            f"capabilities must be object with 'tools', 'resources', 'prompts' arrays\n"
            f"Path: {path}"
        )
    
    # Validate dependencies.skills exists (required for skill injection)
    if "skills" not in config.get("dependencies", {}):
        raise InvalidMCPSchemaError(
            f"dependencies.skills array required (can be empty [])\n"
            f"Path: {path}"
        )
```

### Load MCP Agent (with Skill Injection)

```python
def load_mcp_agent(phase_name: str, agents_registry: dict) -> AgentPrompt:
    """
    Load MCP agent for given phase, inject skill compact rules.
    
    Args:
        phase_name: "character-agent", "dialogue-agent", etc.
        agents_registry: Output from discover_agents()
    
    Returns:
        AgentPrompt with system prompt + injected skill rules
    
    Raises:
        AgentNotFoundError: If phase_name not in registry
        FileNotFoundError: If prompt.md missing
    """
    # Check agent exists
    if phase_name not in agents_registry:
        available = list(agents_registry.keys())
        raise AgentNotFoundError(
            f"Agent '{phase_name}' not found in agents/\n"
            f"Available agents: {available}\n"
            f"Expected path: agents/{phase_name}/agent.json"
        )
    
    agent_config = agents_registry[phase_name]
    
    # Read prompt.md
    if not agent_config.prompt_path.exists():
        raise FileNotFoundError(
            f"prompt.md not found for {phase_name}\n"
            f"Expected path: {agent_config.prompt_path}"
        )
    
    base_prompt = agent_config.prompt_path.read_text(encoding='utf-8')
    
    # Resolve skill compact rules from dependencies
    skill_names = agent_config.config["dependencies"]["skills"]
    compact_rules = resolve_compact_rules_from_registry(skill_names)
    
    # Inject rules into prompt
    prompt_with_context = f"""{base_prompt}

---

## Project Standards (auto-resolved from skill-registry)

{compact_rules}
"""
    
    return AgentPrompt(
        name=phase_name,
        config=agent_config.config,
        prompt=prompt_with_context
    )
```

### Skill Resolution Injection

**Purpose**: Each agent declares skill dependencies in `agent.json` → orchestrator reads skill-registry.md → injects compact rules BEFORE launching agent.

**Workflow**:
1. Agent declares: `"dependencies": {"skills": ["character-design-sheet", "kids-book-writer"]}`
2. Orchestrator reads: `mem_search(query="skill-registry", project="kogi-kids")` → `mem_get_observation(id)`
3. Orchestrator extracts compact rules for those 2 skills from registry
4. Orchestrator injects rules as `## Project Standards (auto-resolved)` section in agent prompt
5. Agent receives full context WITHOUT needing to read registry itself

**Implementation**:
```python
def resolve_compact_rules_from_registry(skill_names: list[str]) -> str:
    """
    Read skill-registry.md, extract compact rules for specified skills.
    
    Returns:
        Markdown text with compact rules for requested skills
    """
    # Try Engram first
    try:
        search_result = mcp_engram_mem_search(
            query="skill-registry", 
            project="kogi-kids"
        )
        if search_result:
            registry_content = mcp_engram_mem_get_observation(id=search_result[0].id)
        else:
            # Fallback: read from file
            registry_content = Path(".atl/skill-registry.md").read_text(encoding='utf-8')
    except Exception as e:
        logger.warning(f"Skill registry not found: {e}. Proceeding without project-specific standards.")
        return ""
    
    # Parse compact rules section
    compact_rules = []
    in_compact_section = False
    current_skill = None
    
    for line in registry_content.split('\n'):
        if line.startswith("## Compact Rules"):
            in_compact_section = True
            continue
        
        if in_compact_section:
            if line.startswith("### "):
                current_skill = line[4:].strip()
            elif current_skill in skill_names and line.strip().startswith("-"):
                compact_rules.append(f"**{current_skill}**: {line.strip()}")
    
    return "\n".join(compact_rules)
```

### Error Types

**AgentNotFoundError**:
```python
class AgentNotFoundError(Exception):
    """Raised when requested agent not in agents/ directory."""
    pass
```

**InvalidMCPSchemaError**:
```python
class InvalidMCPSchemaError(Exception):
    """Raised when agent.json fails MCP 2024-11-05 validation."""
    pass
```

**NoAgentsFoundError**:
```python
class NoAgentsFoundError(Exception):
    """Raised when agents/ directory empty or no valid agents."""
    pass
```

### Execution Flow (MCP Mode)

```
User: "genera video para esta historia"
  ↓
Orchestrator: Check USE_MCP_AGENTS flag
  ├── TRUE → discover_agents("agents/") 
  │   ├── Scan agents/*/agent.json
  │   ├── Validate schemas (fail-fast if any invalid)
  │   └── Build registry: {phase_name: AgentConfig}
  │
  ├── Phase 1: load_mcp_agent("character-agent", registry)
  │   ├── Check agent exists in registry
  │   ├── Read agents/character-agent/prompt.md
  │   ├── Resolve skills: ["character-design-sheet", "kids-book-writer"]
  │   ├── Inject compact rules from skill-registry
  │   └── Launch sub-agent with full context
  │
  ├── Phase 2-6: Repeat for remaining agents
  │
  └── Complete: All artifacts persisted (Engram + files)
```

### Fallback Flow (MCP Error or Legacy Mode)

```
Orchestrator: Check USE_MCP_AGENTS flag
  ├── FALSE → load_legacy_agent("SKILL.md.legacy", phase)
  │   └── Use inline agent definitions (original behavior)
  │
  ├── TRUE but MCP discovery fails → 
  │   ├── Log warning: "MCP discovery failed: {error}. Falling back to legacy mode."
  │   └── load_legacy_agent("SKILL.md.legacy", phase)
  │
  └── Complete: Workflow continues without interruption
```

### Rollback Procedure

If issues arise with MCP mode:

1. Set `USE_MCP_AGENTS=false` (environment variable or config)
2. Restart orchestrator (or reload skill)
3. Orchestrator uses `SKILL.md.legacy` inline definitions
4. No file deletion needed — `agents/` coexists with legacy
5. **Rollback time**: < 30 seconds

---

## Trigger Phrases

Activate this skill when user says:
- "genera video para esta historia"
- "crea prompts de MidJourney para este cuento"
- "transforma esta narrativa en video"
- "generate video from this story"
- "create MidJourney prompts for children's story"
- "video generation workflow"
- "orchestrate agents for video"

Also activate when user explicitly mentions `/video-gen` command.
