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(core): add staleness detection and incremental graph merging
Lum110419357d25a333
diff --git a/packages/core/src/__tests__/staleness.test.ts b/packages/core/src/__tests__/staleness.test.tsnew file mode 100644index 00000000..4a63d727--- /dev/null+++ b/packages/core/src/__tests__/staleness.test.ts@@ -0,0 +1,252 @@+import { describe, it, expect, vi, beforeEach } from "vitest";+import type { KnowledgeGraph, GraphNode, GraphEdge } from "../types.js";++vi.mock("child_process", () => ({+ execSync: vi.fn(),+}));++// Import after mocking+import { execSync } from "child_process";+import { getChangedFiles, isStale, mergeGraphUpdate } from "../staleness.js";++const mockedExecSync = vi.mocked(execSync);++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", () => {+ mockedExecSync.mockReturnValue("src/index.ts\nsrc/utils.ts\n");++ const result = getChangedFiles("/project", "abc123");++ expect(result).toEqual(["src/index.ts", "src/utils.ts"]);+ expect(mockedExecSync).toHaveBeenCalledWith(+ "git diff abc123..HEAD --name-only",+ { cwd: "/project", encoding: "utf-8" },+ );+ });++ it("returns empty array when no changes", () => {+ mockedExecSync.mockReturnValue("");++ const result = getChangedFiles("/project", "abc123");++ expect(result).toEqual([]);+ });++ it("returns empty array on git error", () => {+ mockedExecSync.mockImplementation(() => {+ throw new Error("fatal: bad revision");+ });++ const result = getChangedFiles("/project", "abc123");++ expect(result).toEqual([]);+ });+});++describe("isStale", () => {+ it("returns stale when files have changed", () => {+ mockedExecSync.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", () => {+ mockedExecSync.mockReturnValue("");++ const result = isStale("/project", "abc123");++ expect(result).toEqual({+ stale: false,+ changedFiles: [],+ });+ });+});++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 remain+ expect(+ result.edges.find(+ (e) => e.source === "file-c" && e.target === "file-a",+ ),+ ).toBeDefined();++ // 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/packages/core/src/index.ts b/packages/core/src/index.tsindex 6187b44a..d7e2a052 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -11,3 +11,9 @@ export {} from "./analyzer/llm-analyzer.js";export type { LLMFileAnalysis, LLMProjectSummary } from "./analyzer/llm-analyzer.js";export { SearchEngine, type SearchResult, type SearchOptions } from "./search.js";+export {+ getChangedFiles,+ isStale,+ mergeGraphUpdate,+ type StalenessResult,+} from "./staleness.js";diff --git a/packages/core/src/staleness.ts b/packages/core/src/staleness.tsnew file mode 100644index 00000000..780f42cd--- /dev/null+++ b/packages/core/src/staleness.ts@@ -0,0 +1,90 @@+import { execSync } from "child_process";+import type { KnowledgeGraph, GraphNode, GraphEdge } from "./types.js";++export interface StalenessResult {+ stale: boolean;+ changedFiles: string[];+}++/**+ * 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[] {+ try {+ const output = execSync(`git diff ${lastCommitHash}..HEAD --name-only`, {+ cwd: projectDir,+ encoding: "utf-8",+ });+ return output+ .split("\n")+ .map((line) => line.trim())+ .filter((line) => line.length > 0);+ } catch {+ return [];+ }+}++/**+ * 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,+ };+}++/**+ * 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 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 node is not in the removed set+ const retainedEdges = existingGraph.edges.filter(+ (edge) => !removedNodeIds.has(edge.source),+ );++ return {+ ...existingGraph,+ project: {+ ...existingGraph.project,+ gitCommitHash: newCommitHash,+ analyzedAt: new Date().toISOString(),+ },+ nodes: [...retainedNodes, ...newNodes],+ edges: [...retainedEdges, ...newEdges],+ };+}