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.

fix(dashboard): address all 8 Copilot review findings on code lessons (#753)

FallingLight7d1eec4ba910
diff --git a/understand-anything-plugin/hooks/auto-update-prompt.md b/understand-anything-plugin/hooks/auto-update-prompt.md
index 25ddce05..5a7fbb2a 100644
--- a/understand-anything-plugin/hooks/auto-update-prompt.md
+++ b/understand-anything-plugin/hooks/auto-update-prompt.md
@@ -86,7 +86,7 @@ Do not dispatch assemble-reviewer or graph-reviewer for automatic updates.
## Phase 3 — Conditional architecture and tour
- For `PARTIAL_UPDATE`, dispatch neither agent. The finalizer preserves existing layer assignments and tour prose, removes dangling references/empty layers, and assigns new nodes deterministically by directory depth, graph connectivity, then prior layer order.
-- For `ARCHITECTURE_UPDATE`, dispatch architecture-analyzer on the full merged node/edge set, including previous layers for naming stability, and write `$UA_DIR/intermediate/layers.json`. Then dispatch tour-builder and write `$UA_DIR/intermediate/tour.json`.
+- For `ARCHITECTURE_UPDATE`, dispatch architecture-analyzer on the full merged node/edge set, including previous layers for naming stability, and write `$UA_DIR/intermediate/layers.json`. Then dispatch tour-builder and write `$UA_DIR/intermediate/tour.json`. Then dispatch `code-lesson-writer` (same dispatch shape as SKILL.md §Code Lessons: rebuilt tour, node summaries, language directive) and write `$UA_DIR/intermediate/code-lessons.json`, normalized into `$UA_DIR/intermediate/code-lessons.normalized.json` per the SKILL.md Phase 5 rules. Lessons are best-effort here: retry the dispatch once, and if it still fails leave no staged document, record the warning, and continue — publication (Phase 4) then removes the stale served sidecar instead of leaving lessons for the previous tour.
Retry either required agent once. If it still fails, **STOP** without advancing the baseline.
@@ -100,6 +100,8 @@ node "$PLUGIN_ROOT/skills/understand/finalize-incremental.mjs" "$PROJECT_ROOT"
The finalizer performs deterministic graph/layer/tour validation and independently reruns the shared symbol check on the exact graph before writing. It atomically saves `knowledge-graph.json`, patches changed fingerprints while preserving untouched entries, removes deleted fingerprints, and only then writes `meta.json`. A graph-save failure must never advance the fingerprint or commit baseline. If symbol loss is first detected here, follow the same one-retry procedure, rerun merge and any required architecture/tour phases, then finalize; an already-used or unsuccessful repair must stop with the old graph and baselines intact.
+After the finalizer exits successfully, publish lessons with the same rules as **Lesson publication** in SKILL.md's incremental save gate: atomically move `$UA_DIR/intermediate/code-lessons.normalized.json` over `$UA_DIR/code-lessons.json` when present; when lessons were attempted but skipped or failed, delete a served `$UA_DIR/code-lessons.json` instead; when the finalizer failed, touch nothing so the previous graph and lessons stay consistent. `PARTIAL_UPDATE` never attempts lessons and leaves the served sidecar untouched.
+
Report:
- action taken;
diff --git a/understand-anything-plugin/packages/dashboard/src/__tests__/vite-lessons-scope.test.ts b/understand-anything-plugin/packages/dashboard/src/__tests__/vite-lessons-scope.test.ts
new file mode 100644
index 00000000..218cbf44
--- /dev/null
+++ b/understand-anything-plugin/packages/dashboard/src/__tests__/vite-lessons-scope.test.ts
@@ -0,0 +1,144 @@
+// Regression test for Copilot review #753 finding #6:
+// "Resolve lessons beside the selected graph" — /code-lessons.json must be
+// served from the directory of the *selected* knowledge-graph.json (single
+// candidate, matching the standalone viewer), never from the fallback roots
+// (cwd, cwd/../../..) where another project's sidecar may live.
+import fs from "node:fs";
+import {
+ createServer,
+ request as httpRequest,
+ type Server,
+} from "node:http";
+import os from "node:os";
+import path from "node:path";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { createDataEndpointsMiddleware } from "../../vite.config";
+
+let servers: Server[] = [];
+let originalGraphDir: string | undefined;
+let originalCwd: string;
+let projectA: string; // selected via GRAPH_DIR
+let projectB: string; // fallback cwd root — carries rogue lessons
+
+function writeProjectFile(root: string, relativePath: string, contents: string): void {
+ const filePath = path.join(root, ...relativePath.split("/"));
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
+ fs.writeFileSync(filePath, contents, "utf8");
+}
+
+async function startServer(accessToken: string): Promise<string> {
+ const middleware = createDataEndpointsMiddleware(accessToken);
+ const server = createServer((req, res) => {
+ middleware(req, res, () => {
+ res.statusCode = 404;
+ res.end();
+ });
+ });
+ servers.push(server);
+ await new Promise<void>((resolve, reject) => {
+ server.once("error", reject);
+ server.listen(0, "127.0.0.1", () => resolve());
+ });
+ const address = server.address();
+ if (!address || typeof address === "string") {
+ throw new Error("test server did not expose a TCP port");
+ }
+ return `http://127.0.0.1:${address.port}`;
+}
+
+function requestJson(
+ baseUrl: string,
+ requestPath: string,
+): Promise<{ status: number; body: string }> {
+ return new Promise((resolve, reject) => {
+ const request = httpRequest(`${baseUrl}${requestPath}`, { agent: false }, (response) => {
+ const chunks: Buffer[] = [];
+ response.on("data", (chunk: Buffer) => chunks.push(chunk));
+ response.on("end", () => {
+ resolve({
+ status: response.statusCode ?? 0,
+ body: Buffer.concat(chunks).toString("utf8"),
+ });
+ });
+ });
+ request.once("error", reject);
+ request.end();
+ });
+}
+
+beforeEach(() => {
+ servers = [];
+ originalGraphDir = process.env.GRAPH_DIR;
+ originalCwd = process.cwd();
+ const tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), "ua-lessons-scope-"));
+ projectA = path.join(tempRoot, "project-a");
+ projectB = path.join(tempRoot, "project-b");
+ fs.mkdirSync(projectB, { recursive: true });
+ process.env.GRAPH_DIR = projectA;
+ process.chdir(projectB);
+});
+
+afterEach(() => {
+ for (const server of servers) server.close();
+ servers = [];
+ process.env.GRAPH_DIR = originalGraphDir;
+ process.chdir(originalCwd);
+});
+
+describe("dashboard /code-lessons.json project scoping", () => {
+ it("returns 404 when the selected project has no lessons (no cross-project leak)", async () => {
+ // Project A: graph present, lessons absent. Project B (the cwd fallback
+ // root) carries lessons with a rogue marker.
+ writeProjectFile(
+ projectA,
+ ".ua/knowledge-graph.json",
+ JSON.stringify({ project: { gitCommitHash: "a".repeat(40) }, nodes: [], edges: [] }),
+ );
+ writeProjectFile(
+ projectB,
+ ".ua/code-lessons.json",
+ JSON.stringify({
+ version: 1,
+ generatedAt: "2026-01-01T00:00:00.000Z",
+ files: { "other.ts": { overview: "ROGUE LESSONS FROM PROJECT B", sections: [] } },
+ }),
+ );
+
+ const baseUrl = await startServer("test-token");
+ const result = await requestJson(baseUrl, "/code-lessons.json?token=test-token");
+ expect(result.status).toBe(404);
+ expect(result.body).not.toContain("ROGUE");
+ });
+
+ it("serves lessons from beside the selected graph when present", async () => {
+ writeProjectFile(
+ projectA,
+ ".ua/knowledge-graph.json",
+ JSON.stringify({ project: { gitCommitHash: "a".repeat(40) }, nodes: [], edges: [] }),
+ );
+ writeProjectFile(
+ projectA,
+ ".ua/code-lessons.json",
+ JSON.stringify({
+ version: 1,
+ generatedAt: "2026-01-01T00:00:00.000Z",
+ files: { "a.ts": { overview: "PROJECT A LESSONS", sections: [] } },
+ }),
+ );
+ writeProjectFile(
+ projectB,
+ ".ua/code-lessons.json",
+ JSON.stringify({
+ version: 1,
+ generatedAt: "2026-01-01T00:00:00.000Z",
+ files: { "b.ts": { overview: "ROGUE LESSONS FROM PROJECT B", sections: [] } },
+ }),
+ );
+
+ const baseUrl = await startServer("test-token");
+ const result = await requestJson(baseUrl, "/code-lessons.json?token=test-token");
+ expect(result.status).toBe(200);
+ expect(result.body).toContain("PROJECT A LESSONS");
+ expect(result.body).not.toContain("ROGUE");
+ });
+});
diff --git a/understand-anything-plugin/packages/dashboard/src/components/CodeViewer.tsx b/understand-anything-plugin/packages/dashboard/src/components/CodeViewer.tsx
index 3bac4cfc..aa19714e 100644
--- a/understand-anything-plugin/packages/dashboard/src/components/CodeViewer.tsx
+++ b/understand-anything-plugin/packages/dashboard/src/components/CodeViewer.tsx
@@ -5,6 +5,7 @@ import remarkGfm from "remark-gfm";
import type { CodeLessonSection, CodeLessons } from "@understand-anything/core/types";
import { useDashboardStore } from "../store";
import { useI18n } from "../contexts/I18nContext";
+import { normalizeCodeLessons } from "../utils/codeLessons";
interface CodeViewerProps {
accessToken: string;
@@ -39,10 +40,13 @@ function fetchCodeLessons(token: string): Promise<CodeLessons | null> {
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;
+ // Lessons are agent-generated — validate/drop malformed shapes before
+ // caching so one bad entry can neither crash the viewer nor discard
+ // the remaining valid entries (review #1).
+ const normalized = normalizeCodeLessons(await res.json());
+ if (normalized) {
+ lessonsCache = normalized;
+ return normalized;
}
return null;
})
@@ -209,11 +213,24 @@ export default function CodeViewer({
// (.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.
+ // node's own lineRange highlight until deselected or another node is opened.
const [lessonHighlight, setLessonHighlight] = useState<{ start: number; end: number } | null>(null);
+ // Narrow screens stack the lesson panel below the source and keep it
+ // collapsed by default so the source stays readable (review #5); desktop
+ // keeps the side-by-side panel always visible.
+ const [lessonPanelOpen, setLessonPanelOpen] = useState(
+ () => typeof window !== "undefined" && window.matchMedia("(min-width: 1280px)").matches,
+ );
const codeScrollRef = useRef<HTMLDivElement | null>(null);
const { t } = useI18n();
+ // A lesson-section selection is scoped to the node it was chosen from —
+ // clear it whenever another node is opened so the node's own lineRange
+ // highlight and header range take over again (review #2).
+ useEffect(() => {
+ setLessonHighlight(null);
+ }, [codeViewerNodeId]);
+
useEffect(() => {
if (accessToken === "__demo__") return;
let cancelled = false;
@@ -223,7 +240,10 @@ export default function CodeViewer({
return () => {
cancelled = true;
};
- }, [accessToken]);
+ // Re-run when the file path changes so lessons generated after an
+ // earlier 404 appear on the next file open (review #3). Successful
+ // loads are served from the shared cache.
+ }, [accessToken, node?.filePath]);
useEffect(() => {
if (!node?.filePath) {
@@ -303,9 +323,24 @@ export default function CodeViewer({
return;
}
setLessonHighlight({ start, end });
- if (!showRendered) scrollToLine(start);
+ if (showRendered) {
+ // Rendered markdown has no source-line elements to highlight — switch
+ // to the source view first; the effect below scrolls once lines mount
+ // (review #4).
+ setMdView("source");
+ } else {
+ scrollToLine(start);
+ }
};
+ // Scroll to the selected lesson range after the source lines mount
+ // following a Rendered → Source switch (review #4). Only reacts to
+ // view-mode switches; direct selection scrolls synchronously in
+ // toggleSection, so the deps intentionally cover showRendered only.
+ useEffect(() => {
+ if (!showRendered && lessonHighlight) scrollToLine(lessonHighlight.start);
+ }, [showRendered]);
+
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">
@@ -360,7 +395,7 @@ export default function CodeViewer({
</div>
</div>
- <div className="flex-1 min-h-0 flex overflow-hidden bg-root">
+ <div className="flex-1 min-h-0 flex flex-col xl:flex-row 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>
@@ -380,6 +415,16 @@ export default function CodeViewer({
<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">
+ {lesson && (
+ <button
+ type="button"
+ onClick={() => setLessonPanelOpen((open) => !open)}
+ className="xl:hidden text-[10px] uppercase tracking-wider text-accent hover:text-accent/80 transition-colors"
+ aria-expanded={lessonPanelOpen}
+ >
+ {lessonPanelOpen ? t.codeViewer.hideLesson : t.codeViewer.showLesson}
+ </button>
+ )}
{isMarkdown && (
<div className="flex items-center rounded border border-border-subtle overflow-hidden" role="group">
{(["rendered", "source"] as const).map((view) => (
@@ -448,7 +493,9 @@ export default function CodeViewer({
</div>
{lesson && (
- <aside className="w-72 xl:w-80 shrink-0 border-l border-border-subtle bg-surface overflow-y-auto">
+ <aside
+ className={`${lessonPanelOpen ? "block" : "hidden"} xl:block w-full xl:w-80 shrink-0 border-t xl:border-t-0 xl:border-l border-border-subtle bg-surface overflow-y-auto max-h-[45vh] xl:max-h-none`}
+ >
<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}
diff --git a/understand-anything-plugin/packages/dashboard/src/locales/en.ts b/understand-anything-plugin/packages/dashboard/src/locales/en.ts
index cbb637bb..d4732ef3 100644
--- a/understand-anything-plugin/packages/dashboard/src/locales/en.ts
+++ b/understand-anything-plugin/packages/dashboard/src/locales/en.ts
@@ -186,6 +186,8 @@ export const en = {
lesson: "Lesson",
tourStep: "Tour",
overviewOnly: "Overview only — no section breakdown for this file.",
+ showLesson: "Show lesson",
+ hideLesson: "Hide lesson",
},
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 3eac0544..aed881e2 100644
--- a/understand-anything-plugin/packages/dashboard/src/locales/ja.ts
+++ b/understand-anything-plugin/packages/dashboard/src/locales/ja.ts
@@ -186,6 +186,8 @@ export const ja = {
lesson: "解説",
tourStep: "ツアー",
overviewOnly: "このファイルには概要のみあり、セクションごとの解説はありません。",
+ showLesson: "レッスンを表示",
+ hideLesson: "レッスンを隠す",
},
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 62799226..a4633ee3 100644
--- a/understand-anything-plugin/packages/dashboard/src/locales/ko.ts
+++ b/understand-anything-plugin/packages/dashboard/src/locales/ko.ts
@@ -186,6 +186,8 @@ export const ko = {
lesson: "해설",
tourStep: "투어",
overviewOnly: "이 파일에는 개요만 있고 구간별 해설이 없습니다.",
+ showLesson: "레슨 보기",
+ hideLesson: "레슨 숨기기",
},
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 30e0f68e..94ffabab 100644
--- a/understand-anything-plugin/packages/dashboard/src/locales/ru.ts
+++ b/understand-anything-plugin/packages/dashboard/src/locales/ru.ts
@@ -186,6 +186,8 @@ export const ru = {
lesson: "Конспект",
tourStep: "Обзор",
overviewOnly: "Для этого файла доступен только обзор — без разбора по секциям.",
+ showLesson: "Показать урок",
+ hideLesson: "Скрыть урок",
},
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 c87a9431..cfb22056 100644
--- a/understand-anything-plugin/packages/dashboard/src/locales/vi.ts
+++ b/understand-anything-plugin/packages/dashboard/src/locales/vi.ts
@@ -186,6 +186,8 @@ export const vi = {
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.",
+ showLesson: "Hiện bài học",
+ hideLesson: "Ẩn bài học",
},
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 2155d36f..0c1d18ea 100644
--- a/understand-anything-plugin/packages/dashboard/src/locales/zh-TW.ts
+++ b/understand-anything-plugin/packages/dashboard/src/locales/zh-TW.ts
@@ -186,6 +186,8 @@ export const zhTW = {
lesson: "講解",
tourStep: "導覽",
overviewOnly: "該檔案僅有概覽講解,暫無分段講解。",
+ showLesson: "顯示課程",
+ hideLesson: "隱藏課程",
},
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 d12c9f08..939e24d4 100644
--- a/understand-anything-plugin/packages/dashboard/src/locales/zh.ts
+++ b/understand-anything-plugin/packages/dashboard/src/locales/zh.ts
@@ -186,6 +186,8 @@ export const zh = {
lesson: "讲解",
tourStep: "导览",
overviewOnly: "该文件仅有概览讲解,暂无分段讲解。",
+ showLesson: "显示课程",
+ hideLesson: "隐藏课程",
},
customNode: {
tested: "已测试",
diff --git a/understand-anything-plugin/packages/dashboard/src/utils/__tests__/codeLessons.test.ts b/understand-anything-plugin/packages/dashboard/src/utils/__tests__/codeLessons.test.ts
new file mode 100644
index 00000000..6d29fa30
--- /dev/null
+++ b/understand-anything-plugin/packages/dashboard/src/utils/__tests__/codeLessons.test.ts
@@ -0,0 +1,137 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { normalizeCodeLessons } from "../codeLessons";
+
+function validSection(overrides: Record<string, unknown> = {}): Record<string, unknown> {
+ return {
+ title: "Setup",
+ lineRange: [1, 4],
+ explanation: "Wires up the module.",
+ ...overrides,
+ };
+}
+
+function validFileEntry(overrides: Record<string, unknown> = {}): Record<string, unknown> {
+ return { overview: "A small module.", sections: [validSection()], ...overrides };
+}
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+describe("normalizeCodeLessons", () => {
+ it("returns null for non-object payloads", () => {
+ expect(normalizeCodeLessons(null)).toBeNull();
+ expect(normalizeCodeLessons("text")).toBeNull();
+ expect(normalizeCodeLessons(42)).toBeNull();
+ expect(normalizeCodeLessons([1, 2])).toBeNull();
+ });
+
+ it("returns null when the files envelope is missing or not an object", () => {
+ expect(normalizeCodeLessons({})).toBeNull();
+ expect(normalizeCodeLessons({ files: "nope" })).toBeNull();
+ expect(normalizeCodeLessons({ files: ["a"] })).toBeNull();
+ });
+
+ it("keeps valid entries untouched", () => {
+ const result = normalizeCodeLessons({
+ version: 1,
+ generatedAt: "2026-11-04T00:00:00.000Z",
+ files: { "src/a.ts": validFileEntry() },
+ });
+ expect(result).not.toBeNull();
+ expect(result?.files["src/a.ts"]).toEqual({
+ overview: "A small module.",
+ sections: [{ title: "Setup", lineRange: [1, 4], explanation: "Wires up the module." }],
+ });
+ });
+
+ it("coerces entries without sections to overview-only and keeps siblings (review #1 crash shape)", () => {
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ const result = normalizeCodeLessons({
+ files: {
+ "src/a.ts": { overview: "Broken — no sections field" },
+ "src/b.ts": validFileEntry(),
+ },
+ });
+ expect(result).not.toBeNull();
+ // The crash came from `lesson.sections.length` on a missing field — the
+ // normalized shape guarantees an array, so the overview stays usable.
+ expect(result?.files["src/a.ts"]).toEqual({
+ overview: "Broken — no sections field",
+ sections: [],
+ });
+ expect(result?.files["src/b.ts"]).toBeDefined();
+ expect(warn).toHaveBeenCalledWith(
+ expect.stringContaining('"src/a.ts": sections missing or not an array'),
+ );
+ });
+
+ it("drops entries whose overview is not a string", () => {
+ vi.spyOn(console, "warn").mockImplementation(() => {});
+ const result = normalizeCodeLessons({
+ files: { "src/a.ts": { overview: 42, sections: [] } },
+ });
+ expect(result?.files).toEqual({});
+ });
+
+ it("drops invalid sections while keeping valid siblings", () => {
+ vi.spyOn(console, "warn").mockImplementation(() => {});
+ const result = normalizeCodeLessons({
+ files: {
+ "src/a.ts": {
+ overview: "ok",
+ sections: [
+ validSection({ lineRange: [0, 4] }), // start < 1
+ validSection({ lineRange: [5, 2] }), // start > end
+ validSection({ lineRange: [1] }), // wrong length
+ validSection({ lineRange: ["1", 4] }), // not integers
+ validSection({ title: "" }), // empty title
+ validSection({ title: 7 }), // non-string title
+ validSection({ explanation: null }), // non-string explanation
+ validSection({ tourOrder: "x" }), // non-integer tourOrder
+ validSection(),
+ ],
+ },
+ },
+ });
+ const sections = result?.files["src/a.ts"]?.sections ?? [];
+ expect(sections).toHaveLength(1);
+ expect(sections[0]?.title).toBe("Setup");
+ });
+
+ it("preserves a valid integer tourOrder and omits undefined", () => {
+ const result = normalizeCodeLessons({
+ files: {
+ "src/a.ts": validFileEntry({ sections: [validSection({ tourOrder: 2 })] }),
+ "src/b.ts": validFileEntry(),
+ },
+ });
+ expect(result?.files["src/a.ts"]?.sections[0]?.tourOrder).toBe(2);
+ expect(result?.files["src/b.ts"]?.sections[0]?.tourOrder).toBeUndefined();
+ });
+
+ it("caps sections at 10 per file", () => {
+ vi.spyOn(console, "warn").mockImplementation(() => {});
+ const sections = Array.from({ length: 14 }, (_, i) => validSection({ title: `S${i}` }));
+ const result = normalizeCodeLessons({ files: { "src/a.ts": { overview: "ok", sections } } });
+ expect(result?.files["src/a.ts"]?.sections).toHaveLength(10);
+ });
+
+ it("treats a non-array sections field as empty and accepts an empty overview string", () => {
+ vi.spyOn(console, "warn").mockImplementation(() => {});
+ const result = normalizeCodeLessons({
+ files: {
+ "src/a.ts": { overview: "", sections: "nope" },
+ "src/b.ts": { overview: "", sections: [] },
+ },
+ });
+ expect(result?.files["src/a.ts"]?.sections).toEqual([]);
+ expect(result?.files["src/b.ts"]).toEqual({ overview: "", sections: [] });
+ });
+
+ it("stamps defaults for missing version/generatedAt", () => {
+ const result = normalizeCodeLessons({ files: {} });
+ expect(result?.version).toBe(1);
+ expect(result?.generatedAt).toBe("");
+ });
+});
diff --git a/understand-anything-plugin/packages/dashboard/src/utils/codeLessons.ts b/understand-anything-plugin/packages/dashboard/src/utils/codeLessons.ts
new file mode 100644
index 00000000..5cea1d5f
--- /dev/null
+++ b/understand-anything-plugin/packages/dashboard/src/utils/codeLessons.ts
@@ -0,0 +1,94 @@
+import type { CodeLessonSection, CodeLessons } from "@understand-anything/core/types";
+
+const MAX_SECTIONS_PER_FILE = 10;
+
+function isValidLineRange(value: unknown): value is [number, number] {
+ return (
+ Array.isArray(value) &&
+ value.length === 2 &&
+ Number.isInteger(value[0]) &&
+ Number.isInteger(value[1]) &&
+ value[0] >= 1 &&
+ value[0] <= value[1]
+ );
+}
+
+function normalizeSection(value: unknown): CodeLessonSection | null {
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
+ const section = value as {
+ title?: unknown;
+ explanation?: unknown;
+ lineRange?: unknown;
+ tourOrder?: unknown;
+ };
+ if (typeof section.title !== "string" || section.title.trim().length === 0) return null;
+ if (typeof section.explanation !== "string") return null;
+ if (!isValidLineRange(section.lineRange)) return null;
+ if (section.tourOrder !== undefined && !Number.isInteger(section.tourOrder)) return null;
+ const normalized: CodeLessonSection = {
+ title: section.title,
+ lineRange: [section.lineRange[0], section.lineRange[1]],
+ explanation: section.explanation,
+ };
+ if (section.tourOrder !== undefined) {
+ normalized.tourOrder = section.tourOrder as number;
+ }
+ return normalized;
+}
+
+/**
+ * Defense-in-depth for a generated optional artifact. The lessons document is
+ * written by an agent, so malformed shapes will happen, and one bad entry must
+ * neither crash the viewer nor discard every other file's lessons. Mirrors the
+ * SKILL.md normalize rules: drop invalid entries and sections, cap sections
+ * per file, keep everything else. Returns null only when the envelope itself
+ * is broken (no usable `files` object).
+ */
+export function normalizeCodeLessons(data: unknown): CodeLessons | null {
+ if (!data || typeof data !== "object" || Array.isArray(data)) return null;
+ const candidate = data as { version?: unknown; generatedAt?: unknown; files?: unknown };
+ const files = candidate.files;
+ if (!files || typeof files !== "object" || Array.isArray(files)) return null;
+
+ const normalizedFiles: CodeLessons["files"] = {};
+ for (const [filePath, entry] of Object.entries(files as Record<string, unknown>)) {
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
+ console.warn(`[code-lessons] dropped malformed entry for "${filePath}"`);
+ continue;
+ }
+ const fileEntry = entry as { overview?: unknown; sections?: unknown };
+ if (typeof fileEntry.overview !== "string") {
+ console.warn(`[code-lessons] dropped entry for "${filePath}" (overview must be a string)`);
+ continue;
+ }
+ if (!Array.isArray(fileEntry.sections)) {
+ console.warn(
+ `[code-lessons] "${filePath}": sections missing or not an array — treated as overview-only`,
+ );
+ }
+ const rawSections = Array.isArray(fileEntry.sections) ? fileEntry.sections : [];
+ const sections: CodeLessonSection[] = [];
+ let droppedSections = 0;
+ for (const raw of rawSections) {
+ if (sections.length >= MAX_SECTIONS_PER_FILE) break;
+ const section = normalizeSection(raw);
+ if (section) {
+ sections.push(section);
+ } else {
+ droppedSections += 1;
+ }
+ }
+ if (droppedSections > 0) {
+ console.warn(
+ `[code-lessons] dropped ${droppedSections} malformed section(s) for "${filePath}"`,
+ );
+ }
+ normalizedFiles[filePath] = { overview: fileEntry.overview, sections };
+ }
+
+ return {
+ version: typeof candidate.version === "number" ? candidate.version : 1,
+ generatedAt: typeof candidate.generatedAt === "string" ? candidate.generatedAt : "",
+ files: normalizedFiles,
+ };
+}
diff --git a/understand-anything-plugin/packages/dashboard/vite.config.ts b/understand-anything-plugin/packages/dashboard/vite.config.ts
index ff0e2d2d..b7a2a0ad 100644
--- a/understand-anything-plugin/packages/dashboard/vite.config.ts
+++ b/understand-anything-plugin/packages/dashboard/vite.config.ts
@@ -282,6 +282,156 @@ export function createDashboardDataMiddleware(
};
}
+/**
+ * All data endpoints except /staleness.json. Exported so the test harness
+ * exercises exactly what the dev server serves (review #6).
+ */
+export function createDataEndpointsMiddleware(
+ accessToken: string,
+): DashboardDataMiddleware {
+ return (req, res, next) => {
+ const url = new URL(req.url ?? "/", "http://127.0.0.1:5173");
+ const pathname = url.pathname;
+ const isProtectedEndpoint =
+ pathname === "/knowledge-graph.json" ||
+ pathname === "/domain-graph.json" ||
+ pathname === "/diff-overlay.json" ||
+ pathname === "/meta.json" ||
+ pathname === "/config.json" ||
+ pathname === "/code-lessons.json" ||
+ pathname === "/file-content.json";
+
+ if (!isProtectedEndpoint) {
+ next();
+ return;
+ }
+
+ // FIX 3 — require the one-time token on all data endpoints.
+ // Requests without a matching ?token= get a 403.
+ if (url.searchParams.get("token") !== accessToken) {
+ sendJson(res, 403, { error: "Forbidden: missing or invalid token" });
+ return;
+ }
+
+ if (pathname === "/file-content.json") {
+ const result = readSourceFile(url);
+ sendJson(res, result.statusCode, result.payload);
+ return;
+ }
+
+ if (pathname === "/config.json") {
+ const configCandidates = graphFileCandidates("config.json");
+ for (const candidate of configCandidates) {
+ if (fs.existsSync(candidate)) {
+ try {
+ const raw = JSON.parse(fs.readFileSync(candidate, "utf-8"));
+ sendJson(res, 200, raw);
+ return;
+ } catch {
+ sendJson(res, 500, { error: "Failed to read config file" });
+ return;
+ }
+ }
+ }
+ sendJson(res, 200, { autoUpdate: false, outputLanguage: "en" });
+ return;
+ }
+
+ if (pathname === "/code-lessons.json") {
+ // Lessons belong to the selected project: resolve beside the graph this
+ // server actually selected (single candidate, matching viewer.mjs).
+ // Walking the fallback roots here served another project's sidecar for
+ // matching file paths when the selected project had no lessons of its
+ // own (review #6).
+ const graphFile = findGraphFile("knowledge-graph.json");
+ const lessonsCandidates = graphFile
+ ? [path.join(path.dirname(graphFile), "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"
+ : pathname === "/meta.json"
+ ? "meta.json"
+ : pathname === "/domain-graph.json"
+ ? "domain-graph.json"
+ : "knowledge-graph.json";
+
+ const candidates = graphFileCandidates(fileName);
+
+ for (const candidate of candidates) {
+ if (!fs.existsSync(candidate)) continue;
+
+ // FIX 2 — sanitise absolute file paths before sending the JSON.
+ // Nodes can contain filePath values like /Users/alice/company/src/auth.ts.
+ // We convert those to relative paths (src/auth.ts) so the developer's
+ // home directory and company directory layout are not leaked.
+ try {
+ const raw = JSON.parse(fs.readFileSync(candidate, "utf-8")) as {
+ nodes?: Array<Record<string, unknown>>;
+ [key: string]: unknown;
+ };
+
+ // Derive the project root from the candidate path so we can
+ // make file paths relative to it.
+ const projectRoot = projectRootFromGraphFile(candidate);
+
+ if (Array.isArray(raw.nodes)) {
+ raw.nodes = raw.nodes.map((node) => {
+ if (typeof node.filePath !== "string") return node;
+ const abs = node.filePath;
+ // Only relativise paths that actually sit inside projectRoot.
+ // Leave external or already-relative paths untouched.
+ const rel = abs.startsWith(projectRoot)
+ ? abs.slice(projectRoot.length).replace(/^[\\/]/, "")
+ : path.isAbsolute(abs)
+ ? path.basename(abs) // absolute but outside root — use filename only
+ : abs; // already relative — keep as-is
+ return { ...node, filePath: rel };
+ });
+ }
+
+ res.setHeader("Content-Type", "application/json");
+ res.end(JSON.stringify(raw));
+ } catch (err) {
+ // If we cannot parse or sanitise the file, refuse to serve it
+ // rather than accidentally leaking raw content.
+ console.error("[understand-anything] Failed to sanitise graph file:", err);
+ res.statusCode = 500;
+ res.setHeader("Content-Type", "application/json");
+ res.end(JSON.stringify({ error: "Failed to read graph file" }));
+ }
+ return;
+ }
+
+ // No matching file found on disk.
+ res.statusCode = 404;
+ if (pathname === "/knowledge-graph.json") {
+ res.setHeader("Content-Type", "application/json");
+ res.end(JSON.stringify({ error: "No knowledge graph found. Run /understand first." }));
+ } else {
+ res.end();
+ }
+ };
+}
+
type DashboardViteConfig = UserConfig & {
test: {
environment: "node";
@@ -358,140 +508,7 @@ const config: DashboardViteConfig = {
});
server.middlewares.use(createDashboardDataMiddleware(ACCESS_TOKEN));
-
- server.middlewares.use((req, res, next) => {
- const url = new URL(req.url ?? "/", "http://127.0.0.1:5173");
- const pathname = url.pathname;
- const isProtectedEndpoint =
- pathname === "/knowledge-graph.json" ||
- pathname === "/domain-graph.json" ||
- pathname === "/diff-overlay.json" ||
- pathname === "/meta.json" ||
- pathname === "/config.json" ||
- pathname === "/code-lessons.json" ||
- pathname === "/file-content.json";
-
- if (!isProtectedEndpoint) {
- next();
- return;
- }
-
- // FIX 3 — require the one-time token on all data endpoints.
- // Requests without a matching ?token= get a 403.
- if (url.searchParams.get("token") !== ACCESS_TOKEN) {
- sendJson(res, 403, { error: "Forbidden: missing or invalid token" });
- return;
- }
-
- if (pathname === "/file-content.json") {
- const result = readSourceFile(url);
- sendJson(res, result.statusCode, result.payload);
- return;
- }
-
- if (pathname === "/config.json") {
- const configCandidates = graphFileCandidates("config.json");
- for (const candidate of configCandidates) {
- if (fs.existsSync(candidate)) {
- try {
- const raw = JSON.parse(fs.readFileSync(candidate, "utf-8"));
- sendJson(res, 200, raw);
- return;
- } catch {
- sendJson(res, 500, { error: "Failed to read config file" });
- return;
- }
- }
- }
- sendJson(res, 200, { autoUpdate: false, outputLanguage: "en" });
- 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"
- : pathname === "/meta.json"
- ? "meta.json"
- : pathname === "/domain-graph.json"
- ? "domain-graph.json"
- : "knowledge-graph.json";
-
- const candidates = graphFileCandidates(fileName);
-
- for (const candidate of candidates) {
- if (!fs.existsSync(candidate)) continue;
-
- // FIX 2 — sanitise absolute file paths before sending the JSON.
- // Nodes can contain filePath values like /Users/alice/company/src/auth.ts.
- // We convert those to relative paths (src/auth.ts) so the developer's
- // home directory and company directory layout are not leaked.
- try {
- const raw = JSON.parse(fs.readFileSync(candidate, "utf-8")) as {
- nodes?: Array<Record<string, unknown>>;
- [key: string]: unknown;
- };
-
- // Derive the project root from the candidate path so we can
- // make file paths relative to it.
- const projectRoot = projectRootFromGraphFile(candidate);
-
- if (Array.isArray(raw.nodes)) {
- raw.nodes = raw.nodes.map((node) => {
- if (typeof node.filePath !== "string") return node;
- const abs = node.filePath;
- // Only relativise paths that actually sit inside projectRoot.
- // Leave external or already-relative paths untouched.
- const rel = abs.startsWith(projectRoot)
- ? abs.slice(projectRoot.length).replace(/^[\\/]/, "")
- : path.isAbsolute(abs)
- ? path.basename(abs) // absolute but outside root — use filename only
- : abs; // already relative — keep as-is
- return { ...node, filePath: rel };
- });
- }
-
- res.setHeader("Content-Type", "application/json");
- res.end(JSON.stringify(raw));
- } catch (err) {
- // If we cannot parse or sanitise the file, refuse to serve it
- // rather than accidentally leaking raw content.
- console.error("[understand-anything] Failed to sanitise graph file:", err);
- res.statusCode = 500;
- res.setHeader("Content-Type", "application/json");
- res.end(JSON.stringify({ error: "Failed to read graph file" }));
- }
- return;
- }
-
- // No matching file found on disk.
- res.statusCode = 404;
- if (pathname === "/knowledge-graph.json") {
- res.setHeader("Content-Type", "application/json");
- res.end(JSON.stringify({ error: "No knowledge graph found. Run /understand first." }));
- } else {
- res.end();
- }
- });
+ server.middlewares.use(createDataEndpointsMiddleware(ACCESS_TOKEN));
},
},
],
diff --git a/understand-anything-plugin/skills/understand/SKILL.md b/understand-anything-plugin/skills/understand/SKILL.md
index 2b4a4c52..3e472a68 100644
--- a/understand-anything-plugin/skills/understand/SKILL.md
+++ b/understand-anything-plugin/skills/understand/SKILL.md
@@ -656,7 +656,7 @@ Report to the user: `[Phase 5/7] Writing code lessons...`
>
> $LANGUAGE_DIRECTIVE
-3. **Normalize** `$UA_DIR/intermediate/code-lessons.json` into the final `$UA_DIR/code-lessons.json`. Apply these steps **in order**:
+3. **Normalize** `$UA_DIR/intermediate/code-lessons.json` into a **staged** document at `$UA_DIR/intermediate/code-lessons.normalized.json`. Do NOT write `$UA_DIR/code-lessons.json` here — publication happens only after the graph/tour this run describes is actually saved (see **Lesson publication** under the incremental save gate below, and Phase 7 step 1 for full runs). 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).
@@ -664,7 +664,7 @@ Report to the user: `[Phase 5/7] Writing code lessons...`
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.
+4. **On failure:** retry the dispatch once (see Error Handling); if it still fails, skip lessons entirely — leave no staged document, record the failure in `$PHASE_WARNINGS`, and continue. At publication time the previously served `$UA_DIR/code-lessons.json` is removed in that case, so stale lessons never sit beside a rebuilt tour (see **Lesson publication** below). The dashboard degrades gracefully when the file is absent.
### Incremental deterministic save gate
@@ -676,6 +676,13 @@ node "<SKILL_DIR>/finalize-incremental.mjs" "$PROJECT_ROOT"
This helper validates/deduplicates nodes and edges, reconciles layers/tour, and independently reruns the shared symbol validator on the exact graph to be saved. It then atomically saves the graph, patches only changed fingerprints while preserving all others, removes deleted fingerprints, and only then advances `meta.json`. A cached successful merge report cannot bypass the save check. If symbol loss is first detected here, use the same one-retry procedure above, rerun merge and any required architecture/tour phases, then finalize again; if the retry was already used or remains unresolved, **STOP** with the old graph and baselines intact.
+**Lesson publication.** `$UA_DIR/code-lessons.json` is only ever written after the graph/tour it describes is saved:
+
+- If the finalizer exits successfully and `$UA_DIR/intermediate/code-lessons.normalized.json` exists, atomically move it over `$UA_DIR/code-lessons.json`.
+- If this run attempted lessons and they were skipped or failed (no staged document) while `$UA_DIR/code-lessons.json` exists, delete it — stale lessons with `tourOrder` badges for a rebuilt tour must not survive.
+- If the finalizer fails (**STOP**), touch nothing: the previous `$UA_DIR/code-lessons.json` stays beside the previous graph and tour.
+- `PARTIAL_UPDATE` never attempts lessons (it keeps the existing file untouched — see the Code Lessons section above), so with no staged document the served sidecar stays as-is.
+
- Without `--review`, report the incremental summary and **STOP**. Do not run Phase 6 or the full-save Phase 7; this is what prevents the ordinary local update from paying for whole-graph review.
- With `--review`, copy the newly saved `$UA_DIR/knowledge-graph.json` to `$UA_DIR/intermediate/assembled-graph.json`, then continue to the full graph-reviewer path in Phase 6. Do not run the inline default reviewer.
@@ -851,6 +858,8 @@ Report to the user: `[Phase 7/7] Saving knowledge graph...`
1. Write the final knowledge graph to `$UA_DIR/knowledge-graph.json`.
+ Then publish lessons under the same rules as **Lesson publication** in the incremental save gate: if `$UA_DIR/intermediate/code-lessons.normalized.json` exists, atomically move it over `$UA_DIR/code-lessons.json`; if lessons were attempted but skipped or failed, delete a served `$UA_DIR/code-lessons.json` instead so no stale sidecar survives beside the new graph and tour.
+
2. **Generate structural fingerprints baseline.** This creates the basis for future automatic incremental updates and **must succeed before `meta.json` is written** — otherwise auto-update sees a fresh commit hash with no fingerprints to compare against, classifies every file as STRUCTURAL, and escalates to `FULL_UPDATE` on every subsequent commit (issue #152).
Write the input file:
diff --git a/understand-anything-plugin/skills/understand/prepare-incremental.mjs b/understand-anything-plugin/skills/understand/prepare-incremental.mjs
index d15063ea..fdce93bb 100644
--- a/understand-anything-plugin/skills/understand/prepare-incremental.mjs
+++ b/understand-anything-plugin/skills/understand/prepare-incremental.mjs
@@ -124,6 +124,7 @@ function clearIncrementalScratch(intermediateDir) {
'layers.json',
'tour.json',
'code-lessons.json',
+ 'code-lessons.normalized.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 f7c63f3f..0b451f59 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', 'code-lessons.json']) {
+ for (const name of ['assembled-graph.json', 'layers.json', 'tour.json', 'code-lessons.json', 'code-lessons.normalized.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`);