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
replace init with interactive install supporting opencode, claude code, and antigravity
0xk3vin53716f6b5f0d
diff --git a/README.md b/README.mdindex 291e021..a7bbb93 100644--- a/README.md+++ b/README.md@@ -43,10 +43,16 @@ npm install -g megamemory### Quick Start-#### With [opencode](https://github.com/anomalyco/opencode)+```bash+megamemory install+```++Interactive installer — choose your editor:++#### With [opencode](https://opencode.ai)```bash-megamemory init+megamemory install --target opencode```One command configures everything:@@ -56,7 +62,27 @@ One command configures everything:- Bootstrap command `/user:bootstrap-memory` for initial graph population- Save command `/user:save-memory` to persist session knowledge-Restart opencode after running init.+Restart opencode after running install.++#### With [Claude Code](https://code.claude.com)++```bash+megamemory install --target claudecode+```++Configures:+- MCP server in `~/.claude.json`+- Workflow instructions in `~/.claude/CLAUDE.md`+- Commands in `~/.claude/commands/`++#### With [Antigravity](https://idx.google.com)++```bash+megamemory install --target antigravity+```++Configures:+- MCP server in `./mcp_config.json` (workspace-level)#### With other MCP clients@@ -118,7 +144,7 @@ megamemory serve --port 8080 # custom port| Command | Description ||---------|-------------|| `megamemory` | Start the MCP stdio server |-| `megamemory init` | Configure opencode integration |+| `megamemory install` | Configure editor/agent integration || `megamemory serve` | Launch the web graph explorer || `megamemory merge` | Merge two knowledge.db files || `megamemory conflicts` | List unresolved merge conflicts |@@ -185,7 +211,7 @@ src/merge-cli.ts CLI handlers for merge, conflicts, resolve commandstypes.ts TypeScript typescli-utils.ts Colored output + interactive prompts- init.ts opencode setup wizard+ install.ts multi-target installer (opencode, Claude Code, Antigravity)web.ts HTTP server for graph explorerplugin/megamemory.ts Opencode skill tool plugindiff --git a/package-lock.json b/package-lock.jsonindex 671c541..fd6a4eb 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,12 +1,12 @@{"name": "megamemory",- "version": "1.2.1",+ "version": "1.3.0","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "megamemory",- "version": "1.2.1",+ "version": "1.3.0","license": "MIT","dependencies": {"@modelcontextprotocol/sdk": "^1.12.1",@@ -20,6 +20,7 @@},"devDependencies": {"@types/node": "^20.17.14",+ "@vitest/coverage-v8": "^4.0.18","tsx": "^4.19.2","typescript": "^5.7.3","vitest": "^4.0.18"@@ -28,6 +29,66 @@"node": ">=18"}},+ "node_modules/@babel/helper-string-parser": {+ "version": "7.27.1",+ "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.27.1.tgz",+ "integrity": "sha512-qMlSxKbpRlAridDExk92nSobyDdpPijUq2DW6oDnUqd0iOGxmQjyqhMIihI9+zv4LPyZdRje2cavWPbCbWm3eA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=6.9.0"+ }+ },+ "node_modules/@babel/helper-validator-identifier": {+ "version": "7.28.5",+ "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.28.5.tgz",+ "integrity": "sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=6.9.0"+ }+ },+ "node_modules/@babel/parser": {+ "version": "7.29.0",+ "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.0.tgz",+ "integrity": "sha512-IyDgFV5GeDUVX4YdF/3CPULtVGSXXMLh1xVIgdCgxApktqnQV0r7/8Nqthg+8YLGaAtdyIlo2qIdZrbCv4+7ww==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@babel/types": "^7.29.0"+ },+ "bin": {+ "parser": "bin/babel-parser.js"+ },+ "engines": {+ "node": ">=6.0.0"+ }+ },+ "node_modules/@babel/types": {+ "version": "7.29.0",+ "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.0.tgz",+ "integrity": "sha512-LwdZHpScM4Qz8Xw2iKSzS+cfglZzJGvofQICy7W7v4caru4EaAmyUuO6BGrbyQ2mYV11W0U8j5mBhd14dd3B0A==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@babel/helper-string-parser": "^7.27.1",+ "@babel/helper-validator-identifier": "^7.28.5"+ },+ "engines": {+ "node": ">=6.9.0"+ }+ },+ "node_modules/@bcoe/v8-coverage": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/@bcoe/v8-coverage/-/v8-coverage-1.0.2.tgz",+ "integrity": "sha512-6zABk/ECA/QYSCQ1NGiVwwbQerUCZ+TQbp64Q3AgmfNvurHH0j8TtXa1qbShXA6qqkpAj4V5W8pP6mLe1mcMqA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=18"+ }+ },"node_modules/@esbuild/aix-ppc64": {"version": "0.27.3","resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.3.tgz",@@ -491,6 +552,16 @@"node": ">=18"}},+ "node_modules/@jridgewell/resolve-uri": {+ "version": "3.1.2",+ "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz",+ "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=6.0.0"+ }+ },"node_modules/@jridgewell/sourcemap-codec": {"version": "1.5.5","resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz",@@ -498,6 +569,17 @@"dev": true,"license": "MIT"},+ "node_modules/@jridgewell/trace-mapping": {+ "version": "0.3.31",+ "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz",+ "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@jridgewell/resolve-uri": "^3.1.0",+ "@jridgewell/sourcemap-codec": "^1.4.14"+ }+ },"node_modules/@libsql/darwin-arm64": {"version": "0.5.22","resolved": "https://registry.npmjs.org/@libsql/darwin-arm64/-/darwin-arm64-0.5.22.tgz",@@ -1122,6 +1204,37 @@"undici-types": "~6.21.0"}},+ "node_modules/@vitest/coverage-v8": {+ "version": "4.0.18",+ "resolved": "https://registry.npmjs.org/@vitest/coverage-v8/-/coverage-v8-4.0.18.tgz",+ "integrity": "sha512-7i+N2i0+ME+2JFZhfuz7Tg/FqKtilHjGyGvoHYQ6iLV0zahbsJ9sljC9OcFcPDbhYKCet+sG8SsVqlyGvPflZg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@bcoe/v8-coverage": "^1.0.2",+ "@vitest/utils": "4.0.18",+ "ast-v8-to-istanbul": "^0.3.10",+ "istanbul-lib-coverage": "^3.2.2",+ "istanbul-lib-report": "^3.0.1",+ "istanbul-reports": "^3.2.0",+ "magicast": "^0.5.1",+ "obug": "^2.1.1",+ "std-env": "^3.10.0",+ "tinyrainbow": "^3.0.3"+ },+ "funding": {+ "url": "https://opencollective.com/vitest"+ },+ "peerDependencies": {+ "@vitest/browser": "4.0.18",+ "vitest": "4.0.18"+ },+ "peerDependenciesMeta": {+ "@vitest/browser": {+ "optional": true+ }+ }+ },"node_modules/@vitest/expect": {"version": "4.0.18","resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.0.18.tgz",@@ -1303,6 +1416,18 @@"node": ">=12"}},+ "node_modules/ast-v8-to-istanbul": {+ "version": "0.3.11",+ "resolved": "https://registry.npmjs.org/ast-v8-to-istanbul/-/ast-v8-to-istanbul-0.3.11.tgz",+ "integrity": "sha512-Qya9fkoofMjCBNVdWINMjB5KZvkYfaO9/anwkWnjxibpWUxo5iHl2sOdP7/uAqaRuUYuoo8rDwnbaaKVFxoUvw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@jridgewell/trace-mapping": "^0.3.31",+ "estree-walker": "^3.0.3",+ "js-tokens": "^10.0.0"+ }+ },"node_modules/b4a": {"version": "1.7.3","resolved": "https://registry.npmjs.org/b4a/-/b4a-1.7.3.tgz",@@ -2159,6 +2284,16 @@"integrity": "sha512-Y8T4vYhEfwJOTbouREvG+3XDsjr8E3kIr7uf+JZ0BYloFsttiHU0WfvANVsR7TxNUJa/WpCnw/Ino/p+DeBhBQ==","license": "ISC"},+ "node_modules/has-flag": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz",+ "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },"node_modules/has-symbols": {"version": "1.1.0","resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz",@@ -2192,6 +2327,13 @@"node": ">=16.9.0"}},+ "node_modules/html-escaper": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/html-escaper/-/html-escaper-2.0.2.tgz",+ "integrity": "sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==",+ "dev": true,+ "license": "MIT"+ },"node_modules/http-errors": {"version": "2.0.1","resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz",@@ -2296,6 +2438,45 @@"integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==","license": "ISC"},+ "node_modules/istanbul-lib-coverage": {+ "version": "3.2.2",+ "resolved": "https://registry.npmjs.org/istanbul-lib-coverage/-/istanbul-lib-coverage-3.2.2.tgz",+ "integrity": "sha512-O8dpsF+r0WV/8MNRKfnmrtCWhuKjxrq2w+jpzBL5UZKTi2LeVWnWOmWRxFlesJONmc+wLAGvKQZEOanko0LFTg==",+ "dev": true,+ "license": "BSD-3-Clause",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/istanbul-lib-report": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/istanbul-lib-report/-/istanbul-lib-report-3.0.1.tgz",+ "integrity": "sha512-GCfE1mtsHGOELCU8e/Z7YWzpmybrx/+dSTfLrvY8qRmaY6zXTKWn6WQIjaAFw069icm6GVMNkgu0NzI4iPZUNw==",+ "dev": true,+ "license": "BSD-3-Clause",+ "dependencies": {+ "istanbul-lib-coverage": "^3.0.0",+ "make-dir": "^4.0.0",+ "supports-color": "^7.1.0"+ },+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/istanbul-reports": {+ "version": "3.2.0",+ "resolved": "https://registry.npmjs.org/istanbul-reports/-/istanbul-reports-3.2.0.tgz",+ "integrity": "sha512-HGYWWS/ehqTV3xN10i23tkPkpH46MLCIMFNCaaKNavAXTF1RkqxawEPtnjnGZ6XKSInBKkiOA5BKS+aZiY3AvA==",+ "dev": true,+ "license": "BSD-3-Clause",+ "dependencies": {+ "html-escaper": "^2.0.0",+ "istanbul-lib-report": "^3.0.0"+ },+ "engines": {+ "node": ">=8"+ }+ },"node_modules/jose": {"version": "6.1.3","resolved": "https://registry.npmjs.org/jose/-/jose-6.1.3.tgz",@@ -2305,6 +2486,13 @@"url": "https://github.com/sponsors/panva"}},+ "node_modules/js-tokens": {+ "version": "10.0.0",+ "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-10.0.0.tgz",+ "integrity": "sha512-lM/UBzQmfJRo9ABXbPWemivdCW8V2G8FHaHdypQaIy523snUjog0W71ayWXTjiR+ixeMyVHN2XcpnTd/liPg/Q==",+ "dev": true,+ "license": "MIT"+ },"node_modules/json-schema-traverse": {"version": "1.0.0","resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz",@@ -2365,6 +2553,34 @@"@jridgewell/sourcemap-codec": "^1.5.5"}},+ "node_modules/magicast": {+ "version": "0.5.2",+ "resolved": "https://registry.npmjs.org/magicast/-/magicast-0.5.2.tgz",+ "integrity": "sha512-E3ZJh4J3S9KfwdjZhe2afj6R9lGIN5Pher1pF39UGrXRqq/VDaGVIGN13BjHd2u8B61hArAGOnso7nBOouW3TQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@babel/parser": "^7.29.0",+ "@babel/types": "^7.29.0",+ "source-map-js": "^1.2.1"+ }+ },+ "node_modules/make-dir": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-4.0.0.tgz",+ "integrity": "sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "semver": "^7.5.3"+ },+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },"node_modules/math-intrinsics": {"version": "1.1.0","resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",@@ -3279,6 +3495,19 @@"node": ">=0.10.0"}},+ "node_modules/supports-color": {+ "version": "7.2.0",+ "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz",+ "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "has-flag": "^4.0.0"+ },+ "engines": {+ "node": ">=8"+ }+ },"node_modules/tar-fs": {"version": "3.1.1","resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-3.1.1.tgz",diff --git a/package.json b/package.jsonindex 63ba432..c26a8e2 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "megamemory",- "version": "1.2.1",+ "version": "1.3.0","description": "MCP server that gives coding agents persistent project understanding via a knowledge graph","type": "module","main": "dist/index.js",@@ -53,6 +53,7 @@},"devDependencies": {"@types/node": "^20.17.14",+ "@vitest/coverage-v8": "^4.0.18","tsx": "^4.19.2","typescript": "^5.7.3","vitest": "^4.0.18"diff --git a/src/cli-utils.ts b/src/cli-utils.tsindex ba54699..446bcc4 100644--- a/src/cli-utils.ts+++ b/src/cli-utils.ts@@ -46,6 +46,126 @@ export function ask(question: string): Promise<string> {});}+export async function multiSelect(+ prompt: string,+ options: Array<{ label: string; value: string; description?: string }>+): Promise<string[]> {+ if (options.length === 0) return [];++ if (!process.stdin.isTTY || !process.stdout.isTTY) {+ const answer = await ask(+ `${prompt}\n` ++ options+ .map((opt, idx) => ` ${idx + 1}. ${opt.label}${opt.description ? ` - ${opt.description}` : ""}`)+ .join("\n") ++ "\n\n Enter numbers (comma-separated) or 'a' for all: "+ );++ if (answer.toLowerCase() === "a") {+ return options.map((opt) => opt.value);+ }++ const picks = new Set<string>();+ for (const piece of answer.split(",")) {+ const raw = piece.trim();+ if (!raw) continue;+ const index = parseInt(raw, 10);+ if (isNaN(index) || index < 1 || index > options.length) continue;+ picks.add(options[index - 1].value);+ }+ return [...picks];+ }++ const selected = new Array<boolean>(options.length).fill(false);+ let renderedLineCount = 0;++ const render = () => {+ const lines = [+ "",+ ` ${prompt}`,+ "",+ ...options.map((opt, idx) => {+ const check = selected[idx] ? "x" : " ";+ const number = String(idx + 1);+ const label = opt.label.padEnd(15);+ const desc = opt.description ? ` ${pc.dim(opt.description)}` : "";+ return ` [${check}] ${number}. ${label}${desc}`;+ }),+ "",+ ` ${pc.dim(`Toggle: 1-${options.length} | All: a | Confirm: Enter`)}`,+ ];++ if (renderedLineCount > 0) {+ process.stdout.write(`\r\x1b[${Math.max(renderedLineCount - 1, 0)}A\x1b[J`);+ }+ process.stdout.write(lines.join("\n"));+ renderedLineCount = lines.length;+ };++ return new Promise<string[]>((resolve) => {+ let finished = false;++ const cleanup = () => {+ if (!process.stdin.isTTY) return;+ process.stdin.off("data", onData);+ process.stdin.setRawMode(false);+ process.stdin.pause();+ process.stdout.write("\x1b[?25h");+ };++ const finish = (values: string[]) => {+ if (finished) return;+ finished = true;+ cleanup();+ process.stdout.write("\n\n");+ resolve(values);+ };++ const onData = (chunk: string | Buffer) => {+ const input = chunk.toString("utf8");++ for (const ch of input) {+ if (ch === "\u0003") {+ cleanup();+ process.stdout.write("\n");+ process.exit(130);+ }++ if (ch === "\r" || ch === "\n") {+ const values = options+ .filter((_, idx) => selected[idx])+ .map((opt) => opt.value);+ finish(values);+ return;+ }++ if (ch.toLowerCase() === "a") {+ const shouldSelectAll = selected.some((val) => !val);+ for (let i = 0; i < selected.length; i += 1) {+ selected[i] = shouldSelectAll;+ }+ render();+ continue;+ }++ const numeric = parseInt(ch, 10);+ if (!isNaN(numeric) && numeric >= 1 && numeric <= options.length) {+ const idx = numeric - 1;+ selected[idx] = !selected[idx];+ render();+ }+ }+ };++ process.stdin.setRawMode(true);+ process.stdin.resume();+ process.stdin.setEncoding("utf8");+ process.stdin.on("data", onData);+ process.stdout.write("\x1b[?25l");+ render();+ });+}+/*** Prompt the user for a port when the current one is in use.* Returns the chosen port number, or null if the user wants to cancel.diff --git a/src/index.ts b/src/index.tsindex 9911dcc..61ef14c 100644--- a/src/index.ts+++ b/src/index.ts@@ -20,13 +20,14 @@ ${pc.bold(pc.cyan("megamemory"))} ${pc.green(`v${VERSION}`)} ${pc.dim("— persi${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("install")} Configure editor/agent integration (interactive)${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("--target")} ${pc.dim("NAME")} Install target (opencode, claudecode, antigravity)${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)")}@@ -38,7 +39,8 @@ ${pc.bold("Options:")}${pc.cyan("--version, -v")} Show version${pc.bold("Examples:")}- ${pc.dim("$")} megamemory init ${pc.dim("Setup opencode config, plugins, and commands")}+ ${pc.dim("$")} megamemory install ${pc.dim("Interactive editor integration setup")}+ ${pc.dim("$")} megamemory install --target claudecode ${pc.dim("Non-interactive Claude Code setup")}${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")}@@ -46,7 +48,7 @@ ${pc.bold("Examples:")}${pc.dim("$")} megamemory resolve <group-id> --keep left ${pc.dim("Resolve a conflict")}`.trim();-const KNOWN_COMMANDS = new Set(["init", "serve", "merge", "conflicts", "resolve", "--help", "-h", "--version", "-v"]);+const KNOWN_COMMANDS = new Set(["install", "serve", "merge", "conflicts", "resolve", "--help", "-h", "--version", "-v"]);function parseFlags(args: string[]): { port?: number; rawPort?: string } {const portIdx = args.indexOf("--port");@@ -58,9 +60,9 @@ function parseFlags(args: string[]): { port?: number; rawPort?: string } {const cmd = process.argv[2];switch (cmd) {- case "init": {- const { runInit } = await import("./init.js");- await runInit();+ case "install": {+ const { runInstall } = await import("./install.js");+ await runInstall(process.argv.slice(3));process.exit(0);break;}diff --git a/src/init.ts b/src/init.tsdeleted file mode 100644index d414a19..0000000--- a/src/init.ts+++ /dev/null@@ -1,320 +0,0 @@-import fs from "fs";-import os from "os";-import path from "path";-import { fileURLToPath } from "url";-import pc from "picocolors";-import { success, skip, error, info, heading } from "./cli-utils.js";--// ---- Paths ------const OPENCODE_CONFIG_DIR =- process.env.OPENCODE_CONFIG_DIR ??- path.join(- process.env.XDG_CONFIG_HOME ?? path.join(os.homedir(), ".config"),- "opencode"- );-const OPENCODE_CONFIG_PATH = path.join(OPENCODE_CONFIG_DIR, "opencode.json");-const OPENCODE_AGENTS_MD_PATH = path.join(OPENCODE_CONFIG_DIR, "AGENTS.md");-const OPENCODE_TOOL_DIR = path.join(OPENCODE_CONFIG_DIR, "tool");-const OPENCODE_COMMANDS_DIR = path.join(OPENCODE_CONFIG_DIR, "commands");--// ---- AGENTS.md snippet ------const AGENTS_MD_MARKER = "## Project Knowledge Graph";--const AGENTS_MD_SNIPPET = `-## Project Knowledge Graph--You have access to a project knowledge graph via the \`megamemory\` MCP server and skill tool. This is your persistent memory of the codebase — concepts, architecture, decisions, and how things connect. You write it. You read it. The graph is your memory across sessions.--**Workflow: understand → work → update**--1. **Session start:** Call \`megamemory\` tool with action \`overview\` (or \`megamemory:list_roots\` directly) to orient yourself.-2. **Before each task:** Call \`megamemory\` tool with action \`query\` (or \`megamemory:understand\` directly) to load relevant context.-3. **After each task:** Call \`megamemory\` tool with action \`record\` to create/update/link concepts for what you built.--Be specific in summaries: include parameter names, defaults, file locations, and rationale. Keep concepts max 3 levels deep.-`;--// ---- Helpers ------/**- * Resolve absolute path to the MCP server entry point (dist/index.js).- */-function resolveServerEntryPoint(): string {- const thisDir = path.dirname(fileURLToPath(import.meta.url));-- // Running from dist/ → sibling index.js- const fromDist = path.resolve(thisDir, "index.js");- if (fs.existsSync(fromDist)) return fromDist;-- // Running from src/ via tsx → look in ../dist/- const fromSrc = path.resolve(thisDir, "..", "dist", "index.js");- if (fs.existsSync(fromSrc)) return fromSrc;-- // Fallback: assume dist/ relative to package root- const fromRoot = path.resolve(thisDir, "..", "dist", "index.js");- return fromRoot;-}--/**- * Resolve absolute path to the plugin/megamemory.ts skill file.- */-function resolvePluginSource(): string {- const thisDir = path.dirname(fileURLToPath(import.meta.url));- return path.resolve(thisDir, "..", "plugin", "megamemory.ts");-}--/**- * Resolve absolute path to a file in the commands/ directory.- */-function resolveCommandFile(filename: string): string {- const thisDir = path.dirname(fileURLToPath(import.meta.url));- return path.resolve(thisDir, "..", "commands", filename);-}--// ---- Setup steps ------async function setupMcpConfig(): Promise<void> {- if (!fs.existsSync(OPENCODE_CONFIG_DIR)) {- fs.mkdirSync(OPENCODE_CONFIG_DIR, { recursive: true });- }-- // Read existing config or start fresh- let config: Record<string, unknown> = {};- if (fs.existsSync(OPENCODE_CONFIG_PATH)) {- try {- config = JSON.parse(fs.readFileSync(OPENCODE_CONFIG_PATH, "utf-8"));- } catch {- const backup = `${OPENCODE_CONFIG_PATH}.bak`;- fs.copyFileSync(OPENCODE_CONFIG_PATH, backup);- info(`Backed up malformed config to ${pc.dim(backup)}`);- config = {};- }- }-- if (!config["$schema"]) {- config["$schema"] = "https://opencode.ai/config.json";- }-- // Detect if `megamemory` is globally available (npm link / npm install -g)- // If so, use the short command. Otherwise fall back to absolute path.- const { execSync } = await import("child_process");- let isGlobal = false;- try {- execSync(- process.platform === "win32" ? "where megamemory" : "which megamemory",- { stdio: "ignore" }- );- isGlobal = true;- } catch {- isGlobal = false;- }-- const command: string[] = isGlobal- ? ["megamemory"]- : ["node", resolveServerEntryPoint()];-- // Merge megamemory into mcp key — preserve everything else- const mcp = (config["mcp"] as Record<string, unknown>) ?? {};- const existed = "megamemory" in mcp;-- mcp["megamemory"] = {- type: "local",- command,- enabled: true,- };- config["mcp"] = mcp;-- fs.writeFileSync(- OPENCODE_CONFIG_PATH,- JSON.stringify(config, null, 2) + "\n"- );-- success(- existed- ? `Updated megamemory MCP in ${pc.dim(OPENCODE_CONFIG_PATH)}`- : `Added megamemory MCP to ${pc.dim(OPENCODE_CONFIG_PATH)}`- );- info(`Command: ${pc.cyan(JSON.stringify(command))}`);-}--function setupAgentsMd(): void {- // Check if snippet already exists- if (fs.existsSync(OPENCODE_AGENTS_MD_PATH)) {- const content = fs.readFileSync(OPENCODE_AGENTS_MD_PATH, "utf-8");- if (content.includes(AGENTS_MD_MARKER)) {- skip(`Already contains knowledge graph instructions`);- return;- }- // Append to existing- fs.appendFileSync(OPENCODE_AGENTS_MD_PATH, "\n" + AGENTS_MD_SNIPPET.trimStart());- success(`Appended knowledge graph instructions to ${pc.dim(OPENCODE_AGENTS_MD_PATH)}`);- } else {- fs.writeFileSync(OPENCODE_AGENTS_MD_PATH, AGENTS_MD_SNIPPET.trimStart());- success(`Created ${pc.dim(OPENCODE_AGENTS_MD_PATH)}`);- }-}--function setupToolPlugin(): void {- const source = resolvePluginSource();- const dest = path.join(OPENCODE_TOOL_DIR, "megamemory.ts");-- if (!fs.existsSync(source)) {- skip(`Plugin source not found at ${pc.dim(source)}`);- return;- }-- if (!fs.existsSync(OPENCODE_TOOL_DIR)) {- fs.mkdirSync(OPENCODE_TOOL_DIR, { recursive: true });- }-- const sourceContent = fs.readFileSync(source, "utf-8");-- // Check if already installed and identical- if (fs.existsSync(dest)) {- const existing = fs.readFileSync(dest, "utf-8");- if (existing === sourceContent) {- skip(`Tool plugin already up to date`);- return;- }- // Update- fs.writeFileSync(dest, sourceContent);- success(`Updated tool plugin at ${pc.dim(dest)}`);- } else {- fs.writeFileSync(dest, sourceContent);- success(`Installed tool plugin at ${pc.dim(dest)}`);- }-}--function setupCommand(filename: string, label: string): void {- const source = resolveCommandFile(filename);- const dest = path.join(OPENCODE_COMMANDS_DIR, filename);-- if (!fs.existsSync(source)) {- skip(`Command source not found at ${pc.dim(source)}`);- return;- }-- if (!fs.existsSync(OPENCODE_COMMANDS_DIR)) {- fs.mkdirSync(OPENCODE_COMMANDS_DIR, { recursive: true });- }-- const sourceContent = fs.readFileSync(source, "utf-8");-- if (fs.existsSync(dest)) {- const existing = fs.readFileSync(dest, "utf-8");- if (existing === sourceContent) {- skip(`${label} already up to date`);- return;- }- fs.writeFileSync(dest, sourceContent);- success(`Updated ${label} at ${pc.dim(dest)}`);- } else {- fs.writeFileSync(dest, sourceContent);- success(`Installed ${label} at ${pc.dim(dest)}`);- }-}--// ---- Entry point ------interface StepResult {- name: string;- ok: boolean;- error?: string;-}--export async function runInit(): Promise<void> {- console.log();- console.log(` ${pc.bold(pc.cyan("megamemory"))} ${pc.dim("init")}`);- console.log();-- const steps: StepResult[] = [];-- // Step 1: MCP server config- heading(` 1. MCP server config`);- try {- await setupMcpConfig();- steps.push({ name: "MCP server config", ok: true });- } catch (err) {- const msg = err instanceof Error ? err.message : String(err);- error(`MCP config failed: ${msg}`);- steps.push({ name: "MCP server config", ok: false, error: msg });- }-- console.log();-- // Step 2: Global AGENTS.md- heading(` 2. Global AGENTS.md`);- try {- setupAgentsMd();- steps.push({ name: "Global AGENTS.md", ok: true });- } catch (err) {- const msg = err instanceof Error ? err.message : String(err);- error(`AGENTS.md setup failed: ${msg}`);- steps.push({ name: "Global AGENTS.md", ok: false, error: msg });- }-- console.log();-- // Step 3: Skill tool plugin- heading(` 3. Skill tool plugin`);- try {- setupToolPlugin();- steps.push({ name: "Skill tool plugin", ok: true });- } catch (err) {- const msg = err instanceof Error ? err.message : String(err);- error(`Plugin setup failed: ${msg}`);- steps.push({ name: "Skill tool plugin", ok: false, error: msg });- }-- console.log();-- // Step 4: Bootstrap command- heading(` 4. Bootstrap command`);- try {- setupCommand("bootstrap-memory.md", "bootstrap command");- steps.push({ name: "Bootstrap command", ok: true });- } catch (err) {- const msg = err instanceof Error ? err.message : String(err);- error(`Bootstrap command setup failed: ${msg}`);- steps.push({ name: "Bootstrap command", ok: false, error: msg });- }-- console.log();-- // Step 5: Save memory command- heading(` 5. Save memory command`);- try {- setupCommand("save-memory.md", "save memory command");- steps.push({ name: "Save memory command", ok: true });- } catch (err) {- const msg = err instanceof Error ? err.message : String(err);- error(`Save memory command setup failed: ${msg}`);- steps.push({ name: "Save memory command", ok: false, error: msg });- }-- console.log();-- // Summary- const failed = steps.filter((s) => !s.ok);- if (failed.length === 0) {- console.log(` ${pc.green(pc.bold("Done."))} Restart opencode to pick up changes.`);- console.log(- pc.dim(` Run ${pc.cyan("/user:bootstrap-memory")} to populate a project's knowledge graph.`)- );- console.log(- pc.dim(` Run ${pc.cyan("/user:save-memory")} after a session to save what you learned.`)- );- } else {- console.log(- ` ${pc.yellow(pc.bold("Done with issues."))} ${pc.yellow(`${failed.length} step(s) failed:`)}`- );- for (const f of failed) {- console.log(` ${pc.red("✗")} ${f.name}: ${pc.dim(f.error ?? "unknown error")}`);- }- console.log();- console.log(pc.dim(` Steps that succeeded will still work. Fix the issues above and re-run.`));- }- console.log();-}diff --git a/src/install.ts b/src/install.tsnew file mode 100644index 0000000..0019cd4--- /dev/null+++ b/src/install.ts@@ -0,0 +1,513 @@+import fs from "fs";+import os from "os";+import path from "path";+import { fileURLToPath } from "url";+import pc from "picocolors";+import { success, skip, error, info, heading, warn, multiSelect } from "./cli-utils.js";++export type InstallTarget = "opencode" | "claudecode" | "antigravity";++interface TargetConfig {+ label: string;+ description: string;+ steps: Array<{ name: string; run: () => Promise<void> | void }>;+}++interface StepResult {+ target: InstallTarget;+ targetLabel: string;+ name: string;+ ok: boolean;+ error?: string;+}++interface CommandRuntime {+ opencodeCommand: string[];+ stdioCommand: string;+ stdioArgs: string[];+}++const OPENCODE_CONFIG_DIR =+ process.env.OPENCODE_CONFIG_DIR ??+ path.join(+ process.env.XDG_CONFIG_HOME ?? path.join(os.homedir(), ".config"),+ "opencode"+ );+const OPENCODE_CONFIG_PATH = path.join(OPENCODE_CONFIG_DIR, "opencode.json");+const OPENCODE_AGENTS_MD_PATH = path.join(OPENCODE_CONFIG_DIR, "AGENTS.md");+const OPENCODE_TOOL_DIR = path.join(OPENCODE_CONFIG_DIR, "tool");+const OPENCODE_COMMANDS_DIR = path.join(OPENCODE_CONFIG_DIR, "commands");++const CLAUDE_CONFIG_PATH = path.join(os.homedir(), ".claude.json");+const CLAUDE_DIR = path.join(os.homedir(), ".claude");+const CLAUDE_MD_PATH = path.join(CLAUDE_DIR, "CLAUDE.md");+const CLAUDE_COMMANDS_DIR = path.join(CLAUDE_DIR, "commands");++const ANTIGRAVITY_CONFIG_PATH = path.join(process.cwd(), "mcp_config.json");++const AGENTS_MD_MARKER = "## Project Knowledge Graph";++const AGENTS_MD_SNIPPET = `+## Project Knowledge Graph++You have access to a project knowledge graph via the \`megamemory\` MCP server and skill tool. This is your persistent memory of the codebase — concepts, architecture, decisions, and how things connect. You write it. You read it. The graph is your memory across sessions.++**Workflow: understand → work → update**++1. **Session start:** Call \`megamemory\` tool with action \`overview\` (or \`megamemory:list_roots\` directly) to orient yourself.+2. **Before each task:** Call \`megamemory\` tool with action \`query\` (or \`megamemory:understand\` directly) to load relevant context.+3. **After each task:** Call \`megamemory\` tool with action \`record\` to create/update/link concepts for what you built.++Be specific in summaries: include parameter names, defaults, file locations, and rationale. Keep concepts max 3 levels deep.+`;++function isObject(value: unknown): value is Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}++function resolveServerEntryPoint(): string {+ const thisDir = path.dirname(fileURLToPath(import.meta.url));++ const fromDist = path.resolve(thisDir, "index.js");+ if (fs.existsSync(fromDist)) return fromDist;++ const fromSrc = path.resolve(thisDir, "..", "dist", "index.js");+ if (fs.existsSync(fromSrc)) return fromSrc;++ const fromRoot = path.resolve(thisDir, "..", "dist", "index.js");+ return fromRoot;+}++function resolvePluginSource(): string {+ const thisDir = path.dirname(fileURLToPath(import.meta.url));+ return path.resolve(thisDir, "..", "plugin", "megamemory.ts");+}++function resolveCommandFile(filename: string): string {+ const thisDir = path.dirname(fileURLToPath(import.meta.url));+ return path.resolve(thisDir, "..", "commands", filename);+}++async function detectGlobalCommand(): Promise<CommandRuntime> {+ const { execSync } = await import("child_process");+ let isGlobal = false;++ try {+ execSync(+ process.platform === "win32" ? "where megamemory" : "which megamemory",+ { stdio: "ignore" }+ );+ isGlobal = true;+ } catch {+ isGlobal = false;+ }++ if (isGlobal) {+ return {+ opencodeCommand: ["megamemory"],+ stdioCommand: "megamemory",+ stdioArgs: [],+ };+ }++ const entry = resolveServerEntryPoint();+ return {+ opencodeCommand: ["node", entry],+ stdioCommand: "node",+ stdioArgs: [entry],+ };+}++function setupInstructionFile(filePath: string): void {+ fs.mkdirSync(path.dirname(filePath), { recursive: true });++ if (fs.existsSync(filePath)) {+ const content = fs.readFileSync(filePath, "utf-8");+ if (content.includes(AGENTS_MD_MARKER)) {+ skip(`Already contains knowledge graph instructions`);+ return;+ }+ fs.appendFileSync(filePath, "\n" + AGENTS_MD_SNIPPET.trimStart());+ success(`Appended knowledge graph instructions to ${pc.dim(filePath)}`);+ return;+ }++ fs.writeFileSync(filePath, AGENTS_MD_SNIPPET.trimStart());+ success(`Created ${pc.dim(filePath)}`);+}++function setupToolPlugin(): void {+ const source = resolvePluginSource();+ const dest = path.join(OPENCODE_TOOL_DIR, "megamemory.ts");++ if (!fs.existsSync(source)) {+ skip(`Plugin source not found at ${pc.dim(source)}`);+ return;+ }++ fs.mkdirSync(OPENCODE_TOOL_DIR, { recursive: true });++ const sourceContent = fs.readFileSync(source, "utf-8");++ if (fs.existsSync(dest)) {+ const existing = fs.readFileSync(dest, "utf-8");+ if (existing === sourceContent) {+ skip(`Tool plugin already up to date`);+ return;+ }+ fs.writeFileSync(dest, sourceContent);+ success(`Updated tool plugin at ${pc.dim(dest)}`);+ return;+ }++ fs.writeFileSync(dest, sourceContent);+ success(`Installed tool plugin at ${pc.dim(dest)}`);+}++function setupCommand(destinationDir: string, filename: string, label: string): void {+ const source = resolveCommandFile(filename);+ const dest = path.join(destinationDir, filename);++ if (!fs.existsSync(source)) {+ skip(`Command source not found at ${pc.dim(source)}`);+ return;+ }++ fs.mkdirSync(destinationDir, { recursive: true });++ const sourceContent = fs.readFileSync(source, "utf-8");++ if (fs.existsSync(dest)) {+ const existing = fs.readFileSync(dest, "utf-8");+ if (existing === sourceContent) {+ skip(`${label} already up to date`);+ return;+ }+ fs.writeFileSync(dest, sourceContent);+ success(`Updated ${label} at ${pc.dim(dest)}`);+ return;+ }++ fs.writeFileSync(dest, sourceContent);+ success(`Installed ${label} at ${pc.dim(dest)}`);+}++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 = JSON.parse(fs.readFileSync(OPENCODE_CONFIG_PATH, "utf-8"));+ config = isObject(parsed) ? parsed : {};+ } catch {+ const backup = `${OPENCODE_CONFIG_PATH}.bak`;+ fs.copyFileSync(OPENCODE_CONFIG_PATH, backup);+ info(`Backed up malformed config to ${pc.dim(backup)}`);+ config = {};+ }+ }++ if (!config["$schema"]) {+ config["$schema"] = "https://opencode.ai/config.json";+ }++ const mcp = isObject(config["mcp"]) ? config["mcp"] : {};+ const existed = "megamemory" in mcp;++ mcp["megamemory"] = {+ type: "local",+ command: runtime.opencodeCommand,+ enabled: true,+ };+ config["mcp"] = mcp;++ fs.writeFileSync(OPENCODE_CONFIG_PATH, JSON.stringify(config, null, 2) + "\n");++ success(+ existed+ ? `Updated megamemory MCP in ${pc.dim(OPENCODE_CONFIG_PATH)}`+ : `Added megamemory MCP to ${pc.dim(OPENCODE_CONFIG_PATH)}`+ );+ info(`Command: ${pc.cyan(JSON.stringify(runtime.opencodeCommand))}`);+}++async function setupClaudeConfig(runtime: CommandRuntime): Promise<void> {+ let config: Record<string, unknown> = {};++ if (fs.existsSync(CLAUDE_CONFIG_PATH)) {+ try {+ const parsed = JSON.parse(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(`Malformed ${pc.dim(CLAUDE_CONFIG_PATH)} detected; backed it up to ${pc.dim(backup)}`);+ throw new Error(+ err instanceof Error+ ? `Could not parse ${CLAUDE_CONFIG_PATH}: ${err.message}`+ : `Could not parse ${CLAUDE_CONFIG_PATH}`+ );+ }+ }++ const mcpServers = isObject(config["mcpServers"]) ? config["mcpServers"] : {};+ const existed = "megamemory" in mcpServers;++ mcpServers["megamemory"] = {+ type: "stdio",+ command: runtime.stdioCommand,+ args: runtime.stdioArgs,+ };+ config["mcpServers"] = mcpServers;++ fs.writeFileSync(CLAUDE_CONFIG_PATH, JSON.stringify(config, null, 2) + "\n");++ success(+ existed+ ? `Updated megamemory MCP in ${pc.dim(CLAUDE_CONFIG_PATH)}`+ : `Added megamemory MCP to ${pc.dim(CLAUDE_CONFIG_PATH)}`+ );+ info(`Command: ${pc.cyan(JSON.stringify([runtime.stdioCommand, ...runtime.stdioArgs]))}`);+}++async function setupAntigravityConfig(runtime: CommandRuntime): Promise<void> {+ let config: Record<string, unknown> = {};++ if (fs.existsSync(ANTIGRAVITY_CONFIG_PATH)) {+ try {+ const parsed = JSON.parse(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(`Malformed ${pc.dim(ANTIGRAVITY_CONFIG_PATH)} detected; backed it up to ${pc.dim(backup)}`);+ config = {};+ }+ }++ const mcpServers = isObject(config["mcpServers"]) ? config["mcpServers"] : {};+ const existed = "megamemory" in mcpServers;++ mcpServers["megamemory"] = {+ command: runtime.stdioCommand,+ args: runtime.stdioArgs,+ };+ config["mcpServers"] = mcpServers;++ fs.writeFileSync(ANTIGRAVITY_CONFIG_PATH, JSON.stringify(config, null, 2) + "\n");++ success(+ existed+ ? `Updated megamemory MCP in ${pc.dim(ANTIGRAVITY_CONFIG_PATH)}`+ : `Added megamemory MCP to ${pc.dim(ANTIGRAVITY_CONFIG_PATH)}`+ );+ info(`Command: ${pc.cyan(JSON.stringify([runtime.stdioCommand, ...runtime.stdioArgs]))}`);+}++function createTargetConfigs(runtime: CommandRuntime): Record<InstallTarget, TargetConfig> {+ return {+ opencode: {+ label: "opencode",+ description: "MCP server, AGENTS.md, skill plugin, commands",+ steps: [+ { name: "MCP server config", run: () => setupOpencodeMcpConfig(runtime) },+ { name: "Global AGENTS.md", run: () => setupInstructionFile(OPENCODE_AGENTS_MD_PATH) },+ { name: "Skill tool plugin", run: () => setupToolPlugin() },+ {+ name: "Bootstrap command",+ run: () => setupCommand(OPENCODE_COMMANDS_DIR, "bootstrap-memory.md", "bootstrap command"),+ },+ {+ name: "Save memory command",+ run: () => setupCommand(OPENCODE_COMMANDS_DIR, "save-memory.md", "save memory command"),+ },+ ],+ },+ claudecode: {+ label: "Claude Code",+ description: "MCP server, CLAUDE.md, commands",+ steps: [+ { name: "MCP server config", run: () => setupClaudeConfig(runtime) },+ { name: "Global CLAUDE.md", run: () => setupInstructionFile(CLAUDE_MD_PATH) },+ {+ name: "Bootstrap command",+ run: () => setupCommand(CLAUDE_COMMANDS_DIR, "bootstrap-memory.md", "bootstrap command"),+ },+ {+ name: "Save memory command",+ run: () => setupCommand(CLAUDE_COMMANDS_DIR, "save-memory.md", "save memory command"),+ },+ ],+ },+ antigravity: {+ label: "Antigravity",+ description: "MCP server config (workspace-level)",+ steps: [+ { name: "MCP server config", run: () => setupAntigravityConfig(runtime) },+ ],+ },+ };+}++const VALID_TARGETS: InstallTarget[] = ["opencode", "claudecode", "antigravity"];++function parseTargets(args: string[]): InstallTarget[] {+ const selected = new Set<InstallTarget>();++ for (let i = 0; i < args.length; i += 1) {+ const arg = args[i];+ if (arg === "--target") {+ const value = args[i + 1];+ if (!value) {+ throw new Error(`Missing value for --target. Use one of: ${VALID_TARGETS.join(", ")}`);+ }+ i += 1;+ for (const item of value.split(",")) {+ const candidate = item.trim().toLowerCase();+ if (!candidate) continue;+ if (!VALID_TARGETS.includes(candidate as InstallTarget)) {+ throw new Error(`Unknown target '${candidate}'. Use one of: ${VALID_TARGETS.join(", ")}`);+ }+ selected.add(candidate as InstallTarget);+ }+ continue;+ }++ if (arg.startsWith("--target=")) {+ const value = arg.slice("--target=".length);+ for (const item of value.split(",")) {+ const candidate = item.trim().toLowerCase();+ if (!candidate) continue;+ if (!VALID_TARGETS.includes(candidate as InstallTarget)) {+ throw new Error(`Unknown target '${candidate}'. Use one of: ${VALID_TARGETS.join(", ")}`);+ }+ selected.add(candidate as InstallTarget);+ }+ continue;+ }++ throw new Error(`Unknown install option '${arg}'. Supported: --target <name>`);+ }++ return [...selected];+}++async function chooseTargetsInteractively(): Promise<InstallTarget[]> {+ const selected = await multiSelect("Which editors would you like to configure?", [+ {+ label: "opencode",+ value: "opencode",+ description: "MCP server, AGENTS.md, skill plugin, commands",+ },+ {+ label: "Claude Code",+ value: "claudecode",+ description: "MCP server, CLAUDE.md, commands",+ },+ {+ label: "Antigravity",+ value: "antigravity",+ description: "MCP server config (workspace-level)",+ },+ ]);++ return selected.filter((value): value is InstallTarget =>+ VALID_TARGETS.includes(value as InstallTarget)+ );+}++export async function runInstall(args: string[]): Promise<void> {+ console.log();+ console.log(` ${pc.bold(pc.cyan("megamemory"))} ${pc.dim("install")}`);+ console.log();++ const runtime = await detectGlobalCommand();+ const targetConfigs = createTargetConfigs(runtime);++ let targets: InstallTarget[];+ try {+ targets = parseTargets(args);+ } catch (err) {+ error(err instanceof Error ? err.message : String(err));+ console.log(pc.dim(` Example: ${pc.cyan("megamemory install --target claudecode")}`));+ console.log();+ process.exit(1);+ return;+ }++ if (targets.length === 0) {+ targets = await chooseTargetsInteractively();+ }++ if (targets.length === 0) {+ warn("No targets selected. Nothing to do.");+ console.log();+ return;+ }++ const steps: StepResult[] = [];++ for (const target of targets) {+ const targetConfig = targetConfigs[target];+ heading(` ${pc.cyan(targetConfig.label)} ${pc.dim(`(${targetConfig.description})`)}`);++ for (let i = 0; i < targetConfig.steps.length; i += 1) {+ const step = targetConfig.steps[i];+ heading(` ${i + 1}. ${step.name}`);+ try {+ await step.run();+ steps.push({+ target,+ targetLabel: targetConfig.label,+ name: step.name,+ ok: true,+ });+ } catch (err) {+ const msg = err instanceof Error ? err.message : String(err);+ error(`${step.name} failed: ${msg}`);+ steps.push({+ target,+ targetLabel: targetConfig.label,+ name: step.name,+ ok: false,+ error: msg,+ });+ }+ console.log();+ }+ }++ const failed = steps.filter((s) => !s.ok);+ if (failed.length === 0) {+ console.log(` ${pc.green(pc.bold("Done."))}`);+ if (targets.includes("opencode")) {+ console.log(+ pc.dim(` Restart opencode, then run ${pc.cyan("/user:bootstrap-memory")} in your project.`)+ );+ console.log(+ pc.dim(` Use ${pc.cyan("/user:save-memory")} after each session to persist learnings.`)+ );+ }+ if (targets.includes("claudecode")) {+ console.log(+ pc.dim(` Restart Claude Code so it reloads ${pc.cyan("~/.claude.json")} and commands.`)+ );+ }+ } else {+ console.log(+ ` ${pc.yellow(pc.bold("Done with issues."))} ${pc.yellow(`${failed.length} step(s) failed:`)}`+ );+ for (const f of failed) {+ console.log(+ ` ${pc.red("✗")} ${f.targetLabel} — ${f.name}: ${pc.dim(f.error ?? "unknown error")}`+ );+ }+ console.log();+ console.log(pc.dim(` Steps that succeeded will still work. Fix the issues above and re-run.`));+ }+ console.log();+}