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.

test(lessons): cover normalize-tour, prune rollback paths, and the finalize rollback (#753)

06FallingLight900eeaad30ba24
diff --git a/tests/skill/understand/test_normalize_tour.test.mjs b/tests/skill/understand/test_normalize_tour.test.mjs
new file mode 100644
index 00000000..db847747
--- /dev/null
+++ b/tests/skill/understand/test_normalize_tour.test.mjs
@@ -0,0 +1,129 @@
+import { afterEach, describe, expect, it } from 'vitest';
+import { existsSync, mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { dirname, join, resolve } from 'node:path';
+import { spawnSync } from 'node:child_process';
+import { fileURLToPath } from 'node:url';
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const repoRoot = resolve(__dirname, '../../..');
+const SCRIPT = join(repoRoot, 'understand-anything-plugin', 'skills', 'understand', 'normalize-tour.mjs');
+
+const roots = [];
+
+afterEach(() => {
+ for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true });
+});
+
+function setupFixture({ tour, assembled }) {
+ const root = mkdtempSync(join(tmpdir(), 'ua-normalize-tour-'));
+ roots.push(root);
+ const intermediate = join(root, '.ua', 'intermediate');
+ mkdirSync(intermediate, { recursive: true });
+ if (assembled !== null) {
+ writeFileSync(
+ join(intermediate, 'assembled-graph.json'),
+ typeof assembled === 'string' ? assembled : JSON.stringify(assembled),
+ );
+ }
+ if (tour !== null) {
+ writeFileSync(
+ join(intermediate, 'tour.json'),
+ typeof tour === 'string' ? tour : JSON.stringify(tour),
+ );
+ }
+ return { root, intermediate };
+}
+
+function runScript(root) {
+ return spawnSync(process.execPath, [SCRIPT, root], { cwd: root, encoding: 'utf-8' });
+}
+
+const ASSEMBLED = {
+ nodes: [
+ { id: 'document:README.md', type: 'document', filePath: 'README.md', name: 'README' },
+ { id: 'file:src/main.tsx', type: 'file', filePath: 'src/main.tsx', name: 'main' },
+ { id: 'file:src/utils.ts', type: 'file', filePath: 'src/utils.ts', name: 'utils' },
+ { id: 'config:package.json', type: 'config', filePath: 'package.json', name: 'package' },
+ ],
+ edges: [],
+};
+
+describe('normalize-tour.mjs', () => {
+ it('resolves raw paths through the finalizer pathIndex and applies the full normalization', () => {
+ const { root, intermediate } = setupFixture({
+ assembled: ASSEMBLED,
+ tour: {
+ steps: [
+ { order: 2, title: 'Entry', description: 'Boots.', nodeIds: ['file:src/main.tsx', 'README.md'] },
+ { order: 1, nodesToInspect: ['src/utils.ts', 'package.json', 'file:src/missing.tsx'], whyItMatters: 'Helpers first.' },
+ { order: 3, title: 'Config', description: 'Manifest.', nodeIds: ['config:package.json'] },
+ ],
+ },
+ });
+ const result = runScript(root);
+ expect(result.status).toBe(0);
+ const normalized = JSON.parse(readFileSync(join(intermediate, 'tour.normalized.json'), 'utf-8'));
+ expect(normalized).toHaveLength(3);
+ // A raw README.md reference resolves to the real document: node — the
+ // hand-written rule would have made it a dangling file:README.md.
+ expect(normalized.find(step => step.order === 2).nodeIds).toEqual([
+ 'file:src/main.tsx',
+ 'document:README.md',
+ ]);
+ const step1 = normalized.find(step => step.order === 1);
+ expect(step1.description).toBe('Helpers first.');
+ expect(step1.nodeIds).toEqual(['file:src/utils.ts', 'config:package.json']);
+ expect(normalized.find(step => step.order === 3).nodeIds).toEqual(['config:package.json']);
+ });
+
+ it('sorts steps by order and drops dangling references', () => {
+ const { root, intermediate } = setupFixture({
+ assembled: ASSEMBLED,
+ tour: [
+ { order: 3, title: 'Third', description: 'c', nodeIds: ['file:src/missing.tsx'] },
+ { order: 1, title: 'First', description: 'a', nodeIds: ['file:src/main.tsx'] },
+ ],
+ });
+ const result = runScript(root);
+ expect(result.status).toBe(0);
+ const normalized = JSON.parse(readFileSync(join(intermediate, 'tour.normalized.json'), 'utf-8'));
+ expect(normalized.map(step => step.title)).toEqual(['First', 'Third']);
+ expect(normalized[1].nodeIds).toEqual([]);
+ });
+
+ it('fails with exit 1 when assembled-graph.json is missing', () => {
+ const { root } = setupFixture({ assembled: null, tour: [{ order: 1, title: 'S', description: 'd', nodeIds: [] }] });
+ const result = runScript(root);
+ expect(result.status).toBe(1);
+ expect(result.stderr).toContain('assembled-graph.json is missing');
+ });
+
+ it('fails with exit 1 when tour.json is missing', () => {
+ const { root } = setupFixture({ assembled: ASSEMBLED, tour: null });
+ const result = runScript(root);
+ expect(result.status).toBe(1);
+ expect(result.stderr).toContain('tour.json is missing');
+ });
+
+ it('fails with exit 1 when the assembled graph has no usable nodes', () => {
+ const { root } = setupFixture({ assembled: { nodes: [], edges: [] }, tour: [] });
+ const result = runScript(root);
+ expect(result.status).toBe(1);
+ expect(result.stderr).toContain('no usable nodes');
+ });
+
+ it('accepts the legacy .understand-anything data directory', () => {
+ const root = mkdtempSync(join(tmpdir(), 'ua-normalize-tour-legacy-'));
+ roots.push(root);
+ const intermediate = join(root, '.understand-anything', 'intermediate');
+ mkdirSync(intermediate, { recursive: true });
+ writeFileSync(join(intermediate, 'assembled-graph.json'), JSON.stringify(ASSEMBLED));
+ writeFileSync(join(intermediate, 'tour.json'), JSON.stringify([
+ { order: 1, title: 'S', description: 'd', nodeIds: ['file:src/main.tsx'] },
+ ]));
+ const result = runScript(root);
+ expect(result.status).toBe(0);
+ expect(existsSync(join(root, '.understand-anything', 'intermediate', 'tour.normalized.json'))).toBe(true);
+ });
+});
diff --git a/tests/skill/understand/test_prepare_incremental.test.mjs b/tests/skill/understand/test_prepare_incremental.test.mjs
index fd54637b..c636a873 100644
--- a/tests/skill/understand/test_prepare_incremental.test.mjs
+++ b/tests/skill/understand/test_prepare_incremental.test.mjs
@@ -1,6 +1,7 @@
import { afterEach, describe, expect, it } from 'vitest';
import {
chmodSync,
+ existsSync,
mkdirSync,
mkdtempSync,
readFileSync,
@@ -1533,3 +1534,88 @@ describe('finalize-incremental.mjs', { timeout: 30_000 }, () => {
expect(readFileSync(metaPath, 'utf-8')).toBe(metaBefore);
});
});
+
+describe('finalize rollback after the graph is saved', { timeout: 30_000 }, () => {
+ function setupSkipRun() {
+ const { root, baseCommit } = setupRepository({
+ 'src/index.js': "const value = require('./a');\nmodule.exports = value;\n",
+ 'src/a.js': 'module.exports = 1;\n',
+ 'src/b.js': 'module.exports = 2;\n',
+ });
+ writeProjectFile(
+ root,
+ 'src/index.js',
+ "const value = require('./b');\nmodule.exports = value;\n",
+ );
+ commit(root, 'cosmetic require change');
+ const { plan } = prepare(root, baseCommit);
+ expect(plan.action).toBe('SKIP');
+ const dataDir = join(root, '.ua');
+ const graphPath = join(dataDir, 'knowledge-graph.json');
+ const fingerprintPath = join(dataDir, 'fingerprints.json');
+ const metaPath = join(dataDir, 'meta.json');
+ // Replace meta.json with a directory so the rename in advanceMeta's
+ // atomic write fails with EISDIR AFTER the graph and fingerprints were
+ // already written — exactly the late-failure window the rollback covers.
+ const breakMeta = () => {
+ if (existsSync(metaPath)) rmSync(metaPath);
+ mkdirSync(metaPath);
+ };
+ return { root, baseCommit, plan, graphPath, fingerprintPath, metaPath, breakMeta };
+ }
+
+ it('restores the previous graph and fingerprints when the meta patch fails after the graph is saved', () => {
+ const f = setupSkipRun();
+ // Compare parsed contents: the rollback rewrites via atomicWriteJson
+ // (pretty-printed), so byte identity with the compact baseline is not
+ // expected — content identity is the contract.
+ const graphBefore = JSON.parse(readFileSync(f.graphPath, 'utf-8'));
+ const fingerprintsBefore = JSON.parse(readFileSync(f.fingerprintPath, 'utf-8'));
+ f.breakMeta();
+ const result = spawnSync(process.execPath, [finalizeScript, f.root], {
+ cwd: f.root,
+ encoding: 'utf-8',
+ });
+ expect(result.status).toBe(1);
+ expect(result.stderr).toContain('Rolled back knowledge-graph.json and fingerprints.json');
+ expect(JSON.parse(readFileSync(f.graphPath, 'utf-8'))).toEqual(graphBefore);
+ expect(JSON.parse(readFileSync(f.fingerprintPath, 'utf-8'))).toEqual(fingerprintsBefore);
+ });
+
+ it('deletes a fingerprint store the failed patch created when none existed before', () => {
+ const f = setupSkipRun();
+ const graphBefore = JSON.parse(readFileSync(f.graphPath, 'utf-8'));
+ rmSync(f.fingerprintPath);
+ f.breakMeta();
+ const result = spawnSync(process.execPath, [finalizeScript, f.root], {
+ cwd: f.root,
+ encoding: 'utf-8',
+ });
+ expect(result.status).toBe(1);
+ expect(result.stderr).toContain('Rolled back knowledge-graph.json and fingerprints.json');
+ expect(JSON.parse(readFileSync(f.graphPath, 'utf-8'))).toEqual(graphBefore);
+ // patchFingerprints created the store before advanceMeta failed; the
+ // rollback must remove it — fresh fingerprints beside a restored old
+ // graph would make the next run misclassify every change.
+ expect(existsSync(f.fingerprintPath)).toBe(false);
+ });
+
+ it('still rolls the graph back when the fingerprint snapshot read fails on a corrupted store', () => {
+ const f = setupSkipRun();
+ const graphBefore = JSON.parse(readFileSync(f.graphPath, 'utf-8'));
+ const corrupted = 'this is not json{';
+ writeFileSync(f.fingerprintPath, corrupted, 'utf-8');
+ f.breakMeta();
+ const result = spawnSync(process.execPath, [finalizeScript, f.root], {
+ cwd: f.root,
+ encoding: 'utf-8',
+ });
+ expect(result.status).toBe(1);
+ // The snapshot read happens inside the try, so even a corrupted store
+ // (nothing to restore fingerprints from) must not escape with the new
+ // graph published; the graph still goes back to its previous state.
+ expect(result.stderr).toContain('Rolled back knowledge-graph.json and fingerprints.json');
+ expect(JSON.parse(readFileSync(f.graphPath, 'utf-8'))).toEqual(graphBefore);
+ expect(readFileSync(f.fingerprintPath, 'utf-8')).toBe(corrupted);
+ });
+});