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.
TypeScript antigravity-skillsbusiness-knowledgeclaude-codeclaude-skillscodebase-analysiscodexcodex-skillsdeveloper-tools-ai-agentgemini-cli-skillskarpathy-llm-wikiknowledge-baseknowledge-graphmemoryopencode-skillspi-agentunderstandcodevibe-coding
feat: warn when knowledge graphs are stale
jiang4wqy0bae36ebcf8c
diff --git a/tests/skill/understand/test_skill_graph_freshness.test.mjs b/tests/skill/understand/test_skill_graph_freshness.test.mjsnew file mode 100644index 00000000..f3244118--- /dev/null+++ b/tests/skill/understand/test_skill_graph_freshness.test.mjs@@ -0,0 +1,35 @@+import { readFileSync } from "node:fs";+import { dirname, resolve } from "node:path";+import { fileURLToPath } from "node:url";+import { describe, expect, it } from "vitest";++const __dirname = dirname(fileURLToPath(import.meta.url));+const repoRoot = resolve(__dirname, "../../..");++const graphConsumerSkills = [+ "understand-chat",+ "understand-explain",+ "understand-diff",+ "understand-onboard",+];++describe("graph-consuming skills", () => {+ it.each(graphConsumerSkills)(+ "%s warns when the knowledge graph commit differs from HEAD",+ (skillName) => {+ const skillPath = resolve(+ repoRoot,+ "understand-anything-plugin",+ "skills",+ skillName,+ "SKILL.md",+ );+ const content = readFileSync(skillPath, "utf-8");++ expect(content).toContain("gitCommitHash");+ expect(content).toContain("git rev-parse HEAD");+ expect(content).toContain("stale");+ expect(content).toContain("Run `/understand`");+ },+ );+});diff --git a/understand-anything-plugin/packages/core/src/__tests__/staleness.test.ts b/understand-anything-plugin/packages/core/src/__tests__/staleness.test.tsindex 23b96362..0e57ec9e 100644--- a/understand-anything-plugin/packages/core/src/__tests__/staleness.test.ts+++ b/understand-anything-plugin/packages/core/src/__tests__/staleness.test.ts@@ -1,253 +1,360 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import type { KnowledgeGraph, GraphNode, GraphEdge } from "../types.js";--vi.mock("child_process", () => ({- execFileSync: vi.fn(),-}));--// Import after mocking-import { execFileSync } from "child_process";-import { getChangedFiles, isStale, mergeGraphUpdate } from "../staleness.js";--const mockedExecFileSync = vi.mocked(execFileSync);--const makeNode = (- overrides: Partial<GraphNode> & { id: string; name: string },-): GraphNode => ({- type: "file",- summary: "",- tags: [],- complexity: "simple",- ...overrides,-});--const makeEdge = (- overrides: Partial<GraphEdge> & { source: string; target: string },-): GraphEdge => ({- type: "imports",- direction: "forward",- weight: 1,- ...overrides,-});--function makeGraph(overrides?: Partial<KnowledgeGraph>): KnowledgeGraph {- return {- version: "1.0.0",- project: {- name: "test-project",- languages: ["typescript"],- frameworks: [],- description: "A test project",- analyzedAt: "2026-01-01T00:00:00.000Z",- gitCommitHash: "abc123",- },- nodes: [],- edges: [],- layers: [],- tour: [],- ...overrides,- };-}--beforeEach(() => {- vi.clearAllMocks();+import { describe, it, expect, vi, beforeEach } from "vitest";+import type { KnowledgeGraph, GraphNode, GraphEdge } from "../types.js";++vi.mock("child_process", () => ({+ execFileSync: vi.fn(),+}));++// Import after mocking+import { execFileSync } from "child_process";+import {+ getChangedFiles,+ getGraphFreshness,+ isStale,+ mergeGraphUpdate,+} from "../staleness.js";++const mockedExecFileSync = vi.mocked(execFileSync);++const makeNode = (+ overrides: Partial<GraphNode> & { id: string; name: string },+): GraphNode => ({+ type: "file",+ summary: "",+ tags: [],+ complexity: "simple",+ ...overrides,+});++const makeEdge = (+ overrides: Partial<GraphEdge> & { source: string; target: string },+): GraphEdge => ({+ type: "imports",+ direction: "forward",+ weight: 1,+ ...overrides,+});++function makeGraph(overrides?: Partial<KnowledgeGraph>): KnowledgeGraph {+ return {+ version: "1.0.0",+ project: {+ name: "test-project",+ languages: ["typescript"],+ frameworks: [],+ description: "A test project",+ analyzedAt: "2026-01-01T00:00:00.000Z",+ gitCommitHash: "abc123",+ },+ nodes: [],+ edges: [],+ layers: [],+ tour: [],+ ...overrides,+ };+}++beforeEach(() => {+ vi.clearAllMocks();+});++describe("getChangedFiles", () => {+ it("returns changed file list from git diff", () => {+ mockedExecFileSync.mockReturnValue("src/index.ts\nsrc/utils.ts\n");++ const result = getChangedFiles("/project", "abc123");++ expect(result).toEqual(["src/index.ts", "src/utils.ts"]);+ expect(mockedExecFileSync).toHaveBeenCalledWith(+ "git",+ ["diff", "abc123..HEAD", "--name-only"],+ { cwd: "/project", encoding: "utf-8" },+ );+ });++ it("returns empty array when no changes", () => {+ mockedExecFileSync.mockReturnValue("");++ const result = getChangedFiles("/project", "abc123");++ expect(result).toEqual([]);+ });++ it("returns empty array on git error", () => {+ mockedExecFileSync.mockImplementation(() => {+ throw new Error("fatal: bad revision");+ });++ const result = getChangedFiles("/project", "abc123");++ expect(result).toEqual([]);+ });+});++describe("isStale", () => {+ it("returns stale when files have changed", () => {+ mockedExecFileSync.mockReturnValue("src/index.ts\n");++ const result = isStale("/project", "abc123");++ expect(result).toEqual({+ stale: true,+ changedFiles: ["src/index.ts"],+ });+ });++ it("returns not stale when no files changed", () => {+ mockedExecFileSync.mockReturnValue("");++ const result = isStale("/project", "abc123");++ expect(result).toEqual({+ stale: false,+ changedFiles: [],+ });+ });});-describe("getChangedFiles", () => {- it("returns changed file list from git diff", () => {- mockedExecFileSync.mockReturnValue("src/index.ts\nsrc/utils.ts\n");+describe("getGraphFreshness", () => {+ it("returns fresh when the graph commit matches HEAD", () => {+ mockedExecFileSync.mockReturnValue("abc123\n");- const result = getChangedFiles("/project", "abc123");+ const result = getGraphFreshness("/project", {+ graphCommitHash: "abc123",+ lastAnalyzedAt: "2026-01-01T00:00:00.000Z",+ });- expect(result).toEqual(["src/index.ts", "src/utils.ts"]);+ expect(result).toEqual({+ status: "fresh",+ graphCommitHash: "abc123",+ headCommitHash: "abc123",+ changedFileCount: 0,+ changedFiles: [],+ commitsBehind: 0,+ lastAnalyzedAt: "2026-01-01T00:00:00.000Z",+ });expect(mockedExecFileSync).toHaveBeenCalledWith("git",- ["diff", "abc123..HEAD", "--name-only"],+ ["rev-parse", "HEAD"],{ cwd: "/project", encoding: "utf-8" },);});- it("returns empty array when no changes", () => {- mockedExecFileSync.mockReturnValue("");-- const result = getChangedFiles("/project", "abc123");-- expect(result).toEqual([]);- });-- it("returns empty array on git error", () => {- mockedExecFileSync.mockImplementation(() => {- throw new Error("fatal: bad revision");+ it("returns stale with changed file and commit counts when HEAD moved", () => {+ mockedExecFileSync.mockImplementation((command, args) => {+ expect(command).toBe("git");+ if (Array.isArray(args) && args[0] === "rev-parse") return "def456\n";+ if (Array.isArray(args) && args[0] === "rev-list") return "3\n";+ if (Array.isArray(args) && args[0] === "diff") {+ return "src/index.ts\nsrc/auth.ts\n";+ }+ throw new Error(`unexpected git args: ${String(args)}`);});- const result = getChangedFiles("/project", "abc123");-- expect(result).toEqual([]);- });-});--describe("isStale", () => {- it("returns stale when files have changed", () => {- mockedExecFileSync.mockReturnValue("src/index.ts\n");-- const result = isStale("/project", "abc123");+ const result = getGraphFreshness("/project", {+ graphCommitHash: "abc123",+ lastAnalyzedAt: "2026-01-01T00:00:00.000Z",+ });expect(result).toEqual({- stale: true,- changedFiles: ["src/index.ts"],+ status: "stale",+ graphCommitHash: "abc123",+ headCommitHash: "def456",+ changedFileCount: 2,+ changedFiles: ["src/index.ts", "src/auth.ts"],+ commitsBehind: 3,+ lastAnalyzedAt: "2026-01-01T00:00:00.000Z",});});- it("returns not stale when no files changed", () => {- mockedExecFileSync.mockReturnValue("");-- const result = isStale("/project", "abc123");+ it("returns unknown when graph metadata has no commit hash", () => {+ const result = getGraphFreshness("/project", {+ graphCommitHash: "",+ lastAnalyzedAt: "2026-01-01T00:00:00.000Z",+ });expect(result).toEqual({- stale: false,- changedFiles: [],+ status: "unknown",+ reason: "missing-graph-commit",+ lastAnalyzedAt: "2026-01-01T00:00:00.000Z",});+ expect(mockedExecFileSync).not.toHaveBeenCalled();});-});-describe("mergeGraphUpdate", () => {- it("replaces nodes for changed files", () => {- const existingGraph = makeGraph({- nodes: [- makeNode({- id: "file-a",- name: "a.ts",- filePath: "src/a.ts",- summary: "Old summary",- }),- makeNode({- id: "file-b",- name: "b.ts",- filePath: "src/b.ts",- summary: "Unchanged",- }),- makeNode({- id: "func-a1",- name: "funcA1",- type: "function",- filePath: "src/a.ts",- summary: "Old function",- }),- ],+ it("returns unknown when git HEAD cannot be read", () => {+ mockedExecFileSync.mockImplementation(() => {+ throw new Error("fatal: not a git repository");});- const newNodes = [- makeNode({- id: "file-a-v2",- name: "a.ts",- filePath: "src/a.ts",- summary: "New summary",- }),- makeNode({- id: "func-a2",- name: "funcA2",- type: "function",- filePath: "src/a.ts",- summary: "New function",- }),- ];-- const result = mergeGraphUpdate(- existingGraph,- ["src/a.ts"],- newNodes,- [],- "def456",- );-- // Old nodes from src/a.ts should be gone- expect(result.nodes.find((n) => n.id === "file-a")).toBeUndefined();- expect(result.nodes.find((n) => n.id === "func-a1")).toBeUndefined();-- // New nodes should be present- expect(result.nodes.find((n) => n.id === "file-a-v2")).toBeDefined();- expect(result.nodes.find((n) => n.id === "func-a2")).toBeDefined();-- // Unchanged file should remain- expect(result.nodes.find((n) => n.id === "file-b")).toBeDefined();- });-- it("removes edges originating from changed files", () => {- const existingGraph = makeGraph({- nodes: [- makeNode({ id: "file-a", name: "a.ts", filePath: "src/a.ts" }),- makeNode({ id: "file-b", name: "b.ts", filePath: "src/b.ts" }),- makeNode({ id: "file-c", name: "c.ts", filePath: "src/c.ts" }),- ],- edges: [- // Edge from changed file -> should be removed- makeEdge({ source: "file-a", target: "file-b" }),- // Edge between unchanged files -> should remain- makeEdge({ source: "file-b", target: "file-c" }),- // Edge to changed file from unchanged -> should remain- makeEdge({ source: "file-c", target: "file-a" }),- ],+ const result = getGraphFreshness("/project", {+ graphCommitHash: "abc123",});- const newNodes = [- makeNode({- id: "file-a-v2",- name: "a.ts",- filePath: "src/a.ts",- summary: "Updated",- }),- ];-- const newEdges = [- makeEdge({ source: "file-a-v2", target: "file-c" }),- ];-- const result = mergeGraphUpdate(- existingGraph,- ["src/a.ts"],- newNodes,- newEdges,- "def456",- );-- // Old edge from file-a should be removed- expect(- result.edges.find(- (e) => e.source === "file-a" && e.target === "file-b",- ),- ).toBeUndefined();-- // Edge between unchanged files should remain- expect(- result.edges.find(- (e) => e.source === "file-b" && e.target === "file-c",- ),- ).toBeDefined();-- // Edge to changed file from unchanged should be removed (dangling target)- expect(- result.edges.find(- (e) => e.source === "file-c" && e.target === "file-a",- ),- ).toBeUndefined();-- // New edge should be added- expect(- result.edges.find(- (e) => e.source === "file-a-v2" && e.target === "file-c",- ),- ).toBeDefined();+ expect(result).toEqual({+ status: "unknown",+ reason: "git-head-unavailable",+ graphCommitHash: "abc123",+ });});- it("updates analyzedAt timestamp and gitCommitHash", () => {- const existingGraph = makeGraph();+ it("returns unknown when the graph commit cannot be diffed", () => {+ mockedExecFileSync.mockImplementation((command, args) => {+ expect(command).toBe("git");+ if (Array.isArray(args) && args[0] === "rev-parse") return "def456\n";+ throw new Error("fatal: bad revision");+ });- const before = new Date().toISOString();- const result = mergeGraphUpdate(existingGraph, [], [], [], "def456");- const after = new Date().toISOString();+ const result = getGraphFreshness("/project", {+ graphCommitHash: "missing123",+ });- expect(result.project.gitCommitHash).toBe("def456");- expect(result.project.analyzedAt >= before).toBe(true);- expect(result.project.analyzedAt <= after).toBe(true);+ expect(result).toEqual({+ status: "unknown",+ reason: "graph-commit-unavailable",+ graphCommitHash: "missing123",+ headCommitHash: "def456",+ });});});++describe("mergeGraphUpdate", () => {+ it("replaces nodes for changed files", () => {+ const existingGraph = makeGraph({+ nodes: [+ makeNode({+ id: "file-a",+ name: "a.ts",+ filePath: "src/a.ts",+ summary: "Old summary",+ }),+ makeNode({+ id: "file-b",+ name: "b.ts",+ filePath: "src/b.ts",+ summary: "Unchanged",+ }),+ makeNode({+ id: "func-a1",+ name: "funcA1",+ type: "function",+ filePath: "src/a.ts",+ summary: "Old function",+ }),+ ],+ });++ const newNodes = [+ makeNode({+ id: "file-a-v2",+ name: "a.ts",+ filePath: "src/a.ts",+ summary: "New summary",+ }),+ makeNode({+ id: "func-a2",+ name: "funcA2",+ type: "function",+ filePath: "src/a.ts",+ summary: "New function",+ }),+ ];++ const result = mergeGraphUpdate(+ existingGraph,+ ["src/a.ts"],+ newNodes,+ [],+ "def456",+ );++ // Old nodes from src/a.ts should be gone+ expect(result.nodes.find((n) => n.id === "file-a")).toBeUndefined();+ expect(result.nodes.find((n) => n.id === "func-a1")).toBeUndefined();++ // New nodes should be present+ expect(result.nodes.find((n) => n.id === "file-a-v2")).toBeDefined();+ expect(result.nodes.find((n) => n.id === "func-a2")).toBeDefined();++ // Unchanged file should remain+ expect(result.nodes.find((n) => n.id === "file-b")).toBeDefined();+ });++ it("removes edges originating from changed files", () => {+ const existingGraph = makeGraph({+ nodes: [+ makeNode({ id: "file-a", name: "a.ts", filePath: "src/a.ts" }),+ makeNode({ id: "file-b", name: "b.ts", filePath: "src/b.ts" }),+ makeNode({ id: "file-c", name: "c.ts", filePath: "src/c.ts" }),+ ],+ edges: [+ // Edge from changed file -> should be removed+ makeEdge({ source: "file-a", target: "file-b" }),+ // Edge between unchanged files -> should remain+ makeEdge({ source: "file-b", target: "file-c" }),+ // Edge to changed file from unchanged -> should remain+ makeEdge({ source: "file-c", target: "file-a" }),+ ],+ });++ const newNodes = [+ makeNode({+ id: "file-a-v2",+ name: "a.ts",+ filePath: "src/a.ts",+ summary: "Updated",+ }),+ ];++ const newEdges = [+ makeEdge({ source: "file-a-v2", target: "file-c" }),+ ];++ const result = mergeGraphUpdate(+ existingGraph,+ ["src/a.ts"],+ newNodes,+ newEdges,+ "def456",+ );++ // Old edge from file-a should be removed+ expect(+ result.edges.find(+ (e) => e.source === "file-a" && e.target === "file-b",+ ),+ ).toBeUndefined();++ // Edge between unchanged files should remain+ expect(+ result.edges.find(+ (e) => e.source === "file-b" && e.target === "file-c",+ ),+ ).toBeDefined();++ // Edge to changed file from unchanged should be removed (dangling target)+ expect(+ result.edges.find(+ (e) => e.source === "file-c" && e.target === "file-a",+ ),+ ).toBeUndefined();++ // New edge should be added+ expect(+ result.edges.find(+ (e) => e.source === "file-a-v2" && e.target === "file-c",+ ),+ ).toBeDefined();+ });++ it("updates analyzedAt timestamp and gitCommitHash", () => {+ const existingGraph = makeGraph();++ const before = new Date().toISOString();+ const result = mergeGraphUpdate(existingGraph, [], [], [], "def456");+ const after = new Date().toISOString();++ expect(result.project.gitCommitHash).toBe("def456");+ expect(result.project.analyzedAt >= before).toBe(true);+ expect(result.project.analyzedAt <= after).toBe(true);+ });+});diff --git a/understand-anything-plugin/packages/core/src/index.ts b/understand-anything-plugin/packages/core/src/index.tsindex c5f629aa..cb916e72 100644--- a/understand-anything-plugin/packages/core/src/index.ts+++ b/understand-anything-plugin/packages/core/src/index.ts@@ -1,124 +1,127 @@-export * from "./types.js";-export * from "./persistence/index.js";-export {- KnowledgeGraphSchema,- validateGraph,- sanitizeGraph,- autoFixGraph,- COMPLEXITY_ALIASES,- DIRECTION_ALIASES,- type ValidationResult,- type GraphIssue,-} from "./schema.js";-export { TreeSitterPlugin } from "./plugins/tree-sitter-plugin.js";-export type { LanguageExtractor } from "./plugins/extractors/types.js";-export { builtinExtractors } from "./plugins/extractors/index.js";-export { GraphBuilder } from "./analyzer/graph-builder.js";-export {- buildFileAnalysisPrompt,- buildProjectSummaryPrompt,- parseFileAnalysisResponse,- parseProjectSummaryResponse,-} from "./analyzer/llm-analyzer.js";-export type { LLMFileAnalysis, LLMProjectSummary } from "./analyzer/llm-analyzer.js";-export {- normalizeNodeId,- normalizeComplexity,- normalizeBatchOutput,- type DroppedEdge,- type NormalizationStats,- type NormalizeBatchResult,-} from "./analyzer/normalize-graph.js";-export { SearchEngine, type SearchResult, type SearchOptions } from "./search.js";-export {+export * from "./types.js";+export * from "./persistence/index.js";+export {+ KnowledgeGraphSchema,+ validateGraph,+ sanitizeGraph,+ autoFixGraph,+ COMPLEXITY_ALIASES,+ DIRECTION_ALIASES,+ type ValidationResult,+ type GraphIssue,+} from "./schema.js";+export { TreeSitterPlugin } from "./plugins/tree-sitter-plugin.js";+export type { LanguageExtractor } from "./plugins/extractors/types.js";+export { builtinExtractors } from "./plugins/extractors/index.js";+export { GraphBuilder } from "./analyzer/graph-builder.js";+export {+ buildFileAnalysisPrompt,+ buildProjectSummaryPrompt,+ parseFileAnalysisResponse,+ parseProjectSummaryResponse,+} from "./analyzer/llm-analyzer.js";+export type { LLMFileAnalysis, LLMProjectSummary } from "./analyzer/llm-analyzer.js";+export {+ normalizeNodeId,+ normalizeComplexity,+ normalizeBatchOutput,+ type DroppedEdge,+ type NormalizationStats,+ type NormalizeBatchResult,+} from "./analyzer/normalize-graph.js";+export { SearchEngine, type SearchResult, type SearchOptions } from "./search.js";+export {getChangedFiles,+ getGraphFreshness,isStale,mergeGraphUpdate,+ type GraphFreshnessInput,+ type GraphFreshnessResult,type StalenessResult,} from "./staleness.js";-export {- detectLayers,- buildLayerDetectionPrompt,- parseLayerDetectionResponse,- applyLLMLayers,-} from "./analyzer/layer-detector.js";-export type { LLMLayerResponse } from "./analyzer/layer-detector.js";-export {- buildTourGenerationPrompt,- parseTourGenerationResponse,- generateHeuristicTour,-} from "./analyzer/tour-generator.js";-export {- buildLanguageLessonPrompt,- parseLanguageLessonResponse,- detectLanguageConcepts,- type LanguageLessonResult,-} from "./analyzer/language-lesson.js";-export { PluginRegistry } from "./plugins/registry.js";-export {- LanguageRegistry,- FrameworkRegistry,- builtinLanguageConfigs,- builtinFrameworkConfigs,- LanguageConfigSchema,- FrameworkConfigSchema,-} from "./languages/index.js";-export type {- LanguageConfig,- FrameworkConfig,- TreeSitterConfig,- FilePatternConfig,-} from "./languages/index.js";-export {- parsePluginConfig,- serializePluginConfig,- DEFAULT_PLUGIN_CONFIG,- type PluginConfig,- type PluginEntry,-} from "./plugins/discovery.js";-export {- SemanticSearchEngine,- cosineSimilarity,- type SemanticSearchOptions,-} from "./embedding-search.js";-export {- extractFileFingerprint,- compareFingerprints,- analyzeChanges,- buildFingerprintStore,- contentHash,- type FunctionFingerprint,- type ClassFingerprint,- type ImportFingerprint,- type FileFingerprint,- type FingerprintStore,- type ChangeLevel,- type FileChangeResult,- type ChangeAnalysis,-} from "./fingerprint.js";-export {- classifyUpdate,- type UpdateDecision,-} from "./change-classifier.js";-// Non-code parsers-export {- MarkdownParser,- YAMLConfigParser,- JSONConfigParser,- TOMLParser,- EnvParser,- DockerfileParser,- SQLParser,- GraphQLParser,- ProtobufParser,- TerraformParser,- MakefileParser,- ShellParser,- registerAllParsers,-} from "./plugins/parsers/index.js";-export {- createIgnoreFilter,- DEFAULT_IGNORE_PATTERNS,- type IgnoreFilter,-} from "./ignore-filter.js";-export { generateStarterIgnoreFile } from "./ignore-generator.js";+export {+ detectLayers,+ buildLayerDetectionPrompt,+ parseLayerDetectionResponse,+ applyLLMLayers,+} from "./analyzer/layer-detector.js";+export type { LLMLayerResponse } from "./analyzer/layer-detector.js";+export {+ buildTourGenerationPrompt,+ parseTourGenerationResponse,+ generateHeuristicTour,+} from "./analyzer/tour-generator.js";+export {+ buildLanguageLessonPrompt,+ parseLanguageLessonResponse,+ detectLanguageConcepts,+ type LanguageLessonResult,+} from "./analyzer/language-lesson.js";+export { PluginRegistry } from "./plugins/registry.js";+export {+ LanguageRegistry,+ FrameworkRegistry,+ builtinLanguageConfigs,+ builtinFrameworkConfigs,+ LanguageConfigSchema,+ FrameworkConfigSchema,+} from "./languages/index.js";+export type {+ LanguageConfig,+ FrameworkConfig,+ TreeSitterConfig,+ FilePatternConfig,+} from "./languages/index.js";+export {+ parsePluginConfig,+ serializePluginConfig,+ DEFAULT_PLUGIN_CONFIG,+ type PluginConfig,+ type PluginEntry,+} from "./plugins/discovery.js";+export {+ SemanticSearchEngine,+ cosineSimilarity,+ type SemanticSearchOptions,+} from "./embedding-search.js";+export {+ extractFileFingerprint,+ compareFingerprints,+ analyzeChanges,+ buildFingerprintStore,+ contentHash,+ type FunctionFingerprint,+ type ClassFingerprint,+ type ImportFingerprint,+ type FileFingerprint,+ type FingerprintStore,+ type ChangeLevel,+ type FileChangeResult,+ type ChangeAnalysis,+} from "./fingerprint.js";+export {+ classifyUpdate,+ type UpdateDecision,+} from "./change-classifier.js";+// Non-code parsers+export {+ MarkdownParser,+ YAMLConfigParser,+ JSONConfigParser,+ TOMLParser,+ EnvParser,+ DockerfileParser,+ SQLParser,+ GraphQLParser,+ ProtobufParser,+ TerraformParser,+ MakefileParser,+ ShellParser,+ registerAllParsers,+} from "./plugins/parsers/index.js";+export {+ createIgnoreFilter,+ DEFAULT_IGNORE_PATTERNS,+ type IgnoreFilter,+} from "./ignore-filter.js";+export { generateStarterIgnoreFile } from "./ignore-generator.js";diff --git a/understand-anything-plugin/packages/core/src/staleness.ts b/understand-anything-plugin/packages/core/src/staleness.tsindex 0750ba3f..5948f695 100644--- a/understand-anything-plugin/packages/core/src/staleness.ts+++ b/understand-anything-plugin/packages/core/src/staleness.ts@@ -1,90 +1,207 @@-import { execFileSync } from "child_process";-import type { KnowledgeGraph, GraphNode, GraphEdge } from "./types.js";-+import { execFileSync } from "child_process";+import type { KnowledgeGraph, GraphNode, GraphEdge } from "./types.js";+export interface StalenessResult {stale: boolean;changedFiles: string[];}+export type GraphFreshnessResult =+ | {+ status: "fresh";+ graphCommitHash: string;+ headCommitHash: string;+ changedFileCount: 0;+ changedFiles: [];+ commitsBehind: 0;+ lastAnalyzedAt?: string;+ }+ | {+ status: "stale";+ graphCommitHash: string;+ headCommitHash: string;+ changedFileCount: number;+ changedFiles: string[];+ commitsBehind: number;+ lastAnalyzedAt?: string;+ }+ | {+ status: "unknown";+ reason:+ | "missing-graph-commit"+ | "git-head-unavailable"+ | "graph-commit-unavailable";+ graphCommitHash?: string;+ headCommitHash?: string;+ lastAnalyzedAt?: string;+ };++export interface GraphFreshnessInput {+ graphCommitHash?: string | null;+ lastAnalyzedAt?: string;+}++function runGit(projectDir: string, args: string[]): string {+ return execFileSync("git", args, {+ cwd: projectDir,+ encoding: "utf-8",+ }).trim();+}++function parseChangedFiles(output: string): string[] {+ return output+ .split("\n")+ .map((line) => line.trim())+ .filter((line) => line.length > 0);+}+/*** Get the list of files that changed between a given commit and HEAD.* Returns an empty array if there are no changes or if git encounters an error.*/-export function getChangedFiles(- projectDir: string,- lastCommitHash: string,-): string[] {+export function getChangedFiles(+ projectDir: string,+ lastCommitHash: string,+): string[] {try {- const output = execFileSync('git', ['diff', `${lastCommitHash}..HEAD`, '--name-only'], {+ const output = execFileSync("git", ["diff", `${lastCommitHash}..HEAD`, "--name-only"], {cwd: projectDir,encoding: "utf-8",});- return output- .split("\n")- .map((line) => line.trim())- .filter((line) => line.length > 0);+ return parseChangedFiles(output);} catch {return [];}}--/**- * Check whether the knowledge graph is stale relative to the current HEAD.- */++/**+ * Check whether the knowledge graph is stale relative to the current HEAD.+ */export function isStale(projectDir: string,lastCommitHash: string,): StalenessResult {- const changedFiles = getChangedFiles(projectDir, lastCommitHash);- return {- stale: changedFiles.length > 0,- changedFiles,- };+ const changedFiles = getChangedFiles(projectDir, lastCommitHash);+ return {+ stale: changedFiles.length > 0,+ changedFiles,+ };}/**- * Merge new analysis results into an existing knowledge graph.+ * Describe whether a persisted graph can still be trusted for the current HEAD.*- * 1. Remove old nodes belonging to changed files (matched by filePath).- * 2. Remove old edges where the SOURCE or TARGET node belongs to a changed file.- * 3. Add new nodes and edges.- * 4. Update project.gitCommitHash and project.analyzedAt.- * 5. Return the merged graph.+ * Unknown is intentionally distinct from fresh: if git metadata cannot be read,+ * callers should warn softly rather than imply the graph is current.*/-export function mergeGraphUpdate(- existingGraph: KnowledgeGraph,- changedFilePaths: string[],- newNodes: GraphNode[],- newEdges: GraphEdge[],- newCommitHash: string,-): KnowledgeGraph {- const changedSet = new Set(changedFilePaths);-- // Collect IDs of nodes that belong to changed files (will be removed)- const removedNodeIds = new Set(- existingGraph.nodes- .filter((node) => node.filePath !== undefined && changedSet.has(node.filePath))- .map((node) => node.id),- );+export function getGraphFreshness(+ projectDir: string,+ input: GraphFreshnessInput,+): GraphFreshnessResult {+ const graphCommitHash = input.graphCommitHash?.trim();+ if (!graphCommitHash) {+ return {+ status: "unknown",+ reason: "missing-graph-commit",+ lastAnalyzedAt: input.lastAnalyzedAt,+ };+ }- // Keep nodes that don't belong to changed files- const retainedNodes = existingGraph.nodes.filter(- (node) => !removedNodeIds.has(node.id),- );+ let headCommitHash: string;+ try {+ headCommitHash = runGit(projectDir, ["rev-parse", "HEAD"]);+ } catch {+ return {+ status: "unknown",+ reason: "git-head-unavailable",+ graphCommitHash,+ lastAnalyzedAt: input.lastAnalyzedAt,+ };+ }- // Keep edges whose source or target node is not in the removed set- const retainedEdges = existingGraph.edges.filter(- (edge) => !removedNodeIds.has(edge.source) && !removedNodeIds.has(edge.target),- );+ if (headCommitHash === graphCommitHash) {+ return {+ status: "fresh",+ graphCommitHash,+ headCommitHash,+ changedFileCount: 0,+ changedFiles: [],+ commitsBehind: 0,+ lastAnalyzedAt: input.lastAnalyzedAt,+ };+ }- return {- ...existingGraph,- project: {- ...existingGraph.project,- gitCommitHash: newCommitHash,- analyzedAt: new Date().toISOString(),- },- nodes: [...retainedNodes, ...newNodes],- edges: [...retainedEdges, ...newEdges],- };+ try {+ const commitsBehind = Number.parseInt(+ runGit(projectDir, ["rev-list", "--count", `${graphCommitHash}..HEAD`]),+ 10,+ );+ const changedFiles = parseChangedFiles(+ runGit(projectDir, ["diff", `${graphCommitHash}..HEAD`, "--name-only"]),+ );+ return {+ status: "stale",+ graphCommitHash,+ headCommitHash,+ changedFileCount: changedFiles.length,+ changedFiles,+ commitsBehind: Number.isFinite(commitsBehind) ? commitsBehind : 0,+ lastAnalyzedAt: input.lastAnalyzedAt,+ };+ } catch {+ return {+ status: "unknown",+ reason: "graph-commit-unavailable",+ graphCommitHash,+ headCommitHash,+ lastAnalyzedAt: input.lastAnalyzedAt,+ };+ }}++/**+ * Merge new analysis results into an existing knowledge graph.+ *+ * 1. Remove old nodes belonging to changed files (matched by filePath).+ * 2. Remove old edges where the SOURCE or TARGET node belongs to a changed file.+ * 3. Add new nodes and edges.+ * 4. Update project.gitCommitHash and project.analyzedAt.+ * 5. Return the merged graph.+ */+export function mergeGraphUpdate(+ existingGraph: KnowledgeGraph,+ changedFilePaths: string[],+ newNodes: GraphNode[],+ newEdges: GraphEdge[],+ newCommitHash: string,+): KnowledgeGraph {+ const changedSet = new Set(changedFilePaths);++ // Collect IDs of nodes that belong to changed files (will be removed)+ const removedNodeIds = new Set(+ existingGraph.nodes+ .filter((node) => node.filePath !== undefined && changedSet.has(node.filePath))+ .map((node) => node.id),+ );++ // Keep nodes that don't belong to changed files+ const retainedNodes = existingGraph.nodes.filter(+ (node) => !removedNodeIds.has(node.id),+ );++ // Keep edges whose source or target node is not in the removed set+ const retainedEdges = existingGraph.edges.filter(+ (edge) => !removedNodeIds.has(edge.source) && !removedNodeIds.has(edge.target),+ );++ return {+ ...existingGraph,+ project: {+ ...existingGraph.project,+ gitCommitHash: newCommitHash,+ analyzedAt: new Date().toISOString(),+ },+ nodes: [...retainedNodes, ...newNodes],+ edges: [...retainedEdges, ...newEdges],+ };+}diff --git a/understand-anything-plugin/packages/dashboard/src/App.tsx b/understand-anything-plugin/packages/dashboard/src/App.tsxindex cd1b33c7..305b559b 100644--- a/understand-anything-plugin/packages/dashboard/src/App.tsx+++ b/understand-anything-plugin/packages/dashboard/src/App.tsx@@ -1,715 +1,739 @@-import { useEffect, useState, useMemo, useCallback, lazy, Suspense } from "react";-import { validateGraph } from "@understand-anything/core/schema";-import type { GraphIssue } from "@understand-anything/core/schema";-import { useDashboardStore } from "./store";-import GraphView from "./components/GraphView";-import DomainGraphView from "./components/DomainGraphView";-import KnowledgeGraphView from "./components/KnowledgeGraphView";-import SearchBar from "./components/SearchBar";-import NodeInfo from "./components/NodeInfo";-import LayerLegend from "./components/LayerLegend";-import DiffToggle from "./components/DiffToggle";-import FilterPanel from "./components/FilterPanel";-import ExportMenu from "./components/ExportMenu";-import PersonaSelector from "./components/PersonaSelector";-import ProjectOverview from "./components/ProjectOverview";+import { useEffect, useState, useMemo, useCallback, lazy, Suspense } from "react";+import { validateGraph } from "@understand-anything/core/schema";+import type { GraphIssue } from "@understand-anything/core/schema";+import { useDashboardStore } from "./store";+import GraphView from "./components/GraphView";+import DomainGraphView from "./components/DomainGraphView";+import KnowledgeGraphView from "./components/KnowledgeGraphView";+import SearchBar from "./components/SearchBar";+import NodeInfo from "./components/NodeInfo";+import LayerLegend from "./components/LayerLegend";+import DiffToggle from "./components/DiffToggle";+import FilterPanel from "./components/FilterPanel";+import ExportMenu from "./components/ExportMenu";+import PersonaSelector from "./components/PersonaSelector";+import ProjectOverview from "./components/ProjectOverview";import FileExplorer from "./components/FileExplorer";import WarningBanner from "./components/WarningBanner";+import StalenessBanner, {+ isGraphFreshnessResult,+ type GraphFreshnessResult,+} from "./components/StalenessBanner";import TokenGate from "./components/TokenGate";import MobileLayout from "./components/MobileLayout";-import { useIsMobile } from "./hooks/useIsMobile";-import { useKeyboardShortcuts } from "./hooks/useKeyboardShortcuts";-import type { KeyboardShortcut } from "./hooks/useKeyboardShortcuts";-import { ThemeProvider } from "./themes/index.ts";-import { ThemePicker } from "./components/ThemePicker.tsx";-import type { ThemeConfig } from "./themes/index.ts";-import { I18nProvider, useI18n } from "./contexts/I18nContext.tsx";--// Lazy-load heavy / optional components so they ship in separate chunks.-const CodeViewer = lazy(() => import("./components/CodeViewer"));-const LearnPanel = lazy(() => import("./components/LearnPanel"));-const PathFinderModal = lazy(() => import("./components/PathFinderModal"));-const KeyboardShortcutsHelp = lazy(- () => import("./components/KeyboardShortcutsHelp"),-);-const OnboardingOverlay = lazy(() => import("./components/OnboardingOverlay"));--const DEMO_MODE = import.meta.env.VITE_DEMO_MODE === "true";-const SESSION_TOKEN_KEY = "understand-anything-token";-const ONBOARDING_DISMISSED_KEY = "ua-onboarding-dismissed-v1";-type SidebarTab = "info" | "files";--function shouldShowOnboarding(): boolean {- if (typeof window === "undefined") return false;- const params = new URLSearchParams(window.location.search);- if (params.get("onboard") === "force") return true;- return window.localStorage.getItem(ONBOARDING_DISMISSED_KEY) !== "1";-}--/** Resolve data file URL — in demo mode, use env var URLs; otherwise use local paths with token. */-function dataUrl(fileName: string, token: string | null): string {- if (DEMO_MODE) {- const envMap: Record<string, string | undefined> = {- "knowledge-graph.json": import.meta.env.VITE_GRAPH_URL,- "domain-graph.json": import.meta.env.VITE_DOMAIN_GRAPH_URL,- "meta.json": import.meta.env.VITE_META_URL,+import { useIsMobile } from "./hooks/useIsMobile";+import { useKeyboardShortcuts } from "./hooks/useKeyboardShortcuts";+import type { KeyboardShortcut } from "./hooks/useKeyboardShortcuts";+import { ThemeProvider } from "./themes/index.ts";+import { ThemePicker } from "./components/ThemePicker.tsx";+import type { ThemeConfig } from "./themes/index.ts";+import { I18nProvider, useI18n } from "./contexts/I18nContext.tsx";++// Lazy-load heavy / optional components so they ship in separate chunks.+const CodeViewer = lazy(() => import("./components/CodeViewer"));+const LearnPanel = lazy(() => import("./components/LearnPanel"));+const PathFinderModal = lazy(() => import("./components/PathFinderModal"));+const KeyboardShortcutsHelp = lazy(+ () => import("./components/KeyboardShortcutsHelp"),+);+const OnboardingOverlay = lazy(() => import("./components/OnboardingOverlay"));++const DEMO_MODE = import.meta.env.VITE_DEMO_MODE === "true";+const SESSION_TOKEN_KEY = "understand-anything-token";+const ONBOARDING_DISMISSED_KEY = "ua-onboarding-dismissed-v1";+type SidebarTab = "info" | "files";++function shouldShowOnboarding(): boolean {+ if (typeof window === "undefined") return false;+ const params = new URLSearchParams(window.location.search);+ if (params.get("onboard") === "force") return true;+ return window.localStorage.getItem(ONBOARDING_DISMISSED_KEY) !== "1";+}++/** Resolve data file URL — in demo mode, use env var URLs; otherwise use local paths with token. */+function dataUrl(fileName: string, token: string | null): string {+ if (DEMO_MODE) {+ const envMap: Record<string, string | undefined> = {+ "knowledge-graph.json": import.meta.env.VITE_GRAPH_URL,+ "domain-graph.json": import.meta.env.VITE_DOMAIN_GRAPH_URL,+ "meta.json": import.meta.env.VITE_META_URL,"diff-overlay.json": import.meta.env.VITE_DIFF_OVERLAY_URL,"config.json": import.meta.env.VITE_CONFIG_URL,+ "staleness.json": import.meta.env.VITE_STALENESS_URL,};- const url = envMap[fileName];- if (url) return url;- const base = import.meta.env.BASE_URL || "/";- return `${base.endsWith("/") ? base : `${base}/`}${fileName}`;- }- const path = `/${fileName}`;- return token ? `${path}?token=${encodeURIComponent(token)}` : path;-}--/**- * Resolve the access token from the URL query string or sessionStorage.- * If found in the URL, persist to sessionStorage and strip the param from the address bar.- */-function resolveInitialToken(): string | null {- if (DEMO_MODE) return "__demo__";- const params = new URLSearchParams(window.location.search);- const urlToken = params.get("token");- if (urlToken) {- sessionStorage.setItem(SESSION_TOKEN_KEY, urlToken);- // Clean the URL- params.delete("token");- const cleanSearch = params.toString();- const newUrl =- window.location.pathname + (cleanSearch ? `?${cleanSearch}` : "") + window.location.hash;- window.history.replaceState(null, "", newUrl);- return urlToken;- }- return sessionStorage.getItem(SESSION_TOKEN_KEY);-}--function App() {- const [accessToken, setAccessToken] = useState<string | null>(resolveInitialToken);-- const handleTokenValid = useCallback((token: string) => {- sessionStorage.setItem(SESSION_TOKEN_KEY, token);- setAccessToken(token);- }, []);-- // In demo mode, skip token gate entirely- if (DEMO_MODE) {- return <Dashboard accessToken="__demo__" />;- }-- // Show the token gate when no token is available- if (accessToken === null) {- return <TokenGate onTokenValid={handleTokenValid} />;- }-- return <Dashboard accessToken={accessToken} />;-}--function Dashboard({ accessToken }: { accessToken: string }) {- const setGraph = useDashboardStore((s) => s.setGraph);- const setDomainGraph = useDashboardStore((s) => s.setDomainGraph);- const setDiffOverlay = useDashboardStore((s) => s.setDiffOverlay);- const [loadError, setLoadError] = useState<string | null>(null);+ const url = envMap[fileName];+ if (url) return url;+ const base = import.meta.env.BASE_URL || "/";+ return `${base.endsWith("/") ? base : `${base}/`}${fileName}`;+ }+ const path = `/${fileName}`;+ return token ? `${path}?token=${encodeURIComponent(token)}` : path;+}++/**+ * Resolve the access token from the URL query string or sessionStorage.+ * If found in the URL, persist to sessionStorage and strip the param from the address bar.+ */+function resolveInitialToken(): string | null {+ if (DEMO_MODE) return "__demo__";+ const params = new URLSearchParams(window.location.search);+ const urlToken = params.get("token");+ if (urlToken) {+ sessionStorage.setItem(SESSION_TOKEN_KEY, urlToken);+ // Clean the URL+ params.delete("token");+ const cleanSearch = params.toString();+ const newUrl =+ window.location.pathname + (cleanSearch ? `?${cleanSearch}` : "") + window.location.hash;+ window.history.replaceState(null, "", newUrl);+ return urlToken;+ }+ return sessionStorage.getItem(SESSION_TOKEN_KEY);+}++function App() {+ const [accessToken, setAccessToken] = useState<string | null>(resolveInitialToken);++ const handleTokenValid = useCallback((token: string) => {+ sessionStorage.setItem(SESSION_TOKEN_KEY, token);+ setAccessToken(token);+ }, []);++ // In demo mode, skip token gate entirely+ if (DEMO_MODE) {+ return <Dashboard accessToken="__demo__" />;+ }++ // Show the token gate when no token is available+ if (accessToken === null) {+ return <TokenGate onTokenValid={handleTokenValid} />;+ }++ return <Dashboard accessToken={accessToken} />;+}++function Dashboard({ accessToken }: { accessToken: string }) {+ const setGraph = useDashboardStore((s) => s.setGraph);+ const setDomainGraph = useDashboardStore((s) => s.setDomainGraph);+ const setDiffOverlay = useDashboardStore((s) => s.setDiffOverlay);+ const [loadError, setLoadError] = useState<string | null>(null);const [graphIssues, setGraphIssues] = useState<GraphIssue[]>([]);+ const [graphFreshness, setGraphFreshness] = useState<GraphFreshnessResult | null>(null);const [metaTheme, setMetaTheme] = useState<ThemeConfig | null>(null);const [outputLanguage, setOutputLanguage] = useState<string | undefined>();-- useEffect(() => {- fetch(dataUrl("meta.json", accessToken))- .then((r) => (r.ok ? r.json() : null))- .then((meta) => {- if (meta?.theme) setMetaTheme(meta.theme);- })- .catch(() => {});- fetch(dataUrl("config.json", accessToken))- .then((r) => (r.ok ? r.json() : null))- .then((config) => {- if (config?.outputLanguage) setOutputLanguage(config.outputLanguage);- })- .catch(() => {});- }, []);-++ useEffect(() => {+ fetch(dataUrl("meta.json", accessToken))+ .then((r) => (r.ok ? r.json() : null))+ .then((meta) => {+ if (meta?.theme) setMetaTheme(meta.theme);+ })+ .catch(() => {});+ fetch(dataUrl("config.json", accessToken))+ .then((r) => (r.ok ? r.json() : null))+ .then((config) => {+ if (config?.outputLanguage) setOutputLanguage(config.outputLanguage);+ })+ .catch(() => {});+ }, []);+useEffect(() => {fetch(dataUrl("knowledge-graph.json", accessToken))- .then((res) => res.json())- .then((data: unknown) => {- const result = validateGraph(data);- if (result.success && result.data) {- setGraph(result.data);- setGraphIssues(result.issues);- if ((data as Record<string, unknown>).kind === "knowledge") {- useDashboardStore.getState().setViewMode("knowledge");- useDashboardStore.getState().setIsKnowledgeGraph(true);- }- for (const issue of result.issues) {- if (issue.level === "auto-corrected") {- console.warn(`[graph] auto-corrected: ${issue.message}`);- } else if (issue.level === "dropped") {- console.error(`[graph] dropped: ${issue.message}`);- }- }- } else if (result.fatal) {- console.error("Knowledge graph validation failed:", result.fatal);- setLoadError(`Invalid knowledge graph: ${result.fatal}`);- } else {- console.error("Knowledge graph validation failed: unknown error");- setLoadError("Invalid knowledge graph: unknown validation error");- }- })- .catch((err) => {- console.error("Failed to load knowledge graph:", err);- setLoadError(`Failed to load knowledge graph: ${err instanceof Error ? err.message : String(err)}`);- });+ .then((res) => res.json())+ .then((data: unknown) => {+ const result = validateGraph(data);+ if (result.success && result.data) {+ setGraph(result.data);+ setGraphIssues(result.issues);+ if ((data as Record<string, unknown>).kind === "knowledge") {+ useDashboardStore.getState().setViewMode("knowledge");+ useDashboardStore.getState().setIsKnowledgeGraph(true);+ }+ for (const issue of result.issues) {+ if (issue.level === "auto-corrected") {+ console.warn(`[graph] auto-corrected: ${issue.message}`);+ } else if (issue.level === "dropped") {+ console.error(`[graph] dropped: ${issue.message}`);+ }+ }+ } else if (result.fatal) {+ console.error("Knowledge graph validation failed:", result.fatal);+ setLoadError(`Invalid knowledge graph: ${result.fatal}`);+ } else {+ console.error("Knowledge graph validation failed: unknown error");+ setLoadError("Invalid knowledge graph: unknown validation error");+ }+ })+ .catch((err) => {+ console.error("Failed to load knowledge graph:", err);+ setLoadError(`Failed to load knowledge graph: ${err instanceof Error ? err.message : String(err)}`);+ });}, [setGraph]);useEffect(() => {- fetch(dataUrl("diff-overlay.json", accessToken))- .then((res) => {- if (!res.ok) return null;- return res.json();- })- .then((data: unknown) => {- if (- data &&- typeof data === "object" &&- "changedNodeIds" in data &&- "affectedNodeIds" in data &&- Array.isArray((data as Record<string, unknown>).changedNodeIds) &&- Array.isArray((data as Record<string, unknown>).affectedNodeIds)- ) {- const d = data as { changedNodeIds: string[]; affectedNodeIds: string[] };- if (d.changedNodeIds.length > 0) {- setDiffOverlay(d.changedNodeIds, d.affectedNodeIds);- }- }- })- .catch(() => {});- }, [setDiffOverlay]);-- useEffect(() => {- fetch(dataUrl("domain-graph.json", accessToken))- .then((res) => {- if (!res.ok) return null;- return res.json();- })+ fetch(dataUrl("staleness.json", accessToken))+ .then((res) => (res.ok ? res.json() : null)).then((data: unknown) => {- if (!data) return;- const result = validateGraph(data);- if (result.success && result.data) {- setDomainGraph(result.data);- } else if (result.fatal) {- console.warn(`[domain-graph] validation failed: ${result.fatal}`);+ if (isGraphFreshnessResult(data)) {+ setGraphFreshness(data);}}).catch(() => {});- }, [setDomainGraph]);-- return (- <I18nProvider language={outputLanguage ?? "en"}>- <ThemeProvider metaTheme={metaTheme}>- <DashboardContent+ }, [accessToken]);++ useEffect(() => {+ fetch(dataUrl("diff-overlay.json", accessToken))+ .then((res) => {+ if (!res.ok) return null;+ return res.json();+ })+ .then((data: unknown) => {+ if (+ data &&+ typeof data === "object" &&+ "changedNodeIds" in data &&+ "affectedNodeIds" in data &&+ Array.isArray((data as Record<string, unknown>).changedNodeIds) &&+ Array.isArray((data as Record<string, unknown>).affectedNodeIds)+ ) {+ const d = data as { changedNodeIds: string[]; affectedNodeIds: string[] };+ if (d.changedNodeIds.length > 0) {+ setDiffOverlay(d.changedNodeIds, d.affectedNodeIds);+ }+ }+ })+ .catch(() => {});+ }, [setDiffOverlay]);++ useEffect(() => {+ fetch(dataUrl("domain-graph.json", accessToken))+ .then((res) => {+ if (!res.ok) return null;+ return res.json();+ })+ .then((data: unknown) => {+ if (!data) return;+ const result = validateGraph(data);+ if (result.success && result.data) {+ setDomainGraph(result.data);+ } else if (result.fatal) {+ console.warn(`[domain-graph] validation failed: ${result.fatal}`);+ }+ })+ .catch(() => {});+ }, [setDomainGraph]);++ return (+ <I18nProvider language={outputLanguage ?? "en"}>+ <ThemeProvider metaTheme={metaTheme}>+ <DashboardContentaccessToken={accessToken}loadError={loadError}graphIssues={graphIssues}+ graphFreshness={graphFreshness}/>- </ThemeProvider>- </I18nProvider>- );-}--function DashboardContent({+ </ThemeProvider>+ </I18nProvider>+ );+}++function DashboardContent({accessToken,loadError,graphIssues,+ graphFreshness,}: {accessToken: string;loadError: string | null;graphIssues: GraphIssue[];+ graphFreshness: GraphFreshnessResult | null;}) {- const graph = useDashboardStore((s) => s.graph);- const selectedNodeId = useDashboardStore((s) => s.selectedNodeId);- const tourActive = useDashboardStore((s) => s.tourActive);- const persona = useDashboardStore((s) => s.persona);- const codeViewerOpen = useDashboardStore((s) => s.codeViewerOpen);- const codeViewerExpanded = useDashboardStore((s) => s.codeViewerExpanded);- const expandCodeViewer = useDashboardStore((s) => s.expandCodeViewer);- const collapseCodeViewer = useDashboardStore((s) => s.collapseCodeViewer);- const pathFinderOpen = useDashboardStore((s) => s.pathFinderOpen);- const togglePathFinder = useDashboardStore((s) => s.togglePathFinder);- const nodeTypeFilters = useDashboardStore((s) => s.nodeTypeFilters);- const toggleNodeTypeFilter = useDashboardStore((s) => s.toggleNodeTypeFilter);- const detailLevel = useDashboardStore((s) => s.detailLevel);- const setDetailLevel = useDashboardStore((s) => s.setDetailLevel);- const showFunctionsInClassView = useDashboardStore((s) => s.showFunctionsInClassView);- const toggleShowFunctionsInClassView = useDashboardStore((s) => s.toggleShowFunctionsInClassView);- const [showKeyboardHelp, setShowKeyboardHelp] = useState(false);- const [sidebarTab, setSidebarTab] = useState<SidebarTab>("info");- const [showOnboarding, setShowOnboarding] = useState(shouldShowOnboarding);- const dismissOnboarding = useCallback((remember: boolean) => {- if (remember && typeof window !== "undefined") {- window.localStorage.setItem(ONBOARDING_DISMISSED_KEY, "1");- }- setShowOnboarding(false);- }, []);- const viewMode = useDashboardStore((s) => s.viewMode);- const setViewMode = useDashboardStore((s) => s.setViewMode);- const isKnowledgeGraph = useDashboardStore((s) => s.isKnowledgeGraph);- const domainGraph = useDashboardStore((s) => s.domainGraph);- const layoutIssues = useDashboardStore((s) => s.layoutIssues);- const isMobile = useIsMobile();- const { t } = useI18n();- const allIssues = useMemo(- () => [...graphIssues, ...layoutIssues],- [graphIssues, layoutIssues],- );-- useEffect(() => {- if (selectedNodeId) setSidebarTab("info");- }, [selectedNodeId]);-- // Define keyboard shortcuts- const shortcuts = useMemo<KeyboardShortcut[]>(- () => [- // Help- {- key: "?",- shiftKey: true,- description: t.keyboardShortcuts.showHelp,- action: () => setShowKeyboardHelp((prev) => !prev),- category: "General",- },- // Navigation- {- key: "Escape",- description: t.keyboardShortcuts.escapeDesc,- action: () => {- // Read from store at invocation time to avoid stale closures- const state = useDashboardStore.getState();- if (state.pathFinderOpen) {- state.togglePathFinder();- } else if (state.filterPanelOpen) {- state.toggleFilterPanel();- } else if (state.exportMenuOpen) {- state.toggleExportMenu();- } else if (state.codeViewerExpanded) {- state.collapseCodeViewer();- } else if (state.codeViewerOpen) {- state.closeCodeViewer();- } else if (state.selectedNodeId) {- state.selectNode(null);- } else if (state.navigationLevel === "layer-detail") {- state.navigateToOverview();- } else if (state.tourActive) {- state.stopTour();- } else {- setShowKeyboardHelp(false);- }- },- category: "Navigation",- },- {- key: "/",- description: t.keyboardShortcuts.focusSearch,- action: () => {- const searchInput = document.querySelector<HTMLInputElement>(- '[data-testid="search-input"]'- );- searchInput?.focus();- },- category: "Navigation",- },- // Tour controls- {- key: "ArrowRight",- description: t.keyboardShortcuts.nextStep,- action: () => {- const state = useDashboardStore.getState();- if (state.tourActive) {- state.nextTourStep();- }- },- category: "Tour",- },- {- key: "ArrowLeft",- description: t.keyboardShortcuts.prevStep,- action: () => {- const state = useDashboardStore.getState();- if (state.tourActive) {- state.prevTourStep();- }- },- category: "Tour",- },- // View toggles- {- key: "d",- description: t.keyboardShortcuts.toggleDiff,- action: () => {- const state = useDashboardStore.getState();- state.toggleDiffMode();- },- category: "View",- },- {- key: "f",- description: t.keyboardShortcuts.toggleFilter,- action: () => {- const state = useDashboardStore.getState();- state.toggleFilterPanel();- },- category: "View",- },- {- key: "e",- description: t.keyboardShortcuts.toggleExport,- action: () => {- const state = useDashboardStore.getState();- state.toggleExportMenu();- },- category: "View",- },- {- key: "p",- description: t.keyboardShortcuts.openPathFinder,- action: () => {- const state = useDashboardStore.getState();- state.togglePathFinder();- },- category: "View",- },- ],- [t]- );-- // Register keyboard shortcuts- useKeyboardShortcuts(shortcuts);-- // Determine sidebar content- // NodeInfo always takes priority when a node is selected.- // Learn mode adds LearnPanel below it; otherwise ProjectOverview shows when idle.- const isLearnMode = tourActive || persona === "junior";- const infoSidebarContent = (- <>- {selectedNodeId && <NodeInfo />}- {isLearnMode && (- <Suspense fallback={null}>- <LearnPanel />- </Suspense>- )}- {!selectedNodeId && !isLearnMode && <ProjectOverview />}- </>- );-- const sidebarContent = (- <div className="h-full flex flex-col min-h-0">- <div className="flex items-center gap-1 p-2 border-b border-border-subtle bg-surface shrink-0">- {(["info", "files"] as const).map((tab) => (- <button- key={tab}- type="button"- onClick={() => setSidebarTab(tab)}- className={`flex-1 px-3 py-1.5 rounded-md text-xs font-semibold uppercase tracking-wider transition-colors ${- sidebarTab === tab- ? "bg-accent/15 text-accent"- : "text-text-muted hover:text-text-primary hover:bg-elevated"- }`}- >- {tab === "info" ? t.sidebar.info : t.sidebar.files}- </button>- ))}- </div>- <div className="flex-1 min-h-0 overflow-auto">- {sidebarTab === "files" ? <FileExplorer /> : infoSidebarContent}- </div>- </div>- );-- if (isMobile) {- return (- <MobileLayout- accessToken={accessToken}- showKeyboardHelp={showKeyboardHelp}- setShowKeyboardHelp={setShowKeyboardHelp}+ const graph = useDashboardStore((s) => s.graph);+ const selectedNodeId = useDashboardStore((s) => s.selectedNodeId);+ const tourActive = useDashboardStore((s) => s.tourActive);+ const persona = useDashboardStore((s) => s.persona);+ const codeViewerOpen = useDashboardStore((s) => s.codeViewerOpen);+ const codeViewerExpanded = useDashboardStore((s) => s.codeViewerExpanded);+ const expandCodeViewer = useDashboardStore((s) => s.expandCodeViewer);+ const collapseCodeViewer = useDashboardStore((s) => s.collapseCodeViewer);+ const pathFinderOpen = useDashboardStore((s) => s.pathFinderOpen);+ const togglePathFinder = useDashboardStore((s) => s.togglePathFinder);+ const nodeTypeFilters = useDashboardStore((s) => s.nodeTypeFilters);+ const toggleNodeTypeFilter = useDashboardStore((s) => s.toggleNodeTypeFilter);+ const detailLevel = useDashboardStore((s) => s.detailLevel);+ const setDetailLevel = useDashboardStore((s) => s.setDetailLevel);+ const showFunctionsInClassView = useDashboardStore((s) => s.showFunctionsInClassView);+ const toggleShowFunctionsInClassView = useDashboardStore((s) => s.toggleShowFunctionsInClassView);+ const [showKeyboardHelp, setShowKeyboardHelp] = useState(false);+ const [sidebarTab, setSidebarTab] = useState<SidebarTab>("info");+ const [showOnboarding, setShowOnboarding] = useState(shouldShowOnboarding);+ const dismissOnboarding = useCallback((remember: boolean) => {+ if (remember && typeof window !== "undefined") {+ window.localStorage.setItem(ONBOARDING_DISMISSED_KEY, "1");+ }+ setShowOnboarding(false);+ }, []);+ const viewMode = useDashboardStore((s) => s.viewMode);+ const setViewMode = useDashboardStore((s) => s.setViewMode);+ const isKnowledgeGraph = useDashboardStore((s) => s.isKnowledgeGraph);+ const domainGraph = useDashboardStore((s) => s.domainGraph);+ const layoutIssues = useDashboardStore((s) => s.layoutIssues);+ const isMobile = useIsMobile();+ const { t } = useI18n();+ const allIssues = useMemo(+ () => [...graphIssues, ...layoutIssues],+ [graphIssues, layoutIssues],+ );++ useEffect(() => {+ if (selectedNodeId) setSidebarTab("info");+ }, [selectedNodeId]);++ // Define keyboard shortcuts+ const shortcuts = useMemo<KeyboardShortcut[]>(+ () => [+ // Help+ {+ key: "?",+ shiftKey: true,+ description: t.keyboardShortcuts.showHelp,+ action: () => setShowKeyboardHelp((prev) => !prev),+ category: "General",+ },+ // Navigation+ {+ key: "Escape",+ description: t.keyboardShortcuts.escapeDesc,+ action: () => {+ // Read from store at invocation time to avoid stale closures+ const state = useDashboardStore.getState();+ if (state.pathFinderOpen) {+ state.togglePathFinder();+ } else if (state.filterPanelOpen) {+ state.toggleFilterPanel();+ } else if (state.exportMenuOpen) {+ state.toggleExportMenu();+ } else if (state.codeViewerExpanded) {+ state.collapseCodeViewer();+ } else if (state.codeViewerOpen) {+ state.closeCodeViewer();+ } else if (state.selectedNodeId) {+ state.selectNode(null);+ } else if (state.navigationLevel === "layer-detail") {+ state.navigateToOverview();+ } else if (state.tourActive) {+ state.stopTour();+ } else {+ setShowKeyboardHelp(false);+ }+ },+ category: "Navigation",+ },+ {+ key: "/",+ description: t.keyboardShortcuts.focusSearch,+ action: () => {+ const searchInput = document.querySelector<HTMLInputElement>(+ '[data-testid="search-input"]'+ );+ searchInput?.focus();+ },+ category: "Navigation",+ },+ // Tour controls+ {+ key: "ArrowRight",+ description: t.keyboardShortcuts.nextStep,+ action: () => {+ const state = useDashboardStore.getState();+ if (state.tourActive) {+ state.nextTourStep();+ }+ },+ category: "Tour",+ },+ {+ key: "ArrowLeft",+ description: t.keyboardShortcuts.prevStep,+ action: () => {+ const state = useDashboardStore.getState();+ if (state.tourActive) {+ state.prevTourStep();+ }+ },+ category: "Tour",+ },+ // View toggles+ {+ key: "d",+ description: t.keyboardShortcuts.toggleDiff,+ action: () => {+ const state = useDashboardStore.getState();+ state.toggleDiffMode();+ },+ category: "View",+ },+ {+ key: "f",+ description: t.keyboardShortcuts.toggleFilter,+ action: () => {+ const state = useDashboardStore.getState();+ state.toggleFilterPanel();+ },+ category: "View",+ },+ {+ key: "e",+ description: t.keyboardShortcuts.toggleExport,+ action: () => {+ const state = useDashboardStore.getState();+ state.toggleExportMenu();+ },+ category: "View",+ },+ {+ key: "p",+ description: t.keyboardShortcuts.openPathFinder,+ action: () => {+ const state = useDashboardStore.getState();+ state.togglePathFinder();+ },+ category: "View",+ },+ ],+ [t]+ );++ // Register keyboard shortcuts+ useKeyboardShortcuts(shortcuts);++ // Determine sidebar content+ // NodeInfo always takes priority when a node is selected.+ // Learn mode adds LearnPanel below it; otherwise ProjectOverview shows when idle.+ const isLearnMode = tourActive || persona === "junior";+ const infoSidebarContent = (+ <>+ {selectedNodeId && <NodeInfo />}+ {isLearnMode && (+ <Suspense fallback={null}>+ <LearnPanel />+ </Suspense>+ )}+ {!selectedNodeId && !isLearnMode && <ProjectOverview />}+ </>+ );++ const sidebarContent = (+ <div className="h-full flex flex-col min-h-0">+ <div className="flex items-center gap-1 p-2 border-b border-border-subtle bg-surface shrink-0">+ {(["info", "files"] as const).map((tab) => (+ <button+ key={tab}+ type="button"+ onClick={() => setSidebarTab(tab)}+ className={`flex-1 px-3 py-1.5 rounded-md text-xs font-semibold uppercase tracking-wider transition-colors ${+ sidebarTab === tab+ ? "bg-accent/15 text-accent"+ : "text-text-muted hover:text-text-primary hover:bg-elevated"+ }`}+ >+ {tab === "info" ? t.sidebar.info : t.sidebar.files}+ </button>+ ))}+ </div>+ <div className="flex-1 min-h-0 overflow-auto">+ {sidebarTab === "files" ? <FileExplorer /> : infoSidebarContent}+ </div>+ </div>+ );++ if (isMobile) {+ return (+ <MobileLayout+ accessToken={accessToken}+ showKeyboardHelp={showKeyboardHelp}+ setShowKeyboardHelp={setShowKeyboardHelp}loadError={loadError}allIssues={allIssues}+ graphFreshness={graphFreshness}shortcuts={shortcuts}/>- );- }-- return (- <div className="h-screen w-screen flex flex-col bg-root text-text-primary noise-overlay">- {/* Header */}- <header className="flex items-center px-3 sm:px-5 py-3 bg-surface border-b border-border-subtle shrink-0 gap-2 sm:gap-4">- {/* Left — fixed */}- <div className="flex items-center gap-3 sm:gap-5 shrink-0 min-w-0">- <h1 className="font-heading text-base sm:text-lg text-text-primary tracking-wide truncate max-w-[160px] sm:max-w-[220px] lg:max-w-none">- {graph?.project.name ?? t.common.appName}- </h1>- <div className="w-px h-5 bg-border-subtle hidden sm:block" />- <PersonaSelector />- {graph && !isKnowledgeGraph && domainGraph && (- <>- <div className="w-px h-5 bg-border-subtle" />- <div className="flex items-center bg-elevated rounded-lg p-0.5">- <button- type="button"- onClick={() => setViewMode("domain")}- title={t.drawer.domain}- className={`px-3 py-1 text-xs font-medium rounded-md transition-colors ${- viewMode === "domain"- ? "bg-accent/20 text-accent"- : "text-text-muted hover:text-text-secondary"- }`}- >- {t.drawer.domain}- </button>- <button- type="button"- onClick={() => setViewMode("structural")}- title={t.drawer.structural}- className={`px-3 py-1 text-xs font-medium rounded-md transition-colors ${- viewMode === "structural"- ? "bg-accent/20 text-accent"- : "text-text-muted hover:text-text-secondary"- }`}- >- {t.drawer.structural}- </button>- </div>- </>- )}- </div>-- {/* Middle — scrollable legends */}- <div className="flex-1 min-w-0 overflow-x-auto scrollbar-hide">- <div className="flex items-center gap-4 w-max">- <DiffToggle />- {/* Detail level: file view (architecture) / class view (code structure) */}- {!isKnowledgeGraph && viewMode !== "domain" && (- <>- <div className="w-px h-5 bg-border-subtle" />- <div className="flex items-center bg-elevated rounded-lg p-0.5">- <button- type="button"- onClick={() => setDetailLevel("file")}- title={t.detailLevel.filesTitle}- className={`px-3 py-1 text-xs font-medium rounded-md transition-colors ${- detailLevel === "file"- ? "bg-accent/20 text-accent"- : "text-text-muted hover:text-text-secondary"- }`}- >- {t.detailLevel.files}- </button>- <button- type="button"- onClick={() => setDetailLevel("class")}- title={t.detailLevel.classesTitle}- className={`px-3 py-1 text-xs font-medium rounded-md transition-colors ${- detailLevel === "class"- ? "bg-accent/20 text-accent"- : "text-text-muted hover:text-text-secondary"- }`}- >- {t.detailLevel.classes}- </button>- </div>- {detailLevel === "class" && (- <button- type="button"- onClick={toggleShowFunctionsInClassView}- title={t.detailLevel.fnTitle}- className={`text-[10px] font-semibold uppercase tracking-wider px-2 py-1 rounded border transition-colors ${- showFunctionsInClassView- ? "border-amber-500/50 bg-amber-500/10 text-amber-400"- : "border-border-medium bg-elevated text-text-muted hover:text-text-secondary"- }`}- >- {t.detailLevel.fn}- </button>- )}- </>- )}- <div className="flex items-center gap-1">- {(isKnowledgeGraph ? [- { key: "knowledge" as const, label: t.nodeTypeLabels.all, color: "var(--color-node-article)" },- ] : [- { key: "code" as const, label: t.nodeTypeLabels.code, color: "var(--color-node-file)" },- { key: "config" as const, label: t.nodeTypeLabels.config, color: "var(--color-node-config)" },- { key: "docs" as const, label: t.nodeTypeLabels.docs, color: "var(--color-node-document)" },- { key: "infra" as const, label: t.nodeTypeLabels.infra, color: "var(--color-node-service)" },- { key: "data" as const, label: t.nodeTypeLabels.data, color: "var(--color-node-table)" },- { key: "domain" as const, label: t.nodeTypeLabels.domain, color: "var(--color-node-concept)" },- { key: "knowledge" as const, label: t.nodeTypeLabels.knowledge, color: "var(--color-node-article)" },- ]).map((cat) => (- <button- key={cat.key}- onClick={() => toggleNodeTypeFilter(cat.key)}- className={`text-[10px] font-semibold uppercase tracking-wider px-2 py-1 rounded border transition-colors flex items-center gap-1.5 whitespace-nowrap ${- nodeTypeFilters[cat.key] !== false- ? "border-border-medium bg-elevated text-text-secondary hover:text-text-primary"- : "border-transparent bg-transparent text-text-muted/40 line-through hover:text-text-muted"- }`}- title={`${nodeTypeFilters[cat.key] !== false ? "Hide" : "Show"} ${cat.label} nodes`}- >- <span- className="w-2 h-2 rounded-full shrink-0"- style={{- backgroundColor: cat.color,- opacity: nodeTypeFilters[cat.key] !== false ? 1 : 0.3,- }}- />- {cat.label}- </button>- ))}- </div>- <LayerLegend />- </div>- </div>-- {/* Right — fixed actions */}- <div className="flex items-center gap-2 sm:gap-4 shrink-0">- <FilterPanel />- <ExportMenu />- <button- onClick={togglePathFinder}- className="flex items-center gap-1.5 px-2 sm:px-3 py-1.5 rounded-lg text-sm bg-elevated text-text-secondary hover:text-text-primary transition-colors"- title={t.pathFinder.title}- >- <svg- className="w-4 h-4"- fill="none"- stroke="currentColor"- viewBox="0 0 24 24"- >- <path- strokeLinecap="round"- strokeLinejoin="round"- strokeWidth={2}- d="M13 7h8m0 0v8m0-8l-8 8-4-4-6 6"- />- </svg>- <span className="hidden md:inline">{t.common.path}</span>- </button>- <ThemePicker />- <button- onClick={() => setShowKeyboardHelp(true)}- className="text-text-muted hover:text-accent transition-colors"- title={t.keyboardShortcuts.showHelp}- >- <svg- className="w-5 h-5"- fill="none"- stroke="currentColor"- viewBox="0 0 24 24"- >- <path- strokeLinecap="round"- strokeLinejoin="round"- strokeWidth={2}- d="M8.228 9c.549-1.165 2.03-2 3.772-2 2.21 0 4 1.343 4 3 0 1.4-1.278 2.575-3.006 2.907-.542.104-.994.54-.994 1.093m0 3h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"- />- </svg>- </button>- </div>- </header>-+ );+ }++ return (+ <div className="h-screen w-screen flex flex-col bg-root text-text-primary noise-overlay">+ {/* Header */}+ <header className="flex items-center px-3 sm:px-5 py-3 bg-surface border-b border-border-subtle shrink-0 gap-2 sm:gap-4">+ {/* Left — fixed */}+ <div className="flex items-center gap-3 sm:gap-5 shrink-0 min-w-0">+ <h1 className="font-heading text-base sm:text-lg text-text-primary tracking-wide truncate max-w-[160px] sm:max-w-[220px] lg:max-w-none">+ {graph?.project.name ?? t.common.appName}+ </h1>+ <div className="w-px h-5 bg-border-subtle hidden sm:block" />+ <PersonaSelector />+ {graph && !isKnowledgeGraph && domainGraph && (+ <>+ <div className="w-px h-5 bg-border-subtle" />+ <div className="flex items-center bg-elevated rounded-lg p-0.5">+ <button+ type="button"+ onClick={() => setViewMode("domain")}+ title={t.drawer.domain}+ className={`px-3 py-1 text-xs font-medium rounded-md transition-colors ${+ viewMode === "domain"+ ? "bg-accent/20 text-accent"+ : "text-text-muted hover:text-text-secondary"+ }`}+ >+ {t.drawer.domain}+ </button>+ <button+ type="button"+ onClick={() => setViewMode("structural")}+ title={t.drawer.structural}+ className={`px-3 py-1 text-xs font-medium rounded-md transition-colors ${+ viewMode === "structural"+ ? "bg-accent/20 text-accent"+ : "text-text-muted hover:text-text-secondary"+ }`}+ >+ {t.drawer.structural}+ </button>+ </div>+ </>+ )}+ </div>++ {/* Middle — scrollable legends */}+ <div className="flex-1 min-w-0 overflow-x-auto scrollbar-hide">+ <div className="flex items-center gap-4 w-max">+ <DiffToggle />+ {/* Detail level: file view (architecture) / class view (code structure) */}+ {!isKnowledgeGraph && viewMode !== "domain" && (+ <>+ <div className="w-px h-5 bg-border-subtle" />+ <div className="flex items-center bg-elevated rounded-lg p-0.5">+ <button+ type="button"+ onClick={() => setDetailLevel("file")}+ title={t.detailLevel.filesTitle}+ className={`px-3 py-1 text-xs font-medium rounded-md transition-colors ${+ detailLevel === "file"+ ? "bg-accent/20 text-accent"+ : "text-text-muted hover:text-text-secondary"+ }`}+ >+ {t.detailLevel.files}+ </button>+ <button+ type="button"+ onClick={() => setDetailLevel("class")}+ title={t.detailLevel.classesTitle}+ className={`px-3 py-1 text-xs font-medium rounded-md transition-colors ${+ detailLevel === "class"+ ? "bg-accent/20 text-accent"+ : "text-text-muted hover:text-text-secondary"+ }`}+ >+ {t.detailLevel.classes}+ </button>+ </div>+ {detailLevel === "class" && (+ <button+ type="button"+ onClick={toggleShowFunctionsInClassView}+ title={t.detailLevel.fnTitle}+ className={`text-[10px] font-semibold uppercase tracking-wider px-2 py-1 rounded border transition-colors ${+ showFunctionsInClassView+ ? "border-amber-500/50 bg-amber-500/10 text-amber-400"+ : "border-border-medium bg-elevated text-text-muted hover:text-text-secondary"+ }`}+ >+ {t.detailLevel.fn}+ </button>+ )}+ </>+ )}+ <div className="flex items-center gap-1">+ {(isKnowledgeGraph ? [+ { key: "knowledge" as const, label: t.nodeTypeLabels.all, color: "var(--color-node-article)" },+ ] : [+ { key: "code" as const, label: t.nodeTypeLabels.code, color: "var(--color-node-file)" },+ { key: "config" as const, label: t.nodeTypeLabels.config, color: "var(--color-node-config)" },+ { key: "docs" as const, label: t.nodeTypeLabels.docs, color: "var(--color-node-document)" },+ { key: "infra" as const, label: t.nodeTypeLabels.infra, color: "var(--color-node-service)" },+ { key: "data" as const, label: t.nodeTypeLabels.data, color: "var(--color-node-table)" },+ { key: "domain" as const, label: t.nodeTypeLabels.domain, color: "var(--color-node-concept)" },+ { key: "knowledge" as const, label: t.nodeTypeLabels.knowledge, color: "var(--color-node-article)" },+ ]).map((cat) => (+ <button+ key={cat.key}+ onClick={() => toggleNodeTypeFilter(cat.key)}+ className={`text-[10px] font-semibold uppercase tracking-wider px-2 py-1 rounded border transition-colors flex items-center gap-1.5 whitespace-nowrap ${+ nodeTypeFilters[cat.key] !== false+ ? "border-border-medium bg-elevated text-text-secondary hover:text-text-primary"+ : "border-transparent bg-transparent text-text-muted/40 line-through hover:text-text-muted"+ }`}+ title={`${nodeTypeFilters[cat.key] !== false ? "Hide" : "Show"} ${cat.label} nodes`}+ >+ <span+ className="w-2 h-2 rounded-full shrink-0"+ style={{+ backgroundColor: cat.color,+ opacity: nodeTypeFilters[cat.key] !== false ? 1 : 0.3,+ }}+ />+ {cat.label}+ </button>+ ))}+ </div>+ <LayerLegend />+ </div>+ </div>++ {/* Right — fixed actions */}+ <div className="flex items-center gap-2 sm:gap-4 shrink-0">+ <FilterPanel />+ <ExportMenu />+ <button+ onClick={togglePathFinder}+ className="flex items-center gap-1.5 px-2 sm:px-3 py-1.5 rounded-lg text-sm bg-elevated text-text-secondary hover:text-text-primary transition-colors"+ title={t.pathFinder.title}+ >+ <svg+ className="w-4 h-4"+ fill="none"+ stroke="currentColor"+ viewBox="0 0 24 24"+ >+ <path+ strokeLinecap="round"+ strokeLinejoin="round"+ strokeWidth={2}+ d="M13 7h8m0 0v8m0-8l-8 8-4-4-6 6"+ />+ </svg>+ <span className="hidden md:inline">{t.common.path}</span>+ </button>+ <ThemePicker />+ <button+ onClick={() => setShowKeyboardHelp(true)}+ className="text-text-muted hover:text-accent transition-colors"+ title={t.keyboardShortcuts.showHelp}+ >+ <svg+ className="w-5 h-5"+ fill="none"+ stroke="currentColor"+ viewBox="0 0 24 24"+ >+ <path+ strokeLinecap="round"+ strokeLinejoin="round"+ strokeWidth={2}+ d="M8.228 9c.549-1.165 2.03-2 3.772-2 2.21 0 4 1.343 4 3 0 1.4-1.278 2.575-3.006 2.907-.542.104-.994.54-.994 1.093m0 3h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"+ />+ </svg>+ </button>+ </div>+ </header>+{/* Search */}<SearchBar />+ {/* Graph freshness warning banner */}+ {!loadError && <StalenessBanner freshness={graphFreshness} />}+{/* Validation warning banner */}{allIssues.length > 0 && !loadError && (- <WarningBanner issues={allIssues} />- )}-- {/* Error banner */}- {loadError && (- <div className="px-5 py-3 bg-red-900/30 border-b border-red-700 text-red-200 text-sm">- {loadError}- </div>- )}-- {/* Main content: Graph + Sidebar */}- <div className="flex-1 flex min-h-0 relative">- {/* Graph area */}- <div className="flex-1 min-w-0 min-h-0 relative">- {viewMode === "knowledge" ? (- <KnowledgeGraphView />- ) : viewMode === "domain" && domainGraph ? (- <DomainGraphView />- ) : (- <GraphView />- )}- <div className="absolute top-3 right-3 text-sm text-text-muted/60 pointer-events-none select-none">- {t.common.pressKeyboard}- </div>- </div>-- {/* Right sidebar — telescopes at narrower widths */}- <aside className="w-[260px] md:w-[300px] lg:w-[360px] shrink-0 bg-surface border-l border-border-subtle overflow-auto">- {sidebarContent}- </aside>-- {/* Code viewer slide-up overlay (collapsed state) */}- {codeViewerOpen && !codeViewerExpanded && (- <div className="absolute bottom-0 left-0 right-0 h-[40vh] bg-surface border-t border-border-subtle animate-slide-up z-20 overflow-hidden">- <Suspense fallback={null}>- <CodeViewer accessToken={accessToken} onExpand={expandCodeViewer} />- </Suspense>- </div>- )}- </div>-- {/* Expanded code viewer modal */}- {codeViewerOpen && codeViewerExpanded && (- <div- className="fixed inset-0 z-50 flex items-center justify-center bg-black/65 backdrop-blur-sm p-4 sm:p-6"- onMouseDown={collapseCodeViewer}- >- <div- className="w-[calc(100vw-32px)] max-w-[1120px] h-[calc(100vh-32px)] sm:h-[calc(100vh-48px)] max-h-[820px] rounded-lg border border-border-medium bg-surface shadow-2xl overflow-hidden"- onMouseDown={(event) => event.stopPropagation()}- >- <Suspense fallback={null}>- <CodeViewer- accessToken={accessToken}- presentation="modal"- onClose={collapseCodeViewer}- />- </Suspense>- </div>- </div>- )}-- {/* Keyboard shortcuts help modal */}- {showKeyboardHelp && (- <Suspense fallback={null}>- <KeyboardShortcutsHelp- shortcuts={shortcuts}- onClose={() => setShowKeyboardHelp(false)}- />- </Suspense>- )}-- {/* Path Finder Modal — only mounted when open so its chunk is lazy-loaded on demand. */}- {pathFinderOpen && (- <Suspense fallback={null}>- <PathFinderModal isOpen={pathFinderOpen} onClose={togglePathFinder} />- </Suspense>- )}-- {/* First-visit onboarding overlay — only mounted when needed so its chunk is lazy-loaded on demand. */}- {showOnboarding && (- <Suspense fallback={null}>- <OnboardingOverlay onDismiss={dismissOnboarding} />- </Suspense>- )}- </div>- );-}--export default App;+ <WarningBanner issues={allIssues} />+ )}++ {/* Error banner */}+ {loadError && (+ <div className="px-5 py-3 bg-red-900/30 border-b border-red-700 text-red-200 text-sm">+ {loadError}+ </div>+ )}++ {/* Main content: Graph + Sidebar */}+ <div className="flex-1 flex min-h-0 relative">+ {/* Graph area */}+ <div className="flex-1 min-w-0 min-h-0 relative">+ {viewMode === "knowledge" ? (+ <KnowledgeGraphView />+ ) : viewMode === "domain" && domainGraph ? (+ <DomainGraphView />+ ) : (+ <GraphView />+ )}+ <div className="absolute top-3 right-3 text-sm text-text-muted/60 pointer-events-none select-none">+ {t.common.pressKeyboard}+ </div>+ </div>++ {/* Right sidebar — telescopes at narrower widths */}+ <aside className="w-[260px] md:w-[300px] lg:w-[360px] shrink-0 bg-surface border-l border-border-subtle overflow-auto">+ {sidebarContent}+ </aside>++ {/* Code viewer slide-up overlay (collapsed state) */}+ {codeViewerOpen && !codeViewerExpanded && (+ <div className="absolute bottom-0 left-0 right-0 h-[40vh] bg-surface border-t border-border-subtle animate-slide-up z-20 overflow-hidden">+ <Suspense fallback={null}>+ <CodeViewer accessToken={accessToken} onExpand={expandCodeViewer} />+ </Suspense>+ </div>+ )}+ </div>++ {/* Expanded code viewer modal */}+ {codeViewerOpen && codeViewerExpanded && (+ <div+ className="fixed inset-0 z-50 flex items-center justify-center bg-black/65 backdrop-blur-sm p-4 sm:p-6"+ onMouseDown={collapseCodeViewer}+ >+ <div+ className="w-[calc(100vw-32px)] max-w-[1120px] h-[calc(100vh-32px)] sm:h-[calc(100vh-48px)] max-h-[820px] rounded-lg border border-border-medium bg-surface shadow-2xl overflow-hidden"+ onMouseDown={(event) => event.stopPropagation()}+ >+ <Suspense fallback={null}>+ <CodeViewer+ accessToken={accessToken}+ presentation="modal"+ onClose={collapseCodeViewer}+ />+ </Suspense>+ </div>+ </div>+ )}++ {/* Keyboard shortcuts help modal */}+ {showKeyboardHelp && (+ <Suspense fallback={null}>+ <KeyboardShortcutsHelp+ shortcuts={shortcuts}+ onClose={() => setShowKeyboardHelp(false)}+ />+ </Suspense>+ )}++ {/* Path Finder Modal — only mounted when open so its chunk is lazy-loaded on demand. */}+ {pathFinderOpen && (+ <Suspense fallback={null}>+ <PathFinderModal isOpen={pathFinderOpen} onClose={togglePathFinder} />+ </Suspense>+ )}++ {/* First-visit onboarding overlay — only mounted when needed so its chunk is lazy-loaded on demand. */}+ {showOnboarding && (+ <Suspense fallback={null}>+ <OnboardingOverlay onDismiss={dismissOnboarding} />+ </Suspense>+ )}+ </div>+ );+}++export default App;diff --git a/understand-anything-plugin/packages/dashboard/src/__tests__/vite-staleness.test.ts b/understand-anything-plugin/packages/dashboard/src/__tests__/vite-staleness.test.tsnew file mode 100644index 00000000..bcd71b81--- /dev/null+++ b/understand-anything-plugin/packages/dashboard/src/__tests__/vite-staleness.test.ts@@ -0,0 +1,98 @@+import fs from "fs";+import os from "os";+import path from "path";+import { execFileSync } from "child_process";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++vi.mock("child_process", () => ({+ execFileSync: vi.fn(),+}));++const execFileSyncMock = vi.mocked(execFileSync);++async function loadHelpers() {+ return import("../../vite.config");+}++describe("dashboard graph freshness endpoint helper", () => {+ let originalGraphDir: string | undefined;+ let tempProject: string;++ beforeEach(() => {+ vi.resetModules();+ execFileSyncMock.mockReset();+ originalGraphDir = process.env.GRAPH_DIR;+ tempProject = fs.mkdtempSync(path.join(os.tmpdir(), "ua-dashboard-"));+ process.env.GRAPH_DIR = tempProject;+ });++ afterEach(() => {+ if (originalGraphDir === undefined) {+ delete process.env.GRAPH_DIR;+ } else {+ process.env.GRAPH_DIR = originalGraphDir;+ }+ fs.rmSync(tempProject, { recursive: true, force: true });+ });++ it("reports a stale graph from knowledge graph commit metadata", async () => {+ const graphDir = path.join(tempProject, ".understand-anything");+ fs.mkdirSync(graphDir, { recursive: true });+ fs.writeFileSync(+ path.join(graphDir, "knowledge-graph.json"),+ JSON.stringify({+ project: {+ gitCommitHash: "graph-commit",+ analyzedAt: "2026-07-08T08:00:00.000Z",+ },+ }),+ );++ execFileSyncMock.mockImplementation((_cmd, args) => {+ const joinedArgs = Array.isArray(args) ? args.join(" ") : "";+ if (joinedArgs === "rev-parse HEAD") return "head-commit\n";+ if (joinedArgs === "rev-list --count graph-commit..HEAD") return "3\n";+ if (joinedArgs === "diff graph-commit..HEAD --name-only") {+ return "src/auth.ts\nsrc/routes.ts\n";+ }+ throw new Error(`Unexpected git command: ${joinedArgs}`);+ });++ const { readGraphFreshness } = await loadHelpers();++ expect(readGraphFreshness()).toEqual({+ statusCode: 200,+ payload: {+ status: "stale",+ graphCommitHash: "graph-commit",+ headCommitHash: "head-commit",+ changedFileCount: 2,+ changedFiles: ["src/auth.ts", "src/routes.ts"],+ commitsBehind: 3,+ lastAnalyzedAt: "2026-07-08T08:00:00.000Z",+ },+ });+ });++ it("returns a 404 payload when no knowledge graph exists", async () => {+ const { readGraphFreshness } = await loadHelpers();++ expect(readGraphFreshness()).toEqual({+ statusCode: 404,+ payload: { error: "No knowledge graph found. Run /understand first." },+ });+ });++ it("returns a 500 payload when the knowledge graph cannot be parsed", async () => {+ const graphDir = path.join(tempProject, ".understand-anything");+ fs.mkdirSync(graphDir, { recursive: true });+ fs.writeFileSync(path.join(graphDir, "knowledge-graph.json"), "{not-json");++ const { readGraphFreshness } = await loadHelpers();++ expect(readGraphFreshness()).toEqual({+ statusCode: 500,+ payload: { error: "Failed to read graph file" },+ });+ });+});diff --git a/understand-anything-plugin/packages/dashboard/src/components/MobileLayout.tsx b/understand-anything-plugin/packages/dashboard/src/components/MobileLayout.tsxindex 27e48015..8f88e8da 100644--- a/understand-anything-plugin/packages/dashboard/src/components/MobileLayout.tsx+++ b/understand-anything-plugin/packages/dashboard/src/components/MobileLayout.tsx@@ -1,233 +1,239 @@-import { lazy, Suspense, useEffect, useState } from "react";-import type { GraphIssue } from "@understand-anything/core/schema";-import { useDashboardStore } from "../store";-import { useI18n } from "../contexts/I18nContext";-import GraphView from "./GraphView";-import DomainGraphView from "./DomainGraphView";-import KnowledgeGraphView from "./KnowledgeGraphView";-import SearchBar from "./SearchBar";-import NodeInfo from "./NodeInfo";-import ProjectOverview from "./ProjectOverview";+import { lazy, Suspense, useEffect, useState } from "react";+import type { GraphIssue } from "@understand-anything/core/schema";+import { useDashboardStore } from "../store";+import { useI18n } from "../contexts/I18nContext";+import GraphView from "./GraphView";+import DomainGraphView from "./DomainGraphView";+import KnowledgeGraphView from "./KnowledgeGraphView";+import SearchBar from "./SearchBar";+import NodeInfo from "./NodeInfo";+import ProjectOverview from "./ProjectOverview";import FileExplorer from "./FileExplorer";import WarningBanner from "./WarningBanner";+import StalenessBanner, { type GraphFreshnessResult } from "./StalenessBanner";import MobileBottomNav from "./MobileBottomNav";-import type { MobileTab } from "./MobileBottomNav";-import MobileDrawer from "./MobileDrawer";--const CodeViewer = lazy(() => import("./CodeViewer"));-const LearnPanel = lazy(() => import("./LearnPanel"));-const PathFinderModal = lazy(() => import("./PathFinderModal"));-const KeyboardShortcutsHelp = lazy(() => import("./KeyboardShortcutsHelp"));--interface Props {- accessToken: string;- showKeyboardHelp: boolean;- setShowKeyboardHelp: (value: boolean) => void;+import type { MobileTab } from "./MobileBottomNav";+import MobileDrawer from "./MobileDrawer";++const CodeViewer = lazy(() => import("./CodeViewer"));+const LearnPanel = lazy(() => import("./LearnPanel"));+const PathFinderModal = lazy(() => import("./PathFinderModal"));+const KeyboardShortcutsHelp = lazy(() => import("./KeyboardShortcutsHelp"));++interface Props {+ accessToken: string;+ showKeyboardHelp: boolean;+ setShowKeyboardHelp: (value: boolean) => void;loadError: string | null;allIssues: GraphIssue[];+ graphFreshness: GraphFreshnessResult | null;shortcuts: import("../hooks/useKeyboardShortcuts").KeyboardShortcut[];}--export default function MobileLayout({- accessToken,- showKeyboardHelp,++export default function MobileLayout({+ accessToken,+ showKeyboardHelp,setShowKeyboardHelp,loadError,allIssues,+ graphFreshness,shortcuts,}: Props) {- const graph = useDashboardStore((s) => s.graph);- const selectedNodeId = useDashboardStore((s) => s.selectedNodeId);- const tourActive = useDashboardStore((s) => s.tourActive);- const persona = useDashboardStore((s) => s.persona);- const viewMode = useDashboardStore((s) => s.viewMode);- const domainGraph = useDashboardStore((s) => s.domainGraph);- const codeViewerOpen = useDashboardStore((s) => s.codeViewerOpen);- const closeCodeViewer = useDashboardStore((s) => s.closeCodeViewer);- const pathFinderOpen = useDashboardStore((s) => s.pathFinderOpen);- const togglePathFinder = useDashboardStore((s) => s.togglePathFinder);- const { t } = useI18n();-- const [activeTab, setActiveTab] = useState<MobileTab>("graph");- const [drawerOpen, setDrawerOpen] = useState(false);- const [searchOpen, setSearchOpen] = useState(false);-- // Auto-pivot to Info when a node is selected — keeps feedback visible- // on a small screen where graph and sidebar can't coexist- useEffect(() => {- if (selectedNodeId) setActiveTab("info");- }, [selectedNodeId]);-- // When a code viewer opens (e.g. from the Files tab) keep focus there- useEffect(() => {- if (codeViewerOpen) setSearchOpen(false);- }, [codeViewerOpen]);-- const isLearnMode = tourActive || persona === "junior";- const infoContent = (- <>- {selectedNodeId && <NodeInfo />}- {isLearnMode && (- <Suspense fallback={null}>- <LearnPanel />- </Suspense>- )}- {!selectedNodeId && !isLearnMode && <ProjectOverview />}- </>- );-- return (- <div className="h-screen w-screen flex flex-col bg-root text-text-primary noise-overlay">- {/* Top bar */}- <header className="flex items-center gap-2 px-3 h-12 shrink-0 bg-surface border-b border-border-subtle">- <button- type="button"- onClick={() => setDrawerOpen(true)}- className="w-9 h-9 flex items-center justify-center rounded-lg text-text-secondary hover:text-text-primary hover:bg-elevated transition-colors -ml-1"- aria-label="Open menu"- >- <svg- className="w-5 h-5"- fill="none"- stroke="currentColor"- strokeWidth={1.8}- viewBox="0 0 24 24"- >- <path strokeLinecap="round" d="M4 7h16M4 12h16M4 17h16" />- </svg>- </button>-- <h1 className="font-heading text-base flex-1 min-w-0 truncate text-center text-text-primary tracking-wide">- {graph?.project.name ?? t.common.appName}- </h1>-- <button- type="button"- onClick={() => setSearchOpen((prev) => !prev)}- className={`w-9 h-9 flex items-center justify-center rounded-lg transition-colors -mr-1 ${- searchOpen- ? "text-accent bg-accent/15"- : "text-text-secondary hover:text-text-primary hover:bg-elevated"- }`}- aria-label={searchOpen ? "Hide search" : "Show search"}- aria-pressed={searchOpen}- >- <svg- className="w-5 h-5"- fill="none"- stroke="currentColor"- strokeWidth={1.8}- viewBox="0 0 24 24"- >- <path- strokeLinecap="round"- strokeLinejoin="round"- d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"- />- </svg>- </button>- </header>-+ const graph = useDashboardStore((s) => s.graph);+ const selectedNodeId = useDashboardStore((s) => s.selectedNodeId);+ const tourActive = useDashboardStore((s) => s.tourActive);+ const persona = useDashboardStore((s) => s.persona);+ const viewMode = useDashboardStore((s) => s.viewMode);+ const domainGraph = useDashboardStore((s) => s.domainGraph);+ const codeViewerOpen = useDashboardStore((s) => s.codeViewerOpen);+ const closeCodeViewer = useDashboardStore((s) => s.closeCodeViewer);+ const pathFinderOpen = useDashboardStore((s) => s.pathFinderOpen);+ const togglePathFinder = useDashboardStore((s) => s.togglePathFinder);+ const { t } = useI18n();++ const [activeTab, setActiveTab] = useState<MobileTab>("graph");+ const [drawerOpen, setDrawerOpen] = useState(false);+ const [searchOpen, setSearchOpen] = useState(false);++ // Auto-pivot to Info when a node is selected — keeps feedback visible+ // on a small screen where graph and sidebar can't coexist+ useEffect(() => {+ if (selectedNodeId) setActiveTab("info");+ }, [selectedNodeId]);++ // When a code viewer opens (e.g. from the Files tab) keep focus there+ useEffect(() => {+ if (codeViewerOpen) setSearchOpen(false);+ }, [codeViewerOpen]);++ const isLearnMode = tourActive || persona === "junior";+ const infoContent = (+ <>+ {selectedNodeId && <NodeInfo />}+ {isLearnMode && (+ <Suspense fallback={null}>+ <LearnPanel />+ </Suspense>+ )}+ {!selectedNodeId && !isLearnMode && <ProjectOverview />}+ </>+ );++ return (+ <div className="h-screen w-screen flex flex-col bg-root text-text-primary noise-overlay">+ {/* Top bar */}+ <header className="flex items-center gap-2 px-3 h-12 shrink-0 bg-surface border-b border-border-subtle">+ <button+ type="button"+ onClick={() => setDrawerOpen(true)}+ className="w-9 h-9 flex items-center justify-center rounded-lg text-text-secondary hover:text-text-primary hover:bg-elevated transition-colors -ml-1"+ aria-label="Open menu"+ >+ <svg+ className="w-5 h-5"+ fill="none"+ stroke="currentColor"+ strokeWidth={1.8}+ viewBox="0 0 24 24"+ >+ <path strokeLinecap="round" d="M4 7h16M4 12h16M4 17h16" />+ </svg>+ </button>++ <h1 className="font-heading text-base flex-1 min-w-0 truncate text-center text-text-primary tracking-wide">+ {graph?.project.name ?? t.common.appName}+ </h1>++ <button+ type="button"+ onClick={() => setSearchOpen((prev) => !prev)}+ className={`w-9 h-9 flex items-center justify-center rounded-lg transition-colors -mr-1 ${+ searchOpen+ ? "text-accent bg-accent/15"+ : "text-text-secondary hover:text-text-primary hover:bg-elevated"+ }`}+ aria-label={searchOpen ? "Hide search" : "Show search"}+ aria-pressed={searchOpen}+ >+ <svg+ className="w-5 h-5"+ fill="none"+ stroke="currentColor"+ strokeWidth={1.8}+ viewBox="0 0 24 24"+ >+ <path+ strokeLinecap="round"+ strokeLinejoin="round"+ d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"+ />+ </svg>+ </button>+ </header>+{/* Search (collapsible) */}{searchOpen && <SearchBar />}+ {/* Graph freshness warning */}+ {!loadError && <StalenessBanner freshness={graphFreshness} />}+{/* Validation warnings */}{allIssues.length > 0 && !loadError && <WarningBanner issues={allIssues} />}-- {/* Load error */}- {loadError && (- <div className="px-4 py-3 bg-red-900/30 border-b border-red-700 text-red-200 text-sm">- {loadError}- </div>- )}-- {/* Tabbed content — all panes stay mounted to preserve layout/state.- Inactive panes are kept in the layout (not display:none) so that- ReactFlow keeps real dimensions and pinch/pan don't collapse on- tab switch. */}- <div className="flex-1 min-h-0 relative">- <div- className={`absolute inset-0 ${- activeTab === "graph" ? "" : "invisible pointer-events-none"- }`}- aria-hidden={activeTab !== "graph"}- >- {viewMode === "knowledge" ? (- <KnowledgeGraphView />- ) : viewMode === "domain" && domainGraph ? (- <DomainGraphView />- ) : (- <GraphView />- )}- </div>-- <div- className={`absolute inset-0 overflow-auto bg-surface ${- activeTab === "info" ? "" : "invisible pointer-events-none"- }`}- aria-hidden={activeTab !== "info"}- >- {infoContent}- </div>-- <div- className={`absolute inset-0 overflow-auto bg-surface ${- activeTab === "files" ? "" : "invisible pointer-events-none"- }`}- aria-hidden={activeTab !== "files"}- >- <FileExplorer />- </div>- </div>-- {/* Bottom tab nav */}- <MobileBottomNav activeTab={activeTab} onTabChange={setActiveTab} />-- {/* Drawer */}- <MobileDrawer- open={drawerOpen}- onClose={() => setDrawerOpen(false)}- onTogglePathFinder={togglePathFinder}- onShowKeyboardHelp={() => setShowKeyboardHelp(true)}- />-- {/* Code viewer — always fullscreen on mobile */}- {codeViewerOpen && (- <div- className="fixed inset-0 z-50 flex bg-black/70 backdrop-blur-sm p-2 sm:p-4"- onMouseDown={closeCodeViewer}- >- <div- className="flex-1 rounded-lg border border-border-medium bg-surface shadow-2xl overflow-hidden"- onMouseDown={(event) => event.stopPropagation()}- >- <Suspense fallback={null}>- <CodeViewer- accessToken={accessToken}- presentation="modal"- onClose={closeCodeViewer}- />- </Suspense>- </div>- </div>- )}-- {/* Keyboard help (mobile reads it as a quick reference too) */}- {showKeyboardHelp && (- <Suspense fallback={null}>- <KeyboardShortcutsHelp- shortcuts={shortcuts}- onClose={() => setShowKeyboardHelp(false)}- />- </Suspense>- )}-- {/* Path finder */}- {pathFinderOpen && (- <Suspense fallback={null}>- <PathFinderModal isOpen={pathFinderOpen} onClose={togglePathFinder} />- </Suspense>- )}- </div>- );-}++ {/* Load error */}+ {loadError && (+ <div className="px-4 py-3 bg-red-900/30 border-b border-red-700 text-red-200 text-sm">+ {loadError}+ </div>+ )}++ {/* Tabbed content — all panes stay mounted to preserve layout/state.+ Inactive panes are kept in the layout (not display:none) so that+ ReactFlow keeps real dimensions and pinch/pan don't collapse on+ tab switch. */}+ <div className="flex-1 min-h-0 relative">+ <div+ className={`absolute inset-0 ${+ activeTab === "graph" ? "" : "invisible pointer-events-none"+ }`}+ aria-hidden={activeTab !== "graph"}+ >+ {viewMode === "knowledge" ? (+ <KnowledgeGraphView />+ ) : viewMode === "domain" && domainGraph ? (+ <DomainGraphView />+ ) : (+ <GraphView />+ )}+ </div>++ <div+ className={`absolute inset-0 overflow-auto bg-surface ${+ activeTab === "info" ? "" : "invisible pointer-events-none"+ }`}+ aria-hidden={activeTab !== "info"}+ >+ {infoContent}+ </div>++ <div+ className={`absolute inset-0 overflow-auto bg-surface ${+ activeTab === "files" ? "" : "invisible pointer-events-none"+ }`}+ aria-hidden={activeTab !== "files"}+ >+ <FileExplorer />+ </div>+ </div>++ {/* Bottom tab nav */}+ <MobileBottomNav activeTab={activeTab} onTabChange={setActiveTab} />++ {/* Drawer */}+ <MobileDrawer+ open={drawerOpen}+ onClose={() => setDrawerOpen(false)}+ onTogglePathFinder={togglePathFinder}+ onShowKeyboardHelp={() => setShowKeyboardHelp(true)}+ />++ {/* Code viewer — always fullscreen on mobile */}+ {codeViewerOpen && (+ <div+ className="fixed inset-0 z-50 flex bg-black/70 backdrop-blur-sm p-2 sm:p-4"+ onMouseDown={closeCodeViewer}+ >+ <div+ className="flex-1 rounded-lg border border-border-medium bg-surface shadow-2xl overflow-hidden"+ onMouseDown={(event) => event.stopPropagation()}+ >+ <Suspense fallback={null}>+ <CodeViewer+ accessToken={accessToken}+ presentation="modal"+ onClose={closeCodeViewer}+ />+ </Suspense>+ </div>+ </div>+ )}++ {/* Keyboard help (mobile reads it as a quick reference too) */}+ {showKeyboardHelp && (+ <Suspense fallback={null}>+ <KeyboardShortcutsHelp+ shortcuts={shortcuts}+ onClose={() => setShowKeyboardHelp(false)}+ />+ </Suspense>+ )}++ {/* Path finder */}+ {pathFinderOpen && (+ <Suspense fallback={null}>+ <PathFinderModal isOpen={pathFinderOpen} onClose={togglePathFinder} />+ </Suspense>+ )}+ </div>+ );+}diff --git a/understand-anything-plugin/packages/dashboard/src/components/StalenessBanner.tsx b/understand-anything-plugin/packages/dashboard/src/components/StalenessBanner.tsxnew file mode 100644index 00000000..d53b7df3--- /dev/null+++ b/understand-anything-plugin/packages/dashboard/src/components/StalenessBanner.tsx@@ -0,0 +1,156 @@+import { useState } from "react";++export type GraphFreshnessResult =+ | {+ status: "fresh";+ graphCommitHash: string;+ headCommitHash: string;+ changedFileCount: 0;+ changedFiles: [];+ commitsBehind: 0;+ lastAnalyzedAt?: string;+ }+ | {+ status: "stale";+ graphCommitHash: string;+ headCommitHash: string;+ changedFileCount: number;+ changedFiles: string[];+ commitsBehind: number;+ lastAnalyzedAt?: string;+ }+ | {+ status: "unknown";+ reason:+ | "missing-graph-commit"+ | "git-head-unavailable"+ | "graph-commit-unavailable";+ graphCommitHash?: string;+ headCommitHash?: string;+ lastAnalyzedAt?: string;+ };+type UnknownGraphFreshnessReason = Extract<+ GraphFreshnessResult,+ { status: "unknown" }+>["reason"];++interface StalenessBannerProps {+ freshness: GraphFreshnessResult | null;+}++interface FreshnessBannerContent {+ title: string;+ summary: string;+ action: string;+ changedFiles: string[];+}++function plural(count: number, singular: string, pluralForm = `${singular}s`) {+ return `${count} ${count === 1 ? singular : pluralForm}`;+}++export function isGraphFreshnessResult(data: unknown): data is GraphFreshnessResult {+ if (!data || typeof data !== "object") return false;+ const status = (data as { status?: unknown }).status;+ return status === "fresh" || status === "stale" || status === "unknown";+}++export function buildFreshnessBanner(+ freshness: GraphFreshnessResult | null,+): FreshnessBannerContent | null {+ if (!freshness || freshness.status === "fresh") return null;++ if (freshness.status === "stale") {+ return {+ title: "Knowledge graph may be stale",+ summary: `The graph was generated ${plural(+ freshness.commitsBehind,+ "commit",+ )} before HEAD and ${plural(+ freshness.changedFileCount,+ "file",+ )} have changed since analysis.`,+ action: "Run /understand to refresh it before relying on impact or onboarding answers.",+ changedFiles: freshness.changedFiles,+ };+ }++ const summaryByReason: Record<UnknownGraphFreshnessReason, string> = {+ "missing-graph-commit": "The graph does not include a git commit hash to compare with HEAD.",+ "git-head-unavailable": "The dashboard could not read git HEAD for this project.",+ "graph-commit-unavailable": "The graph commit is not available in this checkout.",+ };++ return {+ title: "Graph freshness could not be verified",+ summary: summaryByReason[freshness.reason],+ action: "Run /understand to regenerate the graph with current git metadata.",+ changedFiles: [],+ };+}++export default function StalenessBanner({ freshness }: StalenessBannerProps) {+ const [expanded, setExpanded] = useState(false);+ const content = buildFreshnessBanner(freshness);++ if (!content) return null;++ const hasFiles = content.changedFiles.length > 0;+ const visibleFiles = content.changedFiles.slice(0, 8);+ const hiddenFileCount = content.changedFiles.length - visibleFiles.length;++ return (+ <div className="bg-amber-950/30 border-b border-amber-700 text-amber-100 text-sm">+ <button+ type="button"+ aria-expanded={expanded}+ onClick={() => setExpanded((prev) => !prev)}+ className="w-full flex items-start gap-3 px-5 py-3 text-left hover:bg-amber-900/10 transition-colors"+ >+ <svg+ className="w-4 h-4 shrink-0 mt-0.5 text-amber-400"+ fill="none"+ stroke="currentColor"+ viewBox="0 0 24 24"+ >+ <path+ strokeLinecap="round"+ strokeLinejoin="round"+ strokeWidth={2}+ d="M12 9v2m0 4h.01M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"+ />+ </svg>+ <span className="flex-1 min-w-0">+ <span className="block font-semibold">{content.title}</span>+ <span className="block text-amber-100/80">{content.summary}</span>+ <span className="block text-amber-100/70">{content.action}</span>+ </span>+ {hasFiles && (+ <span className="text-xs text-amber-300/70 shrink-0">+ {expanded ? "hide files" : "show files"}+ </span>+ )}+ </button>++ {expanded && hasFiles && (+ <div className="px-5 pb-3">+ <div className="border-t border-amber-700/40 pt-2 flex flex-wrap gap-1.5">+ {visibleFiles.map((file) => (+ <code+ key={file}+ className="px-1.5 py-0.5 rounded bg-amber-900/30 text-[11px] text-amber-100"+ >+ {file}+ </code>+ ))}+ {hiddenFileCount > 0 && (+ <span className="text-xs text-amber-200/60">+ +{hiddenFileCount} more+ </span>+ )}+ </div>+ </div>+ )}+ </div>+ );+}diff --git a/understand-anything-plugin/packages/dashboard/src/components/__tests__/StalenessBanner.test.ts b/understand-anything-plugin/packages/dashboard/src/components/__tests__/StalenessBanner.test.tsnew file mode 100644index 00000000..7b9c6afb--- /dev/null+++ b/understand-anything-plugin/packages/dashboard/src/components/__tests__/StalenessBanner.test.ts@@ -0,0 +1,61 @@+import { describe, expect, it } from "vitest";+import { buildFreshnessBanner, isGraphFreshnessResult } from "../StalenessBanner";++describe("buildFreshnessBanner", () => {+ it("returns no banner for fresh or missing freshness data", () => {+ expect(buildFreshnessBanner(null)).toBeNull();+ expect(+ buildFreshnessBanner({+ status: "fresh",+ graphCommitHash: "abc123",+ headCommitHash: "abc123",+ changedFileCount: 0,+ changedFiles: [],+ commitsBehind: 0,+ }),+ ).toBeNull();+ });++ it("summarizes stale graph state with commit and file counts", () => {+ const banner = buildFreshnessBanner({+ status: "stale",+ graphCommitHash: "graph-commit",+ headCommitHash: "head-commit",+ changedFileCount: 2,+ changedFiles: ["src/auth.ts", "src/routes.ts"],+ commitsBehind: 3,+ lastAnalyzedAt: "2026-07-08T08:00:00.000Z",+ });++ expect(banner).toEqual({+ title: "Knowledge graph may be stale",+ summary:+ "The graph was generated 3 commits before HEAD and 2 files have changed since analysis.",+ action: "Run /understand to refresh it before relying on impact or onboarding answers.",+ changedFiles: ["src/auth.ts", "src/routes.ts"],+ });+ });++ it("explains unknown freshness when commit metadata is missing", () => {+ const banner = buildFreshnessBanner({+ status: "unknown",+ reason: "missing-graph-commit",+ lastAnalyzedAt: "2026-07-08T08:00:00.000Z",+ });++ expect(banner).toEqual({+ title: "Graph freshness could not be verified",+ summary: "The graph does not include a git commit hash to compare with HEAD.",+ action: "Run /understand to regenerate the graph with current git metadata.",+ changedFiles: [],+ });+ });++ it("recognizes graph freshness payloads from the dashboard endpoint", () => {+ expect(isGraphFreshnessResult({ status: "fresh" })).toBe(true);+ expect(isGraphFreshnessResult({ status: "stale" })).toBe(true);+ expect(isGraphFreshnessResult({ status: "unknown" })).toBe(true);+ expect(isGraphFreshnessResult({ error: "Forbidden" })).toBe(false);+ expect(isGraphFreshnessResult(null)).toBe(false);+ });+});diff --git a/understand-anything-plugin/packages/dashboard/vite.config.ts b/understand-anything-plugin/packages/dashboard/vite.config.tsindex 0fdef36b..3c77a9ab 100644--- a/understand-anything-plugin/packages/dashboard/vite.config.ts+++ b/understand-anything-plugin/packages/dashboard/vite.config.ts@@ -1,362 +1,409 @@/// <reference types="vitest" />-import { defineConfig } from "vite";-import react from "@vitejs/plugin-react";-import tailwindcss from "@tailwindcss/vite";+import { defineConfig, type UserConfig } from "vite";+import react from "@vitejs/plugin-react";+import tailwindcss from "@tailwindcss/vite";import path from "path";import fs from "fs";import crypto from "crypto";--// Generate a one-time token when the server process starts.-// This token is printed to the terminal and must be in the URL-// to fetch knowledge-graph.json or diff-overlay.json.-const ACCESS_TOKEN = process.env.UNDERSTAND_ACCESS_TOKEN || crypto.randomBytes(16).toString("hex");-const MAX_SOURCE_FILE_BYTES = 1024 * 1024;-+import { getGraphFreshness } from "../core/src/staleness";++// Generate a one-time token when the server process starts.+// This token is printed to the terminal and must be in the URL+// to fetch knowledge-graph.json or diff-overlay.json.+const ACCESS_TOKEN = process.env.UNDERSTAND_ACCESS_TOKEN || crypto.randomBytes(16).toString("hex");+const MAX_SOURCE_FILE_BYTES = 1024 * 1024;+function graphFileCandidates(fileName: string): string[] {const graphDir = process.env.GRAPH_DIR;+ if (graphDir) {+ return [path.resolve(graphDir, `.understand-anything/${fileName}`)];+ }return [- ...(graphDir- ? [path.resolve(graphDir, `.understand-anything/${fileName}`)]- : []),path.resolve(process.cwd(), `.understand-anything/${fileName}`),path.resolve(process.cwd(), `../../../.understand-anything/${fileName}`),];}--function findGraphFile(fileName: string): string | null {- return graphFileCandidates(fileName).find((candidate) => fs.existsSync(candidate)) ?? null;-}--function projectRootFromGraphFile(candidate: string): string {- return path.dirname(path.dirname(candidate));-}--function normalizeGraphPath(filePath: string, projectRoot: string): string | null {- const rawPath = path.isAbsolute(filePath)- ? filePath.startsWith(projectRoot)- ? path.relative(projectRoot, filePath)- : null- : filePath;- if (rawPath === null) return null;- const normalized = path.normalize(rawPath);- if (- !normalized ||- normalized === "." ||- normalized.includes("\0") ||- normalized === ".." ||- normalized.startsWith(`..${path.sep}`) ||- path.isAbsolute(normalized)- ) {- return null;- }- return normalized.split(path.sep).join("/");-}--function graphFilePathSet(graphFile: string, projectRoot: string): Set<string> {- const allowed = new Set<string>();- try {- const raw = JSON.parse(fs.readFileSync(graphFile, "utf-8")) as {- nodes?: Array<Record<string, unknown>>;- };- for (const node of raw.nodes ?? []) {- if (typeof node.filePath !== "string") continue;- const normalized = normalizeGraphPath(node.filePath, projectRoot);- if (normalized) allowed.add(normalized);- }- } catch {- return allowed;- }- return allowed;-}--function detectLanguage(filePath: string): string {- const ext = path.extname(filePath).slice(1).toLowerCase();- const byExt: Record<string, string> = {- bash: "bash",- c: "c",- cc: "cpp",- cpp: "cpp",- cs: "csharp",- css: "css",- go: "go",- h: "c",- hpp: "cpp",- html: "markup",- java: "java",- js: "javascript",- jsx: "jsx",- json: "json",- md: "markdown",- mjs: "javascript",- py: "python",- rb: "ruby",- rs: "rust",- sh: "bash",- ts: "typescript",- tsx: "tsx",- txt: "text",- yaml: "yaml",- yml: "yaml",- };- return byExt[ext] ?? "text";-}--function sendJson(res: import("http").ServerResponse, statusCode: number, payload: unknown) {- res.statusCode = statusCode;- res.setHeader("Content-Type", "application/json");- res.end(JSON.stringify(payload));-}--function rejectFileRequest(message: string, statusCode = 400) {- return { statusCode, payload: { error: message } };-}-++function findGraphFile(fileName: string): string | null {+ return graphFileCandidates(fileName).find((candidate) => fs.existsSync(candidate)) ?? null;+}++function projectRootFromGraphFile(candidate: string): string {+ return path.dirname(path.dirname(candidate));+}++function normalizeGraphPath(filePath: string, projectRoot: string): string | null {+ const rawPath = path.isAbsolute(filePath)+ ? filePath.startsWith(projectRoot)+ ? path.relative(projectRoot, filePath)+ : null+ : filePath;+ if (rawPath === null) return null;+ const normalized = path.normalize(rawPath);+ if (+ !normalized ||+ normalized === "." ||+ normalized.includes("\0") ||+ normalized === ".." ||+ normalized.startsWith(`..${path.sep}`) ||+ path.isAbsolute(normalized)+ ) {+ return null;+ }+ return normalized.split(path.sep).join("/");+}++function graphFilePathSet(graphFile: string, projectRoot: string): Set<string> {+ const allowed = new Set<string>();+ try {+ const raw = JSON.parse(fs.readFileSync(graphFile, "utf-8")) as {+ nodes?: Array<Record<string, unknown>>;+ };+ for (const node of raw.nodes ?? []) {+ if (typeof node.filePath !== "string") continue;+ const normalized = normalizeGraphPath(node.filePath, projectRoot);+ if (normalized) allowed.add(normalized);+ }+ } catch {+ return allowed;+ }+ return allowed;+}++function detectLanguage(filePath: string): string {+ const ext = path.extname(filePath).slice(1).toLowerCase();+ const byExt: Record<string, string> = {+ bash: "bash",+ c: "c",+ cc: "cpp",+ cpp: "cpp",+ cs: "csharp",+ css: "css",+ go: "go",+ h: "c",+ hpp: "cpp",+ html: "markup",+ java: "java",+ js: "javascript",+ jsx: "jsx",+ json: "json",+ md: "markdown",+ mjs: "javascript",+ py: "python",+ rb: "ruby",+ rs: "rust",+ sh: "bash",+ ts: "typescript",+ tsx: "tsx",+ txt: "text",+ yaml: "yaml",+ yml: "yaml",+ };+ return byExt[ext] ?? "text";+}++function sendJson(res: import("http").ServerResponse, statusCode: number, payload: unknown) {+ res.statusCode = statusCode;+ res.setHeader("Content-Type", "application/json");+ res.end(JSON.stringify(payload));+}++function rejectFileRequest(message: string, statusCode = 400) {+ return { statusCode, payload: { error: message } };+}+function readSourceFile(url: URL) {- const requestedPath = url.searchParams.get("path") ?? "";- if (!requestedPath) return rejectFileRequest("Missing path");- if (requestedPath.includes("\0")) return rejectFileRequest("Invalid path");- if (path.isAbsolute(requestedPath)) return rejectFileRequest("Absolute paths are not allowed");-- const normalizedPath = path.normalize(requestedPath);- if (- normalizedPath === "." ||- normalizedPath.startsWith(`..${path.sep}`) ||- normalizedPath === ".." ||- path.isAbsolute(normalizedPath)- ) {- return rejectFileRequest("Path must stay inside the project");- }+ const requestedPath = url.searchParams.get("path") ?? "";+ if (!requestedPath) return rejectFileRequest("Missing path");+ if (requestedPath.includes("\0")) return rejectFileRequest("Invalid path");+ if (path.isAbsolute(requestedPath)) return rejectFileRequest("Absolute paths are not allowed");++ const normalizedPath = path.normalize(requestedPath);+ if (+ normalizedPath === "." ||+ normalizedPath.startsWith(`..${path.sep}`) ||+ normalizedPath === ".." ||+ path.isAbsolute(normalizedPath)+ ) {+ return rejectFileRequest("Path must stay inside the project");+ }++ const graphFile = findGraphFile("knowledge-graph.json");+ if (!graphFile) {+ return rejectFileRequest("No knowledge graph found. Run /understand first.", 404);+ }++ const projectRoot = projectRootFromGraphFile(graphFile);+ const absoluteFile = path.resolve(projectRoot, normalizedPath);+ const relativeToRoot = path.relative(projectRoot, absoluteFile);+ if (+ !relativeToRoot ||+ relativeToRoot.startsWith(`..${path.sep}`) ||+ relativeToRoot === ".." ||+ path.isAbsolute(relativeToRoot)+ ) {+ return rejectFileRequest("Path must stay inside the project");+ }+ const safeRelativePath = relativeToRoot.split(path.sep).join("/");+ if (!graphFilePathSet(graphFile, projectRoot).has(safeRelativePath)) {+ return rejectFileRequest("File is not in the knowledge graph", 404);+ }++ let stat: fs.Stats;+ try {+ stat = fs.statSync(absoluteFile);+ } catch {+ return rejectFileRequest("File not found", 404);+ }++ if (!stat.isFile()) return rejectFileRequest("Path is not a file");+ if (stat.size > MAX_SOURCE_FILE_BYTES) {+ return rejectFileRequest("File is too large to preview", 413);+ }++ const buffer = fs.readFileSync(absoluteFile);+ if (buffer.includes(0)) return rejectFileRequest("Binary files cannot be previewed", 415);++ const content = buffer.toString("utf8");+ return {+ statusCode: 200,+ payload: {+ path: safeRelativePath,+ language: detectLanguage(relativeToRoot),+ content,+ sizeBytes: buffer.byteLength,+ lineCount: content.length === 0 ? 0 : content.split(/\r\n|\n|\r/).length,+ },+ };+}+export function readGraphFreshness() {const graphFile = findGraphFile("knowledge-graph.json");if (!graphFile) {return rejectFileRequest("No knowledge graph found. Run /understand first.", 404);}- const projectRoot = projectRootFromGraphFile(graphFile);- const absoluteFile = path.resolve(projectRoot, normalizedPath);- const relativeToRoot = path.relative(projectRoot, absoluteFile);- if (- !relativeToRoot ||- relativeToRoot.startsWith(`..${path.sep}`) ||- relativeToRoot === ".." ||- path.isAbsolute(relativeToRoot)- ) {- return rejectFileRequest("Path must stay inside the project");- }- const safeRelativePath = relativeToRoot.split(path.sep).join("/");- if (!graphFilePathSet(graphFile, projectRoot).has(safeRelativePath)) {- return rejectFileRequest("File is not in the knowledge graph", 404);- }-- let stat: fs.Stats;+ let graph: {+ project?: {+ gitCommitHash?: unknown;+ analyzedAt?: unknown;+ };+ };try {- stat = fs.statSync(absoluteFile);+ graph = JSON.parse(fs.readFileSync(graphFile, "utf-8"));} catch {- return rejectFileRequest("File not found", 404);- }-- if (!stat.isFile()) return rejectFileRequest("Path is not a file");- if (stat.size > MAX_SOURCE_FILE_BYTES) {- return rejectFileRequest("File is too large to preview", 413);+ return rejectFileRequest("Failed to read graph file", 500);}- const buffer = fs.readFileSync(absoluteFile);- if (buffer.includes(0)) return rejectFileRequest("Binary files cannot be previewed", 415);-- const content = buffer.toString("utf8");+ const project = graph.project;return {statusCode: 200,- payload: {- path: safeRelativePath,- language: detectLanguage(relativeToRoot),- content,- sizeBytes: buffer.byteLength,- lineCount: content.length === 0 ? 0 : content.split(/\r\n|\n|\r/).length,- },+ payload: getGraphFreshness(projectRootFromGraphFile(graphFile), {+ graphCommitHash:+ typeof project?.gitCommitHash === "string" ? project.gitCommitHash : undefined,+ lastAnalyzedAt:+ typeof project?.analyzedAt === "string" ? project.analyzedAt : undefined,+ }),};}-export default defineConfig({+type DashboardViteConfig = UserConfig & {+ test: {+ environment: "node";+ include: string[];+ };+};++const config: DashboardViteConfig = {test: {environment: "node",include: ["src/**/__tests__/**/*.test.ts"],- },-- // FIX 1 — bind only to localhost, not 0.0.0.0- // This blocks access from any other device on the same LAN / WiFi.- server: {- host: "127.0.0.1",- port: 5173,- open: `/?token=${ACCESS_TOKEN}`,- },-- resolve: {- alias: {- "@understand-anything/core/schema": path.resolve(__dirname, "../core/dist/schema.js"),- "@understand-anything/core/search": path.resolve(__dirname, "../core/dist/search.js"),- "@understand-anything/core/types": path.resolve(__dirname, "../core/dist/types.js"),- },- },-- build: {- rollupOptions: {- output: {- manualChunks(id) {- if (!id.includes("node_modules")) return;- if (/[\\/]node_modules[\\/](react|react-dom|scheduler)[\\/]/.test(id)) {- return "react-vendor";- }- if (id.includes("node_modules/@xyflow/")) return "xyflow";- // ELK is ~1.6MB raw — split into its own chunk so it doesn't- // bloat the main bundle. graphology is similarly large.- if (id.includes("node_modules/elkjs/")) return "elk";- if (id.includes("node_modules/graphology")) return "graphology";- if (- id.includes("node_modules/@dagrejs/") ||- id.includes("node_modules/d3-force/")- ) {- return "graph-layout";- }- if (- id.includes("node_modules/react-markdown/") ||- id.includes("node_modules/hast-util-to-jsx-runtime/") ||- /[\\/]node_modules[\\/](remark|rehype|mdast|hast|unist|micromark|decode-named-character-reference|property-information|space-separated-tokens|comma-separated-tokens|html-url-attributes|devlop|bail|ccount|character-entities|is-plain-obj|trim-lines|trough|unified|vfile|zwitch)/.test(id)- ) {- return "markdown";- }- },- },- },- },-- plugins: [- react(),- tailwindcss(),- {- name: "serve-knowledge-graph",- configureServer(server) {- // Print the access URL once so the developer can open it.- server.httpServer?.once("listening", () => {- const address = server.httpServer?.address();- const port = typeof address === "object" && address ? address.port : 5173;- console.log(- `\n 🔑 Dashboard URL: http://127.0.0.1:${port}/?token=${ACCESS_TOKEN}\n`- );- });-- 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" ||+ },++ // FIX 1 — bind only to localhost, not 0.0.0.0+ // This blocks access from any other device on the same LAN / WiFi.+ server: {+ host: "127.0.0.1",+ port: 5173,+ open: `/?token=${ACCESS_TOKEN}`,+ },++ resolve: {+ alias: {+ "@understand-anything/core/schema": path.resolve(__dirname, "../core/dist/schema.js"),+ "@understand-anything/core/search": path.resolve(__dirname, "../core/dist/search.js"),+ "@understand-anything/core/types": path.resolve(__dirname, "../core/dist/types.js"),+ },+ },++ build: {+ rollupOptions: {+ output: {+ manualChunks(id) {+ if (!id.includes("node_modules")) return;+ if (/[\\/]node_modules[\\/](react|react-dom|scheduler)[\\/]/.test(id)) {+ return "react-vendor";+ }+ if (id.includes("node_modules/@xyflow/")) return "xyflow";+ // ELK is ~1.6MB raw — split into its own chunk so it doesn't+ // bloat the main bundle. graphology is similarly large.+ if (id.includes("node_modules/elkjs/")) return "elk";+ if (id.includes("node_modules/graphology")) return "graphology";+ if (+ id.includes("node_modules/@dagrejs/") ||+ id.includes("node_modules/d3-force/")+ ) {+ return "graph-layout";+ }+ if (+ id.includes("node_modules/react-markdown/") ||+ id.includes("node_modules/hast-util-to-jsx-runtime/") ||+ /[\\/]node_modules[\\/](remark|rehype|mdast|hast|unist|micromark|decode-named-character-reference|property-information|space-separated-tokens|comma-separated-tokens|html-url-attributes|devlop|bail|ccount|character-entities|is-plain-obj|trim-lines|trough|unified|vfile|zwitch)/.test(id)+ ) {+ return "markdown";+ }+ },+ },+ },+ },++ plugins: [+ react(),+ tailwindcss(),+ {+ name: "serve-knowledge-graph",+ configureServer(server) {+ // Print the access URL once so the developer can open it.+ server.httpServer?.once("listening", () => {+ const address = server.httpServer?.address();+ const port = typeof address === "object" && address ? address.port : 5173;+ console.log(+ `\n 🔑 Dashboard URL: http://127.0.0.1:${port}/?token=${ACCESS_TOKEN}\n`+ );+ });++ 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 === "/staleness.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" });++ 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 === "/file-content.json") {- const result = readSourceFile(url);+ if (pathname === "/staleness.json") {+ const result = readGraphFreshness();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;- }-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();- }- });- },- },+ 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();+ }+ });+ },+ },],-});+};++export default defineConfig(config);diff --git a/understand-anything-plugin/skills/understand-chat/SKILL.md b/understand-anything-plugin/skills/understand-chat/SKILL.mdindex 9ce96760..c3a4e263 100644--- a/understand-anything-plugin/skills/understand-chat/SKILL.md+++ b/understand-anything-plugin/skills/understand-chat/SKILL.md@@ -1,54 +1,56 @@-----name: understand-chat-description: Use when you need to ask questions about a codebase or understand code using a knowledge graph-argument-hint: "[query]"------# /understand-chat--Answer questions about this codebase using the knowledge graph at `.understand-anything/knowledge-graph.json`.--## Graph Structure Reference--The knowledge graph JSON has this structure:-- `project` — {name, description, languages, frameworks, analyzedAt, gitCommitHash}-- `nodes[]` — each has {id, type, name, filePath?, summary, tags[], complexity, languageNotes?}- - Code node types: file, function, class, module, concept- - Non-code node types: config, document, service, table, endpoint, pipeline, schema, resource- - Domain/knowledge node types: domain, flow, step, article, entity, topic, claim, source- - IDs use the node type as prefix, e.g. `file:path`, `function:path:name`, `config:path`, `article:path`-- `edges[]` — each has {source, target, type, direction, weight}- - Key types: imports, contains, calls, depends_on, configures, documents, deploys, triggers, contains_flow, flow_step, related, cites-- `layers[]` — each has {id, name, description, nodeIds[]}-- `tour[]` — each has {order, title, description, nodeIds[]}--## How to Read Efficiently--1. Use Grep to search within the JSON for relevant entries BEFORE reading the full file-2. Only read sections you need — don't dump the entire graph into context-3. Node names and summaries are the most useful fields for understanding-4. Edges tell you how components connect — follow imports and calls for dependency chains--## Instructions--1. Check that `.understand-anything/knowledge-graph.json` exists in the current project root. If not, tell the user to run `/understand` first.--2. **Read project metadata only** — use Grep or Read with a line limit to extract just the `"project"` section from the top of the file for context (name, description, languages, frameworks).--3. **Search for relevant nodes** — use Grep to search the knowledge graph file for the user's query keywords: "$ARGUMENTS"+---+name: understand-chat+description: Use when you need to ask questions about a codebase or understand code using a knowledge graph+argument-hint: "[query]"+---++# /understand-chat++Answer questions about this codebase using the knowledge graph at `.understand-anything/knowledge-graph.json`.++## Graph Structure Reference++The knowledge graph JSON has this structure:+- `project` — {name, description, languages, frameworks, analyzedAt, gitCommitHash}+- `nodes[]` — each has {id, type, name, filePath?, summary, tags[], complexity, languageNotes?}+ - Code node types: file, function, class, module, concept+ - Non-code node types: config, document, service, table, endpoint, pipeline, schema, resource+ - Domain/knowledge node types: domain, flow, step, article, entity, topic, claim, source+ - IDs use the node type as prefix, e.g. `file:path`, `function:path:name`, `config:path`, `article:path`+- `edges[]` — each has {source, target, type, direction, weight}+ - Key types: imports, contains, calls, depends_on, configures, documents, deploys, triggers, contains_flow, flow_step, related, cites+- `layers[]` — each has {id, name, description, nodeIds[]}+- `tour[]` — each has {order, title, description, nodeIds[]}++## How to Read Efficiently++1. Use Grep to search within the JSON for relevant entries BEFORE reading the full file+2. Only read sections you need — don't dump the entire graph into context+3. Node names and summaries are the most useful fields for understanding+4. Edges tell you how components connect — follow imports and calls for dependency chains++## Instructions++1. Check that `.understand-anything/knowledge-graph.json` exists in the current project root. If not, tell the user to run `/understand` first.++2. **Check graph freshness** — read `project.gitCommitHash` from the graph metadata and run `git rev-parse HEAD` in the project root. If both values exist and differ, warn the user before answering that the knowledge graph may be stale and newer code may be missing from the answer. Suggest: Run `/understand` to refresh the graph. If git metadata is missing or unavailable, continue with a brief best-effort warning instead of blocking.++3. **Read project metadata only** — use Grep or Read with a line limit to extract just the `"project"` section from the top of the file for context (name, description, languages, frameworks).++4. **Search for relevant nodes** — use Grep to search the knowledge graph file for the user's query keywords: "$ARGUMENTS"- Search `"name"` fields: `grep -i "query_keyword"` in the graph file- Search `"summary"` fields for semantic matches- Search `"tags"` arrays for topic matches- Note the `id` values of all matching nodes-4. **Find connected edges** — for each matched node ID, Grep for that ID in the `edges` section to find:+5. **Find connected edges** — for each matched node ID, Grep for that ID in the `edges` section to find:- What it imports or depends on (downstream)- What calls or imports it (upstream)- This gives you the 1-hop subgraph around the query-5. **Read layer context** — Grep for `"layers"` to understand which architectural layers the matched nodes belong to.+6. **Read layer context** — Grep for `"layers"` to understand which architectural layers the matched nodes belong to.-6. **Answer the query** using only the relevant subgraph:+7. **Answer the query** using only the relevant subgraph:- Reference specific files, functions, and relationships from the graph- Explain which layer(s) are relevant and why- Be concise but thorough — link concepts to actual code locationsdiff --git a/understand-anything-plugin/skills/understand-diff/SKILL.md b/understand-anything-plugin/skills/understand-diff/SKILL.mdindex fd33264b..680e5df4 100644--- a/understand-anything-plugin/skills/understand-diff/SKILL.md+++ b/understand-anything-plugin/skills/understand-diff/SKILL.md@@ -1,72 +1,72 @@-----name: understand-diff-description: Use when you need to analyze git diffs or pull requests to understand what changed, affected components, and risks------# /understand-diff--Analyze the current code changes against the knowledge graph at `.understand-anything/knowledge-graph.json`.--## Graph Structure Reference--The knowledge graph JSON has this structure:-- `project` — {name, description, languages, frameworks, analyzedAt, gitCommitHash}-- `nodes[]` — each has {id, type, name, filePath?, summary, tags[], complexity, languageNotes?}- - Code node types: file, function, class, module, concept- - Non-code node types: config, document, service, table, endpoint, pipeline, schema, resource- - Domain/knowledge node types: domain, flow, step, article, entity, topic, claim, source- - IDs use the node type as prefix, e.g. `file:path`, `function:path:name`, `config:path`, `article:path`-- `edges[]` — each has {source, target, type, direction, weight}- - Key types: imports, contains, calls, depends_on, configures, documents, deploys, triggers, contains_flow, flow_step, related, cites-- `layers[]` — each has {id, name, description, nodeIds[]}-- `tour[]` — each has {order, title, description, nodeIds[]}--## How to Read Efficiently--1. Use Grep to search within the JSON for relevant entries BEFORE reading the full file-2. Only read sections you need — don't dump the entire graph into context-3. Node names and summaries are the most useful fields for understanding-4. Edges tell you how components connect — follow imports and calls for dependency chains--## Instructions--1. Check that `.understand-anything/knowledge-graph.json` exists. If not, tell the user to run `/understand` first.--2. **Get the changed files list** (do NOT read the graph yet):- - If on a branch with uncommitted changes: `git diff --name-only`- - If on a feature branch: `git diff main...HEAD --name-only` (or the base branch)- - If the user specifies a PR number: get the diff from that PR--3. **Read project metadata only** — use Grep or Read with a line limit to extract just the `"project"` section for context.+---+name: understand-diff+description: Use when you need to analyze git diffs or pull requests to understand what changed, affected components, and risks+---++# /understand-diff++Analyze the current code changes against the knowledge graph at `.understand-anything/knowledge-graph.json`.++## Graph Structure Reference++The knowledge graph JSON has this structure:+- `project` — {name, description, languages, frameworks, analyzedAt, gitCommitHash}+- `nodes[]` — each has {id, type, name, filePath?, summary, tags[], complexity, languageNotes?}+ - Code node types: file, function, class, module, concept+ - Non-code node types: config, document, service, table, endpoint, pipeline, schema, resource+ - Domain/knowledge node types: domain, flow, step, article, entity, topic, claim, source+ - IDs use the node type as prefix, e.g. `file:path`, `function:path:name`, `config:path`, `article:path`+- `edges[]` — each has {source, target, type, direction, weight}+ - Key types: imports, contains, calls, depends_on, configures, documents, deploys, triggers, contains_flow, flow_step, related, cites+- `layers[]` — each has {id, name, description, nodeIds[]}+- `tour[]` — each has {order, title, description, nodeIds[]}++## How to Read Efficiently++1. Use Grep to search within the JSON for relevant entries BEFORE reading the full file+2. Only read sections you need — don't dump the entire graph into context+3. Node names and summaries are the most useful fields for understanding+4. Edges tell you how components connect — follow imports and calls for dependency chains++## Instructions++1. Check that `.understand-anything/knowledge-graph.json` exists. If not, tell the user to run `/understand` first.++2. **Get the changed files list** (do NOT read the graph yet):+ - If on a branch with uncommitted changes: `git diff --name-only`+ - If on a feature branch: `git diff main...HEAD --name-only` (or the base branch)+ - If the user specifies a PR number: get the diff from that PR++3. **Read project metadata and check graph freshness** — use Grep or Read with a line limit to extract just the `"project"` section for context, including `gitCommitHash`. Run `git rev-parse HEAD` in the project root. If both values exist and differ, warn the user before the diff analysis that the knowledge graph may be stale and impact analysis may miss newer components. Suggest: Run `/understand` to refresh the graph. If git metadata is missing or unavailable, continue with a brief best-effort warning instead of blocking.4. **Find nodes for changed files** — for each changed file path, use Grep to search the knowledge graph for:- Nodes with matching `"filePath"` values (e.g., `grep "changed/file/path"`)- This finds file-level nodes (including non-code types) AND function/class nodes defined in those files- Note the `id` values of all matched nodes--5. **Find connected edges (1-hop)** — for each matched node ID, Grep for that ID in the edges to find:- - What imports or depends on the changed nodes (upstream callers)- - What the changed nodes import or call (downstream dependencies)- - These are the "affected components" — things that might break or need updating--6. **Identify affected layers** — Grep for the matched node IDs in the `"layers"` section to determine which architectural layers are touched.--7. **Provide structured analysis**:- - **Changed Components**: What was directly modified (with summaries from matched nodes)- - **Affected Components**: What might be impacted (from 1-hop edges)- - **Affected Layers**: Which architectural layers are touched and cross-layer concerns- - **Risk Assessment**: Based on node `complexity` values, number of cross-layer edges, and blast radius (number of affected components)- - Suggest what to review carefully and any potential issues--8. **Write diff overlay for dashboard** — after producing the analysis, write the diff data to `.understand-anything/diff-overlay.json` so the dashboard can visualize changed and affected components. The file contains:- ```json- {- "version": "1.0.0",- "baseBranch": "<the base branch used>",- "generatedAt": "<ISO timestamp>",- "changedFiles": ["<list of changed file paths>"],- "changedNodeIds": ["<node IDs from step 4>"],- "affectedNodeIds": ["<node IDs from step 5, excluding changedNodeIds>"]- }- ```- After writing, tell the user they can run `/understand-anything:understand-dashboard` to see the diff overlay visually.++5. **Find connected edges (1-hop)** — for each matched node ID, Grep for that ID in the edges to find:+ - What imports or depends on the changed nodes (upstream callers)+ - What the changed nodes import or call (downstream dependencies)+ - These are the "affected components" — things that might break or need updating++6. **Identify affected layers** — Grep for the matched node IDs in the `"layers"` section to determine which architectural layers are touched.++7. **Provide structured analysis**:+ - **Changed Components**: What was directly modified (with summaries from matched nodes)+ - **Affected Components**: What might be impacted (from 1-hop edges)+ - **Affected Layers**: Which architectural layers are touched and cross-layer concerns+ - **Risk Assessment**: Based on node `complexity` values, number of cross-layer edges, and blast radius (number of affected components)+ - Suggest what to review carefully and any potential issues++8. **Write diff overlay for dashboard** — after producing the analysis, write the diff data to `.understand-anything/diff-overlay.json` so the dashboard can visualize changed and affected components. The file contains:+ ```json+ {+ "version": "1.0.0",+ "baseBranch": "<the base branch used>",+ "generatedAt": "<ISO timestamp>",+ "changedFiles": ["<list of changed file paths>"],+ "changedNodeIds": ["<node IDs from step 4>"],+ "affectedNodeIds": ["<node IDs from step 5, excluding changedNodeIds>"]+ }+ ```+ After writing, tell the user they can run `/understand-anything:understand-dashboard` to see the diff overlay visually.diff --git a/understand-anything-plugin/skills/understand-explain/SKILL.md b/understand-anything-plugin/skills/understand-explain/SKILL.mdindex 224d17ac..d74edf26 100644--- a/understand-anything-plugin/skills/understand-explain/SKILL.md+++ b/understand-anything-plugin/skills/understand-explain/SKILL.md@@ -1,58 +1,60 @@-----name: understand-explain-description: Use when you need a deep-dive explanation of a specific file, function, or module in the codebase-argument-hint: "[file-path]"------# /understand-explain--Provide a thorough, in-depth explanation of a specific code component.--## Graph Structure Reference--The knowledge graph JSON has this structure:-- `project` — {name, description, languages, frameworks, analyzedAt, gitCommitHash}-- `nodes[]` — each has {id, type, name, filePath?, summary, tags[], complexity, languageNotes?}- - Code node types: file, function, class, module, concept- - Non-code node types: config, document, service, table, endpoint, pipeline, schema, resource- - Domain/knowledge node types: domain, flow, step, article, entity, topic, claim, source- - IDs use the node type as prefix, e.g. `file:path`, `function:path:name`, `config:path`, `article:path`-- `edges[]` — each has {source, target, type, direction, weight}- - Key types: imports, contains, calls, depends_on, configures, documents, deploys, triggers, contains_flow, flow_step, related, cites-- `layers[]` — each has {id, name, description, nodeIds[]}-- `tour[]` — each has {order, title, description, nodeIds[]}--## How to Read Efficiently--1. Use Grep to search within the JSON for relevant entries BEFORE reading the full file-2. Only read sections you need — don't dump the entire graph into context-3. Node names and summaries are the most useful fields for understanding-4. Edges tell you how components connect — follow imports and calls for dependency chains--## Instructions--1. Check that `.understand-anything/knowledge-graph.json` exists. If not, tell the user to run `/understand` first.--2. **Find the target node** — use Grep to search the knowledge graph for the component: "$ARGUMENTS"+---+name: understand-explain+description: Use when you need a deep-dive explanation of a specific file, function, or module in the codebase+argument-hint: "[file-path]"+---++# /understand-explain++Provide a thorough, in-depth explanation of a specific code component.++## Graph Structure Reference++The knowledge graph JSON has this structure:+- `project` — {name, description, languages, frameworks, analyzedAt, gitCommitHash}+- `nodes[]` — each has {id, type, name, filePath?, summary, tags[], complexity, languageNotes?}+ - Code node types: file, function, class, module, concept+ - Non-code node types: config, document, service, table, endpoint, pipeline, schema, resource+ - Domain/knowledge node types: domain, flow, step, article, entity, topic, claim, source+ - IDs use the node type as prefix, e.g. `file:path`, `function:path:name`, `config:path`, `article:path`+- `edges[]` — each has {source, target, type, direction, weight}+ - Key types: imports, contains, calls, depends_on, configures, documents, deploys, triggers, contains_flow, flow_step, related, cites+- `layers[]` — each has {id, name, description, nodeIds[]}+- `tour[]` — each has {order, title, description, nodeIds[]}++## How to Read Efficiently++1. Use Grep to search within the JSON for relevant entries BEFORE reading the full file+2. Only read sections you need — don't dump the entire graph into context+3. Node names and summaries are the most useful fields for understanding+4. Edges tell you how components connect — follow imports and calls for dependency chains++## Instructions++1. Check that `.understand-anything/knowledge-graph.json` exists. If not, tell the user to run `/understand` first.++2. **Check graph freshness** — read `project.gitCommitHash` from the graph metadata and run `git rev-parse HEAD` in the project root. If both values exist and differ, warn the user before explaining that the knowledge graph may be stale and newer code may be missing from graph-derived context. Suggest: Run `/understand` to refresh the graph. If git metadata is missing or unavailable, continue with a brief best-effort warning instead of blocking.++3. **Find the target node** — use Grep to search the knowledge graph for the component: "$ARGUMENTS"- For file paths (e.g., `src/auth/login.ts`): search for `"filePath"` matches- For function notation (e.g., `src/auth/login.ts:verifyToken`): search for the function name in `"name"` fields filtered by the file path- Note the exact node `id`, `type`, `summary`, `tags`, and `complexity`-3. **Find all connected edges** — Grep for the target node's ID in the edges section:+4. **Find all connected edges** — Grep for the target node's ID in the edges section:- `"source"` matches → things this node calls/imports/depends on (outgoing)- `"target"` matches → things that call/import/depend on this node (incoming)- Note the connected node IDs and edge types-4. **Read connected nodes** — for each connected node ID from step 3, Grep for those IDs in the nodes section to get their `name`, `summary`, and `type`. This builds the component's neighborhood.+5. **Read connected nodes** — for each connected node ID from step 4, Grep for those IDs in the nodes section to get their `name`, `summary`, and `type`. This builds the component's neighborhood.-5. **Identify the layer** — Grep for the target node's ID in the `"layers"` section to find which architectural layer it belongs to and that layer's description.+6. **Identify the layer** — Grep for the target node's ID in the `"layers"` section to find which architectural layer it belongs to and that layer's description.-6. **Read the actual source file** — Read the source file at the node's `filePath` for the deep-dive analysis.+7. **Read the actual source file** — Read the source file at the node's `filePath` for the deep-dive analysis.-7. **Explain the component in context**:+8. **Explain the component in context**:- Its role in the architecture (which layer, why it exists)- Internal structure (functions, classes it contains — from `contains` edges)- External connections (what it imports, what calls it, what it depends on — from edges)- Data flow (inputs → processing → outputs — from source code)- Explain clearly, assuming the reader may not know the programming language- - Highlight any patterns, idioms, or complexity worth understanding+ - Highlight any patterns, idioms, or complexity worth understandingdiff --git a/understand-anything-plugin/skills/understand-onboard/SKILL.md b/understand-anything-plugin/skills/understand-onboard/SKILL.mdindex f9ae700e..c27759e2 100644--- a/understand-anything-plugin/skills/understand-onboard/SKILL.md+++ b/understand-anything-plugin/skills/understand-onboard/SKILL.md@@ -1,48 +1,50 @@-----name: understand-onboard-description: Use when you need to generate an onboarding guide for new team members joining a project------# /understand-onboard--Generate a comprehensive onboarding guide from the project's knowledge graph.--## Graph Structure Reference--The knowledge graph JSON has this structure:-- `project` — {name, description, languages, frameworks, analyzedAt, gitCommitHash}-- `nodes[]` — each has {id, type, name, filePath?, summary, tags[], complexity, languageNotes?}- - Code node types: file, function, class, module, concept- - Non-code node types: config, document, service, table, endpoint, pipeline, schema, resource- - Domain/knowledge node types: domain, flow, step, article, entity, topic, claim, source- - IDs use the node type as prefix, e.g. `file:path`, `function:path:name`, `config:path`, `article:path`-- `edges[]` — each has {source, target, type, direction, weight}- - Key types: imports, contains, calls, depends_on, configures, documents, deploys, triggers, contains_flow, flow_step, related, cites-- `layers[]` — each has {id, name, description, nodeIds[]}-- `tour[]` — each has {order, title, description, nodeIds[]}--## How to Read Efficiently--1. Use Grep to search within the JSON for relevant entries BEFORE reading the full file-2. Only read sections you need — don't dump the entire graph into context-3. Node names and summaries are the most useful fields for understanding-4. Edges tell you how components connect — follow imports and calls for dependency chains--## Instructions--1. Check that `.understand-anything/knowledge-graph.json` exists. If not, tell the user to run `/understand` first.--2. **Read project metadata** — use Grep or Read with a line limit to extract the `"project"` section (name, description, languages, frameworks).--3. **Read layers** — Grep for `"layers"` to get the full layers array. These define the architecture and will structure the guide.--4. **Read the tour** — Grep for `"tour"` to get the guided walkthrough steps. These provide the recommended learning path.--5. **Read file-level structural nodes only** — use Grep to find nodes with file-level types (`file`, `config`, `document`, `service`, `pipeline`, `table`, `schema`, `resource`, `endpoint`) in the knowledge graph. Skip function-level and class-level nodes to keep the guide high-level. Extract each node's `name`, `filePath`, `summary`, and `complexity`.--6. **Identify complexity hotspots** — from the file-level nodes, find those with the highest `complexity` values. These are areas new developers should approach carefully.--7. **Generate the onboarding guide** with these sections:+---+name: understand-onboard+description: Use when you need to generate an onboarding guide for new team members joining a project+---++# /understand-onboard++Generate a comprehensive onboarding guide from the project's knowledge graph.++## Graph Structure Reference++The knowledge graph JSON has this structure:+- `project` — {name, description, languages, frameworks, analyzedAt, gitCommitHash}+- `nodes[]` — each has {id, type, name, filePath?, summary, tags[], complexity, languageNotes?}+ - Code node types: file, function, class, module, concept+ - Non-code node types: config, document, service, table, endpoint, pipeline, schema, resource+ - Domain/knowledge node types: domain, flow, step, article, entity, topic, claim, source+ - IDs use the node type as prefix, e.g. `file:path`, `function:path:name`, `config:path`, `article:path`+- `edges[]` — each has {source, target, type, direction, weight}+ - Key types: imports, contains, calls, depends_on, configures, documents, deploys, triggers, contains_flow, flow_step, related, cites+- `layers[]` — each has {id, name, description, nodeIds[]}+- `tour[]` — each has {order, title, description, nodeIds[]}++## How to Read Efficiently++1. Use Grep to search within the JSON for relevant entries BEFORE reading the full file+2. Only read sections you need — don't dump the entire graph into context+3. Node names and summaries are the most useful fields for understanding+4. Edges tell you how components connect — follow imports and calls for dependency chains++## Instructions++1. Check that `.understand-anything/knowledge-graph.json` exists. If not, tell the user to run `/understand` first.++2. **Check graph freshness** — read `project.gitCommitHash` from the graph metadata and run `git rev-parse HEAD` in the project root. If both values exist and differ, warn the user before generating the guide that the knowledge graph may be stale and newer code may be missing from onboarding content. Suggest: Run `/understand` to refresh the graph. If git metadata is missing or unavailable, continue with a brief best-effort warning instead of blocking.++3. **Read project metadata** — use Grep or Read with a line limit to extract the `"project"` section (name, description, languages, frameworks).++4. **Read layers** — Grep for `"layers"` to get the full layers array. These define the architecture and will structure the guide.++5. **Read the tour** — Grep for `"tour"` to get the guided walkthrough steps. These provide the recommended learning path.++6. **Read file-level structural nodes only** — use Grep to find nodes with file-level types (`file`, `config`, `document`, `service`, `pipeline`, `table`, `schema`, `resource`, `endpoint`) in the knowledge graph. Skip function-level and class-level nodes to keep the guide high-level. Extract each node's `name`, `filePath`, `summary`, and `complexity`.++7. **Identify complexity hotspots** — from the file-level nodes, find those with the highest `complexity` values. These are areas new developers should approach carefully.++8. **Generate the onboarding guide** with these sections:- **Project Overview**: name, languages, frameworks, description (from project metadata)- **Architecture Layers**: each layer's name, description, and key files (from layers + file nodes)- **Key Concepts**: important patterns and design decisions (from node summaries and tags)@@ -50,6 +52,6 @@ The knowledge graph JSON has this structure:- **File Map**: what each key file does (from file-level nodes, organized by layer)- **Complexity Hotspots**: areas to approach carefully (from complexity values)-8. Format as clean markdown-9. Offer to save the guide to `docs/ONBOARDING.md` in the project-10. Suggest the user commit it to the repo for the team+9. Format as clean markdown+10. Offer to save the guide to `docs/ONBOARDING.md` in the project+11. Suggest the user commit it to the repo for the team