Skip to content

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

fix: address comprehensive code review findings for PR #51

Lum11044d2cb32232de
diff --git a/understand-anything-plugin/packages/core/src/__tests__/language-registry.test.ts b/understand-anything-plugin/packages/core/src/__tests__/language-registry.test.ts
index 289f3db2..03617cae 100644
--- a/understand-anything-plugin/packages/core/src/__tests__/language-registry.test.ts
+++ b/understand-anything-plugin/packages/core/src/__tests__/language-registry.test.ts
@@ -1,5 +1,6 @@
import { describe, it, expect } from "vitest";
import { LanguageRegistry } from "../languages/language-registry.js";
+import { StrictLanguageConfigSchema } from "../languages/types.js";
import { typescriptConfig } from "../languages/configs/typescript.js";
import { pythonConfig } from "../languages/configs/python.js";
@@ -140,4 +141,55 @@ describe("LanguageRegistry", () => {
expect(registry.getForFile(".env.production")?.id).toBe("env");
});
});
+
+ describe("StrictLanguageConfigSchema refinement", () => {
+ it("rejects configs with empty extensions AND no filenames", () => {
+ const result = StrictLanguageConfigSchema.safeParse({
+ id: "empty-lang",
+ displayName: "Empty",
+ extensions: [],
+ concepts: ["nothing"],
+ filePatterns: { entryPoints: [], barrels: [], tests: [], config: [] },
+ });
+ expect(result.success).toBe(false);
+ if (!result.success) {
+ expect(result.error.issues[0].message).toContain("at least one extension or filename");
+ }
+ });
+
+ it("rejects configs with empty extensions AND empty filenames", () => {
+ const result = StrictLanguageConfigSchema.safeParse({
+ id: "empty-lang",
+ displayName: "Empty",
+ extensions: [],
+ filenames: [],
+ concepts: ["nothing"],
+ filePatterns: { entryPoints: [], barrels: [], tests: [], config: [] },
+ });
+ expect(result.success).toBe(false);
+ });
+
+ it("accepts configs with extensions but no filenames", () => {
+ const result = StrictLanguageConfigSchema.safeParse({
+ id: "ext-lang",
+ displayName: "ExtLang",
+ extensions: [".ext"],
+ concepts: ["something"],
+ filePatterns: { entryPoints: [], barrels: [], tests: [], config: [] },
+ });
+ expect(result.success).toBe(true);
+ });
+
+ it("accepts configs with filenames but empty extensions", () => {
+ const result = StrictLanguageConfigSchema.safeParse({
+ id: "filename-lang",
+ displayName: "FilenameLang",
+ extensions: [],
+ filenames: ["Specialfile"],
+ concepts: ["something"],
+ filePatterns: { entryPoints: [], barrels: [], tests: [], config: [] },
+ });
+ expect(result.success).toBe(true);
+ });
+ });
});
diff --git a/understand-anything-plugin/packages/core/src/__tests__/parsers.test.ts b/understand-anything-plugin/packages/core/src/__tests__/parsers.test.ts
index 13dca7e9..b4e008a1 100644
--- a/understand-anything-plugin/packages/core/src/__tests__/parsers.test.ts
+++ b/understand-anything-plugin/packages/core/src/__tests__/parsers.test.ts
@@ -365,6 +365,123 @@ describe("ShellParser", () => {
});
});
+// --- Edge case tests ---
+
+describe("SQLParser edge cases", () => {
+ const parser = new SQLParser();
+
+ it("handles CREATE TABLE IF NOT EXISTS", () => {
+ const content = "CREATE TABLE IF NOT EXISTS users (id INT);";
+ const result = parser.analyzeFile("schema.sql", content);
+ expect(result.definitions).toBeDefined();
+ expect(result.definitions!).toHaveLength(1);
+ expect(result.definitions![0]).toMatchObject({ name: "users", kind: "table" });
+ expect(result.definitions![0].fields).toContain("id");
+ });
+
+ it("handles CREATE OR REPLACE VIEW", () => {
+ const content = "CREATE OR REPLACE VIEW active AS SELECT * FROM users;";
+ const result = parser.analyzeFile("views.sql", content);
+ expect(result.definitions).toBeDefined();
+ expect(result.definitions!.some(d => d.name === "active" && d.kind === "view")).toBe(true);
+ });
+});
+
+describe("GraphQLParser edge cases", () => {
+ const parser = new GraphQLParser();
+
+ it("extracts input type definitions", () => {
+ const content = "input CreateUserInput {\n name: String!\n email: String!\n}";
+ const result = parser.analyzeFile("schema.graphql", content);
+ expect(result.definitions).toBeDefined();
+ const inputDef = result.definitions!.find(d => d.name === "CreateUserInput");
+ expect(inputDef).toBeDefined();
+ expect(inputDef!.kind).toBe("input");
+ expect(inputDef!.fields).toContain("name");
+ });
+});
+
+describe("MakefileParser edge cases", () => {
+ const parser = new MakefileParser();
+
+ it("does not extract .PHONY as a target", () => {
+ const content = ".PHONY: build test\n\nbuild:\n\tgo build\n\ntest:\n\tgo test";
+ const result = parser.analyzeFile("Makefile", content);
+ expect(result.steps).toBeDefined();
+ const targetNames = result.steps!.map(s => s.name);
+ expect(targetNames).not.toContain(".PHONY");
+ expect(targetNames).toContain("build");
+ expect(targetNames).toContain("test");
+ });
+});
+
+describe("ShellParser edge cases", () => {
+ const parser = new ShellParser();
+
+ it("handles function with opening brace on next line", () => {
+ const content = "greet()\n{\n echo \"Hello\"\n}";
+ const result = parser.analyzeFile("script.sh", content);
+ expect(result.functions).toHaveLength(1);
+ expect(result.functions[0].name).toBe("greet");
+ expect(result.functions[0].lineRange[1]).toBeGreaterThan(result.functions[0].lineRange[0]);
+ });
+});
+
+describe("TOMLParser edge cases", () => {
+ const parser = new TOMLParser();
+
+ it("returns empty sections for empty string", () => {
+ const result = parser.analyzeFile("empty.toml", "");
+ expect(result.sections).toBeDefined();
+ expect(result.sections).toHaveLength(0);
+ });
+
+ it("returns empty sections for garbage text", () => {
+ const result = parser.analyzeFile("garbage.toml", "this is not toml at all\nrandom garbage 123");
+ expect(result.sections).toBeDefined();
+ expect(result.sections).toHaveLength(0);
+ });
+});
+
+describe("DockerfileParser edge cases", () => {
+ const parser = new DockerfileParser();
+
+ it("assigns EXPOSE ports to the correct stage in multi-stage build", () => {
+ const content = "FROM node:22 AS builder\nRUN npm install\n\nFROM node:22-slim AS runner\nCOPY --from=builder /app /app\nEXPOSE 3000 8080\nCMD [\"node\", \"server.js\"]";
+ const result = parser.analyzeFile("Dockerfile", content);
+ expect(result.services).toBeDefined();
+ expect(result.services!).toHaveLength(2);
+ // Ports should be on the runner stage (second stage), not the builder
+ expect(result.services![0].ports).toHaveLength(0); // builder has no EXPOSE
+ expect(result.services![1].ports).toContain(3000);
+ expect(result.services![1].ports).toContain(8080);
+ });
+
+ it("includes lineRange for each stage", () => {
+ const content = "FROM node:22 AS builder\nRUN npm install\n\nFROM node:22-slim AS runner\nCOPY . .\nCMD [\"node\", \"start\"]";
+ const result = parser.analyzeFile("Dockerfile", content);
+ expect(result.services).toBeDefined();
+ expect(result.services!).toHaveLength(2);
+ expect(result.services![0].lineRange).toBeDefined();
+ expect(result.services![0].lineRange![0]).toBe(1);
+ expect(result.services![1].lineRange).toBeDefined();
+ expect(result.services![1].lineRange![0]).toBe(4);
+ });
+});
+
+describe("EnvParser edge cases", () => {
+ const parser = new EnvParser();
+
+ it("does not handle export VAR=value syntax", () => {
+ const content = "export DB_HOST=localhost\nAPI_KEY=secret";
+ const result = parser.analyzeFile(".env", content);
+ // The `export` prefix is not handled — only plain KEY=value is parsed
+ const names = result.definitions!.map(d => d.name);
+ expect(names).toContain("API_KEY");
+ expect(names).not.toContain("DB_HOST");
+ });
+});
+
describe("registerAllParsers", () => {
it("registers all 12 parsers with a PluginRegistry", () => {
const registry = new PluginRegistry();
diff --git a/understand-anything-plugin/packages/core/src/__tests__/plugin-registry.test.ts b/understand-anything-plugin/packages/core/src/__tests__/plugin-registry.test.ts
index 5e5976c8..39fec826 100644
--- a/understand-anything-plugin/packages/core/src/__tests__/plugin-registry.test.ts
+++ b/understand-anything-plugin/packages/core/src/__tests__/plugin-registry.test.ts
@@ -1,5 +1,6 @@
import { describe, it, expect } from "vitest";
import { PluginRegistry } from "../plugins/registry.js";
+import { registerAllParsers } from "../plugins/parsers/index.js";
import type { AnalyzerPlugin, StructuralAnalysis, ImportResolution } from "../types.js";
const emptyAnalysis: StructuralAnalysis = {
@@ -192,3 +193,36 @@ describe("PluginRegistry", () => {
expect(result).toBeNull();
});
});
+
+describe("registerAllParsers smoke test", () => {
+ it("all registered parsers return valid StructuralAnalysis for minimal content", () => {
+ const registry = new PluginRegistry();
+ registerAllParsers(registry);
+
+ // Map of file extension -> minimal content for each parser
+ const testCases: [string, string][] = [
+ ["README.md", "# Hello"],
+ ["config.yaml", "key: value"],
+ ["config.json", '{"key": "value"}'],
+ ["config.toml", 'key = "value"'],
+ [".env", "KEY=value"],
+ ["Dockerfile", "FROM node:22"],
+ ["schema.sql", "CREATE TABLE t (id INT);"],
+ ["schema.graphql", "type Query { hello: String }"],
+ ["types.proto", 'syntax = "proto3";'],
+ ["main.tf", 'resource "null" "r" {}'],
+ ["Makefile", "build:\n\techo build"],
+ ["script.sh", "#!/bin/bash\necho hello"],
+ ];
+
+ for (const [filePath, content] of testCases) {
+ const result = registry.analyzeFile(filePath, content);
+ expect(result, `analyzeFile should return a result for ${filePath}`).not.toBeNull();
+ // Verify basic structural analysis shape
+ expect(result).toHaveProperty("functions");
+ expect(result).toHaveProperty("classes");
+ expect(result).toHaveProperty("imports");
+ expect(result).toHaveProperty("exports");
+ }
+ });
+});
diff --git a/understand-anything-plugin/packages/core/src/analyzer/graph-builder.test.ts b/understand-anything-plugin/packages/core/src/analyzer/graph-builder.test.ts
index 6dac807e..a9dc9c90 100644
--- a/understand-anything-plugin/packages/core/src/analyzer/graph-builder.test.ts
+++ b/understand-anything-plugin/packages/core/src/analyzer/graph-builder.test.ts
@@ -1,4 +1,4 @@
-import { describe, it, expect } from "vitest";
+import { describe, it, expect, vi } from "vitest";
import { GraphBuilder } from "./graph-builder.js";
import type { StructuralAnalysis } from "../types.js";
@@ -214,7 +214,7 @@ describe("GraphBuilder", () => {
});
describe("Non-code file support", () => {
- it("adds non-code file nodes with correct types", () => {
+ it("adds non-code file nodes with correct types and nodeType-prefixed ID", () => {
const builder = new GraphBuilder("test", "abc123");
builder.addNonCodeFile("README.md", {
nodeType: "document",
@@ -225,7 +225,7 @@ describe("GraphBuilder", () => {
const graph = builder.build();
expect(graph.nodes).toHaveLength(1);
expect(graph.nodes[0].type).toBe("document");
- expect(graph.nodes[0].id).toBe("file:README.md");
+ expect(graph.nodes[0].id).toBe("document:README.md");
});
it("adds non-code child nodes (definitions)", () => {
@@ -337,5 +337,68 @@ describe("GraphBuilder", () => {
expect(graph.project.languages).toContain("terraform");
expect(graph.project.languages).toContain("protobuf");
});
+
+ it("mapKindToNodeType falls back to concept for unknown kinds and warns", () => {
+ const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
+ const builder = new GraphBuilder("test", "abc123");
+ builder.addNonCodeFileWithAnalysis("schema.sql", {
+ nodeType: "file",
+ summary: "Schema",
+ tags: [],
+ complexity: "simple",
+ definitions: [
+ { name: "doStuff", kind: "procedure", lineRange: [1, 10] as [number, number], fields: [] },
+ ],
+ });
+ const graph = builder.build();
+ const childNode = graph.nodes.find(n => n.name === "doStuff");
+ expect(childNode).toBeDefined();
+ expect(childNode!.type).toBe("concept");
+ expect(warnSpy).toHaveBeenCalledWith(
+ expect.stringContaining('Unknown definition kind "procedure"'),
+ );
+ warnSpy.mockRestore();
+ });
+
+ it("skips duplicate node IDs in addNonCodeFileWithAnalysis and warns", () => {
+ const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
+ const builder = new GraphBuilder("test", "abc123");
+ builder.addNonCodeFileWithAnalysis("schema.sql", {
+ nodeType: "file",
+ summary: "Schema",
+ tags: [],
+ complexity: "simple",
+ definitions: [
+ { name: "users", kind: "table", lineRange: [1, 10] as [number, number], fields: ["id"] },
+ { name: "users", kind: "table", lineRange: [12, 20] as [number, number], fields: ["id", "name"] },
+ ],
+ });
+ const graph = builder.build();
+ // Only the file node + one table node (duplicate skipped)
+ const tableNodes = graph.nodes.filter(n => n.name === "users");
+ expect(tableNodes).toHaveLength(1);
+ expect(warnSpy).toHaveBeenCalledWith(
+ expect.stringContaining('Duplicate node ID "table:schema.sql:users"'),
+ );
+ warnSpy.mockRestore();
+ });
+
+ it("uses nodeType in fileId for contains edges", () => {
+ const builder = new GraphBuilder("test", "abc123");
+ builder.addNonCodeFileWithAnalysis("docker-compose.yml", {
+ nodeType: "config",
+ summary: "Docker compose config",
+ tags: [],
+ complexity: "simple",
+ services: [
+ { name: "web", ports: [3000] },
+ ],
+ });
+ const graph = builder.build();
+ const containsEdge = graph.edges.find(e => e.type === "contains");
+ expect(containsEdge).toBeDefined();
+ expect(containsEdge!.source).toBe("config:docker-compose.yml");
+ expect(containsEdge!.target).toBe("service:docker-compose.yml:web");
+ });
});
});
diff --git a/understand-anything-plugin/packages/core/src/analyzer/graph-builder.ts b/understand-anything-plugin/packages/core/src/analyzer/graph-builder.ts
index 1e30c884..423b49ff 100644
--- a/understand-anything-plugin/packages/core/src/analyzer/graph-builder.ts
+++ b/understand-anything-plugin/packages/core/src/analyzer/graph-builder.ts
@@ -233,7 +233,7 @@ export class GraphBuilder {
if (lang !== "unknown") this.languages.add(lang);
const name = filePath.split("/").pop() ?? filePath;
this.nodes.push({
- id: `file:${filePath}`,
+ id: `${meta.nodeType ?? "file"}:${filePath}`,
type: meta.nodeType,
name,
filePath,
@@ -245,11 +245,18 @@ export class GraphBuilder {
addNonCodeFileWithAnalysis(filePath: string, meta: NonCodeFileAnalysisMeta): void {
this.addNonCodeFile(filePath, meta);
- const fileId = `file:${filePath}`;
+ const fileId = `${meta.nodeType ?? "file"}:${filePath}`;
+
+ const existingIds = new Set(this.nodes.map(n => n.id));
// Create child nodes for definitions (tables, schemas, etc.)
for (const def of meta.definitions ?? []) {
const childId = `${def.kind}:${filePath}:${def.name}`;
+ if (existingIds.has(childId)) {
+ console.warn(`[GraphBuilder] Duplicate node ID "${childId}" — skipping`);
+ continue;
+ }
+ existingIds.add(childId);
this.nodes.push({
id: childId,
type: this.mapKindToNodeType(def.kind),
@@ -266,6 +273,11 @@ export class GraphBuilder {
// Create child nodes for services
for (const svc of meta.services ?? []) {
const childId = `service:${filePath}:${svc.name}`;
+ if (existingIds.has(childId)) {
+ console.warn(`[GraphBuilder] Duplicate node ID "${childId}" — skipping`);
+ continue;
+ }
+ existingIds.add(childId);
this.nodes.push({
id: childId,
type: "service",
@@ -281,6 +293,11 @@ export class GraphBuilder {
// Create child nodes for endpoints
for (const ep of meta.endpoints ?? []) {
const childId = `endpoint:${filePath}:${ep.path}`;
+ if (existingIds.has(childId)) {
+ console.warn(`[GraphBuilder] Duplicate node ID "${childId}" — skipping`);
+ continue;
+ }
+ existingIds.add(childId);
this.nodes.push({
id: childId,
type: "endpoint",
@@ -297,6 +314,11 @@ export class GraphBuilder {
// Create child nodes for steps (pipeline/makefile targets)
for (const step of meta.steps ?? []) {
const childId = `step:${filePath}:${step.name}`;
+ if (existingIds.has(childId)) {
+ console.warn(`[GraphBuilder] Duplicate node ID "${childId}" — skipping`);
+ continue;
+ }
+ existingIds.add(childId);
this.nodes.push({
id: childId,
type: "pipeline",
@@ -313,6 +335,11 @@ export class GraphBuilder {
// Create child nodes for resources (Terraform, etc.)
for (const res of meta.resources ?? []) {
const childId = `resource:${filePath}:${res.name}`;
+ if (existingIds.has(childId)) {
+ console.warn(`[GraphBuilder] Duplicate node ID "${childId}" — skipping`);
+ continue;
+ }
+ existingIds.add(childId);
this.nodes.push({
id: childId,
type: "resource",
@@ -348,7 +375,11 @@ export class GraphBuilder {
variable: "config",
output: "config",
};
- return mapping[kind] ?? "concept";
+ const mapped = mapping[kind];
+ if (!mapped) {
+ console.warn(`[GraphBuilder] Unknown definition kind "${kind}" — falling back to "concept" node type`);
+ }
+ return mapped ?? "concept";
}
build(): KnowledgeGraph {
diff --git a/understand-anything-plugin/packages/core/src/languages/types.ts b/understand-anything-plugin/packages/core/src/languages/types.ts
index c5499a9a..61a35fcb 100644
--- a/understand-anything-plugin/packages/core/src/languages/types.ts
+++ b/understand-anything-plugin/packages/core/src/languages/types.ts
@@ -22,7 +22,7 @@ export const FilePatternConfigSchema = z.object({
export type FilePatternConfig = z.infer<typeof FilePatternConfigSchema>;
-// Complete language configuration
+// Complete language configuration (base schema — used by LanguageRegistry.register())
export const LanguageConfigSchema = z.object({
id: z.string().min(1),
displayName: z.string().min(1),
@@ -35,6 +35,18 @@ export const LanguageConfigSchema = z.object({
export type LanguageConfig = z.infer<typeof LanguageConfigSchema>;
+/**
+ * Strict schema with refinement: ensures at least one extension or filename
+ * is provided so the config can actually be detected by the registry.
+ * Use this for validating new/user-supplied configs (some builtin configs like
+ * kubernetes/github-actions intentionally lack both and rely on future
+ * content-based detection).
+ */
+export const StrictLanguageConfigSchema = LanguageConfigSchema.refine(
+ (c) => c.extensions.length > 0 || (c.filenames !== undefined && c.filenames.length > 0),
+ { message: "LanguageConfig must have at least one extension or filename for detection" }
+);
+
// Framework configuration
export const FrameworkConfigSchema = z.object({
id: z.string().min(1),
diff --git a/understand-anything-plugin/packages/core/src/plugins/parsers/dockerfile-parser.ts b/understand-anything-plugin/packages/core/src/plugins/parsers/dockerfile-parser.ts
index a70726ba..cba4b241 100644
--- a/understand-anything-plugin/packages/core/src/plugins/parsers/dockerfile-parser.ts
+++ b/understand-anything-plugin/packages/core/src/plugins/parsers/dockerfile-parser.ts
@@ -1,5 +1,10 @@
import type { AnalyzerPlugin, StructuralAnalysis, ServiceInfo, StepInfo } from "../../types.js";
+/**
+ * Parses Dockerfiles to extract multi-stage build stages, EXPOSE ports, and instruction steps.
+ * Associates EXPOSE ports with the correct stage based on FROM directive ordering.
+ * Does not parse ARG/ENV variable substitution or heredoc syntax.
+ */
export class DockerfileParser implements AnalyzerPlugin {
name = "dockerfile-parser";
languages = ["dockerfile"];
@@ -20,32 +25,45 @@ export class DockerfileParser implements AnalyzerPlugin {
private extractStages(content: string): ServiceInfo[] {
const stages: ServiceInfo[] = [];
const lines = content.split("\n");
- const ports: number[] = [];
- // Collect all EXPOSE ports
- for (const line of lines) {
- const exposeMatch = line.match(/^EXPOSE\s+(.+)/i);
- if (exposeMatch) {
- const portValues = exposeMatch[1].split(/\s+/);
- for (const p of portValues) {
- const num = parseInt(p, 10);
- if (!isNaN(num)) ports.push(num);
- }
+ // First pass: find FROM line indices
+ const fromLines: number[] = [];
+ for (let i = 0; i < lines.length; i++) {
+ if (/^FROM\s+/i.test(lines[i])) {
+ fromLines.push(i);
}
}
- // Extract FROM stages
- for (const line of lines) {
- const fromMatch = line.match(/^FROM\s+(\S+)(?:\s+[Aa][Ss]\s+(\S+))?/i);
- if (fromMatch) {
- const image = fromMatch[1];
- const name = fromMatch[2] ?? image.split(":")[0].split("/").pop() ?? image;
- stages.push({
- name,
- image,
- ports: stages.length === 0 ? ports : [], // Assign ports to first stage only as default
- });
+ // Second pass: for each stage, collect EXPOSE ports within its range and build ServiceInfo
+ for (let s = 0; s < fromLines.length; s++) {
+ const stageStartLine = fromLines[s];
+ const stageEndLine = s + 1 < fromLines.length ? fromLines[s + 1] - 1 : lines.length - 1;
+
+ const fromMatch = lines[stageStartLine].match(/^FROM\s+(\S+)(?:\s+[Aa][Ss]\s+(\S+))?/i);
+ if (!fromMatch) continue;
+
+ const image = fromMatch[1];
+ const name = fromMatch[2] ?? image.split(":")[0].split("/").pop() ?? image;
+
+ // Collect EXPOSE ports that appear within this stage's range
+ const ports: number[] = [];
+ for (let i = stageStartLine; i <= stageEndLine; i++) {
+ const exposeMatch = lines[i].match(/^EXPOSE\s+(.+)/i);
+ if (exposeMatch) {
+ const portValues = exposeMatch[1].split(/\s+/);
+ for (const p of portValues) {
+ const num = parseInt(p, 10);
+ if (!isNaN(num)) ports.push(num);
+ }
+ }
}
+
+ stages.push({
+ name,
+ image,
+ ports,
+ lineRange: [stageStartLine + 1, stageEndLine + 1],
+ });
}
return stages;
diff --git a/understand-anything-plugin/packages/core/src/plugins/parsers/env-parser.ts b/understand-anything-plugin/packages/core/src/plugins/parsers/env-parser.ts
index a2f22a33..c39a6b0e 100644
--- a/understand-anything-plugin/packages/core/src/plugins/parsers/env-parser.ts
+++ b/understand-anything-plugin/packages/core/src/plugins/parsers/env-parser.ts
@@ -1,5 +1,10 @@
import type { AnalyzerPlugin, StructuralAnalysis, DefinitionInfo } from "../../types.js";
+/**
+ * Parses .env files to extract environment variable definitions.
+ * Handles KEY=value syntax, skipping comments and empty lines.
+ * Does not handle `export VAR=value` syntax or multi-line values.
+ */
export class EnvParser implements AnalyzerPlugin {
name = "env-parser";
languages = ["env"];
diff --git a/understand-anything-plugin/packages/core/src/plugins/parsers/graphql-parser.ts b/understand-anything-plugin/packages/core/src/plugins/parsers/graphql-parser.ts
index 184b6b22..69855147 100644
--- a/understand-anything-plugin/packages/core/src/plugins/parsers/graphql-parser.ts
+++ b/understand-anything-plugin/packages/core/src/plugins/parsers/graphql-parser.ts
@@ -1,5 +1,10 @@
import type { AnalyzerPlugin, StructuralAnalysis, DefinitionInfo, EndpointInfo } from "../../types.js";
+/**
+ * Parses GraphQL schema files to extract type, input, enum, interface, union, and scalar definitions.
+ * Extracts Query, Mutation, and Subscription endpoints as separate endpoint entries.
+ * Does not handle schema directives, fragments, or inline union members.
+ */
export class GraphQLParser implements AnalyzerPlugin {
name = "graphql-parser";
languages = ["graphql"];
diff --git a/understand-anything-plugin/packages/core/src/plugins/parsers/json-parser.ts b/understand-anything-plugin/packages/core/src/plugins/parsers/json-parser.ts
index baf74a55..36db1b76 100644
--- a/understand-anything-plugin/packages/core/src/plugins/parsers/json-parser.ts
+++ b/understand-anything-plugin/packages/core/src/plugins/parsers/json-parser.ts
@@ -1,5 +1,10 @@
import type { AnalyzerPlugin, StructuralAnalysis, SectionInfo, ReferenceResolution } from "../../types.js";
+/**
+ * Parses JSON configuration files to extract top-level key sections and $ref references.
+ * Handles package.json, tsconfig.json, JSON Schema, and OpenAPI spec files.
+ * Does not descend into nested object structures beyond top-level keys.
+ */
export class JSONConfigParser implements AnalyzerPlugin {
name = "json-config-parser";
languages = ["json"];
@@ -57,8 +62,8 @@ export class JSONConfigParser implements AnalyzerPlugin {
sections[i].lineRange[1] = next ? next.lineRange[0] - 1 : lines.length;
}
}
- } catch {
- // JSON parse failed — skip
+ } catch (err) {
+ console.warn(`[json-parser] Failed to parse JSON: ${err instanceof Error ? err.message : String(err)}`);
}
return sections;
}
diff --git a/understand-anything-plugin/packages/core/src/plugins/parsers/makefile-parser.ts b/understand-anything-plugin/packages/core/src/plugins/parsers/makefile-parser.ts
index 4c1b9bf4..5b20139e 100644
--- a/understand-anything-plugin/packages/core/src/plugins/parsers/makefile-parser.ts
+++ b/understand-anything-plugin/packages/core/src/plugins/parsers/makefile-parser.ts
@@ -1,5 +1,10 @@
import type { AnalyzerPlugin, StructuralAnalysis, StepInfo } from "../../types.js";
+/**
+ * Parses Makefiles to extract build targets and their line ranges.
+ * Filters out special Make targets (e.g., .PHONY, .DEFAULT, .SUFFIXES) and variable assignments.
+ * Does not parse target dependencies or recipe commands.
+ */
export class MakefileParser implements AnalyzerPlugin {
name = "makefile-parser";
languages = ["makefile"];
@@ -20,8 +25,11 @@ export class MakefileParser implements AnalyzerPlugin {
const lines = content.split("\n");
for (let i = 0; i < lines.length; i++) {
// Match target: dependencies (not variable assignments or comments)
- const match = lines[i].match(/^([a-zA-Z_][\w.-]*)(?:\s+.*)?:/);
+ const match = lines[i].match(/^([a-zA-Z_.][a-zA-Z0-9_.-]*)(?:\s+.*)?:/);
if (match && !lines[i].includes(":=") && !lines[i].includes("?=")) {
+ const name = match[1];
+ // Skip special Make targets (.PHONY, .DEFAULT, .SUFFIXES, etc.)
+ if (name.startsWith(".")) continue;
// Find end of target (next non-indented non-empty line or EOF)
let endLine = i + 1;
while (endLine < lines.length) {
@@ -33,7 +41,7 @@ export class MakefileParser implements AnalyzerPlugin {
}
}
targets.push({
- name: match[1],
+ name,
lineRange: [i + 1, endLine],
});
}
diff --git a/understand-anything-plugin/packages/core/src/plugins/parsers/markdown-parser.ts b/understand-anything-plugin/packages/core/src/plugins/parsers/markdown-parser.ts
index f0192f96..23008b85 100644
--- a/understand-anything-plugin/packages/core/src/plugins/parsers/markdown-parser.ts
+++ b/understand-anything-plugin/packages/core/src/plugins/parsers/markdown-parser.ts
@@ -1,5 +1,10 @@
import type { AnalyzerPlugin, StructuralAnalysis, ReferenceResolution, SectionInfo } from "../../types.js";
+/**
+ * Parses Markdown files to extract heading sections and local file/image references.
+ * Supports ATX-style headings (# through ######) with line range computation.
+ * Does not extract code blocks, front matter fields, or external URL references.
+ */
export class MarkdownParser implements AnalyzerPlugin {
name = "markdown-parser";
languages = ["markdown"];
diff --git a/understand-anything-plugin/packages/core/src/plugins/parsers/protobuf-parser.ts b/understand-anything-plugin/packages/core/src/plugins/parsers/protobuf-parser.ts
index 6c49886f..1df1b55d 100644
--- a/understand-anything-plugin/packages/core/src/plugins/parsers/protobuf-parser.ts
+++ b/understand-anything-plugin/packages/core/src/plugins/parsers/protobuf-parser.ts
@@ -1,5 +1,10 @@
import type { AnalyzerPlugin, StructuralAnalysis, DefinitionInfo, EndpointInfo } from "../../types.js";
+/**
+ * Parses Protocol Buffer (.proto) files to extract message, enum, and service definitions.
+ * Extracts message fields, enum values, and service RPC method endpoints.
+ * Does not handle nested message types, oneof fields, or proto2 extensions.
+ */
export class ProtobufParser implements AnalyzerPlugin {
name = "protobuf-parser";
languages = ["protobuf"];
@@ -128,6 +133,9 @@ export class ProtobufParser implements AnalyzerPlugin {
if (depth === 0) return i;
}
}
+ if (depth !== 0) {
+ console.warn(`[protobuf-parser] Unbalanced braces detected (depth=${depth}), results may be incomplete`);
+ }
return content.length;
}
}
diff --git a/understand-anything-plugin/packages/core/src/plugins/parsers/shell-parser.ts b/understand-anything-plugin/packages/core/src/plugins/parsers/shell-parser.ts
index 09f6c303..8090c086 100644
--- a/understand-anything-plugin/packages/core/src/plugins/parsers/shell-parser.ts
+++ b/understand-anything-plugin/packages/core/src/plugins/parsers/shell-parser.ts
@@ -1,5 +1,10 @@
import type { AnalyzerPlugin, StructuralAnalysis, ReferenceResolution } from "../../types.js";
+/**
+ * Parses shell scripts (.sh, .bash) to extract function definitions and source references.
+ * Handles both `name() {` and `function name {` styles, including brace on next line.
+ * Does not extract variable declarations, aliases, or trap handlers.
+ */
export class ShellParser implements AnalyzerPlugin {
name = "shell-parser";
languages = ["shell"];
@@ -42,11 +47,12 @@ export class ShellParser implements AnalyzerPlugin {
lines[i].match(/^function\s+(\w+)\s*\{?/);
if (match) {
const name = match[1];
- // Find closing brace
+ // Find closing brace (handle brace on same line or next line)
let endLine = i;
- if (lines[i].includes("{")) {
+ if (lines[i].includes("{") || (i + 1 < lines.length && lines[i + 1]?.trim() === "{")) {
+ const startBraceLine = lines[i].includes("{") ? i : i + 1;
let depth = 0;
- for (let j = i; j < lines.length; j++) {
+ for (let j = startBraceLine; j < lines.length; j++) {
for (const ch of lines[j]) {
if (ch === "{") depth++;
if (ch === "}") depth--;
diff --git a/understand-anything-plugin/packages/core/src/plugins/parsers/sql-parser.ts b/understand-anything-plugin/packages/core/src/plugins/parsers/sql-parser.ts
index 01240b12..eb741a20 100644
--- a/understand-anything-plugin/packages/core/src/plugins/parsers/sql-parser.ts
+++ b/understand-anything-plugin/packages/core/src/plugins/parsers/sql-parser.ts
@@ -1,5 +1,10 @@
import type { AnalyzerPlugin, StructuralAnalysis, DefinitionInfo } from "../../types.js";
+/**
+ * Parses SQL files to extract table, view, and index definitions.
+ * Handles CREATE TABLE, CREATE VIEW, CREATE INDEX with IF NOT EXISTS and OR REPLACE variants.
+ * Does not handle stored procedures, triggers, or schema-qualified names (e.g., public.users).
+ */
export class SQLParser implements AnalyzerPlugin {
name = "sql-parser";
languages = ["sql"];
diff --git a/understand-anything-plugin/packages/core/src/plugins/parsers/terraform-parser.ts b/understand-anything-plugin/packages/core/src/plugins/parsers/terraform-parser.ts
index 0fd44bf6..902b6bba 100644
--- a/understand-anything-plugin/packages/core/src/plugins/parsers/terraform-parser.ts
+++ b/understand-anything-plugin/packages/core/src/plugins/parsers/terraform-parser.ts
@@ -1,5 +1,10 @@
import type { AnalyzerPlugin, StructuralAnalysis, ResourceInfo, DefinitionInfo } from "../../types.js";
+/**
+ * Parses Terraform (.tf) files to extract resource, data, module, variable, and output blocks.
+ * Handles HCL block syntax with brace-matching for line range computation.
+ * Does not handle provider blocks, locals, or terraform configuration blocks.
+ */
export class TerraformParser implements AnalyzerPlugin {
name = "terraform-parser";
languages = ["terraform"];
@@ -117,6 +122,9 @@ export class TerraformParser implements AnalyzerPlugin {
if (depth === 0) return i;
}
}
+ if (depth !== 0) {
+ console.warn(`[terraform-parser] Unbalanced braces detected (depth=${depth}), results may be incomplete`);
+ }
return content.length;
}
}
diff --git a/understand-anything-plugin/packages/core/src/plugins/parsers/toml-parser.ts b/understand-anything-plugin/packages/core/src/plugins/parsers/toml-parser.ts
index 114db913..b54456bd 100644
--- a/understand-anything-plugin/packages/core/src/plugins/parsers/toml-parser.ts
+++ b/understand-anything-plugin/packages/core/src/plugins/parsers/toml-parser.ts
@@ -1,5 +1,10 @@
import type { AnalyzerPlugin, StructuralAnalysis, SectionInfo } from "../../types.js";
+/**
+ * Parses TOML files to extract section headers ([section] and [[array-of-tables]]).
+ * Computes section nesting level from dotted key paths (e.g., [tool.poetry] = level 2).
+ * Does not parse individual key-value pairs within sections.
+ */
export class TOMLParser implements AnalyzerPlugin {
name = "toml-parser";
languages = ["toml"];
diff --git a/understand-anything-plugin/packages/core/src/plugins/parsers/yaml-parser.ts b/understand-anything-plugin/packages/core/src/plugins/parsers/yaml-parser.ts
index 7f9dfd67..bbbaa130 100644
--- a/understand-anything-plugin/packages/core/src/plugins/parsers/yaml-parser.ts
+++ b/understand-anything-plugin/packages/core/src/plugins/parsers/yaml-parser.ts
@@ -1,6 +1,11 @@
import type { AnalyzerPlugin, StructuralAnalysis, SectionInfo } from "../../types.js";
import { parse as parseYAML } from "yaml";
+/**
+ * Parses YAML configuration files to extract top-level key sections.
+ * Uses the `yaml` library for parsing with a regex fallback for malformed input.
+ * Only extracts top-level keys; does not descend into nested structures.
+ */
export class YAMLConfigParser implements AnalyzerPlugin {
name = "yaml-config-parser";
languages = ["yaml"];
@@ -39,7 +44,8 @@ export class YAMLConfigParser implements AnalyzerPlugin {
sections[i].lineRange[1] = next ? next.lineRange[0] - 1 : lines.length;
}
}
- } catch {
+ } catch (err) {
+ console.warn(`[yaml-parser] YAML parse failed, falling back to regex extraction: ${err instanceof Error ? err.message : String(err)}`);
// If YAML parsing fails, fall back to regex
const lines = content.split("\n");
for (let i = 0; i < lines.length; i++) {
diff --git a/understand-anything-plugin/packages/core/src/schema.ts b/understand-anything-plugin/packages/core/src/schema.ts
index f661c284..5b9ad1a9 100644
--- a/understand-anything-plugin/packages/core/src/schema.ts
+++ b/understand-anything-plugin/packages/core/src/schema.ts
@@ -7,8 +7,8 @@ export const EdgeTypeSchema = z.enum([
"reads_from", "writes_to", "transforms", "validates", // Data flow
"depends_on", "tested_by", "configures", // Dependencies
"related", "similar_to", // Semantic
- "deploys", "serves", "migrates", "documents", // Infrastructure
- "provisions", "routes", "defines_schema", "triggers", // Infrastructure
+ "deploys", "serves", "provisions", "triggers", // Infrastructure
+ "migrates", "documents", "routes", "defines_schema", // Schema/Data
]);
// Aliases that LLMs commonly generate instead of canonical node types
diff --git a/understand-anything-plugin/packages/core/src/types.test.ts b/understand-anything-plugin/packages/core/src/types.test.ts
index c12c1065..2407d8d4 100644
--- a/understand-anything-plugin/packages/core/src/types.test.ts
+++ b/understand-anything-plugin/packages/core/src/types.test.ts
@@ -1,5 +1,5 @@
import { describe, it, expect } from "vitest";
-import type { KnowledgeGraph, GraphNode, GraphEdge, EdgeType, StructuralAnalysis, AnalyzerPlugin, ReferenceResolution } from "./types.js";
+import type { KnowledgeGraph, GraphNode, GraphEdge, EdgeType, NodeType, StructuralAnalysis, AnalyzerPlugin, ReferenceResolution } from "./types.js";
describe("KnowledgeGraph types", () => {
it("should create a valid empty KnowledgeGraph", () => {
@@ -117,13 +117,16 @@ describe("KnowledgeGraph types", () => {
});
describe("Extended types", () => {
- it("accepts all 13 node types", () => {
- const nodeTypes: GraphNode["type"][] = [
+ it("accepts all 13 node types via NodeType alias", () => {
+ const nodeTypes: NodeType[] = [
"file", "function", "class", "module", "concept",
"config", "document", "service", "table", "endpoint",
"pipeline", "schema", "resource",
];
expect(nodeTypes).toHaveLength(13);
+ // NodeType and GraphNode["type"] should be interchangeable
+ const check: GraphNode["type"] = nodeTypes[0];
+ expect(check).toBe("file");
});
it("accepts all 26 edge types", () => {
@@ -144,7 +147,7 @@ describe("Extended types", () => {
functions: [], classes: [], imports: [], exports: [],
sections: [{ name: "Introduction", level: 1, lineRange: [1, 10] }],
definitions: [{ name: "users", kind: "table", lineRange: [1, 20], fields: ["id", "name"] }],
- services: [{ name: "web", image: "node:22", ports: [3000] }],
+ services: [{ name: "web", image: "node:22", ports: [3000], lineRange: [1, 5] }],
endpoints: [{ method: "GET", path: "/api/users", lineRange: [5, 15] }],
steps: [{ name: "build", lineRange: [1, 5] }],
resources: [{ name: "aws_s3_bucket.main", kind: "aws_s3_bucket", lineRange: [1, 10] }],
@@ -152,11 +155,19 @@ describe("Extended types", () => {
expect(analysis.sections).toHaveLength(1);
expect(analysis.definitions).toHaveLength(1);
expect(analysis.services).toHaveLength(1);
+ expect(analysis.services![0].lineRange).toEqual([1, 5]);
expect(analysis.endpoints).toHaveLength(1);
expect(analysis.steps).toHaveLength(1);
expect(analysis.resources).toHaveLength(1);
});
+ it("ServiceInfo.lineRange is optional for backward compat", () => {
+ const svcWithout: import("./types.js").ServiceInfo = { name: "web", ports: [3000] };
+ const svcWith: import("./types.js").ServiceInfo = { name: "db", ports: [5432], lineRange: [10, 20] };
+ expect(svcWithout.lineRange).toBeUndefined();
+ expect(svcWith.lineRange).toEqual([10, 20]);
+ });
+
it("StructuralAnalysis is backward compatible (non-code fields are optional)", () => {
const analysis: StructuralAnalysis = {
functions: [], classes: [], imports: [], exports: [],
diff --git a/understand-anything-plugin/packages/core/src/types.ts b/understand-anything-plugin/packages/core/src/types.ts
index d38a68f6..ab92cd7a 100644
--- a/understand-anything-plugin/packages/core/src/types.ts
+++ b/understand-anything-plugin/packages/core/src/types.ts
@@ -1,19 +1,23 @@
-// Edge types (26 total in 6 categories: Structural, Behavioral, Data flow, Dependencies, Semantic, Infrastructure)
+// Node types (13 total: 5 code + 8 non-code)
+export type NodeType =
+ | "file" | "function" | "class" | "module" | "concept"
+ | "config" | "document" | "service" | "table" | "endpoint"
+ | "pipeline" | "schema" | "resource";
+
+// Edge types (26 total in 6 categories: Structural, Behavioral, Data flow, Dependencies, Semantic, Infrastructure/Schema)
export type EdgeType =
| "imports" | "exports" | "contains" | "inherits" | "implements" // Structural
| "calls" | "subscribes" | "publishes" | "middleware" // Behavioral
| "reads_from" | "writes_to" | "transforms" | "validates" // Data flow
| "depends_on" | "tested_by" | "configures" // Dependencies
| "related" | "similar_to" // Semantic
- | "deploys" | "serves" | "migrates" | "documents" // Infrastructure
- | "provisions" | "routes" | "defines_schema" | "triggers"; // Infrastructure
+ | "deploys" | "serves" | "provisions" | "triggers" // Infrastructure
+ | "migrates" | "documents" | "routes" | "defines_schema"; // Schema/Data
// GraphNode with 13 types: 5 code + 8 non-code
export interface GraphNode {
id: string;
- type: "file" | "function" | "class" | "module" | "concept"
- | "config" | "document" | "service" | "table" | "endpoint"
- | "pipeline" | "schema" | "resource";
+ type: NodeType;
name: string;
filePath?: string;
lineRange?: [number, number];
@@ -99,7 +103,8 @@ export interface SectionInfo {
export interface DefinitionInfo {
name: string;
- kind: string; // "table", "message", "type", "schema"
+ /** Parser-reported definition kind. Known values: "table", "view", "index", "message", "enum", "type", "input", "interface", "union", "scalar", "variable", "output", "resource", "data", "section", "target", "stage" */
+ kind: string;
lineRange: [number, number];
fields: string[];
}
@@ -108,6 +113,7 @@ export interface ServiceInfo {
name: string;
image?: string;
ports: number[];
+ lineRange?: [number, number];
}
export interface EndpointInfo {
diff --git a/understand-anything-plugin/packages/dashboard/src/components/CustomNode.tsx b/understand-anything-plugin/packages/dashboard/src/components/CustomNode.tsx
index 75bb1727..f8de4083 100644
--- a/understand-anything-plugin/packages/dashboard/src/components/CustomNode.tsx
+++ b/understand-anything-plugin/packages/dashboard/src/components/CustomNode.tsx
@@ -1,8 +1,10 @@
import { memo } from "react";
import { Handle, Position } from "@xyflow/react";
import type { NodeProps, Node } from "@xyflow/react";
+import type { NodeType } from "@understand-anything/core/types";
-const typeColors: Record<string, string> = {
+// Color maps keyed by NodeType — must be kept in sync with core NodeType union.
+const typeColors: Record<NodeType, string> = {
file: "var(--color-node-file)",
function: "var(--color-node-function)",
class: "var(--color-node-class)",
@@ -18,7 +20,7 @@ const typeColors: Record<string, string> = {
resource: "var(--color-node-resource)",
};
-const typeTextColors: Record<string, string> = {
+const typeTextColors: Record<NodeType, string> = {
file: "text-node-file",
function: "text-node-function",
class: "text-node-class",
@@ -63,10 +65,15 @@ function CustomNodeComponent({
id,
data,
}: NodeProps<CustomFlowNode>) {
- const barColor = typeColors[data.nodeType] ?? typeColors.file;
- const textColor = typeTextColors[data.nodeType] ?? typeTextColors.file;
+ const knownType = data.nodeType as NodeType;
+ const barColor = typeColors[knownType] ?? typeColors.file;
+ const textColor = typeTextColors[knownType] ?? typeTextColors.file;
const complexityColor = complexityColors[data.complexity] ?? complexityColors.simple;
+ if (import.meta.env.DEV && !(knownType in typeColors)) {
+ console.warn(`[CustomNode] Unknown node type "${data.nodeType}" — using "file" colors`);
+ }
+
let extraClass = "";
if (data.isSelected) {
extraClass = "ring-2 ring-accent node-glow";
diff --git a/understand-anything-plugin/packages/dashboard/src/components/GraphView.tsx b/understand-anything-plugin/packages/dashboard/src/components/GraphView.tsx
index 3732fa24..66c47dac 100644
--- a/understand-anything-plugin/packages/dashboard/src/components/GraphView.tsx
+++ b/understand-anything-plugin/packages/dashboard/src/components/GraphView.tsx
@@ -21,7 +21,7 @@ import PortalNode from "./PortalNode";
import type { PortalFlowNode } from "./PortalNode";
import Breadcrumb from "./Breadcrumb";
import { useDashboardStore } from "../store";
-import type { KnowledgeGraph } from "@understand-anything/core/types";
+import type { KnowledgeGraph, NodeType } from "@understand-anything/core/types";
import { useTheme } from "../themes/index.ts";
import {
applyDagreLayout,
@@ -44,6 +44,20 @@ const nodeTypes = {
portal: PortalNode,
};
+import type { NodeCategory } from "../store";
+
+/**
+ * Maps each NodeType to a filter category. Must be kept in sync with core NodeType.
+ * Unknown types default to "code" with a development warning.
+ */
+const NODE_TYPE_TO_CATEGORY: Record<NodeType, NodeCategory> = {
+ file: "code", function: "code", class: "code", module: "code", concept: "code",
+ config: "config",
+ document: "docs",
+ service: "infra", resource: "infra", pipeline: "infra",
+ table: "data", endpoint: "data", schema: "data",
+} as const;
+
// ── Helper components that must live inside <ReactFlow> ────────────────
/** Pans/zooms to tour-highlighted nodes. */
@@ -219,15 +233,6 @@ function useLayerDetailTopology() {
const layerNodeIds = new Set(activeLayer.nodeIds);
- // Map node types to filter categories
- const nodeTypeToCategory: Record<string, string> = {
- file: "code", function: "code", class: "code", module: "code", concept: "code",
- config: "config",
- document: "docs",
- service: "infra", resource: "infra", pipeline: "infra",
- table: "data", endpoint: "data", schema: "data",
- };
-
// All top-level (file-level) node types that should appear in the graph.
// This includes the 8 new non-code types plus the original "file" type.
const fileLevelTypes = new Set([
@@ -245,8 +250,14 @@ function useLayerDetailTopology() {
// Apply node type category filters
filteredGraphNodes = filteredGraphNodes.filter((n) => {
- const category = nodeTypeToCategory[n.type] ?? "code";
- return nodeTypeFilters[category] !== false;
+ const category = NODE_TYPE_TO_CATEGORY[n.type as NodeType];
+ if (!category) {
+ if (import.meta.env.DEV) {
+ console.warn(`[GraphView] Unknown node type "${n.type}" — defaulting to "code" category`);
+ }
+ }
+ const effectiveCategory = category ?? "code";
+ return nodeTypeFilters[effectiveCategory] !== false;
});
let filteredNodeIds = new Set(filteredGraphNodes.map((n) => n.id));
diff --git a/understand-anything-plugin/packages/dashboard/src/components/NodeInfo.tsx b/understand-anything-plugin/packages/dashboard/src/components/NodeInfo.tsx
index 976e24a0..6bee4b40 100644
--- a/understand-anything-plugin/packages/dashboard/src/components/NodeInfo.tsx
+++ b/understand-anything-plugin/packages/dashboard/src/components/NodeInfo.tsx
@@ -1,7 +1,9 @@
import { useState } from "react";
import { useDashboardStore } from "../store";
+import type { NodeType, EdgeType } from "@understand-anything/core/types";
-const typeBadgeColors: Record<string, string> = {
+// Badge color classes keyed by NodeType — must be kept in sync with core NodeType union.
+const typeBadgeColors: Record<NodeType, string> = {
file: "text-node-file border border-node-file/30 bg-node-file/10",
function: "text-node-function border border-node-function/30 bg-node-function/10",
class: "text-node-class border border-node-class/30 bg-node-class/10",
@@ -24,67 +26,50 @@ const complexityBadgeColors: Record<string, string> = {
};
/**
- * Human-readable directional labels for edge types.
- * Returns different text depending on whether the selected node is
- * the source or target of the edge.
+ * Human-readable directional labels for all 26 edge types.
+ * Must be kept in sync with core EdgeType.
+ */
+const EDGE_LABELS: Record<EdgeType, { forward: string; backward: string }> = {
+ imports: { forward: "imports", backward: "imported by" },
+ exports: { forward: "exports to", backward: "exported by" },
+ contains: { forward: "contains", backward: "contained in" },
+ inherits: { forward: "inherits from", backward: "inherited by" },
+ implements: { forward: "implements", backward: "implemented by" },
+ calls: { forward: "calls", backward: "called by" },
+ subscribes: { forward: "subscribes to", backward: "subscribed by" },
+ publishes: { forward: "publishes to", backward: "consumed by" },
+ middleware: { forward: "middleware for", backward: "uses middleware" },
+ reads_from: { forward: "reads from", backward: "read by" },
+ writes_to: { forward: "writes to", backward: "written by" },
+ transforms: { forward: "transforms", backward: "transformed by" },
+ validates: { forward: "validates", backward: "validated by" },
+ depends_on: { forward: "depends on", backward: "depended on by" },
+ tested_by: { forward: "tested by", backward: "tests" },
+ configures: { forward: "configures", backward: "configured by" },
+ related: { forward: "related to", backward: "related to" },
+ similar_to: { forward: "similar to", backward: "similar to" },
+ deploys: { forward: "deploys", backward: "deployed by" },
+ serves: { forward: "serves", backward: "served by" },
+ migrates: { forward: "migrates", backward: "migrated by" },
+ documents: { forward: "documents", backward: "documented by" },
+ provisions: { forward: "provisions", backward: "provisioned by" },
+ routes: { forward: "routes to", backward: "routed from" },
+ defines_schema: { forward: "defines schema for", backward: "schema defined by" },
+ triggers: { forward: "triggers", backward: "triggered by" },
+};
+
+/**
+ * Returns a human-readable directional label for an edge type.
+ * Falls back to formatted type name for unknown edge types.
*/
function getDirectionalLabel(edgeType: string, isSource: boolean): string {
- switch (edgeType) {
- case "imports":
- return isSource ? "imports" : "imported by";
- case "exports":
- return isSource ? "exports to" : "exported by";
- case "contains":
- return isSource ? "contains" : "contained in";
- case "inherits":
- return isSource ? "inherits from" : "inherited by";
- case "implements":
- return isSource ? "implements" : "implemented by";
- case "calls":
- return isSource ? "calls" : "called by";
- case "subscribes":
- return isSource ? "subscribes to" : "subscribed by";
- case "publishes":
- return isSource ? "publishes to" : "consumed by";
- case "middleware":
- return isSource ? "middleware for" : "uses middleware";
- case "reads_from":
- return isSource ? "reads from" : "read by";
- case "writes_to":
- return isSource ? "writes to" : "written by";
- case "transforms":
- return isSource ? "transforms" : "transformed by";
- case "validates":
- return isSource ? "validates" : "validated by";
- case "depends_on":
- return isSource ? "depends on" : "depended on by";
- case "tested_by":
- return isSource ? "tested by" : "tests";
- case "configures":
- return isSource ? "configures" : "configured by";
- case "related":
- return "related to";
- case "similar_to":
- return "similar to";
- case "deploys":
- return isSource ? "deploys" : "deployed by";
- case "serves":
- return isSource ? "serves" : "served by";
- case "migrates":
- return isSource ? "migrates" : "migrated by";
- case "documents":
- return isSource ? "documents" : "documented by";
- case "provisions":
- return isSource ? "provisions" : "provisioned by";
- case "routes":
- return isSource ? "routes to" : "routed from";
- case "defines_schema":
- return isSource ? "defines schema for" : "schema defined by";
- case "triggers":
- return isSource ? "triggers" : "triggered by";
- default:
- return isSource ? edgeType : `${edgeType} (reverse)`;
+ const labels = (EDGE_LABELS as Record<string, { forward: string; backward: string }>)[edgeType];
+ if (!labels) {
+ // Fallback for unknown edge types
+ const formatted = edgeType.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
+ return isSource ? formatted : `${formatted} (reverse)`;
}
+ return isSource ? labels.forward : labels.backward;
}
export default function NodeInfo() {
@@ -132,10 +117,15 @@ export default function NodeInfo() {
.map((e) => graph?.nodes.find((n) => n.id === e.target))
.filter(Boolean);
- const typeBadge = typeBadgeColors[node.type] ?? typeBadgeColors.file;
+ const knownType = node.type as NodeType;
+ const typeBadge = typeBadgeColors[knownType] ?? typeBadgeColors.file;
const complexityBadge =
complexityBadgeColors[node.complexity] ?? complexityBadgeColors.simple;
+ if (import.meta.env.DEV && !(knownType in typeBadgeColors)) {
+ console.warn(`[NodeInfo] Unknown node type "${node.type}" — using "file" badge colors`);
+ }
+
return (
<div className="h-full w-full overflow-auto p-5 animate-fade-slide-in">
{/* Navigation history trail */}
@@ -269,7 +259,7 @@ export default function NodeInfo() {
<div className="space-y-1">
{childNodes.map((child) => {
if (!child) return null;
- const childTypeBadge = typeBadgeColors[child.type] ?? typeBadgeColors.file;
+ const childTypeBadge = typeBadgeColors[child.type as NodeType] ?? typeBadgeColors.file;
const childComplexity = complexityBadgeColors[child.complexity] ?? complexityBadgeColors.simple;
return (
<div
diff --git a/understand-anything-plugin/packages/dashboard/src/store.ts b/understand-anything-plugin/packages/dashboard/src/store.ts
index ab87c4ec..61f310fe 100644
--- a/understand-anything-plugin/packages/dashboard/src/store.ts
+++ b/understand-anything-plugin/packages/dashboard/src/store.ts
@@ -9,6 +9,8 @@ import type {
export type Persona = "non-technical" | "junior" | "experienced";
export type NavigationLevel = "overview" | "layer-detail";
+/** Categories used for node type filter toggles. Single source of truth for NodeCategory. */
+export type NodeCategory = "code" | "config" | "docs" | "infra" | "data";
/** Find which layer a node belongs to. Returns layerId or null. */
function findNodeLayer(graph: KnowledgeGraph, nodeId: string): string | null {
@@ -54,8 +56,8 @@ interface DashboardStore {
nodeHistory: string[];
// Node type category filters
- nodeTypeFilters: Record<string, boolean>;
- toggleNodeTypeFilter: (category: string) => void;
+ nodeTypeFilters: Record<NodeCategory, boolean>;
+ toggleNodeTypeFilter: (category: NodeCategory) => void;
setGraph: (graph: KnowledgeGraph) => void;
selectNode: (nodeId: string | null) => void;
diff --git a/understand-anything-plugin/skills/understand/languages/css.md b/understand-anything-plugin/skills/understand/languages/css.md
index 5b10d5d6..7bdb8f90 100644
--- a/understand-anything-plugin/skills/understand/languages/css.md
+++ b/understand-anything-plugin/skills/understand/languages/css.md
@@ -25,9 +25,9 @@
## Edge Patterns
-- CSS files `configures` the visual appearance of HTML or component files that import them
+- CSS files are `related` to the HTML or component files that import them for styling
- SCSS partial files (`_*.scss`) are `depends_on` by the main stylesheet that `@use`s them
-- CSS variable definition files `configures` all stylesheets that reference those variables
+- CSS variable definition files are `related` to all stylesheets that reference those variables
- CSS Modules are `related` to the component files that import them
## Summary Style
diff --git a/understand-anything-plugin/skills/understand/languages/shell.md b/understand-anything-plugin/skills/understand/languages/shell.md
index c5aa8512..3829b602 100644
--- a/understand-anything-plugin/skills/understand/languages/shell.md
+++ b/understand-anything-plugin/skills/understand/languages/shell.md
@@ -20,7 +20,6 @@
- `entrypoint.sh` — Docker container entry point script
- `install.sh` / `setup.sh` — Environment setup scripts
- `.bashrc` / `.bash_profile` / `.zshrc` — Shell configuration files
-- `Makefile` — Build automation with Make (though technically its own language)
## Edge Patterns
diff --git a/understand-anything-plugin/skills/understand/project-scanner-prompt.md b/understand-anything-plugin/skills/understand/project-scanner-prompt.md
index 0a0f2648..cf16df84 100644
--- a/understand-anything-plugin/skills/understand/project-scanner-prompt.md
+++ b/understand-anything-plugin/skills/understand/project-scanner-prompt.md
@@ -88,7 +88,7 @@ Map file extensions to language identifiers:
| `.cfg`, `.ini`, `.env` | `config` |
| `Dockerfile` (no extension) | `dockerfile` |
| `Makefile` (no extension) | `makefile` |
-| `Jenkinsfile` (no extension) | `groovy` |
+| `Jenkinsfile` (no extension) | `jenkinsfile` |
Collect unique languages, sorted alphabetically.