# Autogen Guide

> Generate interactive guide content.json files from source code. Analyzes React/TypeScript UI components to extract structure, selectors, field metadata, and conditional logic, then produces a Pathfinder guide JSON. Use when the user provides GitHub links to source code and wants to create a guide from it, or asks to auto-generate a guide from code.

- Skill: `grafana/autogen-guide` (Agent Skill, multi-file: 3 files)
- Install (CLI): `npx skillmds@latest add grafana/autogen-guide`
- Raw SKILL.md: https://api.skillmd.com/api/skills/grafana/autogen-guide/raw
- Safety review: pending
- Works with: Claude Code, Claude.ai, OpenAI Codex
- Category: Web & Frontend
- Author: grafana (https://skillmd.com/u/grafana)
- Updated: 2026-09-17
- Page: https://skillmd.com/skills/grafana/autogen-guide

---


# AutoGen Guide from Source Code

Generate an interactive guide `content.json` by analyzing UI source code. This skill orchestrates a multi-phase pipeline where **each phase runs in a sub-agent that loads only the context it needs**. The orchestrator (you) manages the workflow, user interactions, and handoffs.

**Do NOT read external reference files upfront.** Each phase's sub-agent loads its own references. Everything the orchestrator needs is inline below.

This skill implements the **skill-memory convention**. See `.cursor/skills/skill-memory.md` for the shared `assets/`, manifest, and frontmatter standards that this skill extends.

---

## Workflow Overview

```
Input (GitHub URLs)
  │
  ├─ Phase 0: Check for Prior Run ── orchestrator
  │    Output: skip or warm-start based on manifest
  │
  ├─ Phase 1: Acquire & Scope ────── orchestrator (no external reads)
  │    Runs: extract_components.py → assets/component-extraction.json
  │    Writes: source files fetched, scope confirmed by user
  │    Creates: {guide_dir}/assets/
  │
  ├─ Phase 2: Extract & Assess ───── sub-agent loads shared/critical-rules.md
  │    │                               + extraction-patterns.md + selector-strategies.md
  │    │                               + reads assets/component-extraction.json
  │    Writes: {guide_dir}/assets/extraction-report.md
  │
  ├─ Checkpoint: Plan ────────────── orchestrator builds plan, user confirms
  │    Writes: {guide_dir}/assets/guide-plan.md
  │
  ├─ Checkpoint: Package Metadata ── orchestrator gathers manifest fields from user
  │    Writes: {guide_dir}/assets/package-metadata.json
  │
  ├─ Phase 3: Generate Guide ──────── per-section sub-agents, each loads authoring-guide.mdc
  │    │                               + shared/critical-rules.md
  │    │                               + receives component-extraction.json context for its section
  │    │  3.1 Create guide shell (orchestrator)
  │    │  3.2 For each section → sub-agent generates section JSON
  │    │  3.3 Assemble via assemble_guide.py → content.json (with validation)
  │    │  3.4 Generate assets/selector-report.md (orchestrator)
  │    Writes: {guide_dir}/content.json + {guide_dir}/assets/selector-report.md
  │
  ├─ Phase 4: Review & Fix ──────── sub-agent loads review-guide-pr.mdc
  │    Writes: fixed content.json + change report
  │
  ├─ Phase 5a: Write Skill Memory ── orchestrator
  │    Writes: {guide_dir}/assets/manifest.yaml
  │
  ├─ Phase 5b: Generate Package Manifest ── orchestrator
  │    Runs: generate_manifest.py → {guide_dir}/manifest.json
  │
  └─ Phase 6: Validate Package ──── orchestrator
       Runs: assemble_guide.py --validate-only + optional CLI validate --package
```

---

## Critical Rules

Read `.cursor/skills/shared/critical-rules.md` for rules 1–15. These apply to ALL generated guides and are passed to sub-agents in their prompts.

---

## Generated Files

The skill's deliverable lives at the output directory root. Everything in `assets/` is skill-internal context — not consumed by the end product.

```
{guide_dir}/
  content.json                    ← the deliverable (Pathfinder guide)
  manifest.json                   ← the package manifest (generated in Phase 5b)
  assets/
    extraction-report.md          ← component analysis, fields, selectors, grades
    guide-plan.md                 ← section structure and source file assignments
    selector-report.md            ← selector quality assessment
    package-metadata.json         ← manifest fields gathered at Package Metadata checkpoint
    manifest.yaml                 ← provenance, drift detection, skill memory
```

`assets/` files are auto-generated and should not be edited manually.

### Frontmatter disclaimer

Every generated markdown file in `assets/` **must** start with the standard frontmatter from the skill-memory convention, extended with source-specific fields:

```markdown
---
disclaimer: Auto-generated by autogen-guide skill. Do not edit manually.
notice: To regenerate, re-run the skill against this source.
input_sha256: {hex digest}
source: {owner}/{repo}@{commit_sha}:{path}
---
```

### Manifest file

After all phases complete, write `{guide_dir}/assets/manifest.yaml`:

```yaml
# Auto-generated by autogen-guide skill. Do not edit manually.
schema_version: 1
skill_name: "autogen-guide"
generated_at: "{ISO 8601 timestamp}"
input_sha256: "{hex digest — see below}"

source:
  repo: "{owner}/{repo}"
  branch: "{branch}"
  path: "{path}"
  commit_sha: "{sha}"

guide:
  id: "{guide_id}"
  sections:
    - "{section-id-1}"
    - "{section-id-2}"
  total_steps: {N}
  selector_quality:
    green: {N}
    yellow: {N}
    red: {N}

files:
  extraction_report: "assets/extraction-report.md"
  guide_plan: "assets/guide-plan.md"
  selector_report: "assets/selector-report.md"
```

Compute `input_sha256` by hashing the source identity — the commit SHA is the natural fingerprint for source code drift:

```bash
echo -n "{owner}/{repo}:{path}@{commit_sha}" | shasum -a 256
```

This means cosmetic guide edits (title wording, step reordering) do not trigger re-extraction — only an actual source code change does.

---

## Golden Examples

These examples show the target output quality for common UI patterns. Pass the relevant ones to each section's sub-agent.

### Example A: Tab with conditional fields

The most common section pattern. Tab click → fields → conditional fields with `skippable` + `hint`.

```json
{
  "intro": {
    "type": "markdown",
    "content": "Choose how the datasource authenticates with your API. Most public APIs need no auth; private APIs typically use Bearer tokens or API keys."
  },
  "section": {
    "type": "section",
    "id": "authentication-settings",
    "title": "Authentication Settings",
    "requirements": ["on-page:/connections/datasources/edit"],
    "blocks": [
      {
        "type": "interactive",
        "action": "button",
        "reftarget": "Authentication",
        "content": "Click the **Authentication** tab.",
        "tooltip": "Configure credentials for APIs that require authentication."
      },
      {
        "type": "interactive",
        "action": "button",
        "reftarget": "Bearer Token",
        "doIt": false,
        "content": "**Bearer Token** sends a static token in the Authorization header.",
        "tooltip": "Use for JWT-based APIs or personal access tokens.",
        "skippable": true,
        "hint": "Select the auth method that matches your API."
      },
      {
        "type": "interactive",
        "action": "highlight",
        "reftarget": "[aria-label='bearer token']",
        "doIt": false,
        "content": "Paste your **Bearer token** here.",
        "tooltip": "Stored encrypted. Sent as Authorization: Bearer <token> with every request.",
        "skippable": true,
        "hint": "Select Bearer Token auth first to reveal this field."
      }
    ]
  },
  "summary": {
    "type": "markdown",
    "content": "Each auth method reveals its own credential fields when selected."
  }
}
```

Key things: section bookends (intro markdown immediately before each section, summary immediately after — not inside), tab-click before fields, `skippable: true` with `hint` on conditional fields, `doIt: false` on secrets, include `exists-reftarget` in requirements for selector-targeting steps, concise tooltips that don't name the highlighted element.

### Example B: Card grid selection

When the UI uses clickable cards (not a dropdown) for choosing an option. Each card is a `button` action with `doIt: false`.

```json
{
  "type": "interactive",
  "action": "button",
  "reftarget": "Basic Authentication",
  "doIt": false,
  "content": "**Basic Authentication** encodes username and password in the Authorization header.",
  "tooltip": "Sends credentials with every request. Use for simple APIs.",
  "skippable": true,
  "hint": "Click any auth card to see its fields."
}
```

Key things: `action: "button"` with the card's visible text, `doIt: false` so the user makes the choice, `skippable` because only one card applies.

### Example C: Toggle switches and field arrays

Toggles get `doIt: false` with an explanatory tooltip. Field arrays (add/remove) get the "Add" button highlighted with `doIt: false`.

```json
[
  {
    "type": "interactive",
    "action": "highlight",
    "reftarget": "label:has(span:contains('Skip TLS Verify'))",
    "doIt": false,
    "content": "**Skip TLS Verify** disables certificate validation.",
    "tooltip": "Not recommended for production. Only for dev with self-signed certs.",
    "skippable": true,
    "hint": "Scroll to TLS / SSL Settings within the Network tab."
  },
  {
    "type": "interactive",
    "action": "button",
    "reftarget": "Add Custom HTTP Header",
    "doIt": false,
    "content": "Click **Add Custom HTTP Header** to add key-value headers sent with every request.",
    "tooltip": "Common uses: API versioning, content type, request tracing.",
    "skippable": true
  }
]
```

Key things: toggles always `doIt: false`, field array uses button action on "Add" text with `doIt: false` (don't try to interact with dynamic row items).

### Example D: Tab navigation when tab has no stable selector

When a tab has no `data-testid`, use `:contains()` pseudo-selector with `doIt: false` and a `hint`. If the tab text is unique, `action: "button"` with the tab text can work.

```json
{
  "type": "interactive",
  "action": "button",
  "reftarget": "Network",
  "doIt": false,
  "content": "Click the **Network** tab for timeout, TLS/SSL, and proxy settings.",
  "tooltip": "Configure connection behavior and security certificates."
}
```

Key things: `action: "button"` with the tab label text. If the text isn't unique on the page, use `"reftarget": "div[role='tab']:contains('Network')"` or similar structural selector. Always `doIt: false` when the selector is fragile.

### Example E: markdown for complex concepts

When no single element can be targeted but the user needs context. Prefer `markdown` over `noop` so Pathfinder does not number the prose as a step. Use `noop` only for an intentional numbered pause that is not a click/type instruction.

```json
{
  "type": "markdown",
  "content": "**Proxy Settings** offer three modes: **Default** (uses environment vars), **None** (direct), and **URL** (custom proxy). Choose **URL** when you need custom proxy fields."
}
```

Key things: `markdown` for explanation without a selector. Do not use `noop` as a flaky-selector fallback or for “click / enter / select …” copy. Keep it brief.

---

## Phase 0: Check for Prior Run (Orchestrator)

Before starting the full generation pipeline, check whether this guide has been generated before.

1. Check whether `{guide_dir}/assets/manifest.yaml` exists
2. If it does: read the manifest, extract `input_sha256` and `generated_at`
3. Re-hash the current input: `echo -n "{owner}/{repo}:{path}@{current_commit_sha}" | shasum -a 256`
4. Compare hashes:
   - **Match** → no drift; tell the user the guide is up to date and offer options: skip to Phase 4 review, re-generate a specific section, or proceed with a full fresh run
   - **Mismatch** → drift detected; tell the user the source has changed since `{generated_at}` (commit `{stored_sha}` → `{current_sha}`), then proceed with a delta-aware re-run using prior `assets/extraction-report.md` as warm-start context for the Phase 2 sub-agent
5. If manifest does not exist: fresh run — proceed to Phase 1

```
assets/manifest.yaml exists?
  No  → full generation pipeline (Phase 1 onward)
  Yes → re-hash input
          matches stored hash?
            Yes → offer user: skip to review, re-gen section, or fresh run
            No  → delta re-run (use prior assets/ as warm start, then Phase 1 onward)
```

---

## Phase 1: Acquire and Scope (Orchestrator)

You handle this phase directly. No sub-agent needed -- it's mostly tool calls.

### 1.1 Parse the Input

The user provides GitHub references:
- **File URL**: `https://github.com/org/repo/blob/main/src/ConfigEditor.tsx`
- **Directory URL**: `https://github.com/org/repo/tree/main/src/editors/config/`
- **Repo + path hint**: `https://github.com/org/repo` with "look at `src/editors/`"

Extract: `owner`, `repo`, `branch`, `path(s)`.

### 1.2 Fetch the Source Code

Shallow-clone the repo:

```bash
git clone --depth 1 --single-branch --branch <branch> https://github.com/<owner>/<repo>.git /tmp/autogen-<repo>
```

Or for individual files, use the GitHub MCP tools (`get_file_contents`) or `gh` CLI.

If the user has already cloned the repo or provides local file paths, use those directly.

### 1.3 Assess Scope

After fetching the source files, run the component extraction script to get a deterministic count:

```bash
python .cursor/tools/extract_components.py {source_file_1} {source_file_2} ... > {guide_dir}/assets/component-extraction.json
```

Use the `scopeEstimate` output to present scope to the user:

> "The linked directory contains {totalFieldSets} field groups and {totalComponents} interactive elements. This will produce a guide with approximately {N} sections and {M} steps. Should I proceed, narrow, or expand?"

Scope guidelines:
- **< 5 elements**: Too small. Suggest expanding.
- **5-40 elements**: Good scope for one guide.
- **40-80 elements**: Large. Consider splitting into multiple guides.
- **> 80 elements**: Must split or narrow.

### 1.4 Identify the Entry Point

Look for:
- The file the user linked directly
- Default exports named `ConfigEditor`, `QueryEditor`, `SettingsPage`, or similar
- The component registered in `module.ts` or `plugin.json`

### 1.5 Map the Component Tree

From the entry point:
1. Read the entry file, identify local imports (skip `@grafana/*`, `react`, etc.)
2. For each imported component, read its file (one level deep max)
3. Note which file renders which sub-components

Record the commit SHA for provenance:
```bash
git -C /tmp/autogen-<repo> rev-parse HEAD
```

### 1.6 Create the Guide Directory

Create `{guide-id}/` in the workspace root and `{guide-id}/assets/` for generated analysis files. The `guide-id` should be kebab-case, derived from the component's purpose (e.g., `infinity-config-tour`).

Proceed to Phase 2 after the user confirms scope.

---

## Phase 2: Extract & Assess (Sub-Agent)

Launch a sub-agent using the Task tool. This sub-agent loads the extraction and selector reference files, analyzes the source code, and writes a structured report.

### Sub-agent prompt template

Before launching the sub-agent, the orchestrator runs the extraction script:

```bash
python .cursor/tools/extract_components.py {source_files} > {guide_dir}/assets/component-extraction.json
```

The sub-agent receives this structured JSON as context (instead of reading raw source files to enumerate components), and its job shifts to **interpreting** the extraction — identifying section groupings, assessing UI patterns, and writing the prose extraction report.

Fill in `{placeholders}` and pass as the Task prompt:

```
You are analyzing React/TypeScript UI source code to produce an extraction report for a Pathfinder guide.

**Read these reference files first:**
1. `.cursor/skills/shared/critical-rules.md` -- rules 1-15 that apply to all guides
2. `.cursor/skills/autogen-guide/extraction-patterns.md` -- component patterns, props extraction, conditional logic
3. `.cursor/skills/autogen-guide/selector-strategies.md` -- selector grading (Green/Yellow/Red), quality report template

**Pre-computed component extraction** (read this file — components, selectors, and grades are already computed):
{guide_dir}/assets/component-extraction.json

**Source files for context** (read only sections relevant to your section grouping decisions):
{list_of_source_file_paths}

**Entry point component**: {entry_point_file}

**Your task:**
1. Read the component-extraction.json — component inventory, selector grades, and FieldSet groupings are already computed; DO NOT re-count or re-grade from scratch
2. Interpret the extraction: identify logical section groupings (FieldSets map to sections; tabs/sub-components may also create sections)
3. Note UI patterns per section (tab nav, card grid, toggles, field arrays, nested conditionals)
4. Check for plugin.json if present -- extract plugin ID and name
5. Flag any grading caveats (HOC wrapping risks, wrapper mismatches noted in selector-strategies.md)

**Write your results** to `{guide_dir}/assets/extraction-report.md` using the standard frontmatter followed by this structure:

---
disclaimer: Auto-generated by autogen-guide skill. Do not edit manually.
notice: To regenerate, re-run the skill against this source.
input_sha256: {hex digest}
source: {owner}/{repo}@{commit_sha}:{path}
---

## Extraction Report

**Source**: {repo}@{sha} -- {path}
**Entry point**: {entry_point}
**Files analyzed**: N
**Sections identified**: N (list names)
**Interactive elements**: N (from component-extraction.json scopeEstimate)

### Selector Quality
- N/N Green (data-testid or id)
- N/N Yellow (aria-label, button text, name)
- N/N Red (structural only)

### Sections

For each section:
#### Section Name
- Source: file.tsx (lines N–M)
- Fields: (table with columns: Label, Type, Best Selector, Grade, Conditional?)
- UI patterns: tab nav | card grid | toggles | field array | nested conditionals | none

### Conditional Fields
- field → depends on condition

### Weak Selectors
(table with: Element, File:Line, Best Available, Suggested Fix)

**Return** a brief summary: sections found, element count, selector quality breakdown, and any concerns.
```

After the sub-agent completes, present the extraction report summary to the user.

---

## Checkpoint: Build the Guide Plan (Orchestrator)

After the user sees the extraction report, build a structural plan. Read `{guide_dir}/assets/extraction-report.md` and produce `{guide_dir}/assets/guide-plan.md` with the standard frontmatter followed by:

```markdown
---
disclaimer: Auto-generated by autogen-guide skill. Do not edit manually.
notice: To regenerate, re-run the skill against this source.
input_sha256: {hex digest}
source: {owner}/{repo}@{commit_sha}:{path}
---

## Guide Plan

**Guide ID**: {guide-id}
**Title**: {Guide Title}
**Guide type**: Product Tour | Setup Guide | Feature Deep-Dive | Workflow Guide
**Target page**: /connections/datasources/edit (or wherever the guide operates)
**Plugin ID**: {plugin-id} (if applicable)

### Navigation Sequence
How the user reaches the target page (e.g., Main menu → Connections → Data sources → [instance])

### Sections

#### 1. {Section Name}
- Section ID: {kebab-case-id}
- Source file: {path/to/component.tsx} (lines N–M)
- Tab/navigation prerequisite: "Click the Authentication tab" (or none)
- Fields: {count} (target 3–8 interactive steps)
- Key fields: {list of field labels}
- Conditional groups: {e.g., "Bearer Token fields shown when auth type = bearer"}
- UI patterns: tab nav | card grid | toggles | field array | nested conditionals
- Requirements: [on-page:/path]
- Objectives: [] (if any)
- Chains from: independent | section-completed:{previous-id} (only if dependent)

#### 2. {Section Name}
...

### Section Chaining
Only chain when section N creates something section N+1 depends on.
Independent tabs/pages should NOT chain — use `on-page:/path` instead.

### Notes
- Conditional field handling strategy
- Known weak selectors and how they'll be handled
- Any sections that should be skippable
- Step budget concerns (any sections that may exceed 8 steps)
```

**Present the plan to the user.** Let them adjust section order, add/remove sections, or change the navigation sequence before proceeding. Confirm the source file mapping is correct — Phase 3 will pass these code snippets to per-section sub-agents.

---

## Checkpoint: Package Metadata (Orchestrator)

Before generating guide content, gather package metadata from the user.
Present defaults where possible and ask for confirmation or overrides.

**Auto-derived (confirm with user):**
- `id`: {guide-id from plan}
- `description`: {1-line summary derived from extraction report}
- `type`: "guide"

**Requires user input:**
- `category`: What category does this guide belong to?
  Suggest based on context (e.g., "data-availability" for datasource guides,
  "general" as fallback). Present as a question.
- `startingLocation`: Where in Grafana does this guide launch?
  Suggest from target page in plan (e.g., "/connections/datasources/edit").
- `targeting.match`: Where should this guide be recommended?
  Suggest `{ "urlPrefix": "..." }` based on startingLocation.
  Present the suggestion and ask the user to confirm or customize.
- `testEnvironment`: Where should this guide be tested?
  Default suggestion: `{ "tier": "cloud" }`.
- `author.team`: Default "interactive-learning". Ask if different.

Store the confirmed metadata in `{guide_dir}/assets/package-metadata.json`
for use in Phase 5b manifest generation.

```json
{
  "contentJsonPath": "{guide_dir}/content.json",
  "type": "guide",
  "description": "...",
  "category": "...",
  "author": { "team": "interactive-learning" },
  "startingLocation": "...",
  "targeting": { "match": { "urlPrefix": "..." } },
  "testEnvironment": { "tier": "cloud" }
}
```

---

## Phase 3: Generate Guide (Per-Section Sub-Agents)

Instead of one monolithic sub-agent, generate the guide **section by section**. This keeps each sub-agent's context small and focused, prevents quality degradation in later sections, and allows source code context to flow through.

### 3.1 Orchestrator: Create the Guide Shell

Write the initial `{guide_dir}/content.json` with root structure and intro markdown:

```json
{
  "id": "{guide_id}",
  "title": "{guide_title}",
  "blocks": [
    {
      "type": "markdown",
      "content": "{brief intro — what the guide covers, no markdown title}"
    }
  ]
}
```

### 3.2 For Each Section: Launch a Sub-Agent

Iterate through the sections in `{guide_dir}/assets/guide-plan.md`. For each section, launch a sub-agent that generates just that section's JSON.

**Step budget**: aim for **3–8 interactive steps per section**. If a section would need more than 10, split it into sub-sections in the plan first. A complete guide should have **25–50 interactive steps** total.

#### Per-section sub-agent prompt template

Fill in `{placeholders}` and launch via the Task tool:

```
You are generating ONE section of a Pathfinder interactive guide as a JSON object.

**Read these reference files first:**
1. `.cursor/authoring-guide.mdc` -- block types, action types, requirements, best practices
2. `.cursor/skills/shared/critical-rules.md` -- rules 1-15 that apply to all guides (violations are blocking)

**Section to generate:**
- Section ID: {section_id}
- Section title: {section_title}
- Requirements: {section_requirements_array}
- Objectives: {section_objectives_array_or_none}
- Tab/navigation prerequisite: {tab_click_description_or_none}
- Fields in this section (from component-extraction.json for this section's FieldSet):
{extraction_data_for_this_section}

**Source code context** (relevant JSX for this section):
```tsx
{source_code_snippet_for_this_section}
```

**Action decision tree:**
- Select/dropdown → `highlight` with `doIt: false`, explain options in tooltip
- Input with sensible default → `formfill` with targetvalue
- Input without sensible default → `highlight` with `doIt: false`, tooltip explains
- Switch/toggle → `highlight` with `doIt: false`, tooltip explains when to enable
- Button with stable text → `action: "button"`, reftarget: "Button Text"
- SecretInput → always `doIt: false`, never fill secrets
- Red/Yellow selector for input → always `doIt: false`
- Card grid (clickable cards) → `action: "button"` with card text, `doIt: false`, `skippable: true`
- Field array (add/remove) → highlight "Add" button with `doIt: false`, explain the pattern
- Collapsible section → add expand step before child fields
- Tab with no data-testid → `action: "button"` with tab text, `doIt: false`

**Step budget:** Generate 3–8 interactive steps for this section. If the section has more fields than that, prioritize the most important ones and mention the rest in the intro or summary markdown.

**Golden example:**
{paste the matching golden example from SKILL.md — choose the example that best matches this section's UI patterns}

**Your task:**
1. Return a **section package** (not a bare section):
   ```json
   {
     "intro": {"type": "markdown", "content": "1-sentence what you'll do"},
     "section": {"type": "section", "id": "{section_id}", "title": "...", "blocks": [/* interactive steps only */]},
     "summary": {"type": "markdown", "content": "1-sentence what you learned"}
   }
   ```
2. Do **not** put intro/summary markdown inside the section (Pathfinder may number in-section markdown as a step). Interactive steps only inside `section.blocks`.
3. If a tab click is needed, that's the first interactive step
4. Generate steps for each field per the action decision tree
5. Return ONLY the section package JSON — no guide root. `assemble_guide.py` interleaves intro → section → summary.

**Also return** a brief text summary: step count, any selectors you're uncertain about, any fields you omitted and why.
```

#### Building the source code context

For each section, include the **relevant source code snippet** — the JSX that renders this section's UI. Extract this during Phase 2 or at orchestration time:

1. Read the component file identified in the extraction report for this section
2. Find the JSX fragment that renders this section's fields (search for the FieldSet, tab panel, or component boundary)
3. Include 30–80 lines of the relevant JSX in the prompt (trim imports and unrelated code)
4. If the section maps to a sub-component, include that sub-component's full JSX return

This gives the sub-agent direct access to prop names, conditional rendering, and selector attributes — not just the extraction summary.

#### Choosing which golden example to pass

Match the section's UI patterns to the golden examples:

| Section pattern | Golden example |
|----------------|---------------|
| Tab with form fields + conditionals | Example A |
| Card/button grid for selection | Example B |
| Toggle switches or field arrays | Example C |
| Tab with no stable selector | Example D |
| Complex concept needing noop | Example E |
| Mix of patterns | Pass Examples A + the most relevant other |

### 3.3 Orchestrator: Assemble the Guide

After all section sub-agents complete:

1. **Write each returned section package** to a temporary file: `{guide_dir}/assets/section-{section_id}.json` (must include `intro`, `section`, and `summary` — bare section objects fail assembly).
2. **Write the guide-level closing summary** to `{guide_dir}/assets/closing.json` (not into the shell):
   ```json
   {
     "type": "markdown",
     "content": "{summary of what the user explored/configured, list the key sections, suggest next steps}"
   }
   ```
   Keep the shell as **opening blocks only**. Putting closing markdown in the shell before `--sections` yields `intro → closing → sections` and breaks rule 14 bookends.
3. **Run the assembly script** to interleave bookends and validate:
   ```bash
   python .cursor/tools/assemble_guide.py \
     --shell {guide_dir}/assets/guide-shell.json \
     --sections {guide_dir}/assets/section-*.json \
     --closing {guide_dir}/assets/closing.json \
     --output {guide_dir}/content.json
   ```
   The script interleaves each package as intro → section → summary, appends `--closing` last, and **fails** (exit 1) on missing or misordered required bookends. Also validates unique section IDs, no multistep singletons, tooltip lengths, step counts, and no noop-only sections.
4. **If validation fails**: fix the flagged issues in the section package files and re-run.
5. **Spot-check**: read the assembled `blocks` array — each section must sit between its intro and summary markdown.

### 3.4 Orchestrator: Generate Selector Report

After assembly, write `{guide_dir}/assets/selector-report.md` by collating sub-agent feedback. Start the file with the standard frontmatter disclaimer, then:

```markdown
---
disclaimer: Auto-generated by autogen-guide skill. Do not edit manually.
notice: To regenerate, re-run the skill against this source.
input_sha256: {hex digest}
source: {owner}/{repo}@{commit_sha}:{path}
---

## Selector Quality Report

**Generated from**: `{owner}/{repo}@{sha}`
**Date**: {date}
**Guide**: `{guide_id}/content.json`

### Summary
- **Total interactive steps**: N
- **Green (data-testid/id)**: n (percent%)
- **Yellow (aria-label/button text)**: n (percent%)
- **Red (structural only)**: n (percent%)

### Uncertain Selectors
(list selectors that sub-agents flagged as uncertain)

### Suggestions for Source Code Authors
(list elements that would benefit from `data-testid` attributes)
```

### Section chaining guidance

Not every section needs `section-completed:previous`. Use chaining only when a prior section **creates something** the next section depends on:

| Relationship | Use `section-completed`? |
|-------------|------------------------|
| Section 1 creates a datasource, section 2 queries it | Yes |
| Section 1 is "Authentication," section 2 is "Network" (independent tabs) | No |
| Section 1 navigates to a page, section 2 uses elements on that page | No — use `on-page:/path` instead |
| Section is optional / educational only | No |

---

## Phase 4: Review & Fix (Sub-Agent)

Launch a sub-agent to review and fix the assembled guide.

### Sub-agent prompt template

```
You are reviewing an auto-generated Pathfinder guide for quality and correctness.

**Read this reference file first:**
1. `.cursor/review-guide-pr.mdc` -- complete review protocol (sections 1-4 are blocking checks)

**Then read the guide:**
2. `{guide_dir}/content.json`

**Apply every check from sections 1-4** of the review protocol against the guide JSON.

**Additionally check for these auto-generation-specific issues:**
{tailored_items}

For each issue found, **fix it directly** in `{guide_dir}/content.json`.

After fixing all issues, **return a report**:
- List of issues found and how each was fixed
- Any issues that couldn't be auto-fixed (need human decision)
- Confirmation that the guide JSON is valid/parseable
- Confirmation that all section IDs are unique
- Confirmation that the requirements chain is logical
- Step count per section (flag any section with 0 interactive steps or >10)
```

### Building the tailored review checklist

Before launching the review sub-agent, build `{tailored_items}` systematically from the Phase 2 extraction report. Walk through each category and include the item if it applies:

```
**Conditional fields** (include if extraction found conditional rendering):
- These fields are conditional: {list field labels and their conditions}
- Verify each has `skippable: true` and `hint` text explaining the prerequisite
- Verify the prerequisite step (e.g., auth method selection) appears before dependent fields

**Yellow selectors** (include if Yellow-grade selectors were used):
- These steps use Yellow selectors: {list step descriptions and selectors}
- For inputs: verify `doIt: false`
- For buttons: verify `action: "button"` with text match
- Verify tooltips explain the interaction

**Red selectors** (include if Red-grade selectors were used):
- These steps use Red (fragile) selectors: {list step descriptions and selectors}
- ALL must have `doIt: false`
- ALL must have educational tooltips

**Tab navigation** (include if the guide has tabbed UI):
- Tabs in this guide: {list tab names}
- Verify each tab section starts with an interactive step targeting the tab
- Verify the tab-click step uses `action: "button"` with tab text or a stable selector
- Tabs should NOT be targeted via markdown "Click the X tab" — use an interactive step

**Secret fields** (include if SecretInput components were found):
- These fields are secrets: {list labels}
- ALL must have `doIt: false`
- Tooltip should mention values are stored encrypted

**Section chaining** (include always):
- Verify `section-completed` is only used when section N creates something section N+1 depends on
- Independent sections (e.g., different config tabs) should NOT chain
- Every section should have `on-page:/path` if its elements are page-specific

**Step budget** (include always):
- Verify each section has 3–8 interactive steps
- Flag sections with 0 or 1 interactive steps (too thin)
- Flag sections with >10 interactive steps (should be split)
```

---

## Phase 5a: Write Skill Memory Manifest (Orchestrator)

After Phase 4 completes, write `{guide_dir}/assets/manifest.yaml`. Gather the values from prior phases:

- `generated_at`: current ISO 8601 timestamp
- `input_sha256`: computed in Phase 0 / Phase 1 (same value used in frontmatter)
- `commit_sha`: recorded in Phase 1.5
- `sections`: list of section IDs from the assembled guide
- `total_steps`, `selector_quality`: from Phase 4 review report output

```yaml
# Auto-generated by autogen-guide skill. Do not edit manually.
schema_version: 1
skill_name: "autogen-guide"
generated_at: "{ISO 8601 timestamp}"
input_sha256: "{hex digest}"

source:
  repo: "{owner}/{repo}"
  branch: "{branch}"
  path: "{path}"
  commit_sha: "{sha}"

guide:
  id: "{guide_id}"
  sections:
    - "{section-id-1}"
    - "{section-id-2}"
  total_steps: {N}
  selector_quality:
    green: {N}
    yellow: {N}
    red: {N}

files:
  extraction_report: "assets/extraction-report.md"
  guide_plan: "assets/guide-plan.md"
  selector_report: "assets/selector-report.md"
```

This manifest is the entry point for future maintenance runs (Phase 0).

---

## Phase 5b: Generate Package Manifest (Orchestrator)

Generate the Pathfinder package `manifest.json` using the metadata gathered at the Package Metadata checkpoint.

1. Run the manifest generation script:
   ```bash
   python .cursor/tools/generate_manifest.py \
     --input {guide_dir}/assets/package-metadata.json \
     --content {guide_dir}/content.json \
     --output {guide_dir}/manifest.json
   ```

2. The script validates that the `id` in `package-metadata.json` matches the `id` in `content.json` and exits with an error if they differ.

3. Present the generated `manifest.json` to the user for final review before proceeding.

---

## Phase 6: Validate Package (Orchestrator)

After manifest generation:

1. **Run structural validation** on the assembled guide:
   ```bash
   python .cursor/tools/assemble_guide.py --validate-only {guide_dir}/content.json
   ```

2. **Run Pathfinder CLI validation** if available (check for a `grafana-pathfinder-app` checkout):
   ```bash
   node {pathfinder-app}/dist/cli/cli/index.js validate --package {guide_dir}
   ```
   If the CLI is not available, report this as incomplete and instruct the user to run validation manually. The package is still usable but unvalidated.

---

## Final Delivery (Orchestrator)

After Phase 6 completes:

1. **Read the review report** -- check if any issues couldn't be auto-fixed
2. **Validate JSON** -- ensure `{guide_dir}/content.json` parses correctly
3. **Spot-check** -- read the first and last sections to verify bookends and structure
4. **Present to the user** -- summarize what was generated:
   - Guide location: `{guide_dir}/content.json`
   - Package manifest: `{guide_dir}/manifest.json`
   - Sections: N (list names)
   - Total interactive steps: N (average per section)
   - Selector quality: N Green, N Yellow, N Red
   - Any compromises, omitted fields, or known issues
   - Review fixes applied
5. **Note the manifest** -- the `manifest.json` has been generated alongside the guide. If you need this guide to appear in contextual recommendations, verify the `targeting.match` rules.
6. **Note selector improvements** -- point the user to `assets/selector-report.md` for upstream `data-testid` suggestions

---

## External Dependencies

This skill reads two files **outside** its own directory. If they are moved or renamed, sub-agent phases will fail silently:

- `.cursor/authoring-guide.mdc` — block types, action types, requirements (read by Phase 3 section sub-agents)
- `.cursor/review-guide-pr.mdc` — complete review protocol (read by Phase 4 review sub-agent)

This skill implements the **skill-memory convention**. See `.cursor/skills/skill-memory.md` for the shared `assets/`, manifest, and frontmatter standards that this skill extends.

---

## Optional Inputs

The user may provide additional context. Use it when available:

| Input | How to Use |
|-------|-----------|
| **Guide type hint** | "config tour", "setup guide" → influences plan structure |
| **Target page path** | `/connections/datasources/edit` → use in `on-page:` requirements |
| **Plugin ID** | `yesoreyeram-infinity-datasource` → use in `plugin-enabled:` requirement |
| **Audience** | "beginners", "admins" → adjust tone and skippable steps |

---

## Error Handling

### Source code is not React/TypeScript
Report immediately. This skill is designed for React/TSX UI components. For other frameworks, describe what you found and suggest manual guide authoring with the `/new` command.

### No stable selectors found
Generate the guide anyway with all `doIt: false` steps. Every step becomes educational (show-only). Include a prominent note in the extraction report. The guide is still valuable for learning the UI, even if it can't automate interactions.

### Imports from external packages
When a component imports from packages you can't read (e.g., `@company/shared-components`), note the gap. Use the component's props and surrounding context to infer what it renders. Flag uncertainty in the extraction report.

### Very large codebase
If the component tree exceeds 15 files or 3000 lines, stop expanding imports and work with what you have. Report the boundary. Suggest the user narrow scope or split into multiple guides.

### Sub-agent failures
If a sub-agent returns an error or incomplete result, read its output, diagnose the issue, and either retry with adjusted parameters or handle the phase manually as a fallback.

