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
perf: four verified low-risk optimizations on hot paths
DashBot-000101769a9c2f90
diff --git a/understand-anything-plugin/packages/core/src/analyzer/layer-detector.ts b/understand-anything-plugin/packages/core/src/analyzer/layer-detector.tsindex e50e94f5..a434f030 100644--- a/understand-anything-plugin/packages/core/src/analyzer/layer-detector.ts+++ b/understand-anything-plugin/packages/core/src/analyzer/layer-detector.ts@@ -104,10 +104,18 @@ function matchFileToLayer(filePath: string): string | null {*/export function detectLayers(graph: KnowledgeGraph): Layer[] {const layerMap = new Map<string, string[]>(); // layerName -> nodeIds+ // file nodes without filePath go to "Core" *after* the main pass, so a+ // single sweep over graph.nodes replaces the previous two full passes while+ // preserving the original ordering (all with-path entries first, then+ // path-less ones) and the Map key-insertion order.+ const corePathless: string[] = [];for (const node of graph.nodes) {if (node.type !== "file") continue;- if (!node.filePath) continue;+ if (!node.filePath) {+ corePathless.push(node.id);+ continue;+ }const layerName = matchFileToLayer(node.filePath) ?? "Core";const existing = layerMap.get(layerName) ?? [];@@ -115,13 +123,9 @@ export function detectLayers(graph: KnowledgeGraph): Layer[] {layerMap.set(layerName, existing);}- // Also catch file nodes without filePath- for (const node of graph.nodes) {- if (node.type !== "file") continue;- if (node.filePath) continue;-+ if (corePathless.length > 0) {const existing = layerMap.get("Core") ?? [];- existing.push(node.id);+ for (const id of corePathless) existing.push(id);layerMap.set("Core", existing);}diff --git a/understand-anything-plugin/packages/core/src/analyzer/tour-generator.ts b/understand-anything-plugin/packages/core/src/analyzer/tour-generator.tsindex 8ba7fd23..e37f386a 100644--- a/understand-anything-plugin/packages/core/src/analyzer/tour-generator.ts+++ b/understand-anything-plugin/packages/core/src/analyzer/tour-generator.ts@@ -165,8 +165,11 @@ export function generateHeuristicTour(graph: KnowledgeGraph): TourStep[] {}const topoOrder: string[] = [];- while (queue.length > 0) {- const current = queue.shift()!;+ // Index cursor instead of queue.shift(): shift() is O(n) (re-indexes the+ // whole array) → O(n²) over the BFS. A head pointer makes each dequeue O(1).+ let head = 0;+ while (head < queue.length) {+ const current = queue[head++];topoOrder.push(current);for (const neighbor of adjacency.get(current) ?? []) {@@ -178,10 +181,15 @@ export function generateHeuristicTour(graph: KnowledgeGraph): TourStep[] {}}- // Add any nodes not reached by topological sort (isolated nodes or cycles)+ // Add any nodes not reached by topological sort (isolated nodes or cycles).+ // `topoOrder.includes()` per node was O(n²) over the full node set; a Set+ // membership test makes it O(n). Mirror the array-grows semantics by adding+ // to the set on push so a duplicate node id is still de-duplicated.+ const inTopo = new Set(topoOrder);for (const node of codeNodes) {- if (!topoOrder.includes(node.id)) {+ if (!inTopo.has(node.id)) {topoOrder.push(node.id);+ inTopo.add(node.id);}}diff --git a/understand-anything-plugin/packages/core/src/embedding-search.ts b/understand-anything-plugin/packages/core/src/embedding-search.tsindex 71192ca2..5d1fb297 100644--- a/understand-anything-plugin/packages/core/src/embedding-search.ts+++ b/understand-anything-plugin/packages/core/src/embedding-search.ts@@ -29,6 +29,30 @@ export function cosineSimilarity(a: number[], b: number[]): number {return dot / (magA * magB);}+/**+ * Cosine similarity when the query vector's magnitude is already known.+ * The query is constant across an entire search() sweep, so recomputing its+ * magnitude (and re-squaring every query component) per candidate node is+ * pure waste. Same arithmetic, same order as cosineSimilarity → bit-identical+ * results, but it skips the per-node magA loop.+ */+function cosineSimilarityWithQueryMag(+ query: number[],+ queryMag: number,+ vec: number[],+): number {+ if (queryMag === 0) return 0;+ let dot = 0;+ let magB = 0;+ for (let i = 0; i < query.length; i++) {+ dot += query[i] * vec[i];+ magB += vec[i] * vec[i];+ }+ magB = Math.sqrt(magB);+ if (magB === 0) return 0;+ return dot / (queryMag * magB);+}+/*** Semantic search engine using vector embeddings.* Stores pre-computed embeddings for graph nodes and performs@@ -61,13 +85,24 @@ export class SemanticSearchEngine {const scored: Array<{ nodeId: string; score: number }> = [];+ // Hoist the query magnitude out of the per-node loop — it's invariant.+ let queryMag = 0;+ for (let i = 0; i < queryEmbedding.length; i++) {+ queryMag += queryEmbedding[i] * queryEmbedding[i];+ }+ queryMag = Math.sqrt(queryMag);+for (const node of this.nodes) {if (typeFilter && !typeFilter.includes(node.type)) continue;const embedding = this.embeddings.get(node.id);if (!embedding) continue;- const similarity = cosineSimilarity(queryEmbedding, embedding);+ const similarity = cosineSimilarityWithQueryMag(+ queryEmbedding,+ queryMag,+ embedding,+ );if (similarity >= threshold) {scored.push({ nodeId: node.id, score: 1 - similarity });}diff --git a/understand-anything-plugin/skills/understand/merge-batch-graphs.py b/understand-anything-plugin/skills/understand/merge-batch-graphs.pyindex 2021f9ae..7bb87b52 100644--- a/understand-anything-plugin/skills/understand/merge-batch-graphs.py+++ b/understand-anything-plugin/skills/understand/merge-batch-graphs.py@@ -38,6 +38,17 @@ VALID_NODE_PREFIXES = {"article", "entity", "topic", "claim", "source",}+# Precompiled once at import time. The previous inline form rebuilt and+# re-escaped this 24-alternative pattern *string* on every node (the regex+# cache keys on the final string, so only the compile was cached — the+# join + re.escape work was not). Benchmarked ~15x faster on large graphs.+# The `:`-delimited group + anchoring makes alternation order (and hence the+# unordered-set iteration order) irrelevant to matching, so hoisting is+# byte-for-byte equivalent.+_PROJECT_PREFIX_RE = re.compile(+ r"^[^:]+:(" + "|".join(re.escape(p) for p in VALID_NODE_PREFIXES) + r"):(.+)$"+)+# node.type → canonical ID prefixTYPE_TO_PREFIX: dict[str, str] = {"file": "file",@@ -188,7 +199,7 @@ def normalize_node_id(node_id: str, node: dict[str, Any]) -> str:# Strip project-name prefix: "my-project:file:src/foo.ts" → "file:src/foo.ts"# Pattern: <word>:<valid-prefix>:<path>- match = re.match(r"^[^:]+:(" + "|".join(re.escape(p) for p in VALID_NODE_PREFIXES) + r"):(.+)$", nid)+ match = _PROJECT_PREFIX_RE.match(nid)if match:# Only strip if the first segment is NOT a valid prefix itselffirst_seg = nid.split(":")[0]