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(lessons): prune served lessons for files removed from the saved graph (#753)

06FallingLight90b4f3c72f0198
diff --git a/understand-anything-plugin/hooks/auto-update-prompt.md b/understand-anything-plugin/hooks/auto-update-prompt.md
index 33502836..6ae23d81 100644
--- a/understand-anything-plugin/hooks/auto-update-prompt.md
+++ b/understand-anything-plugin/hooks/auto-update-prompt.md
@@ -102,7 +102,13 @@ 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 — only lessons staged by the current invocation: atomically move `$UA_DIR/intermediate/code-lessons.normalized.json` over `$UA_DIR/code-lessons.json` when this run staged it; 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.
+After the finalizer exits successfully, publish lessons with the same rules as **Lesson publication** in SKILL.md's incremental save gate — only lessons staged by the current invocation: atomically move `$UA_DIR/intermediate/code-lessons.normalized.json` over `$UA_DIR/code-lessons.json` when this run staged it; 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, but it can still delete or newly ignore files from the graph while their source-derived lessons survive — so for every action except `SKIP` (and `PARTIAL_UPDATE` in particular), after the finalizer succeeds and the publication rules above have been applied, run:
+
+```bash
+node "$PLUGIN_ROOT/skills/understand/prune-code-lessons.mjs" "$PROJECT_ROOT"
+```
+
+The helper removes only entries whose file path has no node in the saved graph and leaves every surviving lesson byte-identical.
Report:
diff --git a/understand-anything-plugin/skills/understand/SKILL.md b/understand-anything-plugin/skills/understand/SKILL.md
index a1d47e03..5a30c333 100644
--- a/understand-anything-plugin/skills/understand/SKILL.md
+++ b/understand-anything-plugin/skills/understand/SKILL.md
@@ -627,7 +627,13 @@ Required fields: `order`, `title`, `description`, `nodeIds`. Preserve optional `
### 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).
+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) — but once the incremental save gate finalizes successfully, prune entries for files the saved graph no longer contains:
+
+```bash
+node "<SKILL_DIR>/prune-code-lessons.mjs" "$PROJECT_ROOT"
+```
+
+The helper removes only orphaned entries (paths with no node in the saved graph) and leaves every surviving lesson byte-identical. A `PARTIAL_UPDATE` can delete or newly ignore files while their source-derived lessons survive, and the viewer would keep serving lessons the graph no longer knows about.
Report to the user: `[Phase 5/7] Writing code lessons...`
diff --git a/understand-anything-plugin/skills/understand/prune-code-lessons.mjs b/understand-anything-plugin/skills/understand/prune-code-lessons.mjs
new file mode 100644
index 00000000..8e605a01
--- /dev/null
+++ b/understand-anything-plugin/skills/understand/prune-code-lessons.mjs
@@ -0,0 +1,110 @@
+#!/usr/bin/env node
+/**
+ * Prune served code-lessons entries for files that no longer exist in the
+ * saved knowledge graph. A PARTIAL_UPDATE can remove deleted or newly
+ * ignored files from the graph while their source-derived lessons survive in
+ * code-lessons.json — the viewer endpoint then keeps serving lessons for
+ * paths the graph no longer knows about. Run this after a successful partial
+ * save; surviving lessons are left untouched.
+ *
+ * Usage: node prune-code-lessons.mjs <projectRoot>
+ *
+ * Reads $UA_DIR/knowledge-graph.json (file-level node filePaths form the
+ * legal key set — including table/endpoint nodes' filePaths, so a file
+ * that only has entity nodes left keeps its lesson)
+ * $UA_DIR/code-lessons.json (served lessons; missing -> silent no-op)
+ * Writes $UA_DIR/code-lessons.json back only when at least one orphan entry
+ * was removed (atomic temp+rename).
+ */
+
+import { createRequire } from 'node:module';
+import { dirname, isAbsolute, join, resolve } from 'node:path';
+import { fileURLToPath, pathToFileURL } from 'node:url';
+import { existsSync, readFileSync, realpathSync, renameSync, writeFileSync } from 'node:fs';
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const pluginRoot = resolve(__dirname, '../..');
+const require = createRequire(resolve(pluginRoot, 'package.json'));
+
+let core;
+try {
+ core = await import(pathToFileURL(require.resolve('@understand-anything/core')).href);
+} catch {
+ core = await import(pathToFileURL(resolve(pluginRoot, 'packages/core/dist/index.js')).href);
+}
+
+const { resolveUaDir } = core;
+
+function normalizeRelativePath(value) {
+ if (typeof value !== 'string' || !value || isAbsolute(value)) return null;
+ const platformPath = process.platform === 'win32' ? value.replaceAll('\\', '/') : value;
+ const path = platformPath.replace(/^\.\//, '');
+ if (!path || path.split('/').some(part => part === '..')) return null;
+ return path;
+}
+
+function readJson(path) {
+ return JSON.parse(readFileSync(path, 'utf-8'));
+}
+
+function atomicWriteJson(path, value) {
+ const tempPath = `${path}.tmp-${process.pid}-${Date.now()}`;
+ writeFileSync(tempPath, `${JSON.stringify(value, null, 2)}\n`, 'utf-8');
+ renameSync(tempPath, path);
+ // Verify the durable target, not the temporary file.
+ JSON.parse(readFileSync(path, 'utf-8'));
+}
+
+const args = process.argv.slice(2);
+if (args.length !== 1 || args[0].startsWith('--')) {
+ console.error('Usage: node prune-code-lessons.mjs <projectRoot>');
+ process.exit(1);
+}
+
+const projectRoot = realpathSync(args[0]);
+const uaDir = resolveUaDir(projectRoot);
+const graphPath = join(uaDir, 'knowledge-graph.json');
+const lessonsPath = join(uaDir, 'code-lessons.json');
+
+// Silent no-ops: nothing served to prune, or no graph to prune against.
+if (!existsSync(graphPath) || !existsSync(lessonsPath)) {
+ process.exit(0);
+}
+
+const graph = readJson(graphPath);
+const nodes = Array.isArray(graph?.nodes) ? graph.nodes : [];
+
+// Lessons are keyed by relative file path; any node carrying a filePath keeps
+// that path's lesson legal (whole-file nodes, plus table/endpoint entities).
+const legalPaths = new Set();
+for (const node of nodes) {
+ const path = normalizeRelativePath(node?.filePath);
+ if (path) legalPaths.add(path);
+}
+
+const lessons = readJson(lessonsPath);
+const files = lessons && typeof lessons === 'object' && !Array.isArray(lessons)
+ ? lessons.files
+ : null;
+if (!files || typeof files !== 'object' || Array.isArray(files)) {
+ process.exit(0);
+}
+
+const kept = {};
+let removed = 0;
+for (const [filePath, entry] of Object.entries(files)) {
+ const normalized = normalizeRelativePath(filePath);
+ if (normalized && legalPaths.has(normalized)) {
+ kept[filePath] = entry;
+ } else {
+ removed += 1;
+ }
+}
+
+if (removed === 0) {
+ process.stdout.write('Code lessons pruned: nothing to remove\n');
+ process.exit(0);
+}
+
+atomicWriteJson(lessonsPath, { ...lessons, files: kept });
+process.stdout.write(`Code lessons pruned: removed ${removed} orphaned entr${removed === 1 ? 'y' : 'ies'}\n`);