# How the Tour-Builder Generates Dependency-Ordered Learning Tours in Understand-Anything

> Discover how the Understand-Anything tour builder creates dependency-ordered learning tours using a two-phase pipeline that analyzes knowledge graphs and synthesizes pedagogical sequences.

- Repository: [Yuxiang Lin/Understand-Anything](https://github.com/Lum1104/Understand-Anything)
- Tags: internals
- Published: 2026-06-06

---

**The `tour-builder` agent creates dependency-ordered learning tours by executing a two-phase pipeline: first computing structural signals (fan-in rankings, BFS traversal depths, and tightly-coupled clusters) from the knowledge graph via a Node.js analysis script, then synthesizing these signals into a pedagogical sequence that respects actual import and call dependencies.**

The tour-builder is a specialized agent in the [Lum1104/Understand-Anything](https://github.com/Lum1104/Understand-Anything) project that transforms static codebase analysis into interactive learning paths. By analyzing import relationships and call graphs produced by earlier `/understand` pipeline phases, it constructs tours that guide newcomers through code in the exact order dependencies naturally unfold. This ensures learners encounter foundational modules before the files that consume them, creating a pedagogically sound narrative arc.

## Two-Phase Architecture

The tour-builder's operation splits cleanly between **graph analysis** and **pedagogical assembly**, coordinated through JSON intermediates that preserve dependency metadata.

### Phase 1 – Graph-Topology Script

The agent first generates and executes a Node.js script (with Python fallback) that consumes the full knowledge-graph JSON produced by preceding pipeline phases. This script reads the graph's **nodes**, **edges**, and **layers**, then computes six critical structural signals:

| Signal | What it measures | How it drives the tour |
|--------|------------------|------------------------|
| **Fan-In ranking** | Count of incoming edges (how many nodes depend on this) | High fan-in nodes are "important" and introduced early to establish central concepts. |
| **Fan-Out ranking** | Count of outgoing edges (how many dependencies this node has) | High fan-out nodes provide broad architectural overview and become early "orientation" stops. |
| **Entry-point candidates** | Heuristic scoring based on filename, depth, fan-out, fan-in, with special handling for [`README.md`](https://github.com/Lum1104/Understand-Anything/blob/main/README.md) | The highest-scoring candidate becomes Step 1 (or Step 2 if documentation exists). |
| **BFS traversal from entry point** | Breadth-first walk following `imports`/`calls` edges forward only | BFS depth levels map directly to tour steps, ensuring dependencies appear before dependents. |
| **Tightly-coupled clusters** | Small groups with bidirectional imports/calls | Merged into single steps to prevent fragmenting related functionality across multiple stops. |
| **Non-code file inventory** | Grouped by type (`document`, `service`, `data`, `config`) | Documentation, Dockerfiles, and schemas are interleaved at logical breakpoints. |

The script writes these results to [`.understand-anything/tmp/ua-tour-results.json`](https://github.com/Lum1104/Understand-Anything/blob/main/.understand-anything/tmp/ua-tour-results.json) with a schema fully documented in [[`agents/tour-builder.md`](https://github.com/Lum1104/Understand-Anything/blob/main/agents/tour-builder.md)](https://github.com/Lum1104/Understand-Anything/blob/main/understand-anything-plugin/agents/tour-builder.md).

### Phase 2 – Pedagogical Tour Design

After the analysis script completes, the tour-builder agent reads the computed JSON and constructs the final learning sequence:

1. **Establish the starting point** – If [`README.md`](https://github.com/Lum1104/Understand-Anything/blob/main/README.md) exists in entry-point candidates, it becomes Step 1; otherwise, the highest-scoring code entry point opens the tour.
2. **Map BFS depth to steps** – The breadth-first traversal order (`depth 0`, `depth 1`, etc.) forms the tour backbone. At each depth level, the agent selects nodes with the highest fan-in/fan-out scores to maximize conceptual coverage.
3. **Inject clusters** – When tightly-coupled clusters overlap a BFS depth, all cluster nodes merge into a single step, emphasizing cohesive functionality.
4. **Respect layer boundaries** – Layer information from Phase 4 of `/understand` (documented in [[`agents/architecture-analyzer.md`](https://github.com/Lum1104/Understand-Anything/blob/main/agents/architecture-analyzer.md)](https://github.com/Lum1104/Understand-Anything/blob/main/understand-anything-plugin/agents/architecture-analyzer.md)) ensures foundational layers precede dependent ones.
5. **Interleave non-code assets** – Documentation appears first, Dockerfiles follow entry points, and data schemas appear after their consuming models.
6. **Generate descriptions** – Using the `nodeSummaryIndex`, the agent writes 2–4 sentence descriptions for each step, explicitly linking current and previous stops while highlighting architectural significance. Optional `languageLesson` fields annotate language-specific patterns (e.g., TypeScript generics, Docker multi-stage builds).

The final output is normalized according to Phase 5 rules in [[`skills/understand/SKILL.md`](https://github.com/Lum1104/Understand-Anything/blob/main/skills/understand/SKILL.md)](https://github.com/Lum1104/Understand-Anything/blob/main/understand-anything-plugin/skills/understand/SKILL.md) (unwrapping envelopes, prefixing paths with `file:`, etc.) before writing to [`.understand-anything/intermediate/tour.json`](https://github.com/Lum1104/Understand-Anything/blob/main/.understand-anything/intermediate/tour.json).

## Why the Tour Follows Dependency Order

The resulting sequence respects true dependency topology through four coordinated mechanisms:

- **BFS-forward traversal** – By following import/call edges strictly forward from the entry point, the tour guarantees learners encounter providers before consumers, eliminating forward-reference confusion.
- **Centrality-weighted selection** – Fan-in/fan-out rankings surface the most architecturally significant files early, establishing mental anchors before exploring peripheral utilities.
- **Cluster consolidation** – Mutually dependent files (circular imports, tight model-service pairs) appear together, preventing cognitive fragmentation where a single concept spans disjointed steps.
- **Layer-enforced narrative** – The high-level layering (infrastructure → domain → application) provides a semantic scaffold that complements the low-level dependency graph.

## Implementation Walkthrough

The tour generation executes via:

```bash

# Phase 1 – Execute the analysis script written by the agent

node $PROJECT_ROOT/.understand-anything/tmp/ua-tour-analyze.js \
    $PROJECT_ROOT/.understand-anything/tmp/ua-tour-input.json \
    $PROJECT_ROOT/.understand-anything/tmp/ua-tour-results.json

```

The intermediate JSON produced by Phase 1 contains structured dependency metadata:

```json
{
  "entryPointCandidates": [
    {"id":"document:README.md","score":5,"name":"README.md"},
    {"id":"file:src/index.ts","score":7,"name":"index.ts"}
  ],
  "bfsTraversal": {
    "startNode":"file:src/index.ts",
    "order":["file:src/index.ts","file:src/config.ts","file:src/services/auth.ts"],
    "byDepth":{"0":["file:src/index.ts"],"1":["file:src/config.ts","file:src/services/auth.ts"]}
  },
  "clusters":[
    {"nodes":["file:src/services/auth.ts","file:src/models/user.ts"],"edgeCount":4}
  ],
  "nonCodeFiles":{
    "documentation":[{"id":"document:README.md","name":"README.md"}],
    "infrastructure":[{"id":"service:Dockerfile","name":"Dockerfile"}]
  }
}

```

Phase 2 transforms this analysis into the final tour structure:

```json
[
  {
    "order": 1,
    "title": "Project Overview",
    "description": "Start with README.md to understand the project's purpose, architecture, and how to get started.",
    "nodeIds": ["document:README.md"]
  },
  {
    "order": 2,
    "title": "Application Entry Point",
    "description": "The main entry point bootstraps the application, importing core modules and starting the server.",
    "nodeIds": ["file:src/index.ts"],
    "languageLesson": "TypeScript barrel files use 'export * from' to re‑export modules, creating a clean public API surface."
  },
  {
    "order": 3,
    "title": "Core Configuration",
    "description": "Configuration files set up environment variables and global settings that the rest of the code consumes.",
    "nodeIds": ["file:src/config.ts"]
  },
  {
    "order": 4,
    "title": "Authentication Service",
    "description": "The Auth service implements user login and token handling, relying on the User model defined nearby.",
    "nodeIds": ["file:src/services/auth.ts","file:src/models/user.ts"]
  }
]

```

## Key Source Files

Understanding the tour-builder requires familiarity with these repository locations:

- **[`agents/tour-builder.md`](https://github.com/Lum1104/Understand-Anything/blob/main/agents/tour-builder.md)** – Complete agent definition including script requirements, signal computation logic, and tour-design heuristics.
- **[`skills/understand/SKILL.md`](https://github.com/Lum1104/Understand-Anything/blob/main/skills/understand/SKILL.md)** (Phase 5) – Orchestrates agent dispatch and defines normalization rules for the final JSON output.
- **[`agents/architecture-analyzer.md`](https://github.com/Lum1104/Understand-Anything/blob/main/agents/architecture-analyzer.md)** – Supplies layer hierarchy data consumed during Phase 2 to enforce high-level ordering constraints.
- **[`.understand-anything/intermediate/tour.json`](https://github.com/Lum1104/Understand-Anything/blob/main/.understand-anything/intermediate/tour.json)** – Default output path for the generated tour (configurable via pipeline environment).

## Summary

- The tour-builder operates in **two distinct phases**: first computing dependency signals via a Node.js graph-analysis script, then assembling a pedagogical tour from those signals.
- **BFS traversal depth** provides the primary ordering skeleton, guaranteeing that code dependencies precede their consumers.
- **Fan-in and fan-out rankings** identify architecturally central files that warrant early introduction, while **cluster detection** prevents fragmenting tightly-coupled modules.
- **Non-code files** (documentation, Dockerfiles, schemas) are explicitly inventoried and interleaved at narrative breakpoints rather than omitted.
- Final output normalization occurs in **Phase 5** of the `/understand` pipeline, as defined in [`SKILL.md`](https://github.com/Lum1104/Understand-Anything/blob/main/SKILL.md), ensuring consistent JSON envelopes and path prefixes.

## Frequently Asked Questions

### What file format does the tour-builder produce?

The tour-builder emits a JSON array of step objects to [`.understand-anything/intermediate/tour.json`](https://github.com/Lum1104/Understand-Anything/blob/main/.understand-anything/intermediate/tour.json) (or a configurable path). Each object contains `order`, `title`, `description`, `nodeIds`, and an optional `languageLesson` field. The schema is normalized during Phase 5 of the pipeline to unwrap legacy envelope formats and standardize path prefixes.

### How does the tour-builder select the starting point?

The agent prioritizes [`README.md`](https://github.com/Lum1104/Understand-Anything/blob/main/README.md) if present in the **entry-point candidates** list, assigning it Step 1 to establish immediate project context. If no README exists, it selects the highest-scoring code entry point based on heuristic scoring (filename patterns, directory depth, fan-out metrics) computed in Phase 1.

### What happens to modules with circular dependencies?

Circular or tightly-coupled modules are detected via **bidirectional edge analysis** in Phase 1 and grouped into clusters. Rather than splitting these across multiple steps (which would fragment the learning narrative), the entire cluster merges into a single tour stop, allowing learners to understand the mutual dependency relationship holistically.

### Where is the normalization logic for tour output defined?

JSON normalization rules—including unwrapping response envelopes, renaming legacy fields like `step` to `order`, and prefixing raw paths with `file:` or `document:`—are documented in **Phase 5 (Tour)** of [[`skills/understand/SKILL.md`](https://github.com/Lum1104/Understand-Anything/blob/main/skills/understand/SKILL.md)](https://github.com/Lum1104/Understand-Anything/blob/main/understand-anything-plugin/skills/understand/SKILL.md). This phase executes after the tour-builder agent completes its work.