Persistent project knowledge graph for coding agents. MCP server with semantic search, in-process embeddings, and web explorer.
TypeScript agentic-codingaiai-agentsclaude-codecode-contextcoding-agentembeddingsknowledge-graphllmmcpmcp-serveropencodepersistent-memorysqlitetypescript
Add merge conflict tooling and AI resolution flow
0xk3vin33140b02adcd
diff --git a/README.md b/README.mdindex d577fce..291e021 100644--- a/README.md+++ b/README.md@@ -84,6 +84,8 @@ Add megamemory as a stdio MCP server. The command is just `megamemory` (no argum| `link` | Create a typed relationship between two concepts. || `remove_concept` | Soft-delete a concept with a reason. History preserved. || `list_roots` | List all top-level concepts with direct children. |+| `list_conflicts` | List unresolved merge conflicts grouped by merge group. |+| `resolve_conflict` | Resolve a merge conflict by providing verified, correct content based on the current codebase. |**Concept kinds:** `feature` · `module` · `pattern` · `config` · `decision` · `component`@@ -118,19 +120,69 @@ megamemory serve --port 8080 # custom port| `megamemory` | Start the MCP stdio server || `megamemory init` | Configure opencode integration || `megamemory serve` | Launch the web graph explorer |+| `megamemory merge` | Merge two knowledge.db files |+| `megamemory conflicts` | List unresolved merge conflicts |+| `megamemory resolve` | Resolve a merge conflict || `megamemory --help` | Show help || `megamemory --version` | Show version |---+### Merging Knowledge Graphs++When multiple git branches diverge, each may modify `.megamemory/knowledge.db` independently. Since SQLite files can't be auto-merged by git, megamemory provides a dedicated merge system.++#### Merge two databases++```bash+megamemory merge main.db feature.db --into merged.db+```++The merge compares concepts by ID. Identical concepts are deduplicated. Concepts with the same ID but different content are flagged as conflicts — both versions are kept with `::left`/`::right` suffixed IDs and a shared merge group UUID. Use `--left-label` and `--right-label` to tag versions with branch names instead of the defaults.++```bash+megamemory merge main.db feature.db --into merged.db --left-label main --right-label feature-xyz+```++#### View conflicts++```bash+megamemory conflicts # human-readable summary+megamemory conflicts --json # machine-readable output+megamemory conflicts --db path # specify database path+```++#### Resolve conflicts manually++```bash+megamemory resolve <merge-group-uuid> --keep left # keep the left version+megamemory resolve <merge-group-uuid> --keep right # keep the right version+megamemory resolve <merge-group-uuid> --keep both # keep both as separate concepts+```++#### AI-assisted resolution++When an AI agent runs `/merge`, it:++1. Calls `list_conflicts` to get all unresolved conflict groups+2. For each conflict, reads both versions and the actual source files referenced in `file_refs`+3. Verifies what the code actually does now and writes the correct resolved content+4. Calls `resolve_conflict` with `resolved: {summary, why?, file_refs?}` and a `reason` explaining what was verified++The agent does NOT just pick a side — it reads the code and writes the truth. The `resolved` object provides the correct summary, rationale, and file references based on the current codebase state.++---+### How It Works```src/- index.ts CLI entry + MCP server- tools.ts Tool handlers (understand, create, update, link, remove)- db.ts SQLite persistence (libsql, WAL mode)+ index.ts CLI entry + MCP server (8 tools)+ tools.ts Tool handlers (understand, create, update, link, remove, list_conflicts, resolve_conflict)+ db.ts SQLite persistence (libsql, WAL mode, schema v2)embeddings.ts In-process embeddings (all-MiniLM-L6-v2, 384 dims)+ merge.ts Two-way merge engine for knowledge.db files+ merge-cli.ts CLI handlers for merge, conflicts, resolve commandstypes.ts TypeScript typescli-utils.ts Colored output + interactive promptsinit.ts opencode setup wizard@@ -145,8 +197,9 @@ web/```- **Embeddings** — In-process via [Xenova/all-MiniLM-L6-v2](https://huggingface.co/Xenova/all-MiniLM-L6-v2) (ONNX, quantized). No API keys. No network calls after first model download.-- **Storage** — SQLite with WAL mode, soft-delete with history, schema migrations.+- **Storage** — SQLite with WAL mode, soft-delete with history, schema migrations (currently v2).- **Search** — Brute-force cosine similarity over all node embeddings. Fast enough for knowledge graphs with <10k nodes.+- **Merge** — Two-way merge with conflict detection. Concepts compared by ID; conflicts get suffixed IDs and shared merge group UUIDs. AI-assisted resolution via MCP tools.---diff --git a/package-lock.json b/package-lock.jsonindex 5c2a069..d41c346 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,12 +1,12 @@{"name": "megamemory",- "version": "1.1.2",+ "version": "1.2.0","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "megamemory",- "version": "1.1.2",+ "version": "1.2.0","license": "MIT","dependencies": {"@modelcontextprotocol/sdk": "^1.12.1",diff --git a/package.json b/package.jsonindex 068da06..a89fd1d 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "megamemory",- "version": "1.1.2",+ "version": "1.2.0","description": "MCP server that gives coding agents persistent project understanding via a knowledge graph","type": "module","main": "dist/index.js",diff --git a/plugin/megamemory.ts b/plugin/megamemory.tsindex b508cae..29b66ee 100644--- a/plugin/megamemory.ts+++ b/plugin/megamemory.ts@@ -47,15 +47,17 @@ Your persistent memory of the codebase. You write concepts as you work. You quer| \`megamemory:link\` | After tasks | Create relationship between two concepts || \`megamemory:remove_concept\` | On refactor/delete | Soft-delete with reason (history preserved) || \`megamemory:list_roots\` | Session start | All top-level concepts with children + stats |+| \`megamemory:list_conflicts\` | After merge | Lists unresolved merge conflicts grouped by merge_group |+| \`megamemory:resolve_conflict\` | During /merge | Resolve a conflict by providing verified, correct content |`;export default tool({description: SKILL,args: {action: tool.schema- .enum(["query", "record", "overview"])+ .enum(["query", "record", "overview", "merge"]).describe(- "Workflow action: query (before task — understand context), record (after task — create/update/link), overview (session start — list roots)",+ "Workflow action: query (before task — understand context), record (after task — create/update/link), overview (session start — list roots), merge (resolve merge conflicts)",),query: tool.schema.string()@@ -118,8 +120,27 @@ Use the returned context instead of re-reading source files when possible. If no- id: concept to remove- reason: why it was removed${concepts ? `\n\nContext about what to record: "${concepts}"` : ""}`;+ case "merge":+ return `To resolve merge conflicts in the knowledge graph:++1. **List conflicts** → megamemory:list_conflicts+ - Returns all unresolved conflicts grouped by merge_group+ - Each group has competing versions with summaries, file_refs, edges++2. **For each conflict:**+ a. Read both versions' summaries, file_refs, and edges+ b. Read the actual source files referenced in file_refs to determine what the code ACTUALLY does now+ c. Write the correct resolved content based on the current codebase — do NOT just pick a side++3. **Resolve** → megamemory:resolve_conflict+ - merge_group: the UUID of the conflict+ - resolved: {summary, why?, file_refs?} — the verified, correct content+ - reason: what you verified and why this resolution is correct++The goal is accuracy: the resolved concept should describe the code as it actually exists. If referenced files no longer exist, the concept may be outdated — update or remove accordingly.`;+default:- return `Unknown action: ${action}. Use: overview (session start), query (before task), record (after task).`;+ return `Unknown action: ${action}. Use: overview (session start), query (before task), record (after task), merge (resolve conflicts).`;}},});diff --git a/src/__tests__/conflicts.test.ts b/src/__tests__/conflicts.test.tsnew file mode 100644index 0000000..243beff--- /dev/null+++ b/src/__tests__/conflicts.test.ts@@ -0,0 +1,214 @@+import { describe, it, expect, beforeEach, afterEach } from "vitest";+import { KnowledgeDB } from "../db.js";+import { MergeEngine } from "../merge.js";+import { listConflicts, resolveConflict } from "../tools.js";+import fs from "fs";+import path from "path";+import os from "os";++let tmpDir: string;++function createTmpDb(name: string): { db: KnowledgeDB; path: string } {+ const dbPath = path.join(tmpDir, name);+ const db = new KnowledgeDB(dbPath);+ return { db, path: dbPath };+}++function insertTestNode(+ db: KnowledgeDB,+ id: string,+ overrides: Partial<{+ name: string;+ kind: string;+ summary: string;+ why: string | null;+ file_refs: string[] | null;+ parent_id: string | null;+ }> = {}+): void {+ db.insertNode({+ id,+ name: overrides.name ?? id,+ kind: overrides.kind ?? "feature",+ summary: overrides.summary ?? `Summary for ${id}`,+ why: overrides.why ?? null,+ file_refs: overrides.file_refs ?? null,+ parent_id: overrides.parent_id ?? null,+ created_by_task: null,+ embedding: null,+ });+}++beforeEach(() => {+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "megamemory-conflicts-test-"));+});++afterEach(() => {+ fs.rmSync(tmpDir, { recursive: true, force: true });+});++describe("listConflicts tool", () => {+ it("returns empty array when no conflicts exist", () => {+ const { db } = createTmpDb("clean.db");+ insertTestNode(db, "normal-node");++ const result = listConflicts(db);+ expect(result.conflicts).toEqual([]);++ db.close();+ });++ it("groups conflicts by merge_group", () => {+ const left = createTmpDb("left.db");+ const right = createTmpDb("right.db");+ const outputPath = path.join(tmpDir, "output.db");++ // Create two separate conflicts+ insertTestNode(left.db, "concept-a", { summary: "Left A" });+ insertTestNode(right.db, "concept-a", { summary: "Right A" });++ insertTestNode(left.db, "concept-b", { summary: "Left B" });+ insertTestNode(right.db, "concept-b", { summary: "Right B" });++ left.db.close();+ right.db.close();++ const engine = new MergeEngine();+ engine.merge(left.path, right.path, outputPath, {+ leftLabel: "main",+ rightLabel: "feature",+ });++ const output = new KnowledgeDB(outputPath);+ const result = listConflicts(output);++ expect(result.conflicts).toHaveLength(2);++ for (const conflict of result.conflicts) {+ expect(conflict.merge_group).toBeDefined();+ expect(conflict.versions).toHaveLength(2);++ const branches = conflict.versions.map(v => v.source_branch).sort();+ expect(branches).toEqual(["feature", "main"]);+ }++ output.close();+ });++ it("includes full version data in conflict groups", () => {+ const left = createTmpDb("left.db");+ const right = createTmpDb("right.db");+ const outputPath = path.join(tmpDir, "output.db");++ insertTestNode(left.db, "my-feature", {+ name: "My Feature",+ summary: "Left implementation",+ why: "Left reason",+ file_refs: ["src/left.ts"],+ });++ insertTestNode(right.db, "my-feature", {+ name: "My Feature",+ summary: "Right implementation",+ why: "Right reason",+ file_refs: ["src/right.ts"],+ });++ left.db.close();+ right.db.close();++ const engine = new MergeEngine();+ engine.merge(left.path, right.path, outputPath);++ const output = new KnowledgeDB(outputPath);+ const result = listConflicts(output);++ expect(result.conflicts).toHaveLength(1);+ const group = result.conflicts[0];++ const leftVersion = group.versions.find(v => v.source_branch === "left")!;+ const rightVersion = group.versions.find(v => v.source_branch === "right")!;++ expect(leftVersion.summary).toBe("Left implementation");+ expect(leftVersion.why).toBe("Left reason");+ expect(leftVersion.file_refs).toEqual(["src/left.ts"]);+ expect(leftVersion.original_id).toBe("my-feature");++ expect(rightVersion.summary).toBe("Right implementation");+ expect(rightVersion.why).toBe("Right reason");+ expect(rightVersion.file_refs).toEqual(["src/right.ts"]);+ expect(rightVersion.original_id).toBe("my-feature");++ output.close();+ });++ it("returns empty after all conflicts are resolved", () => {+ const left = createTmpDb("left.db");+ const right = createTmpDb("right.db");+ const outputPath = path.join(tmpDir, "output.db");++ insertTestNode(left.db, "feature", { summary: "Left" });+ insertTestNode(right.db, "feature", { summary: "Right" });++ left.db.close();+ right.db.close();++ const engine = new MergeEngine();+ const mergeResult = engine.merge(left.path, right.path, outputPath);+ const mergeGroup = mergeResult.mergeGroups[0];++ const output = new KnowledgeDB(outputPath);++ // Verify conflict exists+ expect(listConflicts(output).conflicts).toHaveLength(1);++ // Resolve: keep left+ output.hardDeleteNode("feature::right");+ output.renameNodeId("feature::left", "feature");+ output.clearNodeMergeFlags("feature");+ output.clearEdgeMergeFlagsByGroup(mergeGroup);++ // Verify no more conflicts+ expect(listConflicts(output).conflicts).toHaveLength(0);++ output.close();+ });++ it("resolveConflict prefers active version for removal conflicts", async () => {+ const left = createTmpDb("left.db");+ const right = createTmpDb("right.db");+ const outputPath = path.join(tmpDir, "output.db");++ insertTestNode(left.db, "feature", { summary: "Legacy behavior" });+ left.db.softDeleteNode("feature", "Removed on left");++ insertTestNode(right.db, "feature", { summary: "Current behavior" });++ left.db.close();+ right.db.close();++ const engine = new MergeEngine();+ const mergeResult = engine.merge(left.path, right.path, outputPath);+ const mergeGroup = mergeResult.mergeGroups[0];++ const output = new KnowledgeDB(outputPath);+ expect(listConflicts(output).conflicts).toHaveLength(1);++ await resolveConflict(output, {+ merge_group: mergeGroup,+ resolved: {+ summary: "Resolved behavior from current code",+ file_refs: ["src/feature.ts"],+ },+ reason: "Verified source implementation and kept active version",+ });++ const resolved = output.getNode("feature");+ expect(resolved).toBeDefined();+ expect(resolved!.removed_at).toBeNull();+ expect(resolved!.summary).toBe("Resolved behavior from current code");+ expect(listConflicts(output).conflicts).toHaveLength(0);++ output.close();+ });+});diff --git a/src/__tests__/db.test.ts b/src/__tests__/db.test.tsindex fa27ff3..a05dcc8 100644--- a/src/__tests__/db.test.ts+++ b/src/__tests__/db.test.ts@@ -274,6 +274,148 @@ describe("KnowledgeDB", () => {});});+ describe("schema v2 - merge columns", () => {+ it("has merge columns on fresh database", () => {+ // Insert a node with merge fields via insertNodeRaw+ db.insertNodeRaw({+ id: "merge-test",+ name: "Merge Test",+ kind: "feature",+ summary: "Testing merge columns",+ merge_group: "test-uuid",+ needs_merge: 1,+ source_branch: "main",+ merge_timestamp: "2024-01-01 00:00:00",+ });++ const node = db.getAllNodesRaw().find(n => n.id === "merge-test");+ expect(node).toBeDefined();+ expect(node!.merge_group).toBe("test-uuid");+ expect(node!.needs_merge).toBe(1);+ expect(node!.source_branch).toBe("main");+ expect(node!.merge_timestamp).toBe("2024-01-01 00:00:00");+ });++ it("has merge columns on edges", () => {+ db.insertNode({+ id: "from-node", name: "From", kind: "feature", summary: "s",+ why: null, file_refs: null, parent_id: null, created_by_task: null, embedding: null,+ });+ db.insertNode({+ id: "to-node", name: "To", kind: "feature", summary: "s",+ why: null, file_refs: null, parent_id: null, created_by_task: null, embedding: null,+ });++ db.insertEdgeRaw({+ from_id: "from-node",+ to_id: "to-node",+ relation: "calls",+ merge_group: "edge-uuid",+ needs_merge: 1,+ source_branch: "feature",+ merge_timestamp: "2024-06-01 12:00:00",+ });++ const edges = db.getAllEdgesRaw();+ const mergeEdge = edges.find(e => e.merge_group === "edge-uuid");+ expect(mergeEdge).toBeDefined();+ expect(mergeEdge!.needs_merge).toBe(1);+ expect(mergeEdge!.source_branch).toBe("feature");+ });+ });++ describe("merge query methods", () => {+ it("getConflictNodes returns only nodes with needs_merge=1", () => {+ db.insertNodeRaw({+ id: "clean", name: "Clean", kind: "feature", summary: "clean",+ });+ db.insertNodeRaw({+ id: "conflict", name: "Conflict", kind: "feature", summary: "conflict",+ merge_group: "uuid-1", needs_merge: 1, source_branch: "left",+ });++ const conflicts = db.getConflictNodes();+ expect(conflicts).toHaveLength(1);+ expect(conflicts[0].id).toBe("conflict");+ });++ it("getNodesByMergeGroup returns nodes sharing a merge_group", () => {+ db.insertNodeRaw({+ id: "a::left", name: "A", kind: "feature", summary: "left",+ merge_group: "group-1", needs_merge: 1, source_branch: "left",+ });+ db.insertNodeRaw({+ id: "a::right", name: "A", kind: "feature", summary: "right",+ merge_group: "group-1", needs_merge: 1, source_branch: "right",+ });+ db.insertNodeRaw({+ id: "other", name: "Other", kind: "feature", summary: "other",+ merge_group: "group-2", needs_merge: 1, source_branch: "left",+ });++ const group1 = db.getNodesByMergeGroup("group-1");+ expect(group1).toHaveLength(2);+ expect(group1.map(n => n.id).sort()).toEqual(["a::left", "a::right"]);+ });++ it("clearNodeMergeFlags resets merge fields to null/0", () => {+ db.insertNodeRaw({+ id: "flagged", name: "Flagged", kind: "feature", summary: "s",+ merge_group: "uuid", needs_merge: 1, source_branch: "main",+ merge_timestamp: "2024-01-01",+ });++ db.clearNodeMergeFlags("flagged");+ const node = db.getAllNodesRaw().find(n => n.id === "flagged")!;+ expect(node.merge_group).toBeNull();+ expect(node.needs_merge).toBe(0);+ expect(node.source_branch).toBeNull();+ expect(node.merge_timestamp).toBeNull();+ });++ it("renameNodeId updates id and all references", () => {+ db.insertNode({+ id: "old-id", name: "Node", kind: "feature", summary: "s",+ why: null, file_refs: null, parent_id: null, created_by_task: null, embedding: null,+ });+ db.insertNode({+ id: "target", name: "Target", kind: "feature", summary: "s",+ why: null, file_refs: null, parent_id: null, created_by_task: null, embedding: null,+ });+ db.insertEdge({ from_id: "old-id", to_id: "target", relation: "calls", description: null });++ const renamed = db.renameNodeId("old-id", "new-id");+ expect(renamed).toBe(true);++ expect(db.getNode("old-id")).toBeUndefined();+ expect(db.getNode("new-id")).toBeDefined();++ // Edge should reference new-id+ const edges = db.getOutgoingEdges("new-id");+ expect(edges).toHaveLength(1);+ expect(edges[0].from_id).toBe("new-id");+ });++ it("hardDeleteNode removes node and its edges permanently", () => {+ db.insertNode({+ id: "to-hard-delete", name: "Del", kind: "feature", summary: "s",+ why: null, file_refs: null, parent_id: null, created_by_task: null, embedding: null,+ });+ db.insertNode({+ id: "other", name: "Other", kind: "feature", summary: "s",+ why: null, file_refs: null, parent_id: null, created_by_task: null, embedding: null,+ });+ db.insertEdge({ from_id: "to-hard-delete", to_id: "other", relation: "calls", description: null });++ db.hardDeleteNode("to-hard-delete");++ // Completely gone, not even in raw query+ const all = db.getAllNodesRaw();+ expect(all.find(n => n.id === "to-hard-delete")).toBeUndefined();+ expect(db.getAllEdgesRaw()).toHaveLength(0);+ });+ });+describe("stats", () => {it("returns correct counts", () => {db.insertNode({diff --git a/src/__tests__/merge.test.ts b/src/__tests__/merge.test.tsnew file mode 100644index 0000000..c6d923d--- /dev/null+++ b/src/__tests__/merge.test.ts@@ -0,0 +1,707 @@+import { describe, it, expect, beforeEach, afterEach } from "vitest";+import { KnowledgeDB } from "../db.js";+import {+ MergeEngine,+ nodesAreIdentical,+ edgeSetsAreIdentical,+ stripMergeSuffix,+ hasMergeSuffix,+ MERGE_SUFFIX_LEFT,+ MERGE_SUFFIX_RIGHT,+} from "../merge.js";+import fs from "fs";+import path from "path";+import os from "os";+import type { NodeRow, EdgeRow } from "../types.js";++let tmpDir: string;++function createTmpDb(name: string): { db: KnowledgeDB; path: string } {+ const dbPath = path.join(tmpDir, name);+ const db = new KnowledgeDB(dbPath);+ return { db, path: dbPath };+}++function insertTestNode(+ db: KnowledgeDB,+ id: string,+ overrides: Partial<{+ name: string;+ kind: string;+ summary: string;+ why: string | null;+ file_refs: string[] | null;+ parent_id: string | null;+ }> = {}+): void {+ db.insertNode({+ id,+ name: overrides.name ?? id,+ kind: overrides.kind ?? "feature",+ summary: overrides.summary ?? `Summary for ${id}`,+ why: overrides.why ?? null,+ file_refs: overrides.file_refs ?? null,+ parent_id: overrides.parent_id ?? null,+ created_by_task: null,+ embedding: null,+ });+}++beforeEach(() => {+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "megamemory-merge-test-"));+});++afterEach(() => {+ fs.rmSync(tmpDir, { recursive: true, force: true });+});++describe("merge helpers", () => {+ describe("stripMergeSuffix", () => {+ it("strips ::left suffix", () => {+ expect(stripMergeSuffix("foo::left")).toBe("foo");+ });++ it("strips ::right suffix", () => {+ expect(stripMergeSuffix("foo::right")).toBe("foo");+ });++ it("returns unchanged if no suffix", () => {+ expect(stripMergeSuffix("foo")).toBe("foo");+ });++ it("handles nested IDs with suffix", () => {+ expect(stripMergeSuffix("parent/child::left")).toBe("parent/child");+ });+ });++ describe("hasMergeSuffix", () => {+ it("detects ::left", () => {+ expect(hasMergeSuffix("foo::left")).toBe(true);+ });++ it("detects ::right", () => {+ expect(hasMergeSuffix("foo::right")).toBe(true);+ });++ it("returns false for clean IDs", () => {+ expect(hasMergeSuffix("foo")).toBe(false);+ });+ });++ describe("nodesAreIdentical", () => {+ it("returns true for identical nodes", () => {+ const base: NodeRow = {+ id: "test",+ name: "Test",+ kind: "feature",+ summary: "A test",+ why: null,+ file_refs: null,+ parent_id: null,+ created_by_task: null,+ created_at: "2024-01-01",+ updated_at: "2024-01-01",+ removed_at: null,+ removed_reason: null,+ embedding: null,+ merge_group: null,+ needs_merge: 0,+ source_branch: null,+ merge_timestamp: null,+ };+ // Different timestamps shouldn't matter+ const other = { ...base, created_at: "2025-01-01", updated_at: "2025-01-01" };+ expect(nodesAreIdentical(base, other)).toBe(true);+ });++ it("returns false for different summaries", () => {+ const base: NodeRow = {+ id: "test", name: "Test", kind: "feature", summary: "A",+ why: null, file_refs: null, parent_id: null, created_by_task: null,+ created_at: "", updated_at: "", removed_at: null, removed_reason: null,+ embedding: null, merge_group: null, needs_merge: 0, source_branch: null, merge_timestamp: null,+ };+ const other = { ...base, summary: "B" };+ expect(nodesAreIdentical(base, other)).toBe(false);+ });++ it("returns false when one is removed and other is not", () => {+ const base: NodeRow = {+ id: "test", name: "Test", kind: "feature", summary: "A",+ why: null, file_refs: null, parent_id: null, created_by_task: null,+ created_at: "", updated_at: "", removed_at: null, removed_reason: null,+ embedding: null, merge_group: null, needs_merge: 0, source_branch: null, merge_timestamp: null,+ };+ const removed = { ...base, removed_at: "2024-01-01", removed_reason: "gone" };+ expect(nodesAreIdentical(base, removed)).toBe(false);+ });++ it("compares file_refs as parsed JSON", () => {+ const a: NodeRow = {+ id: "test", name: "Test", kind: "feature", summary: "A",+ why: null, file_refs: '["a.ts","b.ts"]', parent_id: null, created_by_task: null,+ created_at: "", updated_at: "", removed_at: null, removed_reason: null,+ embedding: null, merge_group: null, needs_merge: 0, source_branch: null, merge_timestamp: null,+ };+ const b = { ...a, file_refs: '["a.ts","b.ts"]' };+ expect(nodesAreIdentical(a, b)).toBe(true);++ const c = { ...a, file_refs: '["a.ts","c.ts"]' };+ expect(nodesAreIdentical(a, c)).toBe(false);+ });+ });++ describe("edgeSetsAreIdentical", () => {+ const makeEdge = (from: string, to: string, rel: string): EdgeRow => ({+ id: 0, from_id: from, to_id: to, relation: rel,+ description: null, created_at: "",+ merge_group: null, needs_merge: 0, source_branch: null, merge_timestamp: null,+ });++ it("returns true for identical sets", () => {+ const a = [makeEdge("x", "y", "calls")];+ const b = [makeEdge("x", "y", "calls")];+ expect(edgeSetsAreIdentical(a, b)).toBe(true);+ });++ it("returns false for different sets", () => {+ const a = [makeEdge("x", "y", "calls")];+ const b = [makeEdge("x", "z", "calls")];+ expect(edgeSetsAreIdentical(a, b)).toBe(false);+ });++ it("returns true for empty sets", () => {+ expect(edgeSetsAreIdentical([], [])).toBe(true);+ });++ it("returns false for different lengths", () => {+ const a = [makeEdge("x", "y", "calls"), makeEdge("x", "z", "depends_on")];+ const b = [makeEdge("x", "y", "calls")];+ expect(edgeSetsAreIdentical(a, b)).toBe(false);+ });+ });+});++describe("MergeEngine", () => {+ let engine: MergeEngine;++ beforeEach(() => {+ engine = new MergeEngine();+ });++ describe("clean merge (no conflicts)", () => {+ it("merges nodes that exist in only one side", () => {+ const left = createTmpDb("left.db");+ const right = createTmpDb("right.db");+ const outputPath = path.join(tmpDir, "output.db");++ insertTestNode(left.db, "node-a", { summary: "Node A" });+ insertTestNode(left.db, "node-b", { summary: "Node B" });+ insertTestNode(right.db, "node-c", { summary: "Node C" });+ insertTestNode(right.db, "node-d", { summary: "Node D" });++ left.db.close();+ right.db.close();++ const result = engine.merge(left.path, right.path, outputPath);++ expect(result.clean).toBe(4);+ expect(result.conceptConflicts).toBe(0);+ expect(result.edgeConflicts).toBe(0);++ const output = new KnowledgeDB(outputPath);+ expect(output.getNode("node-a")).toBeDefined();+ expect(output.getNode("node-b")).toBeDefined();+ expect(output.getNode("node-c")).toBeDefined();+ expect(output.getNode("node-d")).toBeDefined();+ expect(output.getStats().nodes).toBe(4);+ output.close();+ });++ it("deduplicates identical nodes from both sides", () => {+ const left = createTmpDb("left.db");+ const right = createTmpDb("right.db");+ const outputPath = path.join(tmpDir, "output.db");++ insertTestNode(left.db, "shared", { summary: "Same content" });+ insertTestNode(right.db, "shared", { summary: "Same content" });++ left.db.close();+ right.db.close();++ const result = engine.merge(left.path, right.path, outputPath);++ expect(result.clean).toBe(1);+ expect(result.conceptConflicts).toBe(0);++ const output = new KnowledgeDB(outputPath);+ expect(output.getStats().nodes).toBe(1);+ expect(output.getNode("shared")!.summary).toBe("Same content");+ output.close();+ });++ it("merges edges for non-conflicting nodes", () => {+ const left = createTmpDb("left.db");+ const right = createTmpDb("right.db");+ const outputPath = path.join(tmpDir, "output.db");++ insertTestNode(left.db, "node-a");+ insertTestNode(left.db, "node-b");+ left.db.insertEdge({ from_id: "node-a", to_id: "node-b", relation: "calls", description: null });++ insertTestNode(right.db, "node-c");++ left.db.close();+ right.db.close();++ const result = engine.merge(left.path, right.path, outputPath);++ const output = new KnowledgeDB(outputPath);+ const edges = output.getAllEdges();+ expect(edges).toHaveLength(1);+ expect(edges[0].from_id).toBe("node-a");+ expect(edges[0].to_id).toBe("node-b");+ output.close();+ });+ });++ describe("concept conflicts", () => {+ it("creates conflict entries for different content at same ID", () => {+ const left = createTmpDb("left.db");+ const right = createTmpDb("right.db");+ const outputPath = path.join(tmpDir, "output.db");++ insertTestNode(left.db, "feature-x", { summary: "Left version" });+ insertTestNode(right.db, "feature-x", { summary: "Right version" });++ left.db.close();+ right.db.close();++ const result = engine.merge(left.path, right.path, outputPath);++ expect(result.conceptConflicts).toBe(1);+ expect(result.mergeGroups).toHaveLength(1);++ const output = new KnowledgeDB(outputPath);+ const leftVersion = output.getNode("feature-x::left");+ const rightVersion = output.getNode("feature-x::right");++ expect(leftVersion).toBeDefined();+ expect(rightVersion).toBeDefined();+ expect(leftVersion!.summary).toBe("Left version");+ expect(rightVersion!.summary).toBe("Right version");+ expect(leftVersion!.needs_merge).toBe(1);+ expect(rightVersion!.needs_merge).toBe(1);+ expect(leftVersion!.merge_group).toBe(rightVersion!.merge_group);+ expect(leftVersion!.source_branch).toBe("left");+ expect(rightVersion!.source_branch).toBe("right");+ output.close();+ });++ it("uses custom labels for source_branch", () => {+ const left = createTmpDb("left.db");+ const right = createTmpDb("right.db");+ const outputPath = path.join(tmpDir, "output.db");++ insertTestNode(left.db, "concept", { summary: "Main version" });+ insertTestNode(right.db, "concept", { summary: "Feature version" });++ left.db.close();+ right.db.close();++ engine.merge(left.path, right.path, outputPath, {+ leftLabel: "main",+ rightLabel: "feature-xyz",+ });++ const output = new KnowledgeDB(outputPath);+ expect(output.getNode("concept::left")!.source_branch).toBe("main");+ expect(output.getNode("concept::right")!.source_branch).toBe("feature-xyz");+ output.close();+ });+ });++ describe("removal conflicts", () => {+ it("creates conflict when one side removed and other didn't", () => {+ const left = createTmpDb("left.db");+ const right = createTmpDb("right.db");+ const outputPath = path.join(tmpDir, "output.db");++ insertTestNode(left.db, "to-remove", { summary: "Still active" });++ insertTestNode(right.db, "to-remove", { summary: "Still active" });+ right.db.softDeleteNode("to-remove", "No longer needed");++ left.db.close();+ right.db.close();++ const result = engine.merge(left.path, right.path, outputPath);++ // The left has active, right has removed — different removed_at state = conflict+ expect(result.conceptConflicts).toBe(1);++ const output = new KnowledgeDB(outputPath);+ // The left version should be the active one (with suffix)+ const leftNode = output.getAllNodesRaw().find(n => n.id === "to-remove::left");+ const rightNode = output.getAllNodesRaw().find(n => n.id === "to-remove::right");+ expect(leftNode).toBeDefined();+ expect(rightNode).toBeDefined();+ expect(leftNode!.removed_at).toBeNull();+ expect(rightNode!.removed_at).not.toBeNull();+ output.close();+ });++ it("merges cleanly when both sides removed the same node", () => {+ const left = createTmpDb("left.db");+ const right = createTmpDb("right.db");+ const outputPath = path.join(tmpDir, "output.db");++ insertTestNode(left.db, "both-removed", { summary: "Gone" });+ left.db.softDeleteNode("both-removed", "Removed on left");++ insertTestNode(right.db, "both-removed", { summary: "Gone" });+ right.db.softDeleteNode("both-removed", "Removed on right");++ left.db.close();+ right.db.close();++ const result = engine.merge(left.path, right.path, outputPath);++ // Both agree on removal, so it should be clean+ expect(result.conceptConflicts).toBe(0);+ expect(result.removedClean).toBe(1);+ output_check: {+ const output = new KnowledgeDB(outputPath);+ const all = output.getAllNodesRaw();+ expect(all).toHaveLength(1);+ expect(all[0].removed_at).not.toBeNull();+ output.close();+ }+ });+ });++ describe("edge conflicts", () => {+ it("marks edge conflicts when same node has different edges", () => {+ const left = createTmpDb("left.db");+ const right = createTmpDb("right.db");+ const outputPath = path.join(tmpDir, "output.db");++ // Both have the same node with different content (concept conflict)+ insertTestNode(left.db, "node-a", { summary: "Left" });+ insertTestNode(left.db, "node-b");+ left.db.insertEdge({ from_id: "node-a", to_id: "node-b", relation: "calls", description: null });++ insertTestNode(right.db, "node-a", { summary: "Right" });+ insertTestNode(right.db, "node-b");+ insertTestNode(right.db, "node-c");+ right.db.insertEdge({ from_id: "node-a", to_id: "node-c", relation: "depends_on", description: null });++ left.db.close();+ right.db.close();++ const result = engine.merge(left.path, right.path, outputPath);++ expect(result.conceptConflicts).toBe(1); // node-a conflicted+ expect(result.edgeConflicts).toBe(1); // different edge sets for node-a++ const output = new KnowledgeDB(outputPath);+ const edges = output.getAllEdgesRaw();+ const conflictEdges = edges.filter(e => e.needs_merge === 1);+ expect(conflictEdges.length).toBeGreaterThan(0);+ output.close();+ });+ });++ describe("idempotent re-merge", () => {+ it("produces same result when merging the same files twice", () => {+ const left = createTmpDb("left.db");+ const right = createTmpDb("right.db");+ const output1Path = path.join(tmpDir, "output1.db");+ const output2Path = path.join(tmpDir, "output2.db");++ insertTestNode(left.db, "clean-node", { summary: "Clean" });+ insertTestNode(left.db, "conflict-node", { summary: "Left version" });+ insertTestNode(right.db, "conflict-node", { summary: "Right version" });+ insertTestNode(right.db, "other-node", { summary: "Other" });++ left.db.close();+ right.db.close();++ const result1 = engine.merge(left.path, right.path, output1Path);+ const result2 = engine.merge(left.path, right.path, output2Path);++ expect(result1.clean).toBe(result2.clean);+ expect(result1.conceptConflicts).toBe(result2.conceptConflicts);+ expect(result1.edgeConflicts).toBe(result2.edgeConflicts);++ // Verify same node count+ const db1 = new KnowledgeDB(output1Path);+ const db2 = new KnowledgeDB(output2Path);+ expect(db1.getStats().nodes).toBe(db2.getStats().nodes);+ db1.close();+ db2.close();+ });++ it("preserves pre-existing unresolved conflicts", () => {+ const left = createTmpDb("left.db");+ const right = createTmpDb("right.db");+ const outputPath = path.join(tmpDir, "output.db");++ left.db.insertNodeRaw({+ id: "concept::left",+ name: "Concept",+ kind: "feature",+ summary: "Left unresolved",+ merge_group: "existing-group",+ needs_merge: 1,+ source_branch: "left",+ });+ left.db.insertNodeRaw({+ id: "concept::right",+ name: "Concept",+ kind: "feature",+ summary: "Right unresolved",+ merge_group: "existing-group",+ needs_merge: 1,+ source_branch: "right",+ });++ left.db.close();+ right.db.close();++ const result = engine.merge(left.path, right.path, outputPath);++ expect(result.clean).toBe(0);+ expect(result.conceptConflicts).toBe(0);++ const output = new KnowledgeDB(outputPath);+ const nodes = output.getAllNodesRaw();++ expect(nodes.map((n) => n.id).sort()).toEqual([+ "concept::left",+ "concept::right",+ ]);+ expect(nodes.every((n) => n.needs_merge === 1)).toBe(true);+ output.close();+ });+ });++ describe("resolution", () => {+ it("keeps left version and removes right on resolve --keep left", () => {+ const left = createTmpDb("left.db");+ const right = createTmpDb("right.db");+ const outputPath = path.join(tmpDir, "output.db");++ insertTestNode(left.db, "feature", { summary: "Left feature" });+ insertTestNode(right.db, "feature", { summary: "Right feature" });++ left.db.close();+ right.db.close();++ const result = engine.merge(left.path, right.path, outputPath);+ const mergeGroup = result.mergeGroups[0];++ // Now resolve+ const output = new KnowledgeDB(outputPath);+ const leftNode = output.getNode("feature::left")!;+ const rightNode = output.getNode("feature::right")!;+ expect(leftNode).toBeDefined();+ expect(rightNode).toBeDefined();++ // Simulate --keep left resolution+ output.hardDeleteNode("feature::right");+ output.renameNodeId("feature::left", "feature");+ output.clearNodeMergeFlags("feature");+ output.clearEdgeMergeFlagsByGroup(mergeGroup);++ const resolved = output.getNode("feature");+ expect(resolved).toBeDefined();+ expect(resolved!.summary).toBe("Left feature");+ expect(resolved!.needs_merge).toBe(0);+ expect(resolved!.merge_group).toBeNull();++ // Right should be gone+ expect(output.getNode("feature::right")).toBeUndefined();++ output.close();+ });++ it("keeps right version and removes left on resolve --keep right", () => {+ const left = createTmpDb("left.db");+ const right = createTmpDb("right.db");+ const outputPath = path.join(tmpDir, "output.db");++ insertTestNode(left.db, "feature", { summary: "Left feature" });+ insertTestNode(right.db, "feature", { summary: "Right feature" });++ left.db.close();+ right.db.close();++ const result = engine.merge(left.path, right.path, outputPath);+ const mergeGroup = result.mergeGroups[0];++ const output = new KnowledgeDB(outputPath);++ // Simulate --keep right resolution+ output.hardDeleteNode("feature::left");+ output.renameNodeId("feature::right", "feature");+ output.clearNodeMergeFlags("feature");+ output.clearEdgeMergeFlagsByGroup(mergeGroup);++ const resolved = output.getNode("feature");+ expect(resolved).toBeDefined();+ expect(resolved!.summary).toBe("Right feature");+ expect(resolved!.needs_merge).toBe(0);++ expect(output.getNode("feature::left")).toBeUndefined();++ output.close();+ });++ it("keeps both on resolve --keep both with new IDs", () => {+ const left = createTmpDb("left.db");+ const right = createTmpDb("right.db");+ const outputPath = path.join(tmpDir, "output.db");++ insertTestNode(left.db, "feature", { summary: "Left feature" });+ insertTestNode(right.db, "feature", { summary: "Right feature" });++ left.db.close();+ right.db.close();++ engine.merge(left.path, right.path, outputPath);++ const output = new KnowledgeDB(outputPath);++ // Simulate --keep both resolution+ output.renameNodeId("feature::left", "feature-left");+ output.clearNodeMergeFlags("feature-left");+ output.renameNodeId("feature::right", "feature-right");+ output.clearNodeMergeFlags("feature-right");++ expect(output.getNode("feature-left")).toBeDefined();+ expect(output.getNode("feature-right")).toBeDefined();+ expect(output.getNode("feature-left")!.summary).toBe("Left feature");+ expect(output.getNode("feature-right")!.summary).toBe("Right feature");+ expect(output.getStats().nodes).toBe(2);++ output.close();+ });++ it("cleans up edge references after resolution", () => {+ const left = createTmpDb("left.db");+ const right = createTmpDb("right.db");+ const outputPath = path.join(tmpDir, "output.db");++ insertTestNode(left.db, "node-a", { summary: "Left A" });+ insertTestNode(left.db, "node-b");+ left.db.insertEdge({ from_id: "node-a", to_id: "node-b", relation: "calls", description: null });++ insertTestNode(right.db, "node-a", { summary: "Right A" });+ insertTestNode(right.db, "node-b");++ left.db.close();+ right.db.close();++ const result = engine.merge(left.path, right.path, outputPath);+ const mergeGroup = result.mergeGroups[0];++ const output = new KnowledgeDB(outputPath);++ // Resolve keeping left+ output.hardDeleteNode("node-a::right");+ output.renameNodeId("node-a::left", "node-a");+ output.clearNodeMergeFlags("node-a");+ output.clearEdgeMergeFlagsByGroup(mergeGroup);++ // Edges should now reference "node-a" (not "node-a::left")+ const edges = output.getOutgoingEdges("node-a");+ expect(edges).toHaveLength(1);+ expect(edges[0].to_id).toBe("node-b");++ output.close();+ });+ });++ describe("clean node edge to conflicted target", () => {+ it("remaps edges from clean nodes pointing at conflicted targets", () => {+ const left = createTmpDb("left.db");+ const right = createTmpDb("right.db");+ const outputPath = path.join(tmpDir, "output.db");++ // "caller" is the same on both sides (clean, no conflict)+ insertTestNode(left.db, "caller", { summary: "Calls target" });+ insertTestNode(right.db, "caller", { summary: "Calls target" });++ // "target" diverges between sides (conflict)+ insertTestNode(left.db, "target", { summary: "Left target" });+ insertTestNode(right.db, "target", { summary: "Right target" });++ // Edge from clean node to conflicted node — exists on left side+ left.db.insertEdge({ from_id: "caller", to_id: "target", relation: "calls", description: null });++ left.db.close();+ right.db.close();++ const result = engine.merge(left.path, right.path, outputPath);++ expect(result.conceptConflicts).toBe(1); // target conflicted+ expect(result.clean).toBe(1); // caller is clean++ const output = new KnowledgeDB(outputPath);++ // "caller" should exist without suffix+ expect(output.getNode("caller")).toBeDefined();+ // "target" should be split into two suffixed versions+ expect(output.getNode("target::left")).toBeDefined();+ expect(output.getNode("target::right")).toBeDefined();++ // The edge from "caller" should point to "target::left" (since the edge came from the left DB)+ const edges = output.getOutgoingEdges("caller");+ expect(edges).toHaveLength(1);+ expect(edges[0].to_id).toBe("target::left");++ output.close();+ });+ });++ describe("mixed scenarios", () => {+ it("handles a mix of clean, conflict, and removed nodes", () => {+ const left = createTmpDb("left.db");+ const right = createTmpDb("right.db");+ const outputPath = path.join(tmpDir, "output.db");++ // Clean: only in left+ insertTestNode(left.db, "left-only");+ // Clean: only in right+ insertTestNode(right.db, "right-only");+ // Clean: identical in both+ insertTestNode(left.db, "identical", { summary: "Same" });+ insertTestNode(right.db, "identical", { summary: "Same" });+ // Conflict: different+ insertTestNode(left.db, "diverged", { summary: "Left diverged" });+ insertTestNode(right.db, "diverged", { summary: "Right diverged" });+ // Removed cleanly in one side+ insertTestNode(left.db, "removed-left", { summary: "Was here" });+ // (absent in right = clean merge)++ left.db.close();+ right.db.close();++ const result = engine.merge(left.path, right.path, outputPath);++ expect(result.clean).toBe(4); // left-only + right-only + identical + removed-left+ expect(result.conceptConflicts).toBe(1); // diverged+ expect(result.mergeGroups).toHaveLength(1);++ const output = new KnowledgeDB(outputPath);+ expect(output.getNode("left-only")).toBeDefined();+ expect(output.getNode("right-only")).toBeDefined();+ expect(output.getNode("identical")).toBeDefined();+ expect(output.getNode("diverged::left")).toBeDefined();+ expect(output.getNode("diverged::right")).toBeDefined();+ expect(output.getNode("removed-left")).toBeDefined();+ output.close();+ });+ });+});diff --git a/src/db.ts b/src/db.tsindex 0e5a4ec..2882ffb 100644--- a/src/db.ts+++ b/src/db.ts@@ -3,7 +3,7 @@ import path from "path";import fs from "fs";import type { NodeRow, EdgeRow } from "./types.js";-const SCHEMA_VERSION = 1;+const SCHEMA_VERSION = 2;export class KnowledgeDB {private db: Database.Database;@@ -46,6 +46,10 @@ export class KnowledgeDB {removed_at TEXT,removed_reason TEXT,embedding BLOB,+ merge_group TEXT,+ needs_merge INTEGER DEFAULT 0,+ source_branch TEXT,+ merge_timestamp TEXT,FOREIGN KEY (parent_id) REFERENCES nodes(id) ON DELETE SET NULL);@@ -56,6 +60,10 @@ export class KnowledgeDB {relation TEXT NOT NULL,description TEXT,created_at TEXT DEFAULT (datetime('now')),+ merge_group TEXT,+ needs_merge INTEGER DEFAULT 0,+ source_branch TEXT,+ merge_timestamp TEXT,FOREIGN KEY (from_id) REFERENCES nodes(id) ON DELETE CASCADE,FOREIGN KEY (to_id) REFERENCES nodes(id) ON DELETE CASCADE);@@ -63,10 +71,52 @@ export class KnowledgeDB {CREATE INDEX IF NOT EXISTS idx_nodes_parent ON nodes(parent_id);CREATE INDEX IF NOT EXISTS idx_nodes_kind ON nodes(kind);CREATE INDEX IF NOT EXISTS idx_nodes_removed ON nodes(removed_at);+ CREATE INDEX IF NOT EXISTS idx_nodes_merge_group ON nodes(merge_group);+ CREATE INDEX IF NOT EXISTS idx_nodes_needs_merge ON nodes(needs_merge);CREATE INDEX IF NOT EXISTS idx_edges_from ON edges(from_id);CREATE INDEX IF NOT EXISTS idx_edges_to ON edges(to_id);CREATE INDEX IF NOT EXISTS idx_edges_relation ON edges(relation);+ CREATE INDEX IF NOT EXISTS idx_edges_merge_group ON edges(merge_group);+ CREATE INDEX IF NOT EXISTS idx_edges_needs_merge ON edges(needs_merge);`);+ }++ if (version < 2) {+ // Add merge-related columns for existing v1 databases+ const nodeColumns = this.db+ .prepare("PRAGMA table_info(nodes)")+ .all() as Array<{ name: string }>;+ const nodeColNames = new Set(nodeColumns.map((c) => c.name));++ if (!nodeColNames.has("merge_group")) {+ this.db.exec(`+ ALTER TABLE nodes ADD COLUMN merge_group TEXT;+ ALTER TABLE nodes ADD COLUMN needs_merge INTEGER DEFAULT 0;+ ALTER TABLE nodes ADD COLUMN source_branch TEXT;+ ALTER TABLE nodes ADD COLUMN merge_timestamp TEXT;+ CREATE INDEX IF NOT EXISTS idx_nodes_merge_group ON nodes(merge_group);+ CREATE INDEX IF NOT EXISTS idx_nodes_needs_merge ON nodes(needs_merge);+ `);+ }++ const edgeColumns = this.db+ .prepare("PRAGMA table_info(edges)")+ .all() as Array<{ name: string }>;+ const edgeColNames = new Set(edgeColumns.map((c) => c.name));++ if (!edgeColNames.has("merge_group")) {+ this.db.exec(`+ ALTER TABLE edges ADD COLUMN merge_group TEXT;+ ALTER TABLE edges ADD COLUMN needs_merge INTEGER DEFAULT 0;+ ALTER TABLE edges ADD COLUMN source_branch TEXT;+ ALTER TABLE edges ADD COLUMN merge_timestamp TEXT;+ CREATE INDEX IF NOT EXISTS idx_edges_merge_group ON edges(merge_group);+ CREATE INDEX IF NOT EXISTS idx_edges_needs_merge ON edges(needs_merge);+ `);+ }+ }++ if (version < SCHEMA_VERSION) {this.db.pragma(`user_version = ${SCHEMA_VERSION}`);}}@@ -345,6 +395,192 @@ export class KnowledgeDB {return { nodes, edges, removed };}+ // ---- Merge-related methods ----++ getConflictNodes(): NodeRow[] {+ // Don't filter by removed_at — removal conflicts are valid (one side removed, other didn't)+ return this.db+ .prepare("SELECT * FROM nodes WHERE needs_merge = 1")+ .all() as NodeRow[];+ }++ getConflictEdges(): EdgeRow[] {+ return this.db+ .prepare("SELECT * FROM edges WHERE needs_merge = 1")+ .all() as EdgeRow[];+ }++ getNodesByMergeGroup(mergeGroup: string): NodeRow[] {+ return this.db+ .prepare("SELECT * FROM nodes WHERE merge_group = ?")+ .all(mergeGroup) as NodeRow[];+ }++ getEdgesByMergeGroup(mergeGroup: string): EdgeRow[] {+ return this.db+ .prepare("SELECT * FROM edges WHERE merge_group = ?")+ .all(mergeGroup) as EdgeRow[];+ }++ clearNodeMergeFlags(id: string): boolean {+ const result = this.db+ .prepare(+ `UPDATE nodes SET merge_group = NULL, needs_merge = 0, source_branch = NULL,+ merge_timestamp = NULL, updated_at = datetime('now') WHERE id = ?`+ )+ .run(id);+ return result.changes > 0;+ }++ clearEdgeMergeFlagsByGroup(mergeGroup: string): boolean {+ const result = this.db+ .prepare(+ `UPDATE edges SET merge_group = NULL, needs_merge = 0, source_branch = NULL,+ merge_timestamp = NULL WHERE merge_group = ?`+ )+ .run(mergeGroup);+ return result.changes > 0;+ }++ renameNodeId(oldId: string, newId: string): boolean {+ // Temporarily disable foreign keys for the rename operation,+ // since self-referencing FKs (parent_id → id) would block the update.+ // Wrapped in a transaction so all 4 updates succeed or none do.+ this.db.pragma("foreign_keys = OFF");+ try {+ let changed = false;+ this.db.exec("BEGIN");+ try {+ const result = this.db+ .prepare("UPDATE nodes SET id = @newId, updated_at = datetime('now') WHERE id = @oldId")+ .run({ oldId, newId });++ if (result.changes > 0) {+ changed = true;+ // Update parent_id references in children+ this.db+ .prepare("UPDATE nodes SET parent_id = @newId WHERE parent_id = @oldId")+ .run({ oldId, newId });+ // Update edge references+ this.db+ .prepare("UPDATE edges SET from_id = @newId WHERE from_id = @oldId")+ .run({ oldId, newId });+ this.db+ .prepare("UPDATE edges SET to_id = @newId WHERE to_id = @oldId")+ .run({ oldId, newId });+ }+ this.db.exec("COMMIT");+ } catch (err) {+ this.db.exec("ROLLBACK");+ throw err;+ }+ return changed;+ } finally {+ this.db.pragma("foreign_keys = ON");+ }+ }++ getAllNodesRaw(): NodeRow[] {+ return this.db.prepare("SELECT * FROM nodes").all() as NodeRow[];+ }++ getAllEdgesRaw(): EdgeRow[] {+ return this.db.prepare("SELECT * FROM edges").all() as EdgeRow[];+ }++ deleteEdgesForNode(nodeId: string): void {+ this.db+ .prepare("DELETE FROM edges WHERE from_id = ? OR to_id = ?")+ .run(nodeId, nodeId);+ }++ hardDeleteNode(id: string): boolean {+ this.deleteEdgesForNode(id);+ const result = this.db+ .prepare("DELETE FROM nodes WHERE id = ?")+ .run(id);+ return result.changes > 0;+ }++ insertNodeRaw(node: {+ id: string;+ name: string;+ kind: string;+ summary: string;+ why?: string | null;+ file_refs?: string | null;+ parent_id?: string | null;+ created_by_task?: string | null;+ created_at?: string | null;+ updated_at?: string | null;+ removed_at?: string | null;+ removed_reason?: string | null;+ embedding?: Buffer | null;+ merge_group?: string | null;+ needs_merge?: number;+ source_branch?: string | null;+ merge_timestamp?: string | null;+ }): void {+ const stmt = this.db.prepare(`+ INSERT INTO nodes (id, name, kind, summary, why, file_refs, parent_id, created_by_task,+ created_at, updated_at, removed_at, removed_reason, embedding,+ merge_group, needs_merge, source_branch, merge_timestamp)+ VALUES (@id, @name, @kind, @summary, @why, @file_refs, @parent_id, @created_by_task,+ @created_at, @updated_at, @removed_at, @removed_reason, @embedding,+ @merge_group, @needs_merge, @source_branch, @merge_timestamp)+ `);+ stmt.run({+ id: node.id,+ name: node.name,+ kind: node.kind,+ summary: node.summary,+ why: node.why ?? null,+ file_refs: node.file_refs ?? null,+ parent_id: node.parent_id ?? null,+ created_by_task: node.created_by_task ?? null,+ created_at: node.created_at ?? null,+ updated_at: node.updated_at ?? null,+ removed_at: node.removed_at ?? null,+ removed_reason: node.removed_reason ?? null,+ embedding: node.embedding ?? null,+ merge_group: node.merge_group ?? null,+ needs_merge: node.needs_merge ?? 0,+ source_branch: node.source_branch ?? null,+ merge_timestamp: node.merge_timestamp ?? null,+ });+ }++ insertEdgeRaw(edge: {+ from_id: string;+ to_id: string;+ relation: string;+ description?: string | null;+ created_at?: string | null;+ merge_group?: string | null;+ needs_merge?: number;+ source_branch?: string | null;+ merge_timestamp?: string | null;+ }): number {+ const stmt = this.db.prepare(`+ INSERT INTO edges (from_id, to_id, relation, description, created_at,+ merge_group, needs_merge, source_branch, merge_timestamp)+ VALUES (@from_id, @to_id, @relation, @description, @created_at,+ @merge_group, @needs_merge, @source_branch, @merge_timestamp)+ `);+ const result = stmt.run({+ from_id: edge.from_id,+ to_id: edge.to_id,+ relation: edge.relation,+ description: edge.description ?? null,+ created_at: edge.created_at ?? null,+ merge_group: edge.merge_group ?? null,+ needs_merge: edge.needs_merge ?? 0,+ source_branch: edge.source_branch ?? null,+ merge_timestamp: edge.merge_timestamp ?? null,+ });+ return Number(result.lastInsertRowid);+ }+close(): void {this.db.close();}diff --git a/src/index.ts b/src/index.tsindex 895c6f0..9911dcc 100644--- a/src/index.ts+++ b/src/index.ts@@ -22,19 +22,31 @@ ${pc.bold("Commands:")}${pc.cyan("(no command)")} Start the MCP stdio server ${pc.dim("(invoked by your editor)")}${pc.cyan("init")} Configure opencode integration${pc.cyan("serve")} Start the web graph explorer+ ${pc.cyan("merge")} Merge two knowledge.db files+ ${pc.cyan("conflicts")} List unresolved merge conflicts+ ${pc.cyan("resolve")} Resolve a merge conflict${pc.bold("Options:")}${pc.cyan("--port")} ${pc.dim("PORT")} Port for the web explorer ${pc.dim("(default: 4321)")}+ ${pc.cyan("--into")} ${pc.dim("FILE")} Output path for merge ${pc.dim("(default: overwrites file1)")}+ ${pc.cyan("--left-label")} Label for left side in merge ${pc.dim("(default: left)")}+ ${pc.cyan("--right-label")} Label for right side in merge ${pc.dim("(default: right)")}+ ${pc.cyan("--keep")} Resolution strategy: left, right, or both+ ${pc.cyan("--json")} Machine-readable output for conflicts+ ${pc.cyan("--db")} ${pc.dim("PATH")} Database path for conflicts/resolve${pc.cyan("--help, -h")} Show this help${pc.cyan("--version, -v")} Show version${pc.bold("Examples:")}- ${pc.dim("$")} megamemory init ${pc.dim("Setup opencode config, plugins, and commands")}- ${pc.dim("$")} megamemory serve ${pc.dim(`Open graph explorer at ${pc.underline("http://localhost:4321")}`)}- ${pc.dim("$")} megamemory serve --port 8080 ${pc.dim("Custom port")}+ ${pc.dim("$")} megamemory init ${pc.dim("Setup opencode config, plugins, and commands")}+ ${pc.dim("$")} megamemory serve ${pc.dim(`Open graph explorer at ${pc.underline("http://localhost:4321")}`)}+ ${pc.dim("$")} megamemory serve --port 8080 ${pc.dim("Custom port")}+ ${pc.dim("$")} megamemory merge main.db feature.db --into merged.db ${pc.dim("Merge two knowledge DBs")}+ ${pc.dim("$")} megamemory conflicts ${pc.dim("View unresolved conflicts")}+ ${pc.dim("$")} megamemory resolve <group-id> --keep left ${pc.dim("Resolve a conflict")}`.trim();-const KNOWN_COMMANDS = new Set(["init", "serve", "--help", "-h", "--version", "-v"]);+const KNOWN_COMMANDS = new Set(["init", "serve", "merge", "conflicts", "resolve", "--help", "-h", "--version", "-v"]);function parseFlags(args: string[]): { port?: number; rawPort?: string } {const portIdx = args.indexOf("--port");@@ -68,6 +80,27 @@ switch (cmd) {break;}+ case "merge": {+ const { runMerge } = await import("./merge-cli.js");+ await runMerge(process.argv.slice(3));+ process.exit(0);+ break;+ }++ case "conflicts": {+ const { runConflicts } = await import("./merge-cli.js");+ await runConflicts(process.argv.slice(3));+ process.exit(0);+ break;+ }++ case "resolve": {+ const { runResolve } = await import("./merge-cli.js");+ await runResolve(process.argv.slice(3));+ process.exit(0);+ break;+ }+case "--help":case "-h":console.log(HELP);@@ -104,7 +137,7 @@ async function startMcpServer() {const { z } = await import("zod");const path = await import("path");const { KnowledgeDB } = await import("./db.js");- const { understand, createConcept, updateConcept, link, removeConcept, listRoots } =+ const { understand, createConcept, updateConcept, link, removeConcept, listRoots, listConflicts, resolveConflict } =await import("./tools.js");type NodeKind = import("./types.js").NodeKind;@@ -265,6 +298,46 @@ async function startMcpServer() {});+ server.tool(+ "list_conflicts",+ "List all unresolved merge conflicts in the knowledge graph, grouped by merge_group. Each group contains competing versions with full data. Call this when the user runs /merge to begin AI-assisted conflict resolution.",+ {},+ async () => {+ try {+ const result = listConflicts(db);+ return { content: [{ type: "text" as const, text: JSON.stringify(result, null, 2) }] };+ } catch (err) {+ return { content: [{ type: "text" as const, text: `Error: ${err instanceof Error ? err.message : String(err)}` }], isError: true };+ }+ }+ );++ server.tool(+ "resolve_conflict",+ "Resolve a merge conflict by providing the correct resolved content. Read both conflict versions, verify against the current codebase, then provide the accurate resolved summary. Do NOT just pick a side — write the truth.",+ {+ merge_group: z.string().describe("The merge_group UUID of the conflict to resolve"),+ resolved: z.object({+ summary: z.string().describe("The correct, resolved summary for this concept — verified against the current codebase"),+ why: z.string().optional().describe("Updated rationale"),+ file_refs: z.array(z.string()).optional().describe("Updated file references"),+ }).describe("The resolved content to write — must reflect current codebase truth"),+ reason: z.string().describe("Explanation of what you verified and why this resolution is correct"),+ },+ async (params) => {+ try {+ const result = await resolveConflict(db, {+ merge_group: params.merge_group,+ resolved: params.resolved,+ reason: params.reason,+ });+ return { content: [{ type: "text" as const, text: JSON.stringify(result, null, 2) }] };+ } catch (err) {+ return { content: [{ type: "text" as const, text: `Error: ${err instanceof Error ? err.message : String(err)}` }], isError: true };+ }+ }+ );+// ---- Start ----const transport = new StdioServerTransport();await server.connect(transport);diff --git a/src/merge-cli.ts b/src/merge-cli.tsnew file mode 100644index 0000000..f9007f5--- /dev/null+++ b/src/merge-cli.ts@@ -0,0 +1,296 @@+import fs from "fs";+import path from "path";+import pc from "picocolors";+import { KnowledgeDB } from "./db.js";+import { MergeEngine, stripMergeSuffix, MERGE_SUFFIX_LEFT, MERGE_SUFFIX_RIGHT } from "./merge.js";+import { errorBold, success, info, error } from "./cli-utils.js";+import type { NodeRow } from "./types.js";++// ---- Flag parsing helpers ----++function getFlag(args: string[], flag: string): string | undefined {+ const idx = args.indexOf(flag);+ return idx !== -1 && args[idx + 1] ? args[idx + 1] : undefined;+}++function hasFlag(args: string[], flag: string): boolean {+ return args.includes(flag);+}++// Boolean flags that don't consume a following value+const BOOLEAN_FLAGS = new Set(["--json"]);++function getPositionalArgs(args: string[]): string[] {+ const positional: string[] = [];+ let i = 0;+ while (i < args.length) {+ if (args[i].startsWith("--")) {+ if (BOOLEAN_FLAGS.has(args[i])) {+ // Boolean flag — skip only the flag itself+ i += 1;+ } else {+ // Value flag — skip the flag and its value+ i += 2;+ }+ } else {+ positional.push(args[i]);+ i++;+ }+ }+ return positional;+}++// ---- merge command ----++export async function runMerge(args: string[]): Promise<void> {+ const positional = getPositionalArgs(args);++ if (positional.length < 2) {+ errorBold("Usage: megamemory merge <file1> <file2> [--into <output>] [--left-label <name>] [--right-label <name>]");+ process.exit(1);+ }++ const file1 = path.resolve(positional[0]);+ const file2 = path.resolve(positional[1]);+ const into = getFlag(args, "--into");+ const leftLabel = getFlag(args, "--left-label");+ const rightLabel = getFlag(args, "--right-label");++ // Default output: overwrite file1+ const outputPath = into ? path.resolve(into) : file1;++ if (!fs.existsSync(file1)) {+ errorBold(`File not found: ${file1}`);+ process.exit(1);+ }+ if (!fs.existsSync(file2)) {+ errorBold(`File not found: ${file2}`);+ process.exit(1);+ }++ // If overwriting file1, write to a temp file first then rename+ const isOverwrite = outputPath === file1;+ const actualOutput = isOverwrite+ ? `${outputPath}.merge-tmp-${Date.now()}`+ : outputPath;++ try {+ const engine = new MergeEngine();+ const result = engine.merge(file1, file2, actualOutput, { leftLabel, rightLabel });++ if (isOverwrite) {+ fs.renameSync(actualOutput, outputPath);+ }++ const totalConflicts = result.conceptConflicts + result.edgeConflicts;+ const conflictDetail = totalConflicts > 0+ ? ` (${result.conceptConflicts} concept${result.conceptConflicts !== 1 ? "s" : ""}, ${result.edgeConflicts} edge${result.edgeConflicts !== 1 ? "s" : ""})`+ : "";++ if (totalConflicts === 0) {+ success(+ `Merged: ${result.clean} clean, ${result.removedClean} removed, 0 conflicts`+ );+ } else {+ console.log(+ pc.yellow(` ⚠ Merged: ${result.clean} clean, ${totalConflicts} conflicts${conflictDetail}`)+ );+ info(`Run ${pc.cyan("megamemory conflicts")} to view, or let your AI agent run ${pc.cyan("/merge")} to resolve.`);+ }+ } catch (err) {+ // Clean up temp file on error+ if (isOverwrite && fs.existsSync(actualOutput)) {+ fs.unlinkSync(actualOutput);+ }+ errorBold(err instanceof Error ? err.message : String(err));+ process.exit(1);+ }+}++// ---- conflicts command ----++export async function runConflicts(args: string[]): Promise<void> {+ const dbPath = getFlag(args, "--db") ?? getDefaultDbPath();+ const json = hasFlag(args, "--json");++ if (!fs.existsSync(dbPath)) {+ errorBold(`Database not found: ${dbPath}`);+ process.exit(1);+ }++ const db = new KnowledgeDB(dbPath);+ try {+ const conflictNodes = db.getConflictNodes();++ if (conflictNodes.length === 0) {+ if (json) {+ console.log(JSON.stringify({ conflicts: [] }, null, 2));+ } else {+ success("No unresolved conflicts.");+ }+ return;+ }++ // Group by merge_group+ const groups = new Map<string, NodeRow[]>();+ for (const node of conflictNodes) {+ const mg = node.merge_group!;+ if (!groups.has(mg)) groups.set(mg, []);+ groups.get(mg)!.push(node);+ }++ if (json) {+ const output = {+ conflicts: Array.from(groups.entries()).map(([mergeGroup, nodes]) => ({+ merge_group: mergeGroup,+ merge_timestamp: nodes[0].merge_timestamp,+ versions: nodes.map((n) => ({+ id: n.id,+ original_id: stripMergeSuffix(n.id),+ source_branch: n.source_branch,+ name: n.name,+ kind: n.kind,+ summary: n.summary,+ why: n.why,+ file_refs: n.file_refs ? JSON.parse(n.file_refs) : null,+ removed_at: n.removed_at,+ })),+ })),+ };+ console.log(JSON.stringify(output, null, 2));+ return;+ }++ // Human-readable output+ console.log(+ pc.bold(`\n ${groups.size} unresolved conflict${groups.size !== 1 ? "s" : ""}:\n`)+ );++ for (const [mergeGroup, nodes] of groups) {+ const shortGroup = mergeGroup.slice(0, 8);+ const originalId = stripMergeSuffix(nodes[0].id);+ console.log(pc.yellow(` ── ${pc.bold(originalId)} ${pc.dim(`[${shortGroup}...]`)}`));++ for (const node of nodes) {+ const branch = node.source_branch ?? "unknown";+ const truncSummary = node.summary.length > 80+ ? node.summary.slice(0, 77) + "..."+ : node.summary;+ const isRemoved = node.removed_at !== null;++ console.log(+ ` ${pc.cyan(branch)}${isRemoved ? pc.red(" [removed]") : ""}: ${pc.dim(truncSummary)}`+ );++ if (node.file_refs) {+ const refs = JSON.parse(node.file_refs) as string[];+ if (refs.length > 0) {+ console.log(` ${pc.dim("files: " + refs.slice(0, 3).join(", ") + (refs.length > 3 ? ` +${refs.length - 3} more` : ""))}`);+ }+ }+ }+ console.log();+ }++ info(`Resolve with: ${pc.cyan("megamemory resolve <merge_group> --keep <left|right|both>")}`);+ console.log();+ } finally {+ db.close();+ }+}++// ---- resolve command ----++export async function runResolve(args: string[]): Promise<void> {+ const positional = getPositionalArgs(args);++ if (positional.length < 1) {+ errorBold("Usage: megamemory resolve <merge_group> --keep <left|right|both>");+ process.exit(1);+ }++ const mergeGroup = positional[0];+ const keep = getFlag(args, "--keep") as "left" | "right" | "both" | undefined;+ const dbPath = getFlag(args, "--db") ?? getDefaultDbPath();++ if (!keep || !["left", "right", "both"].includes(keep)) {+ errorBold("--keep is required and must be one of: left, right, both");+ process.exit(1);+ }++ if (!fs.existsSync(dbPath)) {+ errorBold(`Database not found: ${dbPath}`);+ process.exit(1);+ }++ const db = new KnowledgeDB(dbPath);+ try {+ const nodes = db.getNodesByMergeGroup(mergeGroup);+ if (nodes.length === 0) {+ errorBold(`No nodes found with merge_group: ${mergeGroup}`);+ process.exit(1);+ }++ const leftNode = nodes.find((n) => n.id.endsWith(MERGE_SUFFIX_LEFT));+ const rightNode = nodes.find((n) => n.id.endsWith(MERGE_SUFFIX_RIGHT));++ if (!leftNode && !rightNode) {+ errorBold("Could not identify left/right versions in this merge group.");+ process.exit(1);+ }++ const originalId = stripMergeSuffix(nodes[0].id);++ if (keep === "both") {+ // Keep both as separate concepts with new unique IDs+ if (leftNode) {+ const newId = `${originalId}-${leftNode.source_branch ?? "left"}`;+ db.renameNodeId(leftNode.id, newId);+ db.clearNodeMergeFlags(newId);+ }+ if (rightNode) {+ const newId = `${originalId}-${rightNode.source_branch ?? "right"}`;+ db.renameNodeId(rightNode.id, newId);+ db.clearNodeMergeFlags(newId);+ }+ db.clearEdgeMergeFlagsByGroup(mergeGroup);+ success(`Kept both versions of "${originalId}" as separate concepts.`);+ } else {+ // keep left or right+ const winner = keep === "left" ? leftNode : rightNode;+ const loser = keep === "left" ? rightNode : leftNode;++ if (!winner) {+ errorBold(`No ${keep} version found in this merge group.`);+ process.exit(1);+ }++ // Remove loser first (before renaming winner to avoid ID collision)+ if (loser) {+ db.hardDeleteNode(loser.id);+ }++ // Rename winner to original ID+ db.renameNodeId(winner.id, originalId);+ db.clearNodeMergeFlags(originalId);+ db.clearEdgeMergeFlagsByGroup(mergeGroup);++ const keptBranch = winner.source_branch ?? keep;+ success(`Resolved "${originalId}" — kept ${pc.cyan(keptBranch)} version.`);++ if (loser) {+ info(`Removed ${pc.dim(loser.source_branch ?? (keep === "left" ? "right" : "left"))} version.`);+ }+ }+ } finally {+ db.close();+ }+}++// ---- helpers ----++function getDefaultDbPath(): string {+ const envPath = process.env.MEGAMEMORY_DB_PATH;+ if (envPath) return envPath;+ return path.join(process.cwd(), ".megamemory", "knowledge.db");+}diff --git a/src/merge.ts b/src/merge.tsnew file mode 100644index 0000000..1798b9c--- /dev/null+++ b/src/merge.ts@@ -0,0 +1,540 @@+import { randomUUID } from "crypto";+import { KnowledgeDB } from "./db.js";+import type { NodeRow, EdgeRow, MergeResult } from "./types.js";++export const MERGE_SUFFIX_LEFT = "::left";+export const MERGE_SUFFIX_RIGHT = "::right";++export interface MergeOptions {+ leftLabel?: string;+ rightLabel?: string;+}++/**+ * Strip the merge suffix (::left or ::right) from an ID.+ */+export function stripMergeSuffix(id: string): string {+ if (id.endsWith(MERGE_SUFFIX_LEFT)) return id.slice(0, -MERGE_SUFFIX_LEFT.length);+ if (id.endsWith(MERGE_SUFFIX_RIGHT)) return id.slice(0, -MERGE_SUFFIX_RIGHT.length);+ return id;+}++/**+ * Check if an ID has a merge suffix.+ */+export function hasMergeSuffix(id: string): boolean {+ return id.endsWith(MERGE_SUFFIX_LEFT) || id.endsWith(MERGE_SUFFIX_RIGHT);+}++/**+ * Deep comparison of two nodes' content fields (ignoring timestamps, embedding, merge metadata).+ */+export function nodesAreIdentical(left: NodeRow, right: NodeRow): boolean {+ if (left.name !== right.name) return false;+ if (left.kind !== right.kind) return false;+ if (left.summary !== right.summary) return false;+ if ((left.why ?? "") !== (right.why ?? "")) return false;+ if ((left.parent_id ?? "") !== (right.parent_id ?? "")) return false;++ // Deep-compare file_refs (stored as JSON strings)+ const leftRefs = left.file_refs ? JSON.parse(left.file_refs) : null;+ const rightRefs = right.file_refs ? JSON.parse(right.file_refs) : null;+ if (JSON.stringify(leftRefs) !== JSON.stringify(rightRefs)) return false;++ // Check removed state+ const leftRemoved = left.removed_at !== null;+ const rightRemoved = right.removed_at !== null;+ if (leftRemoved !== rightRemoved) return false;++ return true;+}++/**+ * Create a normalized edge key for comparison (ignoring IDs and timestamps).+ */+function edgeKey(e: EdgeRow): string {+ return `${e.from_id}|${e.to_id}|${e.relation}|${e.description ?? ""}`;+}++/**+ * Compare two sets of edges by their content (from_id, to_id, relation, description).+ */+export function edgeSetsAreIdentical(left: EdgeRow[], right: EdgeRow[]): boolean {+ if (left.length !== right.length) return false;+ const leftKeys = new Set(left.map(edgeKey));+ const rightKeys = new Set(right.map(edgeKey));+ if (leftKeys.size !== rightKeys.size) return false;+ for (const k of leftKeys) {+ if (!rightKeys.has(k)) return false;+ }+ return true;+}++/**+ * MergeEngine: Merges two knowledge.db files into an output file.+ *+ * Opens left and right DBs read-only, writes to a fresh output DB.+ * Detects conflicts, assigns merge_group UUIDs, and sets needs_merge flags.+ */+export class MergeEngine {+ merge(+ leftPath: string,+ rightPath: string,+ outputPath: string,+ options?: MergeOptions+ ): MergeResult {+ const leftLabel = options?.leftLabel ?? "left";+ const rightLabel = options?.rightLabel ?? "right";++ const leftDb = new KnowledgeDB(leftPath);+ const rightDb = new KnowledgeDB(rightPath);+ const outputDb = new KnowledgeDB(outputPath);++ try {+ return this.performMerge(leftDb, rightDb, outputDb, leftLabel, rightLabel);+ } finally {+ leftDb.close();+ rightDb.close();+ outputDb.close();+ }+ }++ private performMerge(+ leftDb: KnowledgeDB,+ rightDb: KnowledgeDB,+ outputDb: KnowledgeDB,+ leftLabel: string,+ rightLabel: string+ ): MergeResult {+ const leftNodes = leftDb.getAllNodesRaw();+ const rightNodes = rightDb.getAllNodesRaw();+ const leftEdges = leftDb.getAllEdgesRaw();+ const rightEdges = rightDb.getAllEdgesRaw();++ const leftNodeMap = new Map<string, NodeRow>();+ const rightNodeMap = new Map<string, NodeRow>();+ const leftVariantsByCanonical = new Map<string, NodeRow[]>();+ const rightVariantsByCanonical = new Map<string, NodeRow[]>();++ for (const n of leftNodes) {+ leftNodeMap.set(n.id, n);+ const canonical = stripMergeSuffix(n.id);+ if (!leftVariantsByCanonical.has(canonical)) leftVariantsByCanonical.set(canonical, []);+ leftVariantsByCanonical.get(canonical)!.push(n);+ }+ for (const n of rightNodes) {+ rightNodeMap.set(n.id, n);+ const canonical = stripMergeSuffix(n.id);+ if (!rightVariantsByCanonical.has(canonical)) rightVariantsByCanonical.set(canonical, []);+ rightVariantsByCanonical.get(canonical)!.push(n);+ }++ // Build edge maps keyed by node ID+ const leftEdgeMap = new Map<string, EdgeRow[]>();+ const rightEdgeMap = new Map<string, EdgeRow[]>();++ for (const e of leftEdges) {+ if (!leftEdgeMap.has(e.from_id)) leftEdgeMap.set(e.from_id, []);+ leftEdgeMap.get(e.from_id)!.push(e);+ }+ for (const e of rightEdges) {+ if (!rightEdgeMap.has(e.from_id)) rightEdgeMap.set(e.from_id, []);+ rightEdgeMap.get(e.from_id)!.push(e);+ }++ // Collect all unique IDs (strip any existing merge suffixes to get canonical IDs)+ const allIds = new Set<string>();+ for (const id of leftNodeMap.keys()) allIds.add(stripMergeSuffix(id));+ for (const id of rightNodeMap.keys()) allIds.add(stripMergeSuffix(id));++ const result: MergeResult = {+ clean: 0,+ conceptConflicts: 0,+ edgeConflicts: 0,+ removedClean: 0,+ mergeGroups: [],+ };++ const now = new Date().toISOString().replace("T", " ").replace("Z", "");++ // Track which IDs were suffixed (for edge remapping)+ const idRemapping = new Map<string, string>(); // "side:originalId" → suffixedId++ // Deferred edge operations — we insert all nodes first, then edges,+ // to avoid FOREIGN KEY constraint failures when edges reference nodes+ // that haven't been inserted yet.+ type DeferredEdge = {+ from_id: string;+ to_id: string;+ relation: string;+ description: string | null;+ created_at: string | null;+ merge_group: string | null;+ needs_merge: number;+ source_branch: string | null;+ merge_timestamp: string | null;+ _originSide: "left" | "right"; // tracks which input DB this edge came from+ };+ const deferredEdges: DeferredEdge[] = [];+ const insertedNodeIds = new Set<string>();+ const seenPreexistingEdgeKeys = new Set<string>();++ const insertNodeOnce = (node: NodeRow): void => {+ if (insertedNodeIds.has(node.id)) return;+ this.insertNodeAsIs(outputDb, node);+ insertedNodeIds.add(node.id);+ };++ const deferPreexistingEdge = (+ e: EdgeRow,+ originSide: "left" | "right"+ ): void => {+ const key = `${e.from_id}|${e.to_id}|${e.relation}|${e.description ?? ""}|${e.merge_group ?? ""}|${e.needs_merge}|${e.source_branch ?? ""}|${e.merge_timestamp ?? ""}`;+ if (seenPreexistingEdgeKeys.has(key)) return;+ seenPreexistingEdgeKeys.add(key);++ deferredEdges.push({+ from_id: e.from_id,+ to_id: e.to_id,+ relation: e.relation,+ description: e.description,+ created_at: e.created_at,+ merge_group: e.merge_group,+ needs_merge: e.needs_merge,+ source_branch: e.source_branch,+ merge_timestamp: e.merge_timestamp,+ _originSide: originSide,+ });+ };++ // ---- PASS 1: Insert all nodes ----++ // Track which canonical IDs were processed as conflicts vs clean+ const conflictIds = new Set<string>();++ for (const id of allIds) {+ const leftVariants = leftVariantsByCanonical.get(id) ?? [];+ const rightVariants = rightVariantsByCanonical.get(id) ?? [];+ const leftNode = leftNodeMap.get(id);+ const rightNode = rightNodeMap.get(id);++ // Handle pre-existing conflicts (nodes already have ::left/::right IDs from prior merge).+ const preexistingLeft = leftVariants.filter(+ (n) => n.needs_merge === 1 && !!n.merge_group && hasMergeSuffix(n.id)+ );+ const preexistingRight = rightVariants.filter(+ (n) => n.needs_merge === 1 && !!n.merge_group && hasMergeSuffix(n.id)+ );++ if (preexistingLeft.length > 0 || preexistingRight.length > 0) {+ const preexistingAll = [...preexistingLeft, ...preexistingRight];++ // Carry forward all unresolved versions as-is.+ for (const node of preexistingAll) {+ insertNodeOnce(node);+ }++ // Ensure edges from clean nodes can still remap to a valid conflicted target.+ const leftTarget =+ preexistingAll.find((n) => n.id.endsWith(MERGE_SUFFIX_LEFT)) ??+ preexistingAll[0];+ const rightTarget =+ preexistingAll.find((n) => n.id.endsWith(MERGE_SUFFIX_RIGHT)) ??+ preexistingAll[preexistingAll.length - 1] ??+ preexistingAll[0];++ if (leftTarget) idRemapping.set(`left:${id}`, leftTarget.id);+ if (rightTarget) idRemapping.set(`right:${id}`, rightTarget.id);++ // Carry forward outgoing edges from conflicted source nodes.+ for (const node of preexistingLeft) {+ const edges = leftEdgeMap.get(node.id) ?? [];+ for (const e of edges) {+ deferPreexistingEdge(e, "left");+ }+ }+ for (const node of preexistingRight) {+ const edges = rightEdgeMap.get(node.id) ?? [];+ for (const e of edges) {+ deferPreexistingEdge(e, "right");+ }+ }++ conflictIds.add(id);+ continue;+ }++ if (!leftNode && rightNode) {+ // Only in right+ insertNodeOnce(rightNode);+ if (rightNode.removed_at) {+ result.removedClean++;+ } else {+ result.clean++;+ }+ } else if (leftNode && !rightNode) {+ // Only in left+ insertNodeOnce(leftNode);+ if (leftNode.removed_at) {+ result.removedClean++;+ } else {+ result.clean++;+ }+ } else if (leftNode && rightNode) {+ if (nodesAreIdentical(leftNode, rightNode)) {+ // Identical — keep left's copy+ insertNodeOnce(leftNode);+ if (leftNode.removed_at) {+ result.removedClean++;+ } else {+ result.clean++;+ }+ } else {+ // Conflict — insert both with suffixed IDs+ conflictIds.add(id);+ const mergeGroup = randomUUID();+ result.mergeGroups.push(mergeGroup);+ result.conceptConflicts++;++ const leftSuffixed = `${id}${MERGE_SUFFIX_LEFT}`;+ const rightSuffixed = `${id}${MERGE_SUFFIX_RIGHT}`;++ idRemapping.set(`left:${id}`, leftSuffixed);+ idRemapping.set(`right:${id}`, rightSuffixed);++ this.insertConflictNode(outputDb, leftNode, leftSuffixed, mergeGroup, leftLabel, now);+ this.insertConflictNode(outputDb, rightNode, rightSuffixed, mergeGroup, rightLabel, now);++ // Defer edge handling for conflicting nodes+ const leftNodeEdges = leftEdgeMap.get(id) ?? [];+ const rightNodeEdges = rightEdgeMap.get(id) ?? [];+ const edgesConflict = !edgeSetsAreIdentical(leftNodeEdges, rightNodeEdges);++ if (edgesConflict && (leftNodeEdges.length > 0 || rightNodeEdges.length > 0)) {+ result.edgeConflicts++;+ }++ for (const e of leftNodeEdges) {+ deferredEdges.push({+ from_id: leftSuffixed,+ to_id: e.to_id, // will be remapped in pass 2+ relation: e.relation,+ description: e.description,+ created_at: e.created_at,+ merge_group: edgesConflict ? mergeGroup : null,+ needs_merge: edgesConflict ? 1 : 0,+ source_branch: edgesConflict ? leftLabel : null,+ merge_timestamp: edgesConflict ? now : null,+ _originSide: "left",+ });+ }++ for (const e of rightNodeEdges) {+ deferredEdges.push({+ from_id: rightSuffixed,+ to_id: e.to_id, // will be remapped in pass 2+ relation: e.relation,+ description: e.description,+ created_at: e.created_at,+ merge_group: edgesConflict ? mergeGroup : null,+ needs_merge: edgesConflict ? 1 : 0,+ source_branch: edgesConflict ? rightLabel : null,+ merge_timestamp: edgesConflict ? now : null,+ _originSide: "right",+ });+ }+ }+ }+ }++ // ---- PASS 2: Insert all edges ----++ // First, collect non-conflict edges+ for (const id of allIds) {+ if (conflictIds.has(id)) continue; // handled via deferred edges++ const leftNode = leftNodeMap.get(id);+ const rightNode = rightNodeMap.get(id);++ // Skip pre-existing conflicts+ if (leftNode && leftNode.needs_merge && leftNode.merge_group) continue;++ if (!leftNode && rightNode) {+ this.deferEdgesForNode(deferredEdges, rightEdgeMap, rightNode.id, idRemapping, "right");+ } else if (leftNode && !rightNode) {+ this.deferEdgesForNode(deferredEdges, leftEdgeMap, leftNode.id, idRemapping, "left");+ } else if (leftNode && rightNode) {+ // Identical nodes — union of edges from both sides+ this.deferEdgesClean(deferredEdges, leftEdgeMap, rightEdgeMap, leftNode.id, idRemapping);+ }+ }++ // Now insert all deferred edges, remapping target IDs where needed+ for (const edge of deferredEdges) {+ // Remap to_id if the target was conflicted — use _originSide to determine+ // which suffixed version to point at (not from_id suffix, which may be absent+ // for edges from non-conflicted nodes)+ const remappedToId = idRemapping.get(`${edge._originSide}:${edge.to_id}`) ?? edge.to_id;++ outputDb.insertEdgeRaw({+ from_id: edge.from_id,+ to_id: remappedToId,+ relation: edge.relation,+ description: edge.description,+ created_at: edge.created_at,+ merge_group: edge.merge_group,+ needs_merge: edge.needs_merge,+ source_branch: edge.source_branch,+ merge_timestamp: edge.merge_timestamp,+ });+ }++ return result;+ }++ private insertNodeAsIs(db: KnowledgeDB, node: NodeRow): void {+ db.insertNodeRaw({+ id: node.id,+ name: node.name,+ kind: node.kind,+ summary: node.summary,+ why: node.why,+ file_refs: node.file_refs,+ parent_id: node.parent_id,+ created_by_task: node.created_by_task,+ created_at: node.created_at,+ updated_at: node.updated_at,+ removed_at: node.removed_at,+ removed_reason: node.removed_reason,+ embedding: node.embedding,+ merge_group: node.merge_group,+ needs_merge: node.needs_merge,+ source_branch: node.source_branch,+ merge_timestamp: node.merge_timestamp,+ });+ }++ private insertConflictNode(+ db: KnowledgeDB,+ node: NodeRow,+ suffixedId: string,+ mergeGroup: string,+ sourceLabel: string,+ timestamp: string+ ): void {+ db.insertNodeRaw({+ id: suffixedId,+ name: node.name,+ kind: node.kind,+ summary: node.summary,+ why: node.why,+ file_refs: node.file_refs,+ parent_id: node.parent_id,+ created_by_task: node.created_by_task,+ created_at: node.created_at,+ updated_at: node.updated_at,+ removed_at: node.removed_at,+ removed_reason: node.removed_reason,+ embedding: node.embedding,+ merge_group: mergeGroup,+ needs_merge: 1,+ source_branch: sourceLabel,+ merge_timestamp: timestamp,+ });+ }++ /**+ * Defer edges for a non-conflicting node into the deferred list.+ */+ private deferEdgesForNode(+ deferred: Array<{+ from_id: string; to_id: string; relation: string;+ description: string | null; created_at: string | null;+ merge_group: string | null; needs_merge: number;+ source_branch: string | null; merge_timestamp: string | null;+ _originSide: "left" | "right";+ }>,+ edgeMap: Map<string, EdgeRow[]>,+ nodeId: string,+ _idRemapping: Map<string, string>,+ side: "left" | "right"+ ): void {+ const edges = edgeMap.get(nodeId) ?? [];+ for (const e of edges) {+ deferred.push({+ from_id: e.from_id,+ to_id: e.to_id,+ relation: e.relation,+ description: e.description,+ created_at: e.created_at,+ merge_group: null,+ needs_merge: 0,+ source_branch: null,+ merge_timestamp: null,+ _originSide: side,+ });+ }+ }++ /**+ * For identical nodes, defer the union of edges from both sides (deduplicated).+ */+ private deferEdgesClean(+ deferred: Array<{+ from_id: string; to_id: string; relation: string;+ description: string | null; created_at: string | null;+ merge_group: string | null; needs_merge: number;+ source_branch: string | null; merge_timestamp: string | null;+ _originSide: "left" | "right";+ }>,+ leftEdgeMap: Map<string, EdgeRow[]>,+ rightEdgeMap: Map<string, EdgeRow[]>,+ nodeId: string,+ _idRemapping: Map<string, string>+ ): void {+ const leftEdges = leftEdgeMap.get(nodeId) ?? [];+ const rightEdges = rightEdgeMap.get(nodeId) ?? [];++ const seen = new Set<string>();++ // Process left edges first, then right — deduplicate by content key+ for (const e of leftEdges) {+ const key = edgeKey(e);+ if (seen.has(key)) continue;+ seen.add(key);++ deferred.push({+ from_id: e.from_id,+ to_id: e.to_id,+ relation: e.relation,+ description: e.description,+ created_at: e.created_at,+ merge_group: null,+ needs_merge: 0,+ source_branch: null,+ merge_timestamp: null,+ _originSide: "left",+ });+ }++ for (const e of rightEdges) {+ const key = edgeKey(e);+ if (seen.has(key)) continue;+ seen.add(key);++ deferred.push({+ from_id: e.from_id,+ to_id: e.to_id,+ relation: e.relation,+ description: e.description,+ created_at: e.created_at,+ merge_group: null,+ needs_merge: 0,+ source_branch: null,+ merge_timestamp: null,+ _originSide: "right",+ });+ }+ }++}diff --git a/src/tools.ts b/src/tools.tsindex 2908494..5f9c96a 100644--- a/src/tools.ts+++ b/src/tools.ts@@ -6,12 +6,16 @@ import type {UpdateConceptInput,LinkInput,RemoveConceptInput,+ ResolveConflictInput,NodeWithContext,UnderstandOutput,ListRootsOutput,+ ListConflictsOutput,+ ConflictGroup,NodeRow,RelationType,} from "./types.js";+import { stripMergeSuffix } from "./merge.js";/*** Generate a slug ID from a name, optionally prefixed with parent ID.@@ -280,3 +284,115 @@ export function listRoots(db: KnowledgeDB): ListRootsOutput & { hint?: string }return { roots, ...(hint ? { hint } : {}) };}++// ---- Merge conflict tools ----++export function listConflicts(db: KnowledgeDB): ListConflictsOutput {+ const conflictNodes = db.getConflictNodes();++ if (conflictNodes.length === 0) {+ return { conflicts: [] };+ }++ // Group by merge_group+ const groups = new Map<string, NodeRow[]>();+ for (const node of conflictNodes) {+ const mg = node.merge_group!;+ if (!groups.has(mg)) groups.set(mg, []);+ groups.get(mg)!.push(node);+ }++ const conflicts: ConflictGroup[] = [];++ for (const [mergeGroup, nodes] of groups) {+ const versions = nodes.map((n) => {+ const outgoingEdges = db.getOutgoingEdges(n.id);+ const fileRefs = n.file_refs ? JSON.parse(n.file_refs) : null;++ return {+ id: n.id,+ original_id: stripMergeSuffix(n.id),+ source_branch: n.source_branch ?? "unknown",+ name: n.name,+ kind: n.kind as NodeWithContext["kind"],+ summary: n.summary,+ why: n.why,+ file_refs: fileRefs,+ edges: outgoingEdges.map((e) => ({+ to: e.to_id,+ relation: e.relation as RelationType,+ description: e.description,+ })),+ removed_at: n.removed_at,+ removed_reason: n.removed_reason,+ };+ });++ conflicts.push({+ merge_group: mergeGroup,+ merge_timestamp: nodes[0].merge_timestamp,+ versions,+ });+ }++ return { conflicts };+}++export async function resolveConflict(+ db: KnowledgeDB,+ input: ResolveConflictInput+): Promise<{ message: string }> {+ const nodes = db.getNodesByMergeGroup(input.merge_group);++ if (nodes.length === 0) {+ throw new Error(`No nodes found with merge_group: ${input.merge_group}`);+ }++ // Prefer an active (non-removed) node as the base so the resolved concept+ // stays active for removal conflicts. Fall back to first node.+ const base = nodes.find((n) => n.removed_at === null) ?? nodes[0];+ const originalId = stripMergeSuffix(base.id);++ // Delete all conflict copies except the base+ for (const node of nodes) {+ if (node.id !== base.id) {+ db.hardDeleteNode(node.id);+ }+ }++ // Rename the base back to the original clean ID+ if (base.id !== originalId) {+ const renamed = db.renameNodeId(base.id, originalId);+ if (!renamed) {+ throw new Error(`Failed to rename resolved node from ${base.id} to ${originalId}`);+ }+ }++ // Apply the resolved content+ const changes: { summary?: string; why?: string; file_refs?: string[] } = {+ summary: input.resolved.summary,+ };+ if (input.resolved.why !== undefined) changes.why = input.resolved.why;+ if (input.resolved.file_refs !== undefined) changes.file_refs = input.resolved.file_refs;++ const updated = db.updateNode(originalId, changes);+ if (!updated) {+ throw new Error(`Failed to apply resolved content to ${originalId}`);+ }++ // Regenerate embedding with the resolved summary+ const node = db.getNode(originalId);+ if (node) {+ const text = embeddingText(node.name, node.kind, input.resolved.summary);+ const newEmbedding = await embed(text);+ db.updateNode(originalId, { embedding: newEmbedding });+ }++ // Clear merge flags on the resolved node and any associated edges+ db.clearNodeMergeFlags(originalId);+ db.clearEdgeMergeFlagsByGroup(input.merge_group);++ return {+ message: `Resolved "${originalId}". Reason: ${input.reason}`,+ };+}diff --git a/src/types.ts b/src/types.tsindex d0d79cf..38d41cb 100644--- a/src/types.ts+++ b/src/types.ts@@ -13,6 +13,10 @@ export interface Node {updated_at: string;removed_at: string | null;removed_reason: string | null;+ merge_group: string | null;+ needs_merge: boolean;+ source_branch: string | null;+ merge_timestamp: string | null;}export type NodeKind =@@ -30,6 +34,10 @@ export interface Edge {relation: RelationType;description: string | null;created_at: string;+ merge_group: string | null;+ needs_merge: boolean;+ source_branch: string | null;+ merge_timestamp: string | null;}export type RelationType =@@ -150,6 +158,10 @@ export interface NodeRow {removed_at: string | null;removed_reason: string | null;embedding: Buffer | null;+ merge_group: string | null;+ needs_merge: number; // SQLite stores boolean as 0/1+ source_branch: string | null;+ merge_timestamp: string | null;}export interface EdgeRow {@@ -159,4 +171,52 @@ export interface EdgeRow {relation: string;description: string | null;created_at: string;+ merge_group: string | null;+ needs_merge: number; // SQLite stores boolean as 0/1+ source_branch: string | null;+ merge_timestamp: string | null;+}++// ---- Merge types ----++export interface ConflictVersion {+ id: string;+ original_id: string;+ source_branch: string;+ name: string;+ kind: NodeKind;+ summary: string;+ why: string | null;+ file_refs: string[] | null;+ edges: Array<{ to: string; relation: RelationType; description: string | null }>;+ removed_at: string | null;+ removed_reason: string | null;+}++export interface ConflictGroup {+ merge_group: string;+ merge_timestamp: string | null;+ versions: ConflictVersion[];+}++export interface ListConflictsOutput {+ conflicts: ConflictGroup[];+}++export interface ResolveConflictInput {+ merge_group: string;+ resolved: {+ summary: string;+ why?: string;+ file_refs?: string[];+ };+ reason: string;+}++export interface MergeResult {+ clean: number;+ conceptConflicts: number;+ edgeConflicts: number;+ removedClean: number;+ mergeGroups: string[];}