# Content To Sketch Orchestrator

> A multi-agent state graph pipeline for generating hand-drawn, organic concept diagrams. Orchestrates an Art Director agent for semantic metaphor extraction, a deterministic Layout Calculator, and a Renderer agent for Excalidraw JSON generation, featuring a cyclic QA feedback loop.

- Skill: `arn-nj/content-to-sketch-orchestrator` (Agent Skill, multi-file: 20 files)
- Install (CLI): `npx skillmds@latest add arn-nj/content-to-sketch-orchestrator`
- Raw SKILL.md: https://api.skillmd.com/api/skills/arn-nj/content-to-sketch-orchestrator/raw
- Safety review: pending
- Works with: Claude Code, Claude.ai, OpenAI Codex
- Category: DevOps & Infra
- Author: arn-nj (https://skillmd.com/u/arn-nj)
- Updated: 2026-09-22
- Page: https://skillmd.com/skills/arn-nj/content-to-sketch-orchestrator

---


# Content to Sketch (Agentic Orchestration Pipeline)

This skill utilizes a multi-agent state graph to translate abstract technical concepts into highly memorable, hand-drawn visual metaphors. By separating semantic planning from syntactic rendering, the pipeline guarantees high-fidelity educational visuals without geometry degradation.

## Flow Ownership Rule (Mandatory)

- This skill is the single source of truth for sketch generation in this workspace.
- Downstream skills (for example transcript-to-notes, md-to-notes, pdf-to-notes) must not directly author or "quick-fix" diagram geometry.
- If a sketch is low-quality, regenerate through this skill by improving the Art Director preflight inputs (mechanism, analogy, composition), then recompile.
- Manual diagram edits are allowed only for final touch-ups after the full pipeline succeeds; they are not the default repair path.

## The Execution Pipeline (State Graph)

> `[Agentic Pipeline] -> Art Director -> Spatial Router -> Renderer -> QA`

The pipeline is a multi-agent state graph. Each agent reads from and writes to a shared **State object**. Agents must not skip nodes or bypass the defined sequence.

### The State Object (Graph Context)

All agents read from and write to a shared State object containing:
- `raw_input`: The user's original request or markdown chunk.
- `semantic_brief`: The pedagogical plan (metaphor, mechanism, hot path).
- `spatial_map`: Deterministic bounding box and node relationship coordinates.
- `excalidraw_json`: The generated drawing syntax.
- `qa_errors`: Array of validation failures used for cyclic routing.
- `retry_count`: Integer tracking QA loops (max 3).

### Node 1: The Art Director (Planner Agent)
**Role:** Semantic reasoning and pedagogical mapping.
**Task:** Ingest the `raw_input` and generate a pure JSON `semantic_brief`.
**Strict Constraints:**
- Do not write Excalidraw JSON. Do not calculate X/Y coordinates.
- Identify the core technical mechanism (e.g., rate limiting, backpressure).
- Map the mechanism to a physical-world analogy (e.g., nightclub bouncer, toll plaza).
- Define the "Hot Path" (primary execution path) and "Failure Branch".
- Define micro-captions (2-5 words, mechanism-focused, no noun-only labels).
- Output the `semantic_brief` and pass state to Node 2.

### Node 2: The Spatial Router (Deterministic Tooling)
**Role:** Mathematical layout calculation.
**Task:** Read the `semantic_brief` and generate a `spatial_map`.
**Strict Constraints:**
- Assign rough X/Y coordinates, width, and height for each object identified by the Art Director.
- Calculate orthogonal routing for connectors to prevent arrow-through-node overlaps.
- Define parent-child container boundaries for text labels to ensure text fits inside shapes.
- Pass state to Node 3.

### Node 3: The Renderer (Syntax Agent)
**Role:** Syntactic translation and Excalidraw styling.
**Task:** Merge the `semantic_brief` and the `spatial_map` into strict `excalidraw_json`.
**Strict Constraints:**
- Do not invent new metaphors or change micro-captions.
- You must enforce the global style contract:
  - `type: "excalidraw"`
  - `roughness: 2`
  - `fillStyle: "hachure"`
  - `fontFamily: 1` (Virgil)
  - `strokeColor`: `#0B132B` (deep navy), `#000000` (black), or `#C62828` (red for warnings).
  - `fillColor` (Hot Path only): `#5BC0EB` (cyan).
- Map the `spatial_map` coordinates to valid Excalidraw bounding boxes.
- Pass state to Node 4.

### Node 4: The QA Gate (Validator Agent / Deterministic Script)
**Role:** Geometry and schema validation.
**Task:** Evaluate the `excalidraw_json` against the required schema and physical constraints.
**Execution Logic:**
1. Check JSON validity and Excalidraw schema compliance.
2. Check Text Containment: Ensure label dimensions do not exceed their parent shape boundaries.
3. Check Connector Hygiene: Ensure arrow start/end points terminate exactly on shape edges, not in the center.
4. **Conditional Routing:**
   - IF passes all checks: Route to `scripts/compile-excalidraw.js` for headless compilation.
   - IF fails AND `retry_count` < 3: Append specific coordinate or syntax errors to `qa_errors`, increment `retry_count`, and route back to **Node 3 (Renderer)** for targeted fixing.
   - IF fails AND `retry_count` >= 3: Hard fail and output the specific error log to the user.

### Mandatory Initiation Protocol

When invoked, initialize the State object and immediately route the input to **Node 1 (The Art Director)**. Do not attempt to bypass nodes. Print a brief console trace (e.g., `[Agentic Pipeline] -> Art Director -> Spatial Router -> Renderer -> QA`) so the user can observe the state graph execution.


## Pedagogical Visual Synthesizer Contract

This skill is not a generic image generator. It must produce visuals that reduce cognitive load, maximize recall, and expose mechanism-level understanding while preserving all existing GoodNotes compatibility, validation gates, and output modes.

A diagram is considered **truly semantic** only when the learner can infer the main mechanism, dominant path, and failure/constraint branch from geometry, motion, and object relationships before reading most labels.

## Hard Creative Guardrails (Non-Negotiable)

### 1) Ban Generic Text-Grid Layouts
- Do not generate diagrams that are only formatted text in boxes.
- Explicitly forbidden patterns include:
  - Any repeated `What / How / Why` box grid
  - Three-column text cards with no structural mechanism
  - Pure label boards that do not depict interaction, motion, or physical mapping
  - Reusing the same geometry across lessons while only changing labels
- Every visual must be either:
  - **Structural**: components and interactions with clear mechanics, or
  - **Metaphorical**: a concrete physical-world analogy that explains system behavior.

### 2) Art Director Metaphor Extraction (Mandatory Preflight)
Before generating final diagram output, run this required sequence:
1. **Mechanism Extraction**: identify the core technical mechanism (for example rate limiting, queue backpressure, fan-out/fan-in, inheritance, retries, eventual consistency).
2. **Physical Analogy Mapping**: map the mechanism to a physical-world scene (for example nightclub bouncer, toll plaza, loading dock, synchronized factory line, relay race baton exchange).
3. **Label Fusion Plan**: decide where technical labels appear inside the physical drawing so labels explain parts of the analogy rather than floating as detached text.
4. **Composition Check**: verify the scene shows cause/effect motion and constraints, not static blocks.

If any step is missing, output generation must be treated as invalid and regenerated.

### 2.1) Preferred Upstream Input = Semantic Visual Brief
This skill should prefer a structured semantic visual brief over a raw title or vague topic label.

Required upstream fields:
- `coreMechanism`
- `what`
- `how`
- `why`
- `physicalAnalogy`
- `labelFusion`
- `compositionIntent`
- `hotPath`
- `mainConstraint`
- `tradeoff`
- `mustShow`
- `mustNotShow`
- `visualSceneType`
- `sceneObjects`
- `objectToConceptMap`
- `spatialLayout`
- `entryPoint`
- `exitPoint`
- `failureBranch`
- `comparisonAxis`
- `evidenceArtifact`
- `dominantMotion`
- `forbiddenTemplate`
- `objectPalette`
- `shapeQuota`
- `forbiddenGeometry`
- `labelBudget`
- `sceneTest`
- `silhouettePlan`
- `propDensity`
- `asymmetryPlan`
- `antiCardFraming`
- `sceneTexture`
- `premiumSceneTest`
- `diagramIntent`
- `formalFramework`
- `sceneFamilyCandidates`
- `selectedSceneFamily`
- `selectionReason`
- `formalCompanionSuggested`
- `salienceGoal`
- `silhouetteContrastRules`
- `propInventory`
- `textureInventory`

These fields are not decorative metadata. They must drive the actual scene geometry.

If the caller only provides a section title or a shallow topic label, treat that input as under-specified and request or reconstruct a stronger brief before drawing.
If the caller provides only a semantic explanation but no geometry-driving fields, treat that as partially specified and deepen it before rendering.

### 2.2) Automatic Visual Reasoning Layer (Required)
Use `./references/automatic-visual-reasoning.md` before any scene-family or geometry choice.

This layer must decide:
- what kind of visual problem the concept is
- which formal framework best fits it
- which 2-3 semantic scene families are the best candidates
- why the final scene family was selected
- whether a formal companion diagram should also be suggested

Hard rule:
- Do not jump directly from lesson title or semantic summary to `visualSceneType`.
- First resolve `diagramIntent`, `formalFramework`, `sceneFamilyCandidates`, `selectedSceneFamily`, and `selectionReason`.

### 3) Context-Aware Visual Archetypes (Required Selection)
Select one archetype per concept before drawing:
- **System Architecture**: draw interconnected physical components (machines, hubs, pipes, stations, control rooms).
- **Process/Pipeline**: draw directional flow (conveyor belt, assembly line, staged checkpoints, intake-to-output path).
- **Concept vs Concept**: draw comparative composition (weighing scale, split-screen, diverging roads, before/after cross-section).

The selected archetype must be visible in geometry, iconography, and flow direction.

### 3.1) Scene-Family Composition Rule (Required)
The renderer must choose a scene-family-specific geometry, not a universal template.

Examples:
- `cargo-screening-line` → filter gate, accepted load, rejected pile, constrained carrier
- `qa-lane` → item under inspection, multiple test stations, pass/fail branch
- `machine-room-hub` → central core with attached support systems
- `layered-theater-stack` → vertical control hierarchy with stacked layers
- `control-room-levers` → decision console with behavioral consequences

Hard rule:
- `visualSceneType` must control geometry.
- A scene-family name must **not** merely appear as text in the final image.
- The same base layout cannot be reused across unrelated scene families.

### 3.2) Object Vocabulary Rule (Required)
The renderer must think in terms of physical scene objects, not abstract containers.

Preferred object families include:
- gates, conveyors, bins, trays, belts, desks, shelves, booths, levers, switches, pipes, docks, checkpoints, mailboxes, trucks, carts, ladders, archives, benches, inspection tables, workrooms

Hard rule:
- `objectPalette` must name the concrete object vocabulary allowed for the scene.
- `sceneObjects` must be instantiated from that palette.
- If the image could be drawn almost entirely as anonymous rectangles with labels, the scene fails.

### 3.3) Anti-Box Degeneration Rule (Required)
This skill exists to transform content into sketches, not rows of labeled boxes.

Use these required controls:
- `shapeQuota` → define maximum tolerated share of plain rectangles and the minimum required object diversity
- `forbiddenGeometry` → define layouts that are not allowed for this concept
- `labelBudget` → define the maximum amount of visible explanatory text in the final image
- `sceneTest` → define semantic pass/fail checks for the rendered scene

Minimum defaults when not otherwise specified:
- `shapeQuota.maxPlainRectangles <= 0.4`
- `shapeQuota.requireAtLeast` includes at least 3 distinct object families beyond plain text
- `labelBudget.maxVisibleLabels <= 12`
- `labelBudget.maxCaptions <= 1`
- `sceneTest.reusableByRelabelingOnly = false`
- `sceneTest.hotPathVisibleWithoutSentence = true`
- `sceneTest.failureBranchSpatiallyObvious = true`

### 3.4) Canonical Scene-Family Library (Required Starting Point)
Use `./references/canonical-scene-families.md` as the default scene-family catalog.

Rules:
- Prefer one of the canonical families before inventing a new one.
- If you introduce a new family, it must define the same contract: `objectPalette`, `shapeQuota`, `forbiddenGeometry`, `labelBudget`, and `sceneTest`.
- When a lesson is clearly a filtering, verification, routing, memory, delegation, state, or scaffold concept, choosing a generic box layout instead of the matching canonical family is a failure.

### 3.5) Premium Sketch Language Layer (Required for Learner-Facing Final Visuals)
Use `./references/premium-sketch-language.md` whenever the requested output is a final learner-facing image, not merely an internal draft.

Required premium controls:
- `silhouettePlan` → how major objects will differ by outline, not just labels
- `propDensity` → how many supporting props reinforce the world without clutter
- `asymmetryPlan` → how spacing/grouping avoids sterile perfect-grid layout
- `antiCardFraming` → how the scene avoids degenerating into framed cards unless the metaphor truly calls for a board/desk/checklist surface
- `sceneTexture` → subtle environmental lines/rails/curtains/floor markings/shelf lines that prevent floating-object syndrome
- `premiumSceneTest` → premium pass/fail checks above the normal semantic tests

Premium defaults:
- major objects should have distinct silhouettes
- the scene should include 2-5 supporting props
- the layout should not read as a perfect grid unless the concept is literally a board/control panel
- label density should usually be lower than standard semantic diagrams
- texture should be present but subtle

### 3.6) Premium Generation Playbook (Mandatory Render Sequence)
Use `./references/premium-generation-playbook.md` as the mandatory render order for learner-facing premium scenes.

Required pass order:
1. scene skeleton
2. silhouette pass
3. hot-path pass
4. failure/secondary-path pass
5. prop pass
6. asymmetry pass
7. scene-texture pass
8. connector-hygiene pass
9. label pass
10. premium QA gate

Hard rule:
- Do not jump directly from the brief to a tidy final layout.
- If a scene fails during an early pass, regenerate upstream geometry instead of compensating with more labels.

### 4) Excalidraw Scene Styling (Required)
All generated `.excalidraw` scenes must explicitly enforce:
- `type`: `"excalidraw"` (must be the root wrapper on the JSON object)
- `roughness: 2`
- `fillStyle: "hachure"`
- `fontFamily: 1` (Virgil)
- Whiteboard duotone palette with deep navy + cyan accents

Default palette contract:
- `strokeColor` (structural elements): `#0B132B` (deep navy), `#000000` (black), or `#C62828` (red for warnings/constraints)
- `backgroundColor`: `transparent` (unless shape emphasis is required)
- `fillColor` (when used): `#5BC0EB` (cyan) or a pastel equivalent — **reserved exclusively for the Hot Path / primary execution flow**; do not use cyan fills on secondary or background shapes

### 5) Hand-Drawn Style Anchor (Required Append)
Append this exact style anchor to every Excalidraw brief, PNG compile brief, and image-generation prompt:

"Style: Hand-drawn, raw sketch style, slightly imperfect organic lines, minimalist black ink on a clean whiteboard background (no grid), educational whiteboard aesthetic."

If this anchor is missing, the visual request is incomplete.

## When to Use

- **During transcript-to-notes generation**: Add visual aids for each major section or concept
- **Standalone concept visualization**: Request a sketch of a specific idea from any transcript or document  
- **Batch generation**: Auto-generate images for entire course outlines or module breakdowns
- **Markdown integration**: Extract key concepts from existing study notes and create visuals
- **Study material enhancement**: Convert dense text explanations into memorable visual summaries

## Input Modes

### Mode 1: Direct Concept Description (Quick Single Image)
```
"I have a concept: Dependency Injection in software design. 
Create a hand-drawn sketch showing a class with dependencies 
being injected, vs tightly coupled classes."
```

**Triggers**: 
- Type `/content-to-sketch` and describe the concept or architecture
- Provide a short textual description of what to visualize
- Best for: Single concepts, quick diagrams, architectural patterns

### Mode 2: Extract from Markdown File (Batch Generation)
```
"Generate images for each major section in 
BuildRealWorldAgents_BeginnerToPro/BuildRealWorldAgents_BeginnerToPro_GoodNotes_detailed.md"
```

**Triggers**:
- Reference a markdown file (course notes, transcript summary, chapter outline)
- Skill parses headers (## Section Name, ### Subsection) as visual chunks
- Generates at least one image per topic/section with concept-relevant styling
- Best for: Full course visualization, multi-chapter coverage, consistent output

### Mode 3: JSON Config with Multiple Concepts (Advanced Batch)
```json
{
  "course": "BuildRealWorldAgents_BeginnerToPro",
  "png_count_mode": "per-topic",
  "png_count": 8,
  "concepts": [
    {
      "title": "Agent Planning",
      "description": "Agent breaks down goals into steps before execution",
      "style": "flow-diagram"
    },
    {
      "title": "Tool Integration",
      "description": "Agent uses external APIs and code interpreters",
      "style": "architecture"
    }
  ]
}
```

**Triggers**:
- Pass structured data for fine-grained control
- Assign visual styles per concept (flow-diagram, architecture, mindmap, conceptual-sketch)
- Control whether PNG count is explicit or derived from topic count
- Best for: Curated collections, specific styling per concept, production output

## PNG Count Rules

- **Default behavior**: Generate `1 PNG minimum per topic`.
- **Auto mode**: Count is derived from detected topics/sections/headings.
- **Explicit mode**: User can request a fixed count, for example `png_count: 12`.
- **Floor rule**: Never produce fewer PNGs than the number of core topics selected.
- **Expansion rule**: If a topic has multiple distinct ideas, it can receive more than one PNG.

Supported count controls:

```json
{
  "png_count_mode": "per-topic",
  "png_count": 12,
  "min_one_png_per_topic": true
}
```

Count modes:
- `per-topic` → one PNG minimum for every detected or supplied topic
- `fixed` → generate exactly the requested number, but never below topic count
- `topic-density` → generate more PNGs for dense topics with multiple sub-concepts

## Regeneration Protocol (Fix the Flow, Not One File)

When output quality is poor (empty diagrams, static text, repeated boilerplate labels, missing metaphor), use this sequence:

1. Re-run Phase 1 preflight with a stronger mechanism + analogy pairing.
2. Reject any brief that cannot explain cause/effect motion in one sentence.
3. Regenerate `.excalidraw` sources for the full affected lesson set (not only one file).
4. Recompile all affected scenes to `.png`.
5. Re-run validation (PNG integrity + structural QA for text containment and connector hygiene) and update `assets/INDEX.md` with the latest run status.

Hard fail patterns (must trigger regeneration):
- repeated filler labels like `Signal 1`, `Signal 2`, `Signal 3`
- generic box-grid layouts with no visible mechanism
- diagrams where hiding labels leaves no understandable flow

## Output Formats

The skill generates images using **one of three techniques**, selectable per request:

### 1. **Excalidraw Scene JSON (Default Authoring Format)**
- **Tooling target**: semantic `.excalidraw` JSON scene files
- **Style**: Excalidraw-native hand-drawn elements (Virgil, hachure, roughness)
- **Best for**: metaphor-first concept mapping with reusable editable sources
- **Output**: `.excalidraw` files saved under `assets/` or `assets/` (source-of-truth)
- **Compiler stage**: compiled headlessly to `.png` for downstream embedding

### 2. **Compiled PNG (Downstream Consumption Format)**
- **Tool**: headless Excalidraw compiler (`scripts/compile-excalidraw.js`)
- **Style**: preserves Virgil font and roughness properties
- **Best for**: markdown, XMind, and Reveal.js embedding
- **Output**: `.png` files alongside source `.excalidraw` files

### 3. **Mermaid Diagrams** (Flowcharts, Mindmaps, Timelines)
- **Tool**: Built-in `mcp_goodnotes_generate_mermaid_diagram`
- **Styles**: Flowchart, mindmap, timeline
- **Best for**: Complex relationships, hierarchical concepts, sequential processes
- **Output**: Embedded diagram or `.mm` file
- **Example use case**: Decision trees, course progression, concept relationships, project timelines

### 4. **Image Generation Prompts** (For External APIs)
- **Method**: Generate detailed visual prompts optimized for DALL-E, Midjourney, or similar
- **Style**: "Hand-drawn notebook sketch" instructions for consistent aesthetic
- **Best for**: High-fidelity illustrations, stylized visuals, polished course materials
- **Output**: Markdown with prompt + link to generated image (requires external API call)
- **Example use case**: Detailed concept illustrations, professional course materials, cover art

## Procedure

### Step 1: Prepare Your Input
Choose one of the three input modes above and provide:
- **Mode 1 (Quick)**: A clear, 1-2 sentence concept description
- **Mode 2 (File)**: Path to markdown file (e.g., `BuildRealWorldAgents_BeginnerToPro/BuildRealWorldAgents_BeginnerToPro_GoodNotes_detailed.md`)
- **Mode 3 (JSON)**: Structured config with concepts and styling preferences
- Optional count control: `png_count_mode`, `png_count`, or `min_one_png_per_topic`

### Step 2: Specify Output Format
Indicate which technique to use:
- **"Excalidraw scene"** → semantic `.excalidraw` output (default)
- **"Compiled PNG"** → consume compiled output for notes/mindmap/deck embedding
- **"Mermaid diagram"** → Structured relationships, multiple styles
- **"Image generation prompt"** → External API-ready, high-fidelity

If not specified, defaults to **Excalidraw scene** and then compiled PNG for delivery.

If style is not explicitly specified, apply **Dynamic Archetype Synchronization** defaults:
- Conceptual Architecture → `architecture`
- Procedural Workflows → `flow-diagram`
- Discrete Components → `conceptual-sketch`

### Step 2.5: Art Director Preflight (Required)
Before final output creation, produce an internal preflight summary:
- `Diagram intent:` <structure | interaction-over-time | workflow-process | state-lifecycle | filtering-routing | decision-tradeoff | layered-control | service-experience | strategy-evolution | teaching-metaphor>
- `Formal framework:` <c4 | sequence | bpmn | state-diagram | wardley-map | service-blueprint | custom-semantic-sketch | etc>
- `Scene family candidates:` <2-3 ranked scene families>
- `Selected scene family:` <the winning candidate>
- `Selection reason:` <why this scene family best matches the mechanism>
- `Formal companion suggested:` <none | recommended | strongly-recommended>
- `Core mechanism:` <technical mechanism>
- `Chosen archetype:` <system architecture | process/pipeline | concept vs concept>
- `Physical analogy:` <concrete real-world scene>
- `Label fusion:` <where technical labels are embedded in the scene>
- `Composition intent:` <how the scene shows cause/effect and constraints>
- `Hot path:` <dominant execution path or explanatory path>
- `Main constraint:` <what pressure, bottleneck, or rule must stay visible>
- `Visual scene type:` <e.g. cargo-screening-line | QA-lane | layered-theater-stack | machine-room-hub>
- `Scene objects:` <the actual objects to draw>
- `Object-to-concept map:` <which object represents which technical concept>
- `Dominant motion:` <the main visible movement or directional behavior>
- `Failure branch:` <what off-path failure or pressure state is shown>
- `Forbidden template:` <what generic diagram pattern must not be used>
- `Visual salience plan:` <what the learner should notice first, second, and last>
- `Hot path encoding:` <how the primary route is emphasized via position, stroke, color, or scale>
- `Secondary path encoding:` <how non-primary paths are visually demoted>
- `Planning text hidden from final image:` yes/no
- `Arrow routing plan:` <how connectors attach to edges and avoid crossing key objects>
- `Occlusion plan:` <which shapes need opaque bodies or alternate routing so arrows do not show through them>
- `Object palette:` <concrete scene objects allowed for this lesson>
- `Shape quota:` <maximum rectangle share and required object diversity>
- `Forbidden geometry:` <box rows/stacks or other layouts that are disallowed>
- `Label budget:` <max visible labels/captions in final learner-facing image>
- `Scene test:` <how to prove the image is not just a relabeled template>
- `Salience goal:` <what should be seen first, second, and third>
- `Silhouette plan:` <how major objects differ by outline>
- `Silhouette contrast rules:` <which object roles must differ clearly>
- `Prop density:` <how many supporting props and where they sit>
- `Prop inventory:` <which props reinforce the metaphor>
- `Asymmetry plan:` <how the layout avoids sterile perfect-grid balance>
- `Anti-card-framing plan:` <how the scene avoids becoming a board of cards>
- `Scene texture:` <subtle environmental texture cues>
- `Texture inventory:` <which environment marks ground the scene>
- `Premium scene test:` <how to prove the scene feels like a sketch-world, not a worksheet>
- `Style anchor appended:` yes/no

Also include:
- `Excalidraw style contract:` `roughness=2`, `fillStyle=hachure`, `fontFamily=1`, `palette=deep navy + cyan`

Do not render final output until all required fields are resolved.

For learner-facing premium scenes, also record which pass in `premium-generation-playbook.md` produced each major improvement:
- silhouette
- hot path
- failure branch
- props
- asymmetry
- texture
- connector hygiene

### Step 3: Set Course Context
Specify the target course folder:
```
Course: BuildRealWorldAgents_BeginnerToPro
Module: Section 3 - Agent Tool Integration
Concept: How tools are registered and called
```

The skill saves scene source files using naming convention: `<CourseName>_<ModuleName>_sketch_<ConceptName>.excalidraw`, then compiles to `.png` with the same base name.

### Step 4: Request Generation
Invoke with:
```
/content-to-sketch
Input: [concept description OR file path OR JSON config]
Format: [excalidraw-scene | compiled-PNG | mermaid | image-prompt]
Course: [CourseName]
Optional—Module: [ModuleName]
Optional—Style: [style preference]
Optional—PNG Count Mode: [per-topic | fixed | topic-density]
Optional—PNG Count: [number]
```

Examples:
```text
Generate PNGs for each topic in this file. Minimum one PNG per topic.
```

```text
Generate 12 PNGs total, but ensure every topic gets at least one.
```

```text
Generate PNGs for all topics in this markdown. Use topic-density mode and create extra PNGs only for dense sections.
```

### Step 5: Review & Integrate
- **assets/Mermaid**: Image files auto-saved to course folder
- **Image Prompts**: Use prompts with DALL-E or your preferred tool; embed results manually
- Add image references to `<CourseName>_GoodNotes_detailed.md`:
  ```markdown
  ### Tool Integration Concept
  ![Tool Integration Sketch](./assets/BuildRealWorldAgents_BeginnerToPro_Section3_Tool_Integration_sketch.png)
  
  Agents use external tools by:
  1. Registering available APIs
  2. Selecting tools based on goals
  3. Executing and processing results
  ```

## Integration with Notes Pipelines

This skill is **automatically invoked** by all to-notes skills:

### With `transcript-to-notes` Skill (Step 2)
When generating study notes from a transcript, content-to-sketch is called after lesson ingestion but before final notes/mm/xmind and must:
- Consume the lesson's semantic visual brief rather than only its title
- Run Art Director preflight for each lesson
- Generate one `.excalidraw` + one `.png` minimum per lesson
- Validate all PNGs before transcript-to-notes proceeds to markdown generation
- Emit `assets/INDEX.md` as the authoritative sketch inventory

### With `md-to-notes` Skill (Step 6)
When converting markdown documentation to study notes:
- Consume semantic section visual briefs rather than raw headings alone
- Generate architectural diagrams and process flows
- Create visual glossary for technical terms
- Embed in ADHD-friendly chunked notes

### With `pdf-to-notes` Skill (Step 6)
When transforming PDF books to study materials:
- Consume semantic chapter visual briefs rather than raw chapter headings alone
- Create chapter summary visualizations
- Generate concept relationship diagrams
- Visualize key frameworks and models
- Embed in action-oriented study notes

### Manual Invocation
After any to-notes skill completes, you can also request additional visuals:
```
I've just created BuildRealWorldAgents_BeginnerToPro_GoodNotes_detailed.md
from the transcript. Generate hand-drawn PNG sketches for 
each ## section in this file.
```

## Best Practices

1. **Concept Clarity**: Provide clear, specific concept descriptions (2-3 sentences ideal)
2. **Naming Consistency**: Use course folder conventions for saved images
3. **Batch Efficiency**: Use Mode 2 (markdown file) for entire course visualization and let topic count drive the minimum Excalidraw scene count
4. **Style Cohesion**: Choose one dominant format (PNG or Mermaid) per course for visual consistency
5. **Markdown Integration**: Always embed generated images in study notes for context
6. **Styling Options**: Use clean whiteboard background (no grid)
7. **Coverage Rule**: For study-note workflows, every topic should receive at least one PNG unless the user explicitly excludes it
8. **Hot Path Prioritization**: In `architecture` and `flow-diagram`, visually emphasize the primary execution path and demote secondary paths
9. **Mechanism Labels**: Use micro-captions that explain node function in 2-5 words, not noun-only labels

## Supported Style Presets

| Style | Best For | Example Technique |
|-------|----------|-------------------|
| `flow-diagram` | Process flows, decision trees | PNG with arrows and boxes |
| `architecture` | System design, component relationships | Mermaid diagram or PNG |
| `mindmap` | Concept hierarchies, brainstorming | Mermaid mindmap |
| `timeline` | Sequential learning, project phases | Mermaid timeline |
| `conceptual-sketch` | Abstract ideas, metaphors | PNG freeform doodle |
| `entity-relationship` | Data models, relationships | Mermaid flowchart or PNG |

## Dynamic Archetype Synchronization

When upstream notes pipelines provide archetype metadata (or when archetype is inferable from concept text), style selection must default as follows:

| Content Archetype | Default Visual Style | Visual Intent |
|-------------------|----------------------|---------------|
| Conceptual Architecture | `architecture` | System context, component boundaries, interaction paths |
| Procedural Workflows | `flow-diagram` | Step-by-step state transitions and execution flow |
| Discrete Components | `conceptual-sketch` | Internal mechanics and analogy-driven understanding |
| Concept vs Concept | `conceptual-sketch` or `flow-diagram` (split composition) | Side-by-side trade-offs with explicit contrast |

Rules:
- If a user explicitly requests a different style, honor the user override.
- If no style is provided, use the archetype default.
- For batch Mode 2 and Mode 3, apply this mapping per topic/concept, not globally.
- For `Concept vs Concept`, the drawing must include explicit comparative structure (split-screen, scale, or diverging path), not two independent text clusters.

## Cognitive Load Management

Apply this section as a strict constraint for all `architecture` and `flow-diagram` outputs.

### Hot Path Rule (Mandatory)
- Identify the primary execution path (the shortest path that explains the core mechanism).
- Visually prioritize the primary path using one or more of:
  - thicker strokes
  - higher contrast
  - primary color emphasis
  - stronger arrow prominence
- Visually demote secondary systems, optional branches, and edge cases using one or more of:
  - dashed lines
  - grayscale or muted palette
  - lower opacity
  - smaller annotation weight

### Clutter Control
- Keep secondary labels shorter than primary-path labels.
- Limit competing highlights so only one dominant visual path exists per diagram.
- Avoid equal visual weight across all nodes; hierarchy must be obvious at a glance.

### Arrow Routing & Occlusion Hygiene (Mandatory)
- Arrows must attach to the **edge** of a shape, not terminate in the visual middle of a box, ellipse, or diamond.
- Prefer orthogonal or gently bent routing when a straight line would cut across unrelated objects.
- Primary-path arrows must remain easy to trace at notebook reading distance.
- Do not let arrows visually run through label text whenever a clean reroute is possible.
- If a connector would pass behind a neutral shape, give that shape an opaque fill so the connector does not show through the shape body.
- Use arrow z-order intentionally: connectors should usually sit behind node bodies and in front of background decoration.
- If the route is still visually ambiguous, regenerate the scene geometry rather than accepting overlap.

## Analogy-Driven Conceptualization

Apply this section as a strict constraint for `conceptual-sketch` outputs.

### Mandate
- Prohibit generic cloud-and-box diagrams.
- Prohibit `What / How / Why` text-grid diagrams even when technically accurate.
- Map abstract software patterns to concrete, high-efficiency physical systems.
- The visual metaphor must clarify mechanism, not just decorate the concept.

### Art Director Quality Gate
- The final visual must allow a learner to infer mechanism from shape/flow even if labels are briefly hidden.
- Labels should annotate moving parts of the metaphor, not replace the drawing.
- If removing labels does not materially change comprehension, the image is likely too text-dependent and must be redrawn.
- If the same geometry could be reused for a different lesson by changing only the text labels, the image fails the semantic gate and must be redrawn.
- The chosen `visualSceneType` must be visible in the final composition, not merely named in the brief.
- The hot path must be visually dominant without requiring a visible sentence such as `Hot path: ...` in the learner-facing image.
- Planning/debug text such as `Scene:`, `Mechanism:`, `Analogy:`, `Must show:`, and `Forbidden template:` must not appear in the final learner-facing output.
- Labels intended to live inside shape bodies must remain inside the target shape bounds; overflow is a quality failure.
- Connectors must attach cleanly to object edges and should not visibly cut through important node bodies when a clean reroute is possible.
- Arrow/connector overlap with node interiors is a quality failure unless the shape is intentionally acting as a pass-through surface.
- A box-row or box-stack fallback is a quality failure when the concept called for a richer physical scene.
- If more than the allowed `shapeQuota.maxPlainRectangles` of primary objects are plain rectangles, the scene fails and must be regenerated.
- `objectPalette`, `forbiddenGeometry`, `labelBudget`, and `sceneTest` are mandatory controls, not optional decoration.
- Final learner-facing scenes should feel like a world, not a worksheet: distinct silhouettes, a small number of supporting props, controlled asymmetry, low card-framing, and subtle scene texture are required.
- If the scene still reads like a neat dashboard of cards after premium refinement, it fails the premium sketch gate and must be redrawn.
- Premium render passes are sequential and cumulative; skipping silhouette/prop/asymmetry/texture passes and going straight to labels is a process failure.

### Prompting Examples
- Visualize a parallel processing bottleneck using the mechanics of a traffic funnel.
- Visualize rapid context-switching architecture using synchronized choreography of a motorsport pit stop.
- Visualize backpressure and queue saturation using a loading dock with constrained conveyor capacity.

### Analogy Quality Rule
- Each conceptual sketch must include at least one explicit analogy anchor in the caption, title, or callout.
- The analogy must map to the actual system behavior (throughput, contention, sequencing, retries, etc.).

## PNG Labeling Requirements (Micro-Captions)

Upgrade node labeling and accessibility requirements as follows:

- Noun-only node labels are not allowed (for example: `API Gateway`).
- Use **Micro-Captions** that encode mechanism in 2-5 words.
- Preferred format: `Node Name (Mechanism)`.

Examples:
- `API Gateway (Routes & Throttles)`
- `Worker Pool (Executes Parallel Jobs)`
- `Retry Queue (Buffers Failed Calls)`

Label quality rules:
- Every primary-path node must have a mechanism-bearing micro-caption.
- Secondary-path nodes may be shorter but must still indicate function.
- Keep labels concise and scannable for GoodNotes reading distance.

## Excalidraw Compiler Contract

- Source files: `.excalidraw`
- Compiled delivery files: `.png`
- Markdown/XMind/Deck pipelines must reference `.png`, never raw `.excalidraw`.
- `.excalidraw` remains the editable source of truth.
- **Hand-drawn export parity is mandatory**: the compiled PNG must visually preserve Excalidraw roughness, hachure fill, and Virgil-style hand-drawn character.
- **Browser export is the default and required path** for production-quality PNGs.
- **Fallback renderers are disabled by default** because they can flatten or sanitize the Excalidraw sketch aesthetic. Only enable fallback intentionally with `EXCALIDRAW_ALLOW_FALLBACK_RENDERER=1` when debugging.
- Final learner-facing diagrams must not expose internal planning metadata.
- The headless compiler supports three runtime modes:
  - local package runtime from this skill's own `node_modules/@excalidraw/excalidraw/dist/prod/index.js`
  - explicit self-hosted runtime via `--module-url` / `EXCALIDRAW_MODULE_URL`
  - explicit asset/font path via `--asset-path` / `EXCALIDRAW_ASSET_PATH`
- Optional convenience mode: `--self-host-base-url` / `EXCALIDRAW_SELF_HOST_BASE_URL` assumes the runtime entry is served from `<base>/dist/prod/index.js` and fonts from `<base>/dist/prod/`.
- Skill-specific runtime helpers stay co-located in this skill folder (`scripts/`) so the skill remains portable across repositories and operating systems.
- Browser launch is cross-platform:
  - honors `--browser-path`, `EXCALIDRAW_BROWSER_PATH`, or `PUPPETEER_EXECUTABLE_PATH`
  - otherwise auto-detects Chrome/Chromium/Edge on Windows, macOS, and Linux
  - if no browser is present, run `npm run browser:install` inside this skill folder
  - on Linux/WSL, the downloaded browser may still require native shared libraries; prefer a native Linux Chrome/Chromium path when available

## Troubleshooting

**Problem**: PNG looks too clean, empty, or generic  
**Solution**: First verify the PNG came from the browser-based Excalidraw exporter, not a fallback renderer. Fix the browser/runtime path and recompile. If the scene itself is weak, regenerate through Art Director preflight with stronger mechanism/analogy mapping; do not swap to another format as a workaround.

**Problem**: The `.excalidraw` file looks hand-drawn in Excalidraw, but the exported PNG does not  
**Solution**: Treat this as an export-parity failure. Re-run `scripts/compile-excalidraw.js` with a working browser runtime. Do not accept fallback-rendered output unless `EXCALIDRAW_ALLOW_FALLBACK_RENDERER=1` was set intentionally.

**Problem**: Mermaid feels too structured for a free-form concept  
**Solution**: Use PNG sketch mode for artistic freedom

**Problem**: Want external image generation but no API yet  
**Solution**: Request image generation **prompts** (Markdown file); manually submit to DALL-E/Midjourney later

**Problem**: Batch generation created too many images  
**Solution**: Switch to `png_count_mode: fixed`, exclude minor subsections, or define the exact topic list in Mode 3 JSON

**Problem**: Not enough images were generated  
**Solution**: Use `png_count_mode: per-topic` and set `min_one_png_per_topic: true`, or request a higher explicit `png_count`

## ✅ Verified Working Workflow

**Tested with Copilot Studio course notes:**
- ✓ 7 hand-drawn PNG sketches generated successfully
- ✓ All sketches embedded in markdown file with im

…(truncated)
