Skip to content

#1 Persistent memory for AI coding agents based on real-world benchmarks

fix(v0.9.3): address CodeRabbit review findings

Rohit Ghumare18e325799259
diff --git a/src/cli.ts b/src/cli.ts
index 89e18077..14e68b36 100644
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -89,6 +89,18 @@ function getBaseUrl(): string {
return `http://localhost:${getRestPort()}`;
}
+function getViewerUrl(): string {
+ const envUrl = process.env["AGENTMEMORY_VIEWER_URL"];
+ if (envUrl) return envUrl.replace(/\/+$/, "");
+ try {
+ const u = new URL(getBaseUrl());
+ const vPort = (parseInt(u.port || "3111", 10) || 3111) + 2;
+ return `${u.protocol}//${u.hostname}:${vPort}`;
+ } catch {
+ return `http://localhost:${getRestPort() + 2}`;
+ }
+}
+
async function isEngineRunning(): Promise<boolean> {
try {
await fetch(`${getBaseUrl()}/`, {
@@ -435,8 +447,8 @@ async function runStatus() {
const status = healthRes?.status || "unknown";
const version = healthRes?.version || "?";
const sessions = Array.isArray(sessionsRes?.sessions) ? sessionsRes.sessions.length : 0;
- const nodes = graphRes?.nodes || 0;
- const edges = graphRes?.edges || 0;
+ const nodes = Number(graphRes?.totalNodes ?? graphRes?.nodes ?? graphRes?.nodeCount ?? 0);
+ const edges = Number(graphRes?.totalEdges ?? graphRes?.edges ?? graphRes?.edgeCount ?? 0);
const cb = healthRes?.circuitBreaker?.state || "closed";
const heapMB = h?.memory ? Math.round(h.memory.heapUsed / 1048576) : 0;
const uptime = h?.uptimeSeconds ? Math.round(h.uptimeSeconds) : 0;
@@ -459,7 +471,7 @@ async function runStatus() {
`Circuit: ${cb}`,
`Heap: ${heapMB} MB`,
`Uptime: ${uptime}s`,
- `Viewer: http://localhost:${port + 2}`,
+ `Viewer: ${getViewerUrl()}`,
];
if (obsCount > 0) {
@@ -500,7 +512,7 @@ function formatChecks(checks: DoctorCheck[]): string {
async function runDoctor() {
p.intro("agentmemory doctor");
const base = getBaseUrl();
- const viewerPort = getRestPort() + 2;
+ const viewerUrl = getViewerUrl();
const checks: DoctorCheck[] = [];
const serverUp = await isEngineRunning();
@@ -521,13 +533,14 @@ async function runDoctor() {
apiFetch<any>(base, "graph/stats", 3000),
]);
- const viewerUp = await fetch(`http://localhost:${viewerPort}`, { signal: AbortSignal.timeout(2000) })
+ const viewerUp = await fetch(viewerUrl, { signal: AbortSignal.timeout(2000) })
.then((r) => r.ok)
.catch(() => false);
const hasLlm = flags?.provider === "llm";
const hasEmbed = flags?.embeddingProvider === "embeddings";
- const graphHas = (graph?.totalNodes || 0) > 0;
+ const graphNodeCount = Number(graph?.totalNodes ?? graph?.nodes ?? graph?.nodeCount ?? 0);
+ const graphHas = graphNodeCount > 0;
checks.push(
{
@@ -538,7 +551,7 @@ async function runDoctor() {
{
name: "Viewer reachable",
ok: viewerUp,
- hint: viewerUp ? undefined : `Port ${viewerPort} not responding`,
+ hint: viewerUp ? undefined : `${viewerUrl} not responding`,
},
{
name: "LLM provider",
@@ -804,7 +817,7 @@ async function runDemo() {
`Notice: searching "database performance optimization"`,
`found the N+1 query fix — keyword matching can't do that.`,
"",
- `Viewer: http://localhost:${port + 2}`,
+ `Viewer: ${getViewerUrl()}`,
`Clean up with: curl -X DELETE "${base}/agentmemory/sessions?project=${demoProject}"`,
];
@@ -1038,7 +1051,7 @@ async function runImportJsonl(): Promise<void> {
`imported ${json.imported ?? 0} file(s), ${json.observations ?? 0} observation(s) across ${json.sessionIds?.length || 0} session(s)`,
);
if (json.sessionIds && json.sessionIds.length > 0) {
- p.log.info(`View at http://localhost:${port + 2} → Replay tab`);
+ p.log.info(`View at ${getViewerUrl()} → Replay tab`);
}
} catch (err) {
spinner.stop("failed");
diff --git a/src/triggers/api.ts b/src/triggers/api.ts
index 0a84ae7b..3c993f50 100644
--- a/src/triggers/api.ts
+++ b/src/triggers/api.ts
@@ -13,6 +13,7 @@ import {
isConsolidationEnabled,
isAutoCompressEnabled,
isContextInjectionEnabled,
+ detectEmbeddingProvider,
} from "../config.js";
type Response = {
@@ -53,6 +54,36 @@ function requireConfiguredSecret(
};
}
+function flagDisabledResponse(opts: {
+ error: string;
+ flag: string;
+ enableHow: string;
+ docsHref: string;
+}): Response {
+ return {
+ status_code: 503,
+ body: opts,
+ };
+}
+
+function graphDisabledResponse(): Response {
+ return flagDisabledResponse({
+ error: "Knowledge graph not enabled",
+ flag: "GRAPH_EXTRACTION_ENABLED",
+ enableHow: "Set GRAPH_EXTRACTION_ENABLED=true and restart. Requires an LLM provider key.",
+ docsHref: "https://github.com/rohitg00/agentmemory#knowledge-graph",
+ });
+}
+
+function consolidationDisabledResponse(): Response {
+ return flagDisabledResponse({
+ error: "Consolidation pipeline not enabled",
+ flag: "CONSOLIDATION_ENABLED",
+ enableHow: "Set CONSOLIDATION_ENABLED=true and restart. Requires an LLM provider key.",
+ docsHref: "https://github.com/rohitg00/agentmemory#consolidation",
+ });
+}
+
function asNonEmptyString(value: unknown): string | null {
if (typeof value !== "string") return null;
const trimmed = value.trim();
@@ -119,10 +150,12 @@ export function registerApiTriggers(
});
sdk.registerFunction("api::config-flags",
- async (): Promise<Response> => {
+ async (req: ApiRequest): Promise<Response> => {
+ const authErr = checkAuth(req, secret);
+ if (authErr) return authErr;
const env = process.env;
- const provider = env["ANTHROPIC_API_KEY"] || env["GEMINI_API_KEY"] || env["OPENROUTER_API_KEY"] || env["MINIMAX_API_KEY"] ? "llm" : "noop";
- const embeddingProvider = env["OPENAI_API_KEY"] || env["VOYAGE_API_KEY"] || env["COHERE_API_KEY"] || env["OLLAMA_HOST"] ? "embeddings" : "none";
+ const providerKind = env["ANTHROPIC_API_KEY"] || env["GEMINI_API_KEY"] || env["OPENROUTER_API_KEY"] || env["MINIMAX_API_KEY"] ? "llm" : "noop";
+ const embeddingProvider = detectEmbeddingProvider() ? "embeddings" : "none";
const flags = [
{
key: "GRAPH_EXTRACTION_ENABLED",
@@ -173,7 +206,7 @@ export function registerApiTriggers(
status_code: 200,
body: {
version: VERSION,
- provider,
+ provider: providerKind,
embeddingProvider,
flags,
},
@@ -183,7 +216,11 @@ export function registerApiTriggers(
sdk.registerTrigger({
type: "http",
function_id: "api::config-flags",
- config: { api_path: "/agentmemory/config/flags", http_method: "GET" },
+ config: {
+ api_path: "/agentmemory/config/flags",
+ http_method: "GET",
+ middleware_function_ids: ["middleware::api-auth"],
+ },
});
sdk.registerFunction("api::health",
@@ -1019,15 +1056,7 @@ export function registerApiTriggers(
const result = await sdk.trigger({ function_id: "mem::graph-query", payload: req.body || {} });
return { status_code: 200, body: result };
} catch {
- return {
- status_code: 404,
- body: {
- error: "Knowledge graph not enabled",
- flag: "GRAPH_EXTRACTION_ENABLED",
- enableHow: "Set GRAPH_EXTRACTION_ENABLED=true and restart. Requires an LLM provider key.",
- docsHref: "https://github.com/rohitg00/agentmemory#knowledge-graph",
- },
- };
+ return graphDisabledResponse();
}
},
);
@@ -1045,15 +1074,7 @@ export function registerApiTriggers(
const result = await sdk.trigger({ function_id: "mem::graph-stats", payload: {} });
return { status_code: 200, body: result };
} catch {
- return {
- status_code: 404,
- body: {
- error: "Knowledge graph not enabled",
- flag: "GRAPH_EXTRACTION_ENABLED",
- enableHow: "Set GRAPH_EXTRACTION_ENABLED=true and restart. Requires an LLM provider key.",
- docsHref: "https://github.com/rohitg00/agentmemory#knowledge-graph",
- },
- };
+ return graphDisabledResponse();
}
},
);
@@ -1080,15 +1101,7 @@ export function registerApiTriggers(
const result = await sdk.trigger({ function_id: "mem::graph-extract", payload: req.body });
return { status_code: 200, body: result };
} catch {
- return {
- status_code: 404,
- body: {
- error: "Knowledge graph not enabled",
- flag: "GRAPH_EXTRACTION_ENABLED",
- enableHow: "Set GRAPH_EXTRACTION_ENABLED=true and restart. Requires an LLM provider key.",
- docsHref: "https://github.com/rohitg00/agentmemory#knowledge-graph",
- },
- };
+ return graphDisabledResponse();
}
},
);
@@ -1107,15 +1120,7 @@ export function registerApiTriggers(
});
return { status_code: 200, body: result };
} catch {
- return {
- status_code: 404,
- body: {
- error: "Consolidation pipeline not enabled",
- flag: "CONSOLIDATION_ENABLED",
- enableHow: "Set CONSOLIDATION_ENABLED=true and restart. Requires an LLM provider key.",
- docsHref: "https://github.com/rohitg00/agentmemory#consolidation",
- },
- };
+ return consolidationDisabledResponse();
}
},
);
diff --git a/src/viewer/index.html b/src/viewer/index.html
index 1f32447f..5de2f87f 100644
--- a/src/viewer/index.html
+++ b/src/viewer/index.html
@@ -9,6 +9,7 @@
:root {
--bg: #F9F9F7;
--bg-alt: #F0F0EC;
+ --bg-subtle: #F4F4F0;
--bg-inset: #E8E8E3;
--border: #111111;
--border-light: #D4D4CF;
@@ -43,6 +44,7 @@
html[data-theme="dark"] {
--bg: #1a1a1e;
--bg-alt: #232328;
+ --bg-subtle: #1f1f24;
--bg-inset: #2a2a30;
--border: #444;
--border-light: #3a3a42;
@@ -77,6 +79,8 @@
line-height: 1.6;
overflow: hidden;
height: 100vh;
+ display: flex;
+ flex-direction: column;
background-image: radial-gradient(circle, #D4D4CF 0.5px, transparent 0.5px);
background-size: 16px 16px;
}
@@ -168,7 +172,7 @@
border-bottom-color: var(--accent);
}
- .view { display: none; height: calc(100vh - 90px); overflow-y: auto; padding: 24px; }
+ .view { display: none; flex: 1 1 auto; min-height: 0; overflow-y: auto; padding: 24px; }
.view.active { display: block; }
.stats-grid {
@@ -588,7 +592,7 @@
/* Feature flag banner system — compact collapsed by default */
.flag-banners { padding: 0 0 10px 0; }
- .flag-summary {
+ button.flag-summary {
display: flex; align-items: center; gap: 12px;
padding: 8px 14px; border-radius: 4px;
border: 1px solid var(--border);
@@ -596,8 +600,11 @@
font-family: var(--font-ui); font-size: 12px;
color: var(--ink-muted);
cursor: pointer; user-select: none;
+ width: 100%; text-align: left;
+ appearance: none;
}
- .flag-summary:hover { background: var(--bg-alt); }
+ button.flag-summary:hover,
+ button.flag-summary:focus-visible { background: var(--bg-alt); outline: 2px solid var(--border); outline-offset: 1px; }
.flag-summary .flag-count { color: var(--ink); font-weight: 600; }
.flag-summary .flag-pill {
display: inline-block; padding: 1px 8px; border-radius: 10px;
@@ -1119,8 +1126,8 @@
var dotClass = healthStatus === 'healthy' ? 'healthy' : healthStatus === 'degraded' ? 'degraded' : healthStatus === 'critical' ? 'critical' : '';
var activeSessions = d.sessions.filter(function(s) { return s.status === 'active'; }).length;
var gs = d.graphStats || {};
- var nodeCount = (gs.nodes !== undefined) ? gs.nodes : (gs.nodeCount || 0);
- var edgeCount = (gs.edges !== undefined) ? gs.edges : (gs.edgeCount || 0);
+ var nodeCount = gs.totalNodes !== undefined ? gs.totalNodes : (gs.nodes !== undefined ? gs.nodes : (gs.nodeCount || 0));
+ var edgeCount = gs.totalEdges !== undefined ? gs.totalEdges : (gs.edges !== undefined ? gs.edges : (gs.edgeCount || 0));
var fMetrics = h.functionMetrics || [];
var cb = h.circuitBreaker || null;
var workers = snap.workers || [];
@@ -1432,8 +1439,8 @@
var sb = document.getElementById('graph-sidebar');
if (!sb) return;
var gs = state.graph.stats || {};
- var nodeCount = gs.nodes !== undefined ? gs.nodes : (gs.nodeCount || state.graph.nodes.length);
- var edgeCount = gs.edges !== undefined ? gs.edges : (gs.edgeCount || state.graph.edges.length);
+ var nodeCount = gs.totalNodes !== undefined ? gs.totalNodes : (gs.nodes !== undefined ? gs.nodes : (gs.nodeCount || state.graph.nodes.length));
+ var edgeCount = gs.totalEdges !== undefined ? gs.totalEdges : (gs.edges !== undefined ? gs.edges : (gs.edgeCount || state.graph.edges.length));
var html = '<input type="text" class="graph-search" id="graph-search" placeholder="Search nodes...">';
@@ -3356,12 +3363,12 @@
'<button class="flag-close" data-dismiss-flag="' + b.dismissKey + '" aria-label="Dismiss">&times;</button>' +
'</div>';
}).join('');
- host.innerHTML = '<div class="flag-summary" data-action="toggle-flags">' +
+ host.innerHTML = '<button type="button" class="flag-summary" data-action="toggle-flags" aria-expanded="' + (expanded ? 'true' : 'false') + '" aria-controls="flag-list">' +
pills +
'<span class="flag-count">Feature flags</span>' +
'<span style="color:var(--ink-faint);">— click to ' + (expanded ? 'collapse' : 'expand') + '</span>' +
- '<span class="flag-toggle">' + (expanded ? '&#9650;' : '&#9660;') + '</span>' +
- '</div>' +
+ '<span class="flag-toggle" aria-hidden="true">' + (expanded ? '&#9650;' : '&#9660;') + '</span>' +
+ '</button>' +
'<div class="flag-list' + (expanded ? ' open' : '') + '" id="flag-list">' + listHtml + '</div>';
}
async function fetchFlags() {