How tour-builder Creates Dependency-Ordered Learning Tours in Understand-Anything

The tour-builder agent generates dependency-ordered learning tours by either prompting an LLM with the project's knowledge graph structure or falling back to a topological sort algorithm that respects code dependencies.

The Understand-Anything project from Egonex-AI provides an intelligent way to explore unfamiliar codebases through guided tours. The tour-builder component analyzes the structural dependencies of source code to create step-by-step learning paths that ensure learners encounter concepts in a logical order. This article examines how the tour-builder creates dependency-ordered learning tours by dissecting the implementation in tour-generator.ts and the agent orchestration logic.

How the Tour-Builder Pipeline Works

The tour-builder follows a dual-path strategy for generating tours. It first attempts to use a Large Language Model (LLM) to generate human-readable tours based on the knowledge graph. If the LLM is unavailable or returns invalid data, it falls back to a deterministic heuristic algorithm that performs topological sorting on the dependency graph.

According to the agent specification in agents/tour-builder.md, the decision flow follows this logic:

  1. If an LLM is configured and the prompt succeeds, parse the LLM response.
  2. If the parsed steps are empty, fall back to the heuristic algorithm.
  3. If no LLM is available, generate the tour entirely from graph topology.

LLM-Based Tour Generation

When a language model is available, the tour-builder constructs a detailed prompt describing the entire knowledge graph and requests a structured JSON response.

Building the Prompt with buildTourGenerationPrompt

The buildTourGenerationPrompt function in tour-generator.ts (line 7) constructs a comprehensive prompt that includes:

  • Project metadata
  • All nodes formatted as - [type] name (path): summary
  • All edges formatted as - source --type--> target
  • Output specifications requiring ordered steps with titles, descriptions, node IDs, and optional language notes

This detailed context allows the LLM to understand the codebase structure and suggest a logical learning progression that respects actual dependencies.

Parsing Responses with parseTourGenerationResponse

The parseTourGenerationResponse function in tour-generator.ts (line 70) handles the raw LLM output. It extracts JSON blocks from markdown code fences, validates each tour step for required fields (numeric order, non-empty title and description, at least one nodeIds), and returns a clean array of TourStep objects. If parsing fails or validation errors occur, the function returns an empty array, triggering the fallback mechanism.

Heuristic Fallback Algorithm

When LLM generation fails or is unavailable, the generateHeuristicTour function in tour-generator.ts (line 122) creates a dependency-ordered tour using graph theory principles.

Topological Sorting with Kahn's Algorithm

The heuristic algorithm implements Kahn's algorithm to ensure dependencies are respected:

  1. Separate concept nodes (type concept) from regular code nodes to handle them separately.
  2. Build adjacency and indegree maps for code nodes only.
  3. Identify entry points by finding nodes with zero incoming edges.
  4. Perform topological sort using a queue-based approach that processes nodes only after all their dependencies have been visited.

This ensures that learners never encounter a module before its dependencies are explained.

Handling Concept Nodes and Layers

The algorithm includes two additional refinements:

  • Layer awareness: If the knowledge graph contains explicit layers, nodes are grouped by layer while preserving topological order. If no layers exist, the algorithm batches three nodes per step.
  • Concept aggregation: After processing all code nodes, any concept nodes are added as a final "Key Concepts" step, ensuring theoretical foundations are taught in context after practical code examples.

Implementation Examples

Generating a Tour Using the Heuristic Algorithm

import { generateHeuristicTour } from '@understand-anything/core/analyzer/tour-generator';
import type { KnowledgeGraph } from '@understand-anything/core/types';

// Assume `graph` is the KnowledgeGraph produced by the analysis pipeline
const tourSteps = generateHeuristicTour(graph);

// `tourSteps` is an array of TourStep objects ready for the UI
console.log(tourSteps);

Using an LLM with Heuristic Fallback

import {
  buildTourGenerationPrompt,
  parseTourGenerationResponse,
  generateHeuristicTour,
} from '@understand-anything/core/analyzer/tour-generator';
import type { KnowledgeGraph, TourStep } from '@understand-anything/core/types';
import { callLLM } from '@understand-anything/core/llm'; // fictional wrapper

async function getTour(graph: KnowledgeGraph): Promise<TourStep[]> {
  const prompt = buildTourGenerationPrompt(graph);
  const llmReply = await callLLM(prompt);     // returns raw string

  const parsed = parseTourGenerationResponse(llmReply);
  return parsed.length ? parsed : generateHeuristicTour(graph);
}

Rendering the Tour in a React Dashboard

import { useTour } from '@/hooks/useTour';

function TourPanel() {
  const { steps } = useTour(); // reads from `.understand-anything` intermediate storage
  return (
    <ul>
      {steps.map((s) => (
        <li key={s.order}>
          <strong>{s.title}</strong> – {s.description}
        </li>
      ))}
    </ul>
  );
}

Key Files in the Implementation

The tour-builder functionality spans several files in the Egonex-AI/Understand-Anything repository:

  • tour-generator.ts: Contains buildTourGenerationPrompt, parseTourGenerationResponse, and generateHeuristicTour functions.
  • agents/tour-builder.md: Documents the high-level agent orchestration and decision flow.
  • types.ts: Defines KnowledgeGraph, TourStep, Node, Edge, and Layer interfaces.
  • tour-generator.test.ts: Unit tests validating both LLM-based and heuristic generation paths.

Summary

  • The tour-builder creates dependency-ordered learning tours through a dual-path approach: LLM generation with heuristic fallback.
  • buildTourGenerationPrompt constructs detailed knowledge graph descriptions for LLM consumption at line 7 of tour-generator.ts.
  • parseTourGenerationResponse validates and sanitizes LLM outputs, extracting structured TourStep arrays at line 70.
  • generateHeuristicTour implements Kahn's topological sort algorithm at line 122 to ensure code dependencies are respected when LLM generation fails.
  • Concept nodes are separated from code nodes and presented as a final "Key Concepts" step.
  • The resulting tour steps are stored in intermediate files and consumed by the dashboard UI for interactive rendering.

Frequently Asked Questions

How does the tour-builder handle circular dependencies in the codebase?

When using the heuristic algorithm, the topological sort naturally handles circular dependencies by only processing nodes whose indegree reaches zero. If a cycle exists, nodes in the cycle will have at least one incoming edge remaining, causing them to be processed after the acyclic portions of the graph. The LLM-based approach may attempt to intelligently break cycles based on semantic understanding, but the heuristic ensures deterministic behavior by processing available nodes in layer order.

What happens if the LLM returns an invalid tour structure?

The parseTourGenerationResponse function validates each step for required fields including numeric order, non-empty title and description, and at least one nodeIds entry. If any validation fails or the JSON parsing encounters an error, the function returns an empty array. This empty result triggers the orchestration logic to fall back to generateHeuristicTour, ensuring users always receive a valid tour even when LLM outputs are malformed.

Can the tour-builder work without any LLM configuration?

Yes. When no LLM is configured or available, the agent skips the prompt-based generation entirely and calls generateHeuristicTour directly. This function performs a complete topological analysis of the knowledge graph using Kahn's algorithm, groups nodes by layers if available, and produces a valid tour structure without any external API dependencies. This makes the system fully functional for offline or privacy-sensitive environments.

How are concept nodes different from code nodes in tour generation?

Concept nodes (type concept) represent abstract ideas or theoretical foundations rather than specific files or functions. During heuristic generation, these nodes are separated from the code dependency graph and added as a final "Key Concepts" step after all practical code modules are explained. This ensures learners understand the implementation before studying the underlying theory, or can review concepts after seeing them applied in context.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →