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
Polish CLI with colors, graceful errors, and port conflict handling
0xk3vin0ef74016a6a4
diff --git a/.gitignore b/.gitignoreindex 9473030..e671307 100644--- a/.gitignore+++ b/.gitignore@@ -3,3 +3,4 @@ dist/.megamemory/.osgrep/*.db+.osgrepdiff --git a/package-lock.json b/package-lock.jsonindex 2c77c4f..dd27242 100644--- a/package-lock.json+++ b/package-lock.json@@ -7,10 +7,12 @@"": {"name": "megamemory","version": "1.0.0",+ "license": "MIT","dependencies": {"@modelcontextprotocol/sdk": "^1.12.1","@xenova/transformers": "^2.17.2","better-sqlite3": "^11.7.0",+ "picocolors": "^1.1.1","zod": "^3.24.2"},"bin": {@@ -21,6 +23,9 @@"@types/node": "^20.17.14","tsx": "^4.19.2","typescript": "^5.7.3"+ },+ "engines": {+ "node": ">=18"}},"node_modules/@esbuild/aix-ppc64": {@@ -1901,6 +1906,12 @@"url": "https://opencollective.com/express"}},+ "node_modules/picocolors": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",+ "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",+ "license": "ISC"+ },"node_modules/pkce-challenge": {"version": "5.0.1","resolved": "https://registry.npmjs.org/pkce-challenge/-/pkce-challenge-5.0.1.tgz",diff --git a/package.json b/package.jsonindex 9091d04..079e189 100644--- a/package.json+++ b/package.json@@ -39,6 +39,7 @@"@modelcontextprotocol/sdk": "^1.12.1","@xenova/transformers": "^2.17.2","better-sqlite3": "^11.7.0",+ "picocolors": "^1.1.1","zod": "^3.24.2"},"devDependencies": {diff --git a/src/cli-utils.ts b/src/cli-utils.tsnew file mode 100644index 0000000..ba54699--- /dev/null+++ b/src/cli-utils.ts@@ -0,0 +1,83 @@+import pc from "picocolors";+import { createInterface } from "readline";++// ---- Styled output helpers ----++export function error(msg: string): void {+ console.error(pc.red(` ✗ ${msg}`));+}++export function errorBold(msg: string): void {+ console.error(pc.red(pc.bold(`Error: ${msg}`)));+}++export function warn(msg: string): void {+ console.log(pc.yellow(` ⚠ ${msg}`));+}++export function success(msg: string): void {+ console.log(pc.green(` ✓ ${msg}`));+}++export function skip(msg: string): void {+ console.log(pc.dim(` – ${msg}`));+}++export function info(msg: string): void {+ console.log(pc.dim(` ${msg}`));+}++export function heading(msg: string): void {+ console.log(pc.bold(msg));+}++// ---- Interactive prompts ----++export function ask(question: string): Promise<string> {+ const rl = createInterface({+ input: process.stdin,+ output: process.stdout,+ });+ return new Promise((resolve) => {+ rl.question(question, (answer) => {+ rl.close();+ resolve(answer.trim());+ });+ });+}++/**+ * 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.+ */+export async function askPort(currentPort: number): Promise<number | null> {+ // Loop instead of recursion to avoid stack overflow on repeated invalid input+ while (true) {+ const suggested = currentPort + 1;+ const answer = await ask(+ pc.yellow(` Port ${pc.bold(String(currentPort))} is already in use.\n`) ++ ` Enter a different port ${pc.dim(`(Enter for ${suggested}, q to quit)`)}: `+ );++ if (answer === "" || answer === undefined) return suggested;+ if (answer.toLowerCase() === "q" || answer.toLowerCase() === "quit") return null;++ const parsed = parseInt(answer, 10);+ if (isNaN(parsed) || parsed < 1 || parsed > 65535) {+ console.log(pc.red(` Invalid port '${answer}'. Must be a number between 1 and 65535.`));+ continue;+ }+ return parsed;+ }+}++/**+ * Validate a port number. Returns an error message or null if valid.+ */+export function validatePort(value: unknown, rawInput?: string): string | null {+ if (typeof value === "number" && !isNaN(value) && value >= 1 && value <= 65535) {+ return null;+ }+ const display = rawInput ?? String(value);+ return `Invalid port '${display}'. Port must be a number between 1 and 65535.`;+}diff --git a/src/index.ts b/src/index.tsindex b7dd3ed..895c6f0 100644--- a/src/index.ts+++ b/src/index.ts@@ -3,6 +3,8 @@import { readFileSync } from "fs";import { dirname, resolve } from "path";import { fileURLToPath } from "url";+import pc from "picocolors";+import { errorBold, validatePort } from "./cli-utils.js";// ---- CLI routing ----@@ -14,31 +16,31 @@ const VERSION = JSON.parse().version;const HELP = `-megamemory v${VERSION} — persistent project knowledge graph for coding agents--Commands:- (no command) Start the MCP stdio server (invoked by opencode)- init Configure opencode integration- serve Start the web graph explorer--Options:- --port PORT Port for the web explorer (default: 4321)- --help, -h Show this help- --version, -v Show version--Examples:- megamemory init Setup opencode config, plugins, and commands- megamemory serve Open graph explorer at http://localhost:4321- megamemory serve --port 8080 Custom port+${pc.bold(pc.cyan("megamemory"))} ${pc.green(`v${VERSION}`)} ${pc.dim("— persistent project knowledge graph for coding agents")}++${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.bold("Options:")}+ ${pc.cyan("--port")} ${pc.dim("PORT")} Port for the web explorer ${pc.dim("(default: 4321)")}+ ${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")}`.trim();-function parseFlags(args: string[]): { port?: number } {+const KNOWN_COMMANDS = new Set(["init", "serve", "--help", "-h", "--version", "-v"]);++function parseFlags(args: string[]): { port?: number; rawPort?: string } {const portIdx = args.indexOf("--port");- const port =- portIdx !== -1 && args[portIdx + 1]- ? parseInt(args[portIdx + 1], 10)- : undefined;- return { port };+ const rawPort = portIdx !== -1 && args[portIdx + 1] ? args[portIdx + 1] : undefined;+ const port = rawPort ? parseInt(rawPort, 10) : undefined;+ return { port, rawPort };}const cmd = process.argv[2];@@ -53,8 +55,16 @@ switch (cmd) {case "serve": {const flags = parseFlags(process.argv.slice(3));+ const port = flags.port ?? 4321;++ const portError = validatePort(port, flags.rawPort);+ if (portError) {+ errorBold(portError);+ process.exit(1);+ }+const { runServe } = await import("./web.js");- runServe(flags.port ?? 4321);+ await runServe(port);break;}@@ -66,12 +76,18 @@ switch (cmd) {case "--version":case "-v":- console.log(VERSION);+ console.log(`${pc.bold("megamemory")} ${pc.green(`v${VERSION}`)}`);process.exit(0);break;default:- // No command or unknown → start MCP server+ if (cmd && !KNOWN_COMMANDS.has(cmd)) {+ // User typed an unknown command — don't silently start MCP+ errorBold(`Unknown command '${cmd}'.`);+ console.log(pc.dim(` Run ${pc.cyan("megamemory --help")} for usage.\n`));+ process.exit(1);+ }+ // No command → start MCP server (normal invocation by editor)await startMcpServer();break;}diff --git a/src/init.ts b/src/init.tsindex c6b84cd..51c98ee 100644--- a/src/init.ts+++ b/src/init.ts@@ -1,5 +1,7 @@import fs from "fs";import path from "path";+import pc from "picocolors";+import { success, skip, error, info, heading } from "./cli-utils.js";// ---- Paths ----@@ -32,10 +34,6 @@ Be specific in summaries: include parameter names, defaults, file locations, and// ---- Helpers -----function log(msg: string): void {- console.log(` ${msg}`);-}-/*** Resolve absolute path to the MCP server entry point (dist/index.js).*/@@ -86,7 +84,7 @@ async function setupMcpConfig(): Promise<void> {} catch {const backup = `${OPENCODE_CONFIG_PATH}.bak`;fs.copyFileSync(OPENCODE_CONFIG_PATH, backup);- log(`Backed up malformed config to ${backup}`);+ info(`Backed up malformed config to ${pc.dim(backup)}`);config = {};}}@@ -126,12 +124,12 @@ async function setupMcpConfig(): Promise<void> {JSON.stringify(config, null, 2) + "\n");- log(+ success(existed- ? `Updated megamemory MCP in ${OPENCODE_CONFIG_PATH}`- : `Added megamemory MCP to ${OPENCODE_CONFIG_PATH}`+ ? `Updated megamemory MCP in ${pc.dim(OPENCODE_CONFIG_PATH)}`+ : `Added megamemory MCP to ${pc.dim(OPENCODE_CONFIG_PATH)}`);- log(` Command: ${JSON.stringify(command)}`);+ info(`Command: ${pc.cyan(JSON.stringify(command))}`);}function setupAgentsMd(): void {@@ -139,15 +137,15 @@ function setupAgentsMd(): void {if (fs.existsSync(OPENCODE_AGENTS_MD_PATH)) {const content = fs.readFileSync(OPENCODE_AGENTS_MD_PATH, "utf-8");if (content.includes(AGENTS_MD_MARKER)) {- log(`Already contains knowledge graph instructions — skipped`);+ skip(`Already contains knowledge graph instructions`);return;}// Append to existingfs.appendFileSync(OPENCODE_AGENTS_MD_PATH, "\n" + AGENTS_MD_SNIPPET.trimStart());- log(`Appended knowledge graph instructions to ${OPENCODE_AGENTS_MD_PATH}`);+ success(`Appended knowledge graph instructions to ${pc.dim(OPENCODE_AGENTS_MD_PATH)}`);} else {fs.writeFileSync(OPENCODE_AGENTS_MD_PATH, AGENTS_MD_SNIPPET.trimStart());- log(`Created ${OPENCODE_AGENTS_MD_PATH}`);+ success(`Created ${pc.dim(OPENCODE_AGENTS_MD_PATH)}`);}}@@ -156,7 +154,7 @@ function setupToolPlugin(): void {const dest = path.join(OPENCODE_TOOL_DIR, "megamemory.ts");if (!fs.existsSync(source)) {- log(`Plugin source not found at ${source} — skipped`);+ skip(`Plugin source not found at ${pc.dim(source)}`);return;}@@ -170,15 +168,15 @@ function setupToolPlugin(): void {if (fs.existsSync(dest)) {const existing = fs.readFileSync(dest, "utf-8");if (existing === sourceContent) {- log(`Tool plugin already up to date — skipped`);+ skip(`Tool plugin already up to date`);return;}// Updatefs.writeFileSync(dest, sourceContent);- log(`Updated tool plugin at ${dest}`);+ success(`Updated tool plugin at ${pc.dim(dest)}`);} else {fs.writeFileSync(dest, sourceContent);- log(`Installed tool plugin at ${dest}`);+ success(`Installed tool plugin at ${pc.dim(dest)}`);}}@@ -187,7 +185,7 @@ function setupBootstrapCommand(): void {const dest = path.join(OPENCODE_COMMANDS_DIR, "bootstrap-memory.md");if (!fs.existsSync(source)) {- log(`Command source not found at ${source} — skipped`);+ skip(`Command source not found at ${pc.dim(source)}`);return;}@@ -200,36 +198,100 @@ function setupBootstrapCommand(): void {if (fs.existsSync(dest)) {const existing = fs.readFileSync(dest, "utf-8");if (existing === sourceContent) {- log(`Bootstrap command already up to date — skipped`);+ skip(`Bootstrap command already up to date`);return;}fs.writeFileSync(dest, sourceContent);- log(`Updated bootstrap command at ${dest}`);+ success(`Updated bootstrap command at ${pc.dim(dest)}`);} else {fs.writeFileSync(dest, sourceContent);- log(`Installed bootstrap command at ${dest}`);+ success(`Installed bootstrap command at ${pc.dim(dest)}`);}}// ---- Entry point ----+interface StepResult {+ name: string;+ ok: boolean;+ error?: string;+}+export async function runInit(): Promise<void> {- console.log("\nmegamemory init\n");+ console.log();+ console.log(` ${pc.bold(pc.cyan("megamemory"))} ${pc.dim("init")}`);+ console.log();- console.log("1. MCP server config:");- await setupMcpConfig();+ const steps: StepResult[] = [];- console.log("\n2. Global AGENTS.md:");- setupAgentsMd();+ // 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("\n3. Skill tool plugin:");- setupToolPlugin();+ console.log();- console.log("\n4. Bootstrap command:");- setupBootstrapCommand();+ // 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(- "\nDone. Restart opencode to pick up changes." +- "\nRun /user:bootstrap-memory in any project to populate its knowledge graph.\n"- );+ 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 {+ setupBootstrapCommand();+ 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();++ // 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")} in any project to populate its knowledge graph.`)+ );+ } 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/web.ts b/src/web.tsindex 53a025c..783e54f 100644--- a/src/web.ts+++ b/src/web.ts@@ -1,12 +1,22 @@import http from "http";import fs from "fs";import path from "path";+import { fileURLToPath } from "url";+import pc from "picocolors";import { KnowledgeDB } from "./db.js";import { buildNodeWithContext } from "./tools.js";+import { errorBold, askPort } from "./cli-utils.js";import type { NodeRow } from "./types.js";+const VERSION = JSON.parse(+ fs.readFileSync(+ path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "package.json"),+ "utf-8"+ )+).version;+function resolveHtmlPath(): string {- const thisDir = path.dirname(new URL(import.meta.url).pathname);+ const thisDir = path.dirname(fileURLToPath(import.meta.url));// From dist/ → ../web/index.htmlconst fromDist = path.resolve(thisDir, "..", "web", "index.html");if (fs.existsSync(fromDist)) return fromDist;@@ -41,15 +51,71 @@ function parseFileRefs(raw: string | null): string[] | null {}}-export function runServe(port: number): void {+function printBanner(port: number, dbPath: string): void {+ console.log();+ console.log(` ${pc.bold(pc.cyan("megamemory"))} ${pc.green(`v${VERSION}`)} ${pc.dim("explorer")}`);+ console.log();+ console.log(` ${pc.dim("➜")} ${pc.bold("Local:")} ${pc.cyan(pc.underline(`http://localhost:${port}`))}`);+ console.log(` ${pc.dim("➜")} ${pc.bold("DB:")} ${pc.dim(dbPath)}`);+ console.log();+ console.log(" Press Ctrl+C to stop.");+ console.log();+}++/**+ * Attempt to listen on the given port. If EADDRINUSE, prompt the user+ * for an alternative port and retry. Returns a promise that resolves+ * once the server is listening.+ */+function listenWithRetry(+ server: http.Server,+ port: number,+ dbPath: string,+): Promise<void> {+ return new Promise((resolve, reject) => {+ const onError = async (err: NodeJS.ErrnoException) => {+ if (err.code === "EADDRINUSE") {+ server.removeListener("error", onError);+ try {+ const newPort = await askPort(port);+ if (newPort === null) {+ console.log(pc.dim(" Cancelled.\n"));+ process.exit(0);+ }+ // Retry with the new port+ resolve(listenWithRetry(server, newPort, dbPath));+ } catch (promptErr) {+ reject(promptErr);+ }+ } else if (err.code === "EACCES") {+ errorBold(`Permission denied for port ${port}. Try a port above 1024.`);+ process.exit(1);+ } else {+ reject(err);+ }+ };++ server.once("error", onError);++ server.listen(port, () => {+ server.removeListener("error", onError);+ printBanner(port, dbPath);+ resolve();+ });+ });+}++export async function runServe(port: number): Promise<void> {const dbPath =process.env.MEGAMEMORY_DB_PATH ??path.join(process.cwd(), ".megamemory", "knowledge.db");if (!fs.existsSync(dbPath)) {- console.error(- `No database found at ${dbPath}\n` +- `Run megamemory in a project that has been used with the MCP server, or set MEGAMEMORY_DB_PATH.`+ console.log();+ errorBold(`No database found at ${pc.dim(dbPath)}`);+ console.log(+ pc.dim(` Run megamemory in a project that has been used with the MCP server,\n`) ++ pc.dim(` or set ${pc.cyan("MEGAMEMORY_DB_PATH")} environment variable.\n`));process.exit(1);}@@ -58,11 +124,13 @@ export function runServe(port: number): void {const htmlPath = resolveHtmlPath();if (!fs.existsSync(htmlPath)) {- console.error(`HTML file not found at ${htmlPath}`);+ console.log();+ errorBold(`HTML file not found at ${pc.dim(htmlPath)}`);+ console.log(pc.dim(` This may indicate an incomplete installation. Try reinstalling megamemory.\n`));process.exit(1);}- const htmlContent = fs.readFileSync(htmlPath, "utf-8");+ const htmlContent = fs.readFileSync(htmlPath, "utf-8").replaceAll("{{VERSION}}", VERSION);const server = http.createServer((req, res) => {const url = new URL(req.url ?? "/", `http://localhost:${port}`);@@ -135,14 +203,11 @@ export function runServe(port: number): void {notFound(res);});- server.listen(port, () => {- console.log(`megamemory explorer running at http://localhost:${port}`);- console.log(`Database: ${dbPath}`);- console.log(`Press Ctrl+C to stop.\n`);- });+ await listenWithRetry(server, port, dbPath);// Graceful shutdownprocess.on("SIGINT", () => {+ console.log(pc.dim("\n Shutting down...\n"));server.close();db.close();process.exit(0);