Skip to content

Graphs that teach > graphs that impress. Turn any code into an interactive knowledge graph you can explore, search, and ask questions about. Works with Claude Code, Codex, Cursor, Copilot, Gemini CLI, and more.

feat(dashboard): per-file code lessons in the code viewer, aligned with the tour

FallingLight8ddf5d9c6a54
diff --git a/CLAUDE.md b/CLAUDE.md
index 3928a346..a73b03a8 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -14,7 +14,7 @@ An open-source tool combining LLM intelligence + static analysis to produce inte
- **packages/dashboard** — React + TypeScript web dashboard (React Flow, Zustand, TailwindCSS v4)
- **src/** — Skill TypeScript source for `/understand-chat`, `/understand-diff`, `/understand-explain`, `/understand-onboard`
- **skills/** — Skill definitions (`/understand`, `/understand-dashboard`, etc.)
- - **agents/** — Agent definitions (project-scanner, file-analyzer, architecture-analyzer, tour-builder, graph-reviewer)
+ - **agents/** — Agent definitions (project-scanner, file-analyzer, architecture-analyzer, tour-builder, code-lesson-writer, graph-reviewer)
## Dashboard
- Dark luxury theme: deep blacks (#0a0a0a), gold/amber accents (#d4a574), DM Serif Display typography
@@ -22,6 +22,7 @@ An open-source tool combining LLM intelligence + static analysis to produce inte
- No ChatPanel or Monaco Editor
- Sidebar tabs: `Info` (ProjectOverview default → NodeInfo when node selected → LearnPanel in Learn persona, composing) and `Files` (FileExplorer tree built from the structural graph)
- Code viewer: prism-react-renderer source viewer that slides up from the bottom on file node click; an expand button promotes it into a full-screen modal. Source content is fetched from the dev server's `/file-content.json` endpoint, gated by access token + a graph-derived path allowlist
+- Code lessons: `/understand` Phase 5 dispatches the `code-lesson-writer` agent to write `.ua/code-lessons.json` — per-file learning explanations aligned with the tour (detailed sections for tour-covered files, overview-only for the rest). The dev server and `bin/viewer.mjs` serve it from `/code-lessons.json` (same token gate); the code viewer renders it as a right-hand lesson panel where clicking a section highlights its line range. Optional file — absent means no panel. Line ranges may drift on `PARTIAL_UPDATE` until the next tour rerun
- Schema validation on graph load with error banner
## Agent Pipeline
diff --git a/tests/skill/viewer/test_viewer.test.mjs b/tests/skill/viewer/test_viewer.test.mjs
index bcce56c7..5aa1ff06 100644
--- a/tests/skill/viewer/test_viewer.test.mjs
+++ b/tests/skill/viewer/test_viewer.test.mjs
@@ -178,6 +178,37 @@ describe.skipIf(!existsSync(VIEWER_DIST))("understand-anything-viewer", () => {
expect([403, 404]).toContain(res.status);
});
+ it("serves code lessons from the data directory", async () => {
+ // Absent file → 404; the dashboard renders the viewer without lessons.
+ const missing = await fetch(`${base()}/code-lessons.json?token=${viewer.token}`);
+ expect(missing.status).toBe(404);
+
+ const lessons = {
+ version: 1,
+ generatedAt: "2026-10-22T00:00:00.000Z",
+ files: {
+ "src/a.ts": {
+ overview: "Entry fixture.",
+ sections: [
+ { title: "The export", lineRange: [1, 1], explanation: "Declares a.", tourOrder: 1 },
+ ],
+ },
+ },
+ };
+ writeFileSync(join(root, ".ua", "code-lessons.json"), JSON.stringify(lessons));
+
+ const denied = await fetch(`${base()}/code-lessons.json`);
+ expect(denied.status).toBe(403);
+
+ const res = await fetch(`${base()}/code-lessons.json?token=${viewer.token}`);
+ expect(res.status).toBe(200);
+ const body = await res.json();
+ expect(body.files["src/a.ts"].overview).toBe("Entry fixture.");
+ expect(body.files["src/a.ts"].sections[0].lineRange).toEqual([1, 1]);
+
+ rmSync(join(root, ".ua", "code-lessons.json"));
+ });
+
it("falls back to legacy .understand-anything/ projects", async () => {
const legacyRoot = setupProject(".understand-anything");
const legacyViewer = await startViewer(legacyRoot);
diff --git a/understand-anything-plugin/agents/code-lesson-writer.md b/understand-anything-plugin/agents/code-lesson-writer.md
new file mode 100644
index 00000000..268f59e1
--- /dev/null
+++ b/understand-anything-plugin/agents/code-lesson-writer.md
@@ -0,0 +1,124 @@
+---
+name: code-lesson-writer
+description: |
+ Writes per-file learning explanations for the dashboard code viewer. For files
+ covered by the guided tour it reads the actual source and splits it into
+ explained segments aligned with line ranges; for all other files it produces
+ a brief overview from the provided node summaries.
+---
+
+# Code Lesson Writer
+
+You are an expert technical educator who writes source-reading lessons. Your job
+is to produce per-file learning explanations that appear next to the source code
+in the dashboard's code viewer, so a reader can study each file with guidance
+that matches the project's guided tour.
+
+## Task
+
+Given the project's tour steps and file-level node summaries, produce a
+`code-lessons.json` document keyed by file path. Files referenced by the tour
+receive **detailed lessons** (overview + explained segments anchored to line
+ranges, read from the actual source). All other files receive **overview-only
+lessons** composed from the node summaries — do NOT read those files.
+
+**Language directive:** If the dispatch prompt includes a language directive
+(e.g., "Generate all textual content in **Chinese**"), apply it to every
+`title`, `overview`, and `explanation` you write. Keep technical terms clear —
+some concepts may benefit from bilingual explanation (English term + local
+translation). Use native-level terminology appropriate for technical education.
+
+---
+
+## Detailed Lessons (tour-covered files)
+
+For every file that appears in the dispatch prompt's **Detailed files** list:
+
+1. **Read the actual source file** from disk (paths are relative to the
+ provided project root).
+2. **Write an `overview`** (2-5 sentences): what this file is responsible for,
+ how it fits into the project, and how it relates to the tour step(s) that
+ reference it.
+3. **Split the file into 2-10 `sections`** following the file's logical
+ structure (imports, types, constants, one per function/class/method group,
+ exports). Each section:
+ - `title` — short, descriptive (2-6 words)
+ - `lineRange` — `[startLine, endLine]` (1-based, inclusive), MUST match the
+ real lines you read; sections must not overlap
+ - `explanation` — 2-6 sentences of markdown explaining WHAT the code does,
+ WHY it is written this way, and any non-obvious design decisions,
+ patterns, or gotchas worth noticing
+ - `tourOrder` — when a tour step explains this area of the file, the order
+ of that tour step (integer). Omit when no step corresponds.
+
+Sections should collectively cover the significant parts of the file. Boilerplate
+(import blocks of framework files, generated code) may be summarized in a single
+section or skipped when genuinely uninformative.
+
+## Overview-Only Lessons (all other files)
+
+For every remaining file in the dispatch prompt's node list, write an
+`overview` (1-3 sentences) derived from that node's `summary` and the tour
+narrative, with an **empty `sections` array**. Do NOT read these files and do
+NOT invent line ranges.
+
+## Output Format
+
+Produce a single, valid JSON object:
+
+```json
+{
+ "version": 1,
+ "generatedAt": "<ISO 8601 timestamp>",
+ "files": {
+ "src/main.tsx": {
+ "overview": "Application entry point. Mounts the React root and wires global providers...",
+ "sections": [
+ {
+ "title": "Bootstrap and providers",
+ "lineRange": [1, 24],
+ "explanation": "...",
+ "tourOrder": 2
+ }
+ ]
+ },
+ "src/utils/format.ts": {
+ "overview": "Small formatting helpers used across the UI...",
+ "sections": []
+ }
+ }
+}
+```
+
+**Required structure:**
+- `version` — integer, currently `1`
+- `generatedAt` — ISO 8601 timestamp of generation
+- `files` — object keyed by **relative file path with forward slashes**, exactly
+ matching the paths given in the dispatch prompt (never absolute paths)
+- Each entry: `overview` (string, required) and `sections` (array, required)
+
+## Critical Constraints
+
+- NEVER invent line ranges. Every `lineRange` must be verified against the
+ source you actually read for that file.
+- NEVER use absolute paths or backslashes in `files` keys.
+- Sections within one file must not overlap and must have `startLine <= endLine`.
+- At most 10 sections per file.
+- Only files listed in the dispatch prompt may appear in `files`.
+- Trust the provided tour steps and node summaries for project context; only
+ tour-covered files require reading source from disk.
+- Explanations must be grounded in the code you read — do not fabricate
+ behavior, APIs, or design rationale that is not visible in the source or the
+ provided summaries.
+
+## Writing Results
+
+After producing the JSON:
+
+1. Write the JSON object to the exact output path given in your dispatch prompt
+ (normally `$UA_DIR/intermediate/code-lessons.json` inside the project's data
+ directory — `.ua/`, or the legacy `.understand-anything/` when present).
+2. Respond with ONLY a brief text summary: number of detailed lessons and
+ number of overview-only lessons.
+
+Do NOT include the full JSON in your text response.
diff --git a/understand-anything-plugin/packages/core/src/types.ts b/understand-anything-plugin/packages/core/src/types.ts
index e65aa2a1..9b7b4490 100644
--- a/understand-anything-plugin/packages/core/src/types.ts
+++ b/understand-anything-plugin/packages/core/src/types.ts
@@ -93,6 +93,29 @@ export interface TourStep {
languageLesson?: string;
}
+// One explained segment of a source file. When the file is a tour stop,
+// `tourOrder` links the section back to the TourStep with that order.
+export interface CodeLessonSection {
+ title: string;
+ lineRange: [number, number];
+ explanation: string;
+ tourOrder?: number;
+}
+
+// Per-file learning explanation served from the project data directory
+// (`.ua/code-lessons.json`) alongside the knowledge graph.
+export interface CodeLessonFile {
+ overview: string;
+ sections: CodeLessonSection[];
+}
+
+// Root document of code-lessons.json, keyed by graph-relative file path.
+export interface CodeLessons {
+ version: number;
+ generatedAt: string;
+ files: Record<string, CodeLessonFile>;
+}
+
// ProjectMeta
export interface ProjectMeta {
name: string;
diff --git a/understand-anything-plugin/packages/dashboard/src/components/CodeViewer.tsx b/understand-anything-plugin/packages/dashboard/src/components/CodeViewer.tsx
index c7256063..3bac4cfc 100644
--- a/understand-anything-plugin/packages/dashboard/src/components/CodeViewer.tsx
+++ b/understand-anything-plugin/packages/dashboard/src/components/CodeViewer.tsx
@@ -1,7 +1,8 @@
-import { useEffect, useMemo, useState } from "react";
+import { useEffect, useMemo, useRef, useState } from "react";
import { Highlight, themes } from "prism-react-renderer";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
+import type { CodeLessonSection, CodeLessons } from "@understand-anything/core/types";
import { useDashboardStore } from "../store";
import { useI18n } from "../contexts/I18nContext";
@@ -25,6 +26,34 @@ type SourceState =
| { status: "loaded"; source: SourceFile; error: null }
| { status: "error"; source: null; error: string };
+// Module-level cache so the sidebar and modal CodeViewer instances (and
+// repeat opens) share one /code-lessons.json fetch. Only successful loads are
+// cached — a 404 (no lessons yet) is retried on the next file open so lessons
+// generated after this page load still appear without a manual reload.
+let lessonsCache: CodeLessons | null = null;
+let lessonsPromise: Promise<CodeLessons | null> | null = null;
+
+function fetchCodeLessons(token: string): Promise<CodeLessons | null> {
+ if (lessonsCache) return Promise.resolve(lessonsCache);
+ if (!lessonsPromise) {
+ lessonsPromise = fetch(`/code-lessons.json?token=${encodeURIComponent(token)}`)
+ .then(async (res) => {
+ if (!res.ok) return null;
+ const data = (await res.json()) as CodeLessons;
+ if (data && typeof data === "object" && data.files && typeof data.files === "object") {
+ lessonsCache = data;
+ return data;
+ }
+ return null;
+ })
+ .catch(() => null)
+ .finally(() => {
+ lessonsPromise = null;
+ });
+ }
+ return lessonsPromise;
+}
+
function fileContentUrl(filePath: string, token: string): string {
const params = new URLSearchParams({ token, path: filePath });
return `/file-content.json?${params.toString()}`;
@@ -118,6 +147,38 @@ function MarkdownView({ content }: { content: string }) {
);
}
+/** Compact markdown view for lesson explanations, styled for the dark theme. */
+function LessonMarkdown({ content }: { content: string }) {
+ return (
+ <ReactMarkdown
+ components={{
+ p: ({ children }) => <p className="mb-1.5 last:mb-0">{children}</p>,
+ strong: ({ children }) => (
+ <strong className="font-semibold text-text-primary">{children}</strong>
+ ),
+ code: ({ className, children }) => {
+ const isBlock = className?.includes("language-");
+ return isBlock ? (
+ <code className="block bg-elevated rounded px-2 py-1.5 mb-1.5 overflow-x-auto text-[11px] leading-relaxed">
+ {children}
+ </code>
+ ) : (
+ <code className="bg-elevated rounded px-1 py-0.5 text-[11px] text-accent">{children}</code>
+ );
+ },
+ ul: ({ children }) => (
+ <ul className="list-disc list-inside mb-1.5 space-y-0.5">{children}</ul>
+ ),
+ ol: ({ children }) => (
+ <ol className="list-decimal list-inside mb-1.5 space-y-0.5">{children}</ol>
+ ),
+ }}
+ >
+ {content}
+ </ReactMarkdown>
+ );
+}
+
export default function CodeViewer({
accessToken,
presentation = "sidebar",
@@ -144,8 +205,26 @@ export default function CodeViewer({
// Markdown files default to the rendered view (#555); toggle back to
// source for line numbers / lineRange highlighting.
const [mdView, setMdView] = useState<"rendered" | "source">("rendered");
+ // Per-file learning explanations from the project data directory
+ // (.ua/code-lessons.json), aligned with the guided tour.
+ const [lessons, setLessons] = useState<CodeLessons | null>(null);
+ // Line range selected from a lesson section — takes precedence over the
+ // node's own lineRange highlight until deselected or the file changes.
+ const [lessonHighlight, setLessonHighlight] = useState<{ start: number; end: number } | null>(null);
+ const codeScrollRef = useRef<HTMLDivElement | null>(null);
const { t } = useI18n();
+ useEffect(() => {
+ if (accessToken === "__demo__") return;
+ let cancelled = false;
+ fetchCodeLessons(accessToken).then((data) => {
+ if (!cancelled) setLessons(data);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [accessToken]);
+
useEffect(() => {
if (!node?.filePath) {
setState({ status: "error", source: null, error: "This node does not have a file path." });
@@ -163,6 +242,7 @@ export default function CodeViewer({
const controller = new AbortController();
setState({ status: "loading", source: null, error: null });
+ setLessonHighlight(null);
fetch(fileContentUrl(node.filePath, accessToken), { signal: controller.signal })
.then(async (res) => {
@@ -184,10 +264,19 @@ export default function CodeViewer({
return () => controller.abort();
}, [accessToken, node?.filePath]);
+ const lesson = node?.filePath ? lessons?.files[node.filePath] ?? null : null;
+ // A lesson-section selection overrides the node's own lineRange highlight.
const highlightedRange = useMemo(() => {
+ if (lessonHighlight) return lessonHighlight;
if (!node?.lineRange) return null;
return { start: node.lineRange[0], end: node.lineRange[1] };
- }, [node?.lineRange]);
+ }, [lessonHighlight, node?.lineRange]);
+
+ const scrollToLine = (line: number) => {
+ codeScrollRef.current
+ ?.querySelector(`[data-line="${line}"]`)
+ ?.scrollIntoView({ block: "center", behavior: "smooth" });
+ };
if (!node) {
return (
@@ -207,6 +296,16 @@ export default function CodeViewer({
const isModal = presentation === "modal";
const handleClose = onClose ?? closeCodeViewer;
+ const toggleSection = (section: CodeLessonSection) => {
+ const [start, end] = section.lineRange;
+ if (lessonHighlight && lessonHighlight.start === start && lessonHighlight.end === end) {
+ setLessonHighlight(null);
+ return;
+ }
+ setLessonHighlight({ start, end });
+ if (!showRendered) scrollToLine(start);
+ };
+
return (
<div className="h-full w-full flex flex-col bg-surface overflow-hidden">
<div className="flex items-start gap-3 px-4 py-3 bg-elevated border-b border-border-subtle shrink-0">
@@ -261,88 +360,158 @@ export default function CodeViewer({
</div>
</div>
- <div className="flex-1 min-h-0 overflow-auto bg-root">
- {state.status === "loading" && (
- <div className="p-5 text-sm text-text-muted">{t.codeViewer.loading}</div>
- )}
+ <div className="flex-1 min-h-0 flex overflow-hidden bg-root">
+ <div ref={codeScrollRef} className="flex-1 min-w-0 overflow-auto">
+ {state.status === "loading" && (
+ <div className="p-5 text-sm text-text-muted">{t.codeViewer.loading}</div>
+ )}
- {state.status === "error" && (
- <div className="p-5">
- <div className="rounded-lg border border-border-subtle bg-elevated p-4">
- <div className="text-sm font-medium text-text-primary mb-2">{t.codeViewer.sourceUnavailable}</div>
- <p className="text-sm text-text-secondary leading-relaxed">{state.error}</p>
+ {state.status === "error" && (
+ <div className="p-5">
+ <div className="rounded-lg border border-border-subtle bg-elevated p-4">
+ <div className="text-sm font-medium text-text-primary mb-2">{t.codeViewer.sourceUnavailable}</div>
+ <p className="text-sm text-text-secondary leading-relaxed">{state.error}</p>
+ </div>
</div>
- </div>
- )}
+ )}
- {source && (
- <>
- <div className="px-4 py-2 border-b border-border-subtle bg-surface text-[11px] text-text-muted flex items-center justify-between">
- <span>{source.lineCount} {t.codeViewer.linesLabel}</span>
- <div className="flex items-center gap-3">
- {isMarkdown && (
- <div className="flex items-center rounded border border-border-subtle overflow-hidden" role="group">
- {(["rendered", "source"] as const).map((view) => (
- <button
- key={view}
- type="button"
- onClick={() => setMdView(view)}
- className={`px-2 py-0.5 text-[10px] uppercase tracking-wider transition-colors ${
- mdView === view
- ? "bg-accent/15 text-accent"
- : "text-text-muted hover:text-text-primary"
- }`}
- aria-pressed={mdView === view}
- >
- {view === "rendered" ? t.codeViewer.rendered : t.codeViewer.source}
- </button>
- ))}
- </div>
- )}
- <span>{formatBytes(source.sizeBytes)}</span>
+ {source && (
+ <>
+ <div className="px-4 py-2 border-b border-border-subtle bg-surface text-[11px] text-text-muted flex items-center justify-between">
+ <span>{source.lineCount} {t.codeViewer.linesLabel}</span>
+ <div className="flex items-center gap-3">
+ {isMarkdown && (
+ <div className="flex items-center rounded border border-border-subtle overflow-hidden" role="group">
+ {(["rendered", "source"] as const).map((view) => (
+ <button
+ key={view}
+ type="button"
+ onClick={() => setMdView(view)}
+ className={`px-2 py-0.5 text-[10px] uppercase tracking-wider transition-colors ${
+ mdView === view
+ ? "bg-accent/15 text-accent"
+ : "text-text-muted hover:text-text-primary"
+ }`}
+ aria-pressed={mdView === view}
+ >
+ {view === "rendered" ? t.codeViewer.rendered : t.codeViewer.source}
+ </button>
+ ))}
+ </div>
+ )}
+ <span>{formatBytes(source.sizeBytes)}</span>
+ </div>
</div>
+ {showRendered && <MarkdownView content={source.content} />}
+ {!showRendered && (
+ <Highlight code={source.content} language={language} theme={themes.vsDark}>
+ {({ className, style, tokens, getLineProps, getTokenProps }) => (
+ <pre
+ className={`${className} min-w-max p-0 m-0 ${
+ isModal ? "text-xs leading-5" : "text-[11px] leading-5"
+ } font-mono`}
+ style={{ ...style, background: "transparent" }}
+ >
+ {tokens.map((line, index) => {
+ const lineNumber = index + 1;
+ const isHighlighted =
+ highlightedRange !== null &&
+ lineNumber >= highlightedRange.start &&
+ lineNumber <= highlightedRange.end;
+ const lineProps = getLineProps({ line });
+ return (
+ <div
+ key={lineNumber}
+ {...lineProps}
+ data-line={lineNumber}
+ className={`${lineProps.className} flex ${
+ isHighlighted ? "bg-accent/15" : "hover:bg-elevated/40"
+ }`}
+ >
+ <span className="w-12 shrink-0 select-none border-r border-border-subtle pr-3 text-right text-text-muted bg-surface/60">
+ {lineNumber}
+ </span>
+ <span className="pl-3 pr-6 whitespace-pre">
+ {line.map((token, key) => (
+ <span key={key} {...getTokenProps({ token })} />
+ ))}
+ </span>
+ </div>
+ );
+ })}
+ </pre>
+ )}
+ </Highlight>
+ )}
+ </>
+ )}
+ </div>
+
+ {lesson && (
+ <aside className="w-72 xl:w-80 shrink-0 border-l border-border-subtle bg-surface overflow-y-auto">
+ <div className="sticky top-0 z-10 px-4 py-2.5 bg-surface border-b border-border-subtle">
+ <h3 className="text-[11px] font-semibold text-accent uppercase tracking-wider">
+ {t.codeViewer.lesson}
+ </h3>
</div>
- {showRendered && <MarkdownView content={source.content} />}
- {!showRendered && (
- <Highlight code={source.content} language={language} theme={themes.vsDark}>
- {({ className, style, tokens, getLineProps, getTokenProps }) => (
- <pre
- className={`${className} min-w-max p-0 m-0 ${
- isModal ? "text-xs leading-5" : "text-[11px] leading-5"
- } font-mono`}
- style={{ ...style, background: "transparent" }}
- >
- {tokens.map((line, index) => {
- const lineNumber = index + 1;
- const isHighlighted =
- highlightedRange !== null &&
- lineNumber >= highlightedRange.start &&
- lineNumber <= highlightedRange.end;
- const lineProps = getLineProps({ line });
+ <div className="p-4 space-y-3">
+ <div className="text-sm text-text-secondary leading-relaxed">
+ <LessonMarkdown content={lesson.overview} />
+ </div>
+
+ {lesson.sections.length > 0 && (
+ <div className="space-y-2">
+ {lesson.sections.map((section, i) => {
+ const [start, end] = section.lineRange;
+ const active =
+ lessonHighlight !== null &&
+ lessonHighlight.start === start &&
+ lessonHighlight.end === end;
return (
<div
- key={lineNumber}
- {...lineProps}
- className={`${lineProps.className} flex ${
- isHighlighted ? "bg-accent/15" : "hover:bg-elevated/40"
+ key={i}
+ className={`rounded-lg border transition-colors ${
+ active
+ ? "border-accent/40 bg-accent/5"
+ : "border-border-subtle bg-elevated hover:border-accent/20"
}`}
>
- <span className="w-12 shrink-0 select-none border-r border-border-subtle pr-3 text-right text-text-muted bg-surface/60">
- {lineNumber}
- </span>
- <span className="pl-3 pr-6 whitespace-pre">
- {line.map((token, key) => (
- <span key={key} {...getTokenProps({ token })} />
- ))}
- </span>
+ <button
+ type="button"
+ onClick={() => toggleSection(section)}
+ aria-pressed={active}
+ className="w-full text-left px-3 py-2"
+ >
+ <div className="flex items-center gap-2">
+ <span className="text-xs font-medium text-text-primary flex-1 min-w-0 truncate">
+ {section.title}
+ </span>
+ {section.tourOrder !== undefined && (
+ <span className="text-[9px] font-semibold uppercase tracking-wider text-accent border border-accent/30 rounded px-1 py-0.5 shrink-0">
+ {t.codeViewer.tourStep} {section.tourOrder}
+ </span>
+ )}
+ </div>
+ <div className="text-[10px] font-mono text-text-muted mt-0.5">
+ {t.codeViewer.lines} {start}–{end}
+ </div>
+ </button>
+ {active && (
+ <div className="px-3 pb-2.5 pt-2 border-t border-border-subtle/60 text-xs text-text-secondary leading-relaxed">
+ <LessonMarkdown content={section.explanation} />
+ </div>
+ )}
</div>
);
})}
- </pre>
+ </div>
)}
- </Highlight>
- )}
- </>
+
+ {lesson.sections.length === 0 && (
+ <p className="text-[11px] text-text-muted">{t.codeViewer.overviewOnly}</p>
+ )}
+ </div>
+ </aside>
)}
</div>
</div>
diff --git a/understand-anything-plugin/packages/dashboard/src/locales/en.ts b/understand-anything-plugin/packages/dashboard/src/locales/en.ts
index b3600f6b..cbb637bb 100644
--- a/understand-anything-plugin/packages/dashboard/src/locales/en.ts
+++ b/understand-anything-plugin/packages/dashboard/src/locales/en.ts
@@ -183,6 +183,9 @@ export const en = {
sourceUnavailable: "Source unavailable",
rendered: "Rendered",
source: "Source",
+ lesson: "Lesson",
+ tourStep: "Tour",
+ overviewOnly: "Overview only — no section breakdown for this file.",
},
customNode: {
tested: "Tested",
diff --git a/understand-anything-plugin/packages/dashboard/src/locales/ja.ts b/understand-anything-plugin/packages/dashboard/src/locales/ja.ts
index 763c8ebd..3eac0544 100644
--- a/understand-anything-plugin/packages/dashboard/src/locales/ja.ts
+++ b/understand-anything-plugin/packages/dashboard/src/locales/ja.ts
@@ -183,6 +183,9 @@ export const ja = {
sourceUnavailable: "ソースが利用できません",
rendered: "プレビュー",
source: "ソース",
+ lesson: "解説",
+ tourStep: "ツアー",
+ overviewOnly: "このファイルには概要のみあり、セクションごとの解説はありません。",
},
customNode: {
tested: "テスト済み",
diff --git a/understand-anything-plugin/packages/dashboard/src/locales/ko.ts b/understand-anything-plugin/packages/dashboard/src/locales/ko.ts
index c41b37bf..62799226 100644
--- a/understand-anything-plugin/packages/dashboard/src/locales/ko.ts
+++ b/understand-anything-plugin/packages/dashboard/src/locales/ko.ts
@@ -183,6 +183,9 @@ export const ko = {
sourceUnavailable: "소스 사용 불가",
rendered: "렌더링",
source: "소스",
+ lesson: "해설",
+ tourStep: "투어",
+ overviewOnly: "이 파일에는 개요만 있고 구간별 해설이 없습니다.",
},
customNode: {
tested: "테스트됨",
diff --git a/understand-anything-plugin/packages/dashboard/src/locales/ru.ts b/understand-anything-plugin/packages/dashboard/src/locales/ru.ts
index 73a80ca1..30e0f68e 100644
--- a/understand-anything-plugin/packages/dashboard/src/locales/ru.ts
+++ b/understand-anything-plugin/packages/dashboard/src/locales/ru.ts
@@ -183,6 +183,9 @@ export const ru = {
sourceUnavailable: "Исходный код недоступен",
rendered: "Просмотр",
source: "Исходник",
+ lesson: "Конспект",
+ tourStep: "Обзор",
+ overviewOnly: "Для этого файла доступен только обзор — без разбора по секциям.",
},
customNode: {
tested: "Покрыт тестами",
diff --git a/understand-anything-plugin/packages/dashboard/src/locales/vi.ts b/understand-anything-plugin/packages/dashboard/src/locales/vi.ts
index 5c85f35e..c87a9431 100644
--- a/understand-anything-plugin/packages/dashboard/src/locales/vi.ts
+++ b/understand-anything-plugin/packages/dashboard/src/locales/vi.ts
@@ -183,6 +183,9 @@ export const vi = {
sourceUnavailable: "Không có mã nguồn",
rendered: "Đã kết xuất",
source: "Mã nguồn",
+ lesson: "Bài giảng",
+ tourStep: "Tham quan",
+ overviewOnly: "Tệp này chỉ có tổng quan, chưa có giải thích theo từng phần.",
},
customNode: {
tested: "Đã kiểm thử",
diff --git a/understand-anything-plugin/packages/dashboard/src/locales/zh-TW.ts b/understand-anything-plugin/packages/dashboard/src/locales/zh-TW.ts
index a6554384..2155d36f 100644
--- a/understand-anything-plugin/packages/dashboard/src/locales/zh-TW.ts
+++ b/understand-anything-plugin/packages/dashboard/src/locales/zh-TW.ts
@@ -183,6 +183,9 @@ export const zhTW = {
sourceUnavailable: "原始碼不可用",
rendered: "渲染",
source: "原始碼",
+ lesson: "講解",
+ tourStep: "導覽",
+ overviewOnly: "該檔案僅有概覽講解,暫無分段講解。",
},
customNode: {
tested: "已測試",
diff --git a/understand-anything-plugin/packages/dashboard/src/locales/zh.ts b/understand-anything-plugin/packages/dashboard/src/locales/zh.ts
index eeeddf38..d12c9f08 100644
--- a/understand-anything-plugin/packages/dashboard/src/locales/zh.ts
+++ b/understand-anything-plugin/packages/dashboard/src/locales/zh.ts
@@ -183,6 +183,9 @@ export const zh = {
sourceUnavailable: "源码不可用",
rendered: "渲染",
source: "源码",
+ lesson: "讲解",
+ tourStep: "导览",
+ overviewOnly: "该文件仅有概览讲解,暂无分段讲解。",
},
customNode: {
tested: "已测试",
diff --git a/understand-anything-plugin/packages/dashboard/vite.config.ts b/understand-anything-plugin/packages/dashboard/vite.config.ts
index 22391bcf..ff0e2d2d 100644
--- a/understand-anything-plugin/packages/dashboard/vite.config.ts
+++ b/understand-anything-plugin/packages/dashboard/vite.config.ts
@@ -368,6 +368,7 @@ const config: DashboardViteConfig = {
pathname === "/diff-overlay.json" ||
pathname === "/meta.json" ||
pathname === "/config.json" ||
+ pathname === "/code-lessons.json" ||
pathname === "/file-content.json";
if (!isProtectedEndpoint) {
@@ -406,6 +407,26 @@ const config: DashboardViteConfig = {
return;
}
+ if (pathname === "/code-lessons.json") {
+ const lessonsCandidates = graphFileCandidates("code-lessons.json");
+ for (const candidate of lessonsCandidates) {
+ if (!fs.existsSync(candidate)) continue;
+ try {
+ const raw = fs.readFileSync(candidate, "utf-8");
+ res.setHeader("Content-Type", "application/json");
+ res.end(raw);
+ } catch {
+ sendJson(res, 500, { error: "Failed to read code lessons file" });
+ }
+ return;
+ }
+ // Code lessons are optional — absent file means the dashboard
+ // renders the code viewer without the lesson panel.
+ res.statusCode = 404;
+ res.end();
+ return;
+ }
+
const fileName =
pathname === "/diff-overlay.json"
? "diff-overlay.json"
diff --git a/understand-anything-plugin/packages/viewer/bin/viewer.mjs b/understand-anything-plugin/packages/viewer/bin/viewer.mjs
index 6b535a1d..3095518b 100644
--- a/understand-anything-plugin/packages/viewer/bin/viewer.mjs
+++ b/understand-anything-plugin/packages/viewer/bin/viewer.mjs
@@ -312,6 +312,7 @@ const PROTECTED = new Set([
"/diff-overlay.json",
"/meta.json",
"/config.json",
+ "/code-lessons.json",
"/file-content.json",
"/staleness.json",
]);
@@ -363,6 +364,23 @@ const server = createServer((req, res) => {
return;
}
+ if (pathname === "/code-lessons.json") {
+ const candidate = path.join(graphDir, "code-lessons.json");
+ if (fs.existsSync(candidate)) {
+ try {
+ sendJson(res, 200, JSON.parse(fs.readFileSync(candidate, "utf-8")));
+ } catch {
+ sendJson(res, 500, { error: "Failed to read code lessons file" });
+ }
+ return;
+ }
+ // Code lessons are optional — absent file means the dashboard
+ // renders the code viewer without the lesson panel.
+ res.statusCode = 404;
+ res.end();
+ return;
+ }
+
serveGraphJson(res, pathname.slice(1));
});
diff --git a/understand-anything-plugin/skills/understand/SKILL.md b/understand-anything-plugin/skills/understand/SKILL.md
index 778b800c..2b4a4c52 100644
--- a/understand-anything-plugin/skills/understand/SKILL.md
+++ b/understand-anything-plugin/skills/understand/SKILL.md
@@ -554,7 +554,7 @@ All four fields (`id`, `name`, `description`, `nodeIds`) are required.
## Phase 5 — TOUR
-Run this phase for full analysis and for incremental plans where `rerunTour === true`. For `PARTIAL_UPDATE`, dispatch no tour agent and do not rewrite the narrative; finalization only removes dangling node IDs from the existing steps.
+Run this phase for full analysis and for incremental plans where `rerunTour === true`. For `PARTIAL_UPDATE`, dispatch no tour agent and do not rewrite the narrative; finalization only removes dangling node IDs from the existing steps. The code-lessons step below runs under the same condition.
Report to the user: `[Phase 5/7] Building guided tour...`
@@ -625,6 +625,47 @@ Each element of the final `tour` array MUST have this shape:
Required fields: `order`, `title`, `description`, `nodeIds`. Preserve optional `languageLesson` when present.
+### Code Lessons — per-file learning explanations
+
+Run this step whenever the tour is (re)built — full analysis and incremental plans with `rerunTour === true`. For `PARTIAL_UPDATE`, keep the existing `$UA_DIR/code-lessons.json` untouched (line ranges may drift slightly; the next `rerunTour` rebuild refreshes them).
+
+Report to the user: `[Phase 5/7] Writing code lessons...`
+
+1. **Resolve tour-covered files.** For each normalized tour step, resolve every `nodeIds` entry to its file-level node and collect the node's `filePath`. Record for each covered file the smallest referencing step `order` as its primary tour anchor.
+
+2. **Dispatch a subagent** using the `code-lesson-writer` agent definition (at `agents/code-lesson-writer.md`). Pass these parameters in the dispatch prompt:
+
+> Write per-file code lessons for this codebase.
+> Project root: `$PROJECT_ROOT`
+> Write output to: `$UA_DIR/intermediate/code-lessons.json`
+>
+> Tour steps:
+> ```json
+> [<the normalized tour array>]
+> ```
+>
+> Detailed files (read source from disk; produce overview + sections):
+> ```json
+> [{"filePath": "src/main.tsx", "tourOrder": 2}, ...]
+> ```
+>
+> All other file-level nodes (overview only — do NOT read these files):
+> ```json
+> [list of {filePath, summary} for every file-level node NOT in the detailed list]
+> ```
+>
+> $LANGUAGE_DIRECTIVE
+
+3. **Normalize** `$UA_DIR/intermediate/code-lessons.json` into the final `$UA_DIR/code-lessons.json`. Apply these steps **in order**:
+ 1. **Unwrap envelope:** Accept both `{ "files": {...} }` and a bare files object at the top level.
+ 2. **Drop unknown files:** Remove entries whose key does not exactly match a file-level node's `filePath` (relative, forward slashes).
+ 3. **Validate sections:** `lineRange` must be two integers `[start, end]` with `1 <= start <= end`; drop invalid sections, then enforce a maximum of 10 sections per file (truncate beyond that).
+ 4. **Validate tour anchors:** Drop any `tourOrder` that does not match a tour step's `order`.
+ 5. **Fallback overview:** If `overview` is missing or empty, substitute the matching node's `summary`.
+ 6. **Stamp metadata:** Ensure `version: 1` and `generatedAt` (current ISO 8601 timestamp) are present.
+
+4. **On failure:** retry the dispatch once (see Error Handling); if it still fails, skip lessons entirely — do not write a partial `$UA_DIR/code-lessons.json`, record the failure in `$PHASE_WARNINGS`, and continue. The dashboard degrades gracefully when the file is absent.
+
### Incremental deterministic save gate
After the applicable Phase 4/5 work is complete, finalize either incremental action:
@@ -870,6 +911,7 @@ Report to the user: `[Phase 7/7] Saving knowledge graph...`
- Edges created (broken down by type)
- Layers identified (with names)
- Tour steps generated (count)
+ - Code lessons written (detailed / overview-only counts; report when skipped)
- Any warnings from the reviewer
- Path to the output file: `$UA_DIR/knowledge-graph.json`
diff --git a/understand-anything-plugin/skills/understand/prepare-incremental.mjs b/understand-anything-plugin/skills/understand/prepare-incremental.mjs
index 9b8d0c61..d15063ea 100644
--- a/understand-anything-plugin/skills/understand/prepare-incremental.mjs
+++ b/understand-anything-plugin/skills/understand/prepare-incremental.mjs
@@ -123,6 +123,7 @@ function clearIncrementalScratch(intermediateDir) {
'batches.json',
'layers.json',
'tour.json',
+ 'code-lessons.json',
'incremental-symbol-report.json',
'incremental-edge-candidates.json',
]);
diff --git a/understand-anything-plugin/skills/understand/prepare-symbol-retry.mjs b/understand-anything-plugin/skills/understand/prepare-symbol-retry.mjs
index bed832d8..f7c63f3f 100644
--- a/understand-anything-plugin/skills/understand/prepare-symbol-retry.mjs
+++ b/understand-anything-plugin/skills/understand/prepare-symbol-retry.mjs
@@ -123,7 +123,7 @@ async function main() {
atomicWriteJson(join(intermediateDir, 'batch-0.json'), retained);
// Force another merge and regenerate any architecture/tour based on the
// incomplete candidate. Keep the failure report for inspection.
- for (const name of ['assembled-graph.json', 'layers.json', 'tour.json']) {
+ for (const name of ['assembled-graph.json', 'layers.json', 'tour.json', 'code-lessons.json']) {
if (existsSync(join(intermediateDir, name))) unlinkSync(join(intermediateDir, name));
}
process.stdout.write(`Prepared symbol retry 1/1 for ${paths.size} file(s); dispatch batches from ${retryPath}\n`);