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
fix(install): preserve existing user files
0xk3vine4596198b682
diff --git a/README.md b/README.mdindex 99772d5..e280ad9 100644--- a/README.md+++ b/README.md@@ -53,6 +53,9 @@ megamemory installRun the interactive installer and choose your editor:+> [!NOTE]+> The installer only updates config files after a successful read/merge, and it will not overwrite existing plugin/command files unless they are already marked as MegaMemory-managed.+#### With [opencode](https://opencode.ai)```bashdiff --git a/commands/bootstrap-memory.md b/commands/bootstrap-memory.mdindex c871acf..b15ec9f 100644--- a/commands/bootstrap-memory.md+++ b/commands/bootstrap-memory.md@@ -1,3 +1,4 @@+<!-- MegaMemory-managed file. Safe for megamemory install to update. --># Bootstrap Project Knowledge GraphRUN { git ls-files; git ls-files --others --exclude-standard; } 2>/dev/null | sort -u | xargs wc -l 2>/dev/null | sort -rn | head -150diff --git a/commands/save-memory.md b/commands/save-memory.mdindex b6f3bc4..ac26724 100644--- a/commands/save-memory.md+++ b/commands/save-memory.md@@ -1,3 +1,4 @@+<!-- MegaMemory-managed file. Safe for megamemory install to update. --># Save Session KnowledgeYou are saving what you learned this session into the megamemory knowledge graph.diff --git a/plugin/megamemory.ts b/plugin/megamemory.tsindex 535fa74..ee53979 100644--- a/plugin/megamemory.ts+++ b/plugin/megamemory.ts@@ -1,3 +1,4 @@+// MegaMemory-managed file. Safe for megamemory install to update.import { tool } from "@opencode-ai/plugin";const SKILL = `diff --git a/src/__tests__/install.test.ts b/src/__tests__/install.test.tsnew file mode 100644index 0000000..3d99d6f--- /dev/null+++ b/src/__tests__/install.test.ts@@ -0,0 +1,220 @@+import fs from "fs";+import os from "os";+import path from "path";+import { fileURLToPath } from "url";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++const { execSyncMock } = vi.hoisted(() => ({+ execSyncMock: vi.fn((command: string) => {+ if (+ command === "which megamemory" ||+ command === "where megamemory" ||+ command === "which codex" ||+ command === "where codex"+ ) {+ throw new Error("not found");+ }++ return Buffer.from("");+ }),+}));++vi.mock("child_process", () => ({+ execSync: execSyncMock,+}));++const PROJECT_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..");+const PLUGIN_SOURCE_PATH = path.join(PROJECT_ROOT, "plugin", "megamemory.ts");+const BOOTSTRAP_SOURCE_PATH = path.join(PROJECT_ROOT, "commands", "bootstrap-memory.md");+const SAVE_SOURCE_PATH = path.join(PROJECT_ROOT, "commands", "save-memory.md");+const EXPECTED_ENTRY = path.join(PROJECT_ROOT, "dist", "index.js");++interface Sandbox {+ root: string;+ homeDir: string;+ workspaceDir: string;+ opencodeDir: string;+}++const originalEnv = {+ HOME: process.env.HOME,+ OPENCODE_CONFIG_DIR: process.env.OPENCODE_CONFIG_DIR,+};+const originalCwd = process.cwd();++function makeSandbox(): Sandbox {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), "megamemory-install-test-"));+ const homeDir = path.join(root, "home");+ const workspaceDir = path.join(root, "workspace");+ const opencodeDir = path.join(root, "opencode-config");++ fs.mkdirSync(homeDir, { recursive: true });+ fs.mkdirSync(workspaceDir, { recursive: true });+ fs.mkdirSync(opencodeDir, { recursive: true });++ return { root, homeDir, workspaceDir, opencodeDir };+}++async function loadInstallModule(sandbox: Sandbox) {+ process.env.HOME = sandbox.homeDir;+ process.env.OPENCODE_CONFIG_DIR = sandbox.opencodeDir;+ process.chdir(sandbox.workspaceDir);+ vi.resetModules();+ return import("../install.js");+}++beforeEach(() => {+ execSyncMock.mockClear();+ vi.spyOn(console, "log").mockImplementation(() => undefined);+});++afterEach(() => {+ vi.restoreAllMocks();+ process.chdir(originalCwd);++ if (originalEnv.HOME === undefined) {+ delete process.env.HOME;+ } else {+ process.env.HOME = originalEnv.HOME;+ }++ if (originalEnv.OPENCODE_CONFIG_DIR === undefined) {+ delete process.env.OPENCODE_CONFIG_DIR;+ } else {+ process.env.OPENCODE_CONFIG_DIR = originalEnv.OPENCODE_CONFIG_DIR;+ }+});++describe("runInstall", () => {+ it("merges a valid opencode config without removing unrelated keys", async () => {+ const sandbox = makeSandbox();+ const opencodeConfigPath = path.join(sandbox.opencodeDir, "opencode.json");++ fs.writeFileSync(+ opencodeConfigPath,+ `${JSON.stringify(+ {+ theme: "dark",+ mcp: {+ existing: { type: "remote", url: "https://example.test" },+ },+ },+ null,+ 2+ )}\n`+ );++ const { runInstall } = await loadInstallModule(sandbox);+ await runInstall(["--target", "opencode"]);++ const updated = JSON.parse(fs.readFileSync(opencodeConfigPath, "utf-8"));++ expect(updated.theme).toBe("dark");+ expect(updated.$schema).toBe("https://opencode.ai/config.json");+ expect(updated.mcp.existing).toEqual({ type: "remote", url: "https://example.test" });+ expect(updated.mcp.megamemory).toEqual({+ type: "local",+ command: ["node", EXPECTED_ENTRY],+ enabled: true,+ });+ });++ it("leaves malformed antigravity config untouched", async () => {+ const sandbox = makeSandbox();+ const antigravityConfigPath = path.join(sandbox.workspaceDir, "mcp_config.json");+ const malformed = '{"mcpServers": ';++ fs.writeFileSync(antigravityConfigPath, malformed);++ const { runInstall } = await loadInstallModule(sandbox);+ await runInstall(["--target", "antigravity"]);++ expect(fs.readFileSync(antigravityConfigPath, "utf-8")).toBe(malformed);+ expect(fs.existsSync(`${antigravityConfigPath}.bak`)).toBe(false);+ });++ it("leaves claude config untouched when mcpServers has an unsupported shape", async () => {+ const sandbox = makeSandbox();+ const claudeConfigPath = path.join(sandbox.homeDir, ".claude.json");+ const original = `${JSON.stringify({ mcpServers: [] }, null, 2)}\n`;++ fs.writeFileSync(claudeConfigPath, original);++ const { runInstall } = await loadInstallModule(sandbox);+ await runInstall(["--target", "claudecode"]);++ expect(fs.readFileSync(claudeConfigPath, "utf-8")).toBe(original);+ });++ it("skips later opencode steps when the MCP config step fails", async () => {+ const sandbox = makeSandbox();+ const opencodeConfigPath = path.join(sandbox.opencodeDir, "opencode.json");++ fs.writeFileSync(opencodeConfigPath, '{"mcp": ');++ const { runInstall } = await loadInstallModule(sandbox);+ await runInstall(["--target", "opencode"]);++ expect(fs.readFileSync(opencodeConfigPath, "utf-8")).toBe('{"mcp": ');+ expect(fs.existsSync(path.join(sandbox.opencodeDir, "AGENTS.md"))).toBe(false);+ expect(fs.existsSync(path.join(sandbox.opencodeDir, "tool", "megamemory.ts"))).toBe(false);+ expect(fs.existsSync(path.join(sandbox.opencodeDir, "commands", "bootstrap-memory.md"))).toBe(false);+ expect(fs.existsSync(path.join(sandbox.opencodeDir, "commands", "save-memory.md"))).toBe(false);+ });++ it("updates managed files and skips conflicting unmarked files", async () => {+ const sandbox = makeSandbox();+ const opencodeConfigPath = path.join(sandbox.opencodeDir, "opencode.json");+ const pluginPath = path.join(sandbox.opencodeDir, "tool", "megamemory.ts");+ const bootstrapPath = path.join(sandbox.opencodeDir, "commands", "bootstrap-memory.md");+ const savePath = path.join(sandbox.opencodeDir, "commands", "save-memory.md");++ fs.writeFileSync(opencodeConfigPath, `${JSON.stringify({}, null, 2)}\n`);+ fs.mkdirSync(path.dirname(pluginPath), { recursive: true });+ fs.mkdirSync(path.dirname(bootstrapPath), { recursive: true });+ fs.writeFileSync(+ pluginPath,+ "// MegaMemory-managed file. Safe for megamemory install to update.\nexport default 'old';\n"+ );+ fs.writeFileSync(bootstrapPath, "# My custom command\n");++ const { runInstall } = await loadInstallModule(sandbox);+ await runInstall(["--target", "opencode"]);++ expect(fs.readFileSync(pluginPath, "utf-8")).toBe(fs.readFileSync(PLUGIN_SOURCE_PATH, "utf-8"));+ expect(fs.readFileSync(bootstrapPath, "utf-8")).toBe("# My custom command\n");+ expect(fs.readFileSync(savePath, "utf-8")).toBe(fs.readFileSync(SAVE_SOURCE_PATH, "utf-8"));+ });++ it("is idempotent on repeated opencode installs", async () => {+ const sandbox = makeSandbox();+ const { runInstall } = await loadInstallModule(sandbox);++ await runInstall(["--target", "opencode"]);++ const firstConfig = fs.readFileSync(path.join(sandbox.opencodeDir, "opencode.json"), "utf-8");+ const firstAgents = fs.readFileSync(path.join(sandbox.opencodeDir, "AGENTS.md"), "utf-8");+ const firstPlugin = fs.readFileSync(path.join(sandbox.opencodeDir, "tool", "megamemory.ts"), "utf-8");+ const firstBootstrap = fs.readFileSync(+ path.join(sandbox.opencodeDir, "commands", "bootstrap-memory.md"),+ "utf-8"+ );+ const firstSave = fs.readFileSync(+ path.join(sandbox.opencodeDir, "commands", "save-memory.md"),+ "utf-8"+ );++ await runInstall(["--target", "opencode"]);++ expect(fs.readFileSync(path.join(sandbox.opencodeDir, "opencode.json"), "utf-8")).toBe(firstConfig);+ expect(fs.readFileSync(path.join(sandbox.opencodeDir, "AGENTS.md"), "utf-8")).toBe(firstAgents);+ expect(fs.readFileSync(path.join(sandbox.opencodeDir, "tool", "megamemory.ts"), "utf-8")).toBe(firstPlugin);+ expect(fs.readFileSync(path.join(sandbox.opencodeDir, "commands", "bootstrap-memory.md"), "utf-8")).toBe(+ firstBootstrap+ );+ expect(fs.readFileSync(path.join(sandbox.opencodeDir, "commands", "save-memory.md"), "utf-8")).toBe(firstSave);+ expect(firstPlugin).toBe(fs.readFileSync(PLUGIN_SOURCE_PATH, "utf-8"));+ expect(firstBootstrap).toBe(fs.readFileSync(BOOTSTRAP_SOURCE_PATH, "utf-8"));+ expect(firstSave).toBe(fs.readFileSync(SAVE_SOURCE_PATH, "utf-8"));+ });+});diff --git a/src/install.ts b/src/install.tsindex 6b1eb29..98ec489 100644--- a/src/install.ts+++ b/src/install.ts@@ -10,7 +10,7 @@ export type InstallTarget = "opencode" | "claudecode" | "antigravity" | "codex";interface TargetConfig {label: string;description: string;- steps: Array<{ name: string; run: () => Promise<void> | void }>;+ steps: Array<{ name: string; critical?: boolean; run: () => Promise<void> | void }>;}interface StepResult {@@ -50,6 +50,7 @@ const CODEX_CONFIG_PATH = path.join(CODEX_DIR, "config.toml");const CODEX_AGENTS_MD_PATH = path.join(CODEX_DIR, "AGENTS.md");const AGENTS_MD_MARKER = "## Project Knowledge Graph";+const MANAGED_FILE_MARKER = "MegaMemory-managed file. Safe for megamemory install to update.";const AGENTS_MD_SNIPPET = `## Project Knowledge Graph@@ -142,6 +143,43 @@ function parseJsonc(text: string): unknown {return JSON.parse(stripJsonComments(text));}+function formatConfigReadError(filePath: string, reason: string): Error {+ return new Error(+ `Could not safely update ${filePath}: ${reason}. Left the existing file unchanged.`+ );+}++function readJsonConfigForMerge(+ filePath: string,+ nestedKey: string+): Record<string, unknown> {+ if (!fs.existsSync(filePath)) {+ return {};+ }++ let parsed: unknown;+ try {+ parsed = parseJsonc(fs.readFileSync(filePath, "utf-8"));+ } catch (err) {+ const reason = err instanceof Error ? `could not parse JSON (${err.message})` : "could not parse JSON";+ throw formatConfigReadError(filePath, reason);+ }++ if (!isObject(parsed)) {+ throw formatConfigReadError(filePath, "top-level JSON value is not an object");+ }++ if (nestedKey in parsed && !isObject(parsed[nestedKey])) {+ throw formatConfigReadError(filePath, `'${nestedKey}' is present but is not an object`);+ }++ return parsed;+}++function isManagedInstallFile(content: string): boolean {+ return content.includes(MANAGED_FILE_MARKER);+}+function resolveServerEntryPoint(): string {const thisDir = path.dirname(fileURLToPath(import.meta.url));@@ -245,6 +283,14 @@ function setupToolPlugin(): void {skip(`Tool plugin already up to date`);return;}++ if (!isManagedInstallFile(existing)) {+ warn(+ `Existing tool plugin at ${pc.dim(dest)} is not marked as MegaMemory-managed. Left it untouched.`+ );+ return;+ }+fs.writeFileSync(dest, sourceContent);success(`Updated tool plugin at ${pc.dim(dest)}`);return;@@ -273,6 +319,12 @@ function setupCommand(destinationDir: string, filename: string, label: string):skip(`${label} already up to date`);return;}++ if (!isManagedInstallFile(existing)) {+ warn(`Existing ${label} at ${pc.dim(dest)} is not marked as MegaMemory-managed. Left it untouched.`);+ return;+ }+fs.writeFileSync(dest, sourceContent);success(`Updated ${label} at ${pc.dim(dest)}`);return;@@ -285,19 +337,7 @@ function setupCommand(destinationDir: string, filename: string, label: string):async function setupOpencodeMcpConfig(runtime: CommandRuntime): Promise<void> {fs.mkdirSync(OPENCODE_CONFIG_DIR, { recursive: true });- let config: Record<string, unknown> = {};- if (fs.existsSync(OPENCODE_CONFIG_PATH)) {- try {- const parsed = parseJsonc(fs.readFileSync(OPENCODE_CONFIG_PATH, "utf-8"));- config = isObject(parsed) ? parsed : {};- } catch {- const backup = `${OPENCODE_CONFIG_PATH}.bak`;- fs.copyFileSync(OPENCODE_CONFIG_PATH, backup);- warn(`Could not parse ${pc.dim(OPENCODE_CONFIG_PATH)}; backed it up to ${pc.dim(backup)}.`);- warn("Created a fresh config with only the megamemory entry. Merge your old settings from the backup if needed.");- config = {};- }- }+ const config = readJsonConfigForMerge(OPENCODE_CONFIG_PATH, "mcp");if (!config["$schema"]) {config["$schema"] = "https://opencode.ai/config.json";@@ -324,27 +364,7 @@ async function setupOpencodeMcpConfig(runtime: CommandRuntime): Promise<void> {}async function setupClaudeConfig(runtime: CommandRuntime): Promise<void> {- let config: Record<string, unknown> = {};-- if (fs.existsSync(CLAUDE_CONFIG_PATH)) {- try {- const parsed = parseJsonc(fs.readFileSync(CLAUDE_CONFIG_PATH, "utf-8"));- if (!isObject(parsed)) {- throw new Error("Top-level JSON value is not an object");- }- config = parsed;- } catch (err) {- const backup = `${CLAUDE_CONFIG_PATH}.bak`;- fs.copyFileSync(CLAUDE_CONFIG_PATH, backup);- warn(`Could not parse ${pc.dim(CLAUDE_CONFIG_PATH)}; backed it up to ${pc.dim(backup)}.`);- warn("Created a fresh config with only the megamemory entry. Merge your old settings from the backup if needed.");- throw new Error(- err instanceof Error- ? `Could not parse ${CLAUDE_CONFIG_PATH}: ${err.message}`- : `Could not parse ${CLAUDE_CONFIG_PATH}`- );- }- }+ const config = readJsonConfigForMerge(CLAUDE_CONFIG_PATH, "mcpServers");const mcpServers = isObject(config["mcpServers"]) ? config["mcpServers"] : {};const existed = "megamemory" in mcpServers;@@ -367,20 +387,7 @@ async function setupClaudeConfig(runtime: CommandRuntime): Promise<void> {}async function setupAntigravityConfig(runtime: CommandRuntime): Promise<void> {- let config: Record<string, unknown> = {};-- if (fs.existsSync(ANTIGRAVITY_CONFIG_PATH)) {- try {- const parsed = parseJsonc(fs.readFileSync(ANTIGRAVITY_CONFIG_PATH, "utf-8"));- config = isObject(parsed) ? parsed : {};- } catch {- const backup = `${ANTIGRAVITY_CONFIG_PATH}.bak`;- fs.copyFileSync(ANTIGRAVITY_CONFIG_PATH, backup);- warn(`Could not parse ${pc.dim(ANTIGRAVITY_CONFIG_PATH)}; backed it up to ${pc.dim(backup)}.`);- warn("Created a fresh config with only the megamemory entry. Merge your old settings from the backup if needed.");- config = {};- }- }+ const config = readJsonConfigForMerge(ANTIGRAVITY_CONFIG_PATH, "mcpServers");const mcpServers = isObject(config["mcpServers"]) ? config["mcpServers"] : {};const existed = "megamemory" in mcpServers;@@ -495,7 +502,7 @@ function createTargetConfigs(runtime: CommandRuntime): Record<InstallTarget, Tarlabel: "opencode",description: "MCP server, AGENTS.md, skill plugin, commands",steps: [- { name: "MCP server config", run: () => setupOpencodeMcpConfig(runtime) },+ { name: "MCP server config", critical: true, run: () => setupOpencodeMcpConfig(runtime) },{ name: "Global AGENTS.md", run: () => setupInstructionFile(OPENCODE_AGENTS_MD_PATH) },{ name: "Skill tool plugin", run: () => setupToolPlugin() },{@@ -512,7 +519,7 @@ function createTargetConfigs(runtime: CommandRuntime): Record<InstallTarget, Tarlabel: "Claude Code",description: "MCP server, CLAUDE.md, commands",steps: [- { name: "MCP server config", run: () => setupClaudeConfig(runtime) },+ { name: "MCP server config", critical: true, run: () => setupClaudeConfig(runtime) },{ name: "Global CLAUDE.md", run: () => setupInstructionFile(CLAUDE_MD_PATH) },{name: "Bootstrap command",@@ -528,14 +535,14 @@ function createTargetConfigs(runtime: CommandRuntime): Record<InstallTarget, Tarlabel: "Antigravity",description: "MCP server config (workspace-level)",steps: [- { name: "MCP server config", run: () => setupAntigravityConfig(runtime) },+ { name: "MCP server config", critical: true, run: () => setupAntigravityConfig(runtime) },],},codex: {label: "Codex",description: "MCP server, AGENTS.md",steps: [- { name: "MCP server config", run: () => setupCodexConfig(runtime) },+ { name: "MCP server config", critical: true, run: () => setupCodexConfig(runtime) },{ name: "Global AGENTS.md", run: () => setupInstructionFile(CODEX_AGENTS_MD_PATH) },],},@@ -670,6 +677,11 @@ export async function runInstall(args: string[]): Promise<void> {ok: false,error: msg,});++ if (step.critical) {+ warn(`Skipping remaining ${targetConfig.label} steps because ${step.name} failed.`);+ break;+ }}console.log();}