Skip to content

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

feat(status): GET /agentmemory/status and a viewer Health tab (#1408)

Rohit Ghumare20f26e4e1026
diff --git a/AGENTS.md b/AGENTS.md
index a2226903..58f7e87e 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -119,7 +119,7 @@ Hook scripts in `src/hooks/` are standalone Node.js scripts (no iii-sdk import).
## Current Stats (v0.9.29)
- 54 MCP tools (8 visible by default, `AGENTMEMORY_TOOLS=all` for all)
-- 130 REST endpoints
+- 131 REST endpoints
- 6 MCP resources, 3 MCP prompts
- 12 hooks, 17 skills
- 260+ iii functions
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a95daeda..38fc2ba6 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -18,6 +18,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
### Added
+- **`GET /agentmemory/status` and a Health tab in the viewer.** One report of what is wrong and how to fix it: the health monitor state and alerts, the LLM and embedding providers and the circuit breaker, functions failing on at least 20% of their calls (with a provider-specific fix for summarize, compress and graph extraction), observations missing from the search index (the same exact check the boot reconcile runs), graph snapshot age, ports, uptime, the pinned engine version and every feature flag with how to enable it. Browsers get an HTML page with no scripts and a strict CSP; everything else gets JSON (`?format=json` or `?format=html` force either). Every probe is time-boxed at 5 s so a slow store cannot hang the page. Uses the same bearer auth as the rest of the API.
- **`agentmemory console`** launches the iii web console (workers, functions, triggers, queues, traces) through the pinned engine, against the ports agentmemory resolved, one port above the viewer by default (`--console-port` overrides). Engine 0.22 ships the console as part of `iii` and downloads it on first use, so the "install iii console?" prompt on start and the `skipConsoleInstall` preference are gone; the ready panel now points at the command instead.
### Fixed
diff --git a/README.md b/README.md
index 8c376ddd..8fc01484 100644
--- a/README.md
+++ b/README.md
@@ -1608,7 +1608,7 @@ Create `~/.agentmemory/.env`:
<h2 id="api"><picture><source media="(prefers-color-scheme: dark)" srcset="assets/tags/light/section-api.svg"><img src="assets/tags/section-api.svg" alt="API" height="32" /></picture></h2>
-130 endpoints on port `3111`. The REST API binds to `127.0.0.1` by default. Protected endpoints require `Authorization: Bearer <secret>` when `AGENTMEMORY_SECRET` is set, and mesh sync endpoints require `AGENTMEMORY_SECRET` on both peers.
+131 endpoints on port `3111`. The REST API binds to `127.0.0.1` by default. Protected endpoints require `Authorization: Bearer <secret>` when `AGENTMEMORY_SECRET` is set, and mesh sync endpoints require `AGENTMEMORY_SECRET` on both peers.
<details>
<summary>Key endpoints</summary>
diff --git a/plugin/skills/agentmemory-rest-api/REFERENCE.md b/plugin/skills/agentmemory-rest-api/REFERENCE.md
index a176863c..bacd540f 100644
--- a/plugin/skills/agentmemory-rest-api/REFERENCE.md
+++ b/plugin/skills/agentmemory-rest-api/REFERENCE.md
@@ -5,7 +5,7 @@ Generated from `src/triggers/api.ts`. Do not edit the block below by hand; run `
<!-- AUTOGEN:rest START - generated by scripts/skills/generate.ts, do not edit by hand -->
The REST API is the primary surface. All paths are under `http://localhost:3111` (override with `--port`). When `AGENTMEMORY_SECRET` is set, send `Authorization: Bearer $AGENTMEMORY_SECRET`; localhost is otherwise open.
-130 registered endpoints:
+131 registered endpoints:
| Method | Path |
| --- | --- |
@@ -130,6 +130,7 @@ The REST API is the primary surface. All paths are under `http://localhost:3111`
| POST | `/agentmemory/snapshot/create` |
| POST | `/agentmemory/snapshot/restore` |
| GET | `/agentmemory/snapshots` |
+| GET | `/agentmemory/status` |
| POST | `/agentmemory/summarize` |
| GET | `/agentmemory/team/feed` |
| GET | `/agentmemory/team/profile` |
diff --git a/src/cli.ts b/src/cli.ts
index de20cad9..832428eb 100644
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -79,7 +79,7 @@ import { isFirstRun, readPrefs, resetPrefs, writePrefs } from "./cli/preferences
import { runOnboarding } from "./cli/onboarding.js";
import { setBootVerbose } from "./logger.js";
import { hydrateProcessEnvFromFile } from "./config.js";
-import { VERSION } from "./version.js";
+import { III_PINNED_VERSION, VERSION } from "./version.js";
import { getAllTools, ESSENTIAL_TOOLS } from "./mcp/tools-registry.js";
import { knownAgents } from "./cli/connect/index.js";
@@ -130,7 +130,7 @@ if (args.includes("--version") || args.includes("-V")) {
// constant and the two package.json dependencies together.
// AGENTMEMORY_III_VERSION overrides the pin for anyone running a
// self-managed engine.
-const IIPINNED_DEFAULT_VERSION = "0.22.1";
+const IIPINNED_DEFAULT_VERSION = III_PINNED_VERSION;
const IIPINNED_VERSION =
process.env["AGENTMEMORY_III_VERSION"] || IIPINNED_DEFAULT_VERSION;
const IIIENGINE_INSTALL_CMD = `curl -fsSL https://install.iii.dev/iii/main/install.sh | VERSION=${IIPINNED_VERSION} sh`;
diff --git a/src/functions/search.ts b/src/functions/search.ts
index bb585aa0..2b8858bd 100644
--- a/src/functions/search.ts
+++ b/src/functions/search.ts
@@ -309,7 +309,9 @@ export async function indexRecords(
return count
}
-export async function reconcileIndex(kv: StateKV): Promise<number> {
+export async function findUnindexedObservations(
+ kv: StateKV,
+): Promise<{ sessions: number; missing: CompressedObservation[] }> {
const idx = getSearchIndex()
const sessions = await kv.list<Session>(KV.sessions)
const indexed = idx.observationCountsBySession()
@@ -323,6 +325,12 @@ export async function reconcileIndex(kv: StateKV): Promise<number> {
missing.push(obs)
}
}
+ return { sessions: sessions.length, missing }
+}
+
+export async function reconcileIndex(kv: StateKV): Promise<number> {
+ const idx = getSearchIndex()
+ const { missing } = await findUnindexedObservations(kv)
const stillMissing = missing.filter((obs) => !idx.has(obs.id))
if (stillMissing.length === 0) return 0
return indexRecords(stillMissing, [])
diff --git a/src/functions/status.ts b/src/functions/status.ts
new file mode 100644
index 00000000..552fe6c0
--- /dev/null
+++ b/src/functions/status.ts
@@ -0,0 +1,378 @@
+export type StatusLevel = "ok" | "info" | "warn" | "error";
+
+export interface StatusProblem {
+ level: Exclude<StatusLevel, "ok">;
+ code: string;
+ message: string;
+ fix?: string;
+}
+
+export interface FunctionMetricInput {
+ functionId: string;
+ totalCalls: number;
+ successCount: number;
+ failureCount: number;
+ avgLatencyMs: number;
+}
+
+export interface StatusFlag {
+ key: string;
+ label: string;
+ enabled: boolean;
+ needsLlm: boolean;
+ enableHow: string;
+}
+
+export interface GraphStatsInput {
+ totalNodes?: number;
+ totalEdges?: number;
+ fromSnapshot?: boolean;
+ updatedAt?: string;
+ dirty?: boolean;
+ warning?: string;
+}
+
+export interface StatusInputs {
+ now: Date;
+ version: string;
+ engineVersion: string;
+ uptimeSeconds: number;
+ ports: { rest: number | null; streams: number | null; viewer: number | null };
+ health: {
+ status?: string;
+ alerts?: string[];
+ notes?: string[];
+ connectionState?: string;
+ } | null;
+ circuitBreaker: { state?: string; failures?: number } | null;
+ functionMetrics: FunctionMetricInput[];
+ provider: string;
+ embeddingProvider: string;
+ flags: StatusFlag[];
+ index: {
+ bm25Documents: number;
+ vectorDocuments: number | null;
+ observationsIndexed: number;
+ missingObservations: number | null;
+ sessions: number | null;
+ };
+ graph: GraphStatsInput | null;
+ graphExtractionEnabled: boolean;
+}
+
+export interface StatusReport {
+ status: StatusLevel;
+ checkedAt: string;
+ service: {
+ version: string;
+ engineVersion: string;
+ uptimeSeconds: number;
+ ports: StatusInputs["ports"];
+ };
+ health: StatusInputs["health"];
+ provider: { llm: string; embeddings: string; circuitBreaker: StatusInputs["circuitBreaker"] };
+ index: StatusInputs["index"];
+ graph: (GraphStatsInput & { ageSeconds: number | null; extractionEnabled: boolean }) | null;
+ functions: Array<FunctionMetricInput & { failureRate: number }>;
+ flags: StatusFlag[];
+ problems: StatusProblem[];
+}
+
+const FAILURE_RATE_THRESHOLD = 0.2;
+const FAILURE_MIN_CALLS = 5;
+const GRAPH_SNAPSHOT_STALE_SECONDS = 24 * 60 * 60;
+const LEVEL_RANK: Record<StatusLevel, number> = { ok: 0, info: 1, warn: 2, error: 3 };
+
+const FUNCTION_FIXES: Record<string, string> = {
+ "mem::summarize":
+ "Summaries come from your LLM provider. Check the provider key, model name and rate limits in ~/.agentmemory/.env, then look for provider errors in the server log.",
+ "mem::compress":
+ "Compression calls your LLM provider. Check the provider key and model, or set AGENTMEMORY_AUTO_COMPRESS=false to use zero-LLM compression.",
+ "mem::graph-extract":
+ "Graph extraction calls your LLM provider. Check the provider key and model, or set GRAPH_EXTRACTION_ENABLED=false.",
+};
+
+function secondsBetween(later: Date, earlierIso: string | undefined): number | null {
+ if (!earlierIso) return null;
+ const earlier = Date.parse(earlierIso);
+ if (Number.isNaN(earlier)) return null;
+ return Math.max(0, Math.round((later.getTime() - earlier) / 1000));
+}
+
+export function evaluateStatus(input: StatusInputs): StatusReport {
+ const problems: StatusProblem[] = [];
+
+ if (!input.health) {
+ problems.push({
+ level: "info",
+ code: "health-check-unavailable",
+ message: "The health monitor has no snapshot yet or did not answer in time, so its state was not checked.",
+ });
+ }
+ const healthStatus = input.health?.status;
+ if (healthStatus === "critical") {
+ problems.push({ level: "error", code: "health-critical", message: "The health monitor reports a critical state." });
+ } else if (healthStatus === "degraded") {
+ problems.push({ level: "warn", code: "health-degraded", message: "The health monitor reports a degraded state." });
+ }
+ for (const alert of input.health?.alerts ?? []) {
+ problems.push({ level: "warn", code: "health-alert", message: alert });
+ }
+
+ if (input.circuitBreaker?.state === "open") {
+ problems.push({
+ level: "error",
+ code: "provider-circuit-open",
+ message: `LLM provider calls are paused after ${input.circuitBreaker.failures ?? 0} consecutive failures.`,
+ fix: "Check the provider key and model in ~/.agentmemory/.env. Calls resume automatically once the provider answers again.",
+ });
+ }
+
+ if (input.provider === "noop") {
+ problems.push({
+ level: "info",
+ code: "no-llm-provider",
+ message: "No LLM provider is configured, so summaries, consolidation and graph extraction stay off. Search still works.",
+ fix: "Add one provider key (for example ANTHROPIC_API_KEY or OPENAI_API_KEY) to ~/.agentmemory/.env and restart.",
+ });
+ }
+
+ const functions = input.functionMetrics.map((m) => ({
+ ...m,
+ failureRate: m.totalCalls > 0 ? m.failureCount / m.totalCalls : 0,
+ }));
+ for (const fn of functions) {
+ if (fn.totalCalls < FAILURE_MIN_CALLS || fn.failureRate < FAILURE_RATE_THRESHOLD) continue;
+ problems.push({
+ level: "warn",
+ code: "function-failing",
+ message: `${fn.functionId} failed ${fn.failureCount} of ${fn.totalCalls} calls (${Math.round(fn.failureRate * 100)}%).`,
+ fix: FUNCTION_FIXES[fn.functionId] ?? "Look for this function id in the server log to see the error.",
+ });
+ }
+
+ const missingObservations = input.index.missingObservations;
+ if (missingObservations !== null && missingObservations > 0) {
+ problems.push({
+ level: "warn",
+ code: "index-missing-observations",
+ message: `${missingObservations} stored observations are not in the search index, so search cannot find them.`,
+ fix: "Restart agentmemory: the boot reconcile re-indexes observations missing from the snapshot.",
+ });
+ }
+ if (missingObservations === null) {
+ problems.push({
+ level: "info",
+ code: "index-check-unavailable",
+ message: "The session store did not answer in time, so the search index was not checked for missing observations.",
+ });
+ }
+
+ let graph: StatusReport["graph"] = null;
+ if (input.graph) {
+ const ageSeconds = secondsBetween(input.now, input.graph.updatedAt);
+ graph = { ...input.graph, ageSeconds, extractionEnabled: input.graphExtractionEnabled };
+ if (input.graphExtractionEnabled && !input.graph.fromSnapshot) {
+ problems.push({
+ level: "warn",
+ code: "graph-no-snapshot",
+ message: "Graph extraction is on but no graph snapshot exists, so graph counts read as zero.",
+ fix: "Use Rebuild Graph in the viewer, or POST /agentmemory/graph/snapshot-rebuild.",
+ });
+ } else if (input.graph.fromSnapshot && ageSeconds !== null && ageSeconds > GRAPH_SNAPSHOT_STALE_SECONDS) {
+ const age = ageSeconds >= 2 * 86400 ? `${Math.floor(ageSeconds / 86400)} days` : `${Math.round(ageSeconds / 3600)} hours`;
+ problems.push({
+ level: "info",
+ code: "graph-snapshot-stale",
+ message: `The graph snapshot is ${age} old, so dashboard graph counts can lag the live graph.`,
+ fix: "POST /agentmemory/graph/snapshot-rebuild refreshes it.",
+ });
+ }
+ if (input.graph.dirty) {
+ problems.push({
+ level: "info",
+ code: "graph-snapshot-dirty",
+ message: "The graph snapshot was read while a write was in flight; counts are eventually consistent.",
+ });
+ }
+ }
+
+ const status = problems.reduce<StatusLevel>(
+ (worst, p) => (LEVEL_RANK[p.level] > LEVEL_RANK[worst] ? p.level : worst),
+ "ok",
+ );
+
+ return {
+ status,
+ checkedAt: input.now.toISOString(),
+ service: {
+ version: input.version,
+ engineVersion: input.engineVersion,
+ uptimeSeconds: input.uptimeSeconds,
+ ports: input.ports,
+ },
+ health: input.health,
+ provider: {
+ llm: input.provider,
+ embeddings: input.embeddingProvider,
+ circuitBreaker: input.circuitBreaker,
+ },
+ index: input.index,
+ graph,
+ functions,
+ flags: input.flags,
+ problems,
+ };
+}
+
+function escapeHtml(value: unknown): string {
+ return String(value ?? "")
+ .replace(/&/g, "&amp;")
+ .replace(/</g, "&lt;")
+ .replace(/>/g, "&gt;")
+ .replace(/"/g, "&quot;")
+ .replace(/'/g, "&#39;");
+}
+
+function formatDuration(seconds: number | null): string {
+ if (seconds === null) return "unknown";
+ if (seconds < 60) return `${seconds}s`;
+ const minutes = Math.floor(seconds / 60);
+ if (minutes < 60) return `${minutes}m`;
+ const hours = Math.floor(minutes / 60);
+ if (hours < 48) return `${hours}h ${minutes % 60}m`;
+ return `${Math.floor(hours / 24)}d`;
+}
+
+function row(label: string, value: string): string {
+ return `<tr><th>${escapeHtml(label)}</th><td>${value}</td></tr>`;
+}
+
+export function renderStatusHtml(report: StatusReport, styleNonce: string): string {
+ const problems = report.problems.length
+ ? report.problems
+ .map(
+ (p) =>
+ `<li class="p ${p.level}"><span class="lvl">${p.level}</span><div><p>${escapeHtml(p.message)}</p>` +
+ (p.fix ? `<p class="fix">${escapeHtml(p.fix)}</p>` : "") +
+ `</div></li>`,
+ )
+ .join("")
+ : `<li class="p ok"><span class="lvl">ok</span><div><p>No problems found.</p></div></li>`;
+
+ const functions = report.functions.length
+ ? report.functions
+ .slice()
+ .sort((a, b) => b.totalCalls - a.totalCalls)
+ .map(
+ (f) =>
+ `<tr${f.failureRate >= FAILURE_RATE_THRESHOLD && f.totalCalls >= FAILURE_MIN_CALLS ? ' class="bad"' : ""}>` +
+ `<td>${escapeHtml(f.functionId)}</td><td>${f.totalCalls}</td><td>${f.failureCount}</td>` +
+ `<td>${Math.round(f.failureRate * 100)}%</td><td>${Math.round(f.avgLatencyMs)} ms</td></tr>`,
+ )
+ .join("")
+ : `<tr><td colspan="5">No function calls recorded yet.</td></tr>`;
+
+ const flags = report.flags
+ .map(
+ (f) =>
+ `<tr><td>${escapeHtml(f.label)}</td><td>${f.enabled ? "on" : "off"}</td>` +
+ `<td>${f.enabled ? "" : escapeHtml(f.enableHow)}</td></tr>`,
+ )
+ .join("");
+
+ const idx = report.index;
+ const graph = report.graph;
+ const ports = report.service.ports;
+
+ return `<!DOCTYPE html>
+<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
+<title>agentmemory status</title>
+<style nonce="${escapeHtml(styleNonce)}">
+:root{--bg:#fafaf9;--ink:#18181b;--muted:#52525b;--line:#e4e4e7;--ok:#15803d;--info:#1d4ed8;--warn:#b45309;--error:#b91c1c}
+@media (prefers-color-scheme:dark){:root{--bg:#0c0c0e;--ink:#f4f4f5;--muted:#a1a1aa;--line:#27272a;--ok:#4ade80;--info:#93c5fd;--warn:#fbbf24;--error:#f87171}}
+*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--ink);font:14px/1.5 ui-sans-serif,system-ui,-apple-system,sans-serif}
+main{max-width:960px;margin:0 auto;padding:32px 16px 64px}
+header{display:flex;align-items:baseline;gap:12px;flex-wrap:wrap;border-bottom:2px solid var(--ink);padding-bottom:12px;margin-bottom:24px}
+h1{font-size:22px;margin:0}h2{font-size:13px;letter-spacing:.08em;text-transform:uppercase;color:var(--muted);margin:32px 0 8px}
+.badge{font-weight:700;text-transform:uppercase;letter-spacing:.06em;font-size:12px;padding:2px 8px;border:1.5px solid currentColor}
+.ok{color:var(--ok)}.info{color:var(--info)}.warn{color:var(--warn)}.error{color:var(--error)}
+.meta{color:var(--muted);font-size:12px;margin-left:auto}
+ul.problems{list-style:none;padding:0;margin:0}
+li.p{display:grid;grid-template-columns:64px 1fr;gap:12px;padding:12px 0;border-bottom:1px solid var(--line)}
+li.p p{margin:0;color:var(--ink)}li.p .fix{color:var(--muted);margin-top:4px}
+.lvl{font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.06em;padding-top:2px}
+table{width:100%;border-collapse:collapse}th,td{text-align:left;padding:6px 8px;border-bottom:1px solid var(--line);vertical-align:top}
+th{color:var(--muted);font-weight:500;width:220px}
+table.list th{width:auto;font-size:12px}tr.bad td{color:var(--error)}
+code{font:12px ui-monospace,SFMono-Regular,Menlo,monospace}
+a{color:inherit}
+</style></head><body><main>
+<header><h1>agentmemory</h1><span class="badge ${report.status}">${report.status}</span>
+<span class="meta">v${escapeHtml(report.service.version)} · engine ${escapeHtml(report.service.engineVersion)} · checked ${escapeHtml(report.checkedAt)} · <a href="">refresh</a> · <a href="?format=json">json</a></span></header>
+<h2>Problems</h2><ul class="problems">${problems}</ul>
+<h2>Service</h2><table>
+${row("Uptime", escapeHtml(formatDuration(report.service.uptimeSeconds)))}
+${row("REST port", escapeHtml(ports.rest ?? "unknown"))}
+${row("Streams port", escapeHtml(ports.streams ?? "unknown"))}
+${row("Viewer port", escapeHtml(ports.viewer ?? "not running"))}
+${row("Health monitor", escapeHtml(report.health?.status ?? "no data yet"))}
+${row("Engine connection", escapeHtml(report.health?.connectionState ?? "unknown"))}
+</table>
+<h2>Providers</h2><table>
+${row("LLM", escapeHtml(report.provider.llm))}
+${row("Embeddings", escapeHtml(report.provider.embeddings))}
+${row("Circuit breaker", escapeHtml(report.provider.circuitBreaker ? `${report.provider.circuitBreaker.state ?? "unknown"} (${report.provider.circuitBreaker.failures ?? 0} failures)` : "not in use"))}
+</table>
+<h2>Search index</h2><table>
+${row("BM25 documents", escapeHtml(idx.bm25Documents))}
+${row("Vector documents", escapeHtml(idx.vectorDocuments ?? "vector search off"))}
+${row("Observations indexed", escapeHtml(idx.observationsIndexed))}
+${row("Missing from index", escapeHtml(idx.missingObservations ?? "not checked"))}
+${row("Sessions", escapeHtml(idx.sessions ?? "unknown"))}
+</table>
+<h2>Knowledge graph</h2><table>
+${graph
+ ? row("Extraction", graph.extractionEnabled ? "on" : "off") +
+ row("Nodes / edges", escapeHtml(`${graph.totalNodes ?? 0} / ${graph.totalEdges ?? 0}`)) +
+ row("Snapshot age", escapeHtml(graph.fromSnapshot ? formatDuration(graph.ageSeconds) : "no snapshot"))
+ : row("Graph", "unavailable")}
+</table>
+<h2>Functions</h2><table class="list"><tr><th>Function</th><th>Calls</th><th>Failed</th><th>Failure rate</th><th>Avg latency</th></tr>${functions}</table>
+<h2>Features</h2><table class="list"><tr><th>Feature</th><th>State</th><th>How to enable</th></tr>${flags}</table>
+<h2>More</h2><p>Environment checks (keys, engine binary, stale pid files) run on your machine with <code>agentmemory doctor</code>. This page as JSON: <code>GET /agentmemory/status</code> with <code>Accept: application/json</code>.</p>
+</main></body></html>`;
+}
+
+export const UNINDEXED_SCAN_REUSE_MS = 30_000;
+
+export function singleFlight<T>(
+ run: () => Promise<T>,
+ reuseMs: number,
+ now: () => number = Date.now,
+): () => Promise<T> {
+ let current: { promise: Promise<T>; settledAt: number | null } | null = null;
+ return () => {
+ if (current && (current.settledAt === null || now() - current.settledAt < reuseMs)) {
+ return current.promise;
+ }
+ const entry: { promise: Promise<T>; settledAt: number | null } = { promise: run(), settledAt: null };
+ entry.promise.then(
+ () => {
+ entry.settledAt = now();
+ },
+ () => {
+ if (current === entry) current = null;
+ },
+ );
+ current = entry;
+ return entry.promise;
+ };
+}
+
+export function prefersHtml(accept: string | undefined, format: string | undefined): boolean {
+ if (format === "json") return false;
+ if (format === "html") return true;
+ if (!accept) return false;
+ return /\btext\/html\b/.test(accept);
+}
diff --git a/src/index.ts b/src/index.ts
index 2cef7451..60138963 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -549,7 +549,7 @@ async function main() {
`Ready. ${embeddingProvider ? "Triple-stream (BM25+Vector+Graph)" : "BM25+Graph"} search active.`,
);
bootLog(
- `REST API: 130 endpoints at http://localhost:${config.restPort}/agentmemory/*`,
+ `REST API: 131 endpoints at http://localhost:${config.restPort}/agentmemory/*`,
);
bootLog(
`MCP surface (opt-in via \`npx @agentmemory/mcp\`): ${getAllTools().length} tools · 6 resources · 3 prompts`,
diff --git a/src/triggers/api.ts b/src/triggers/api.ts
index 9130381f..78426e80 100644
--- a/src/triggers/api.ts
+++ b/src/triggers/api.ts
@@ -1,5 +1,6 @@
import { TriggerAction, type IIIClient } from "iii-sdk";
import type { HttpRequest } from "@iii-dev/helpers/http";
+import { randomBytes } from "node:crypto";
import type { Session, CompressedObservation, HookPayload, CommitLink, SessionSummary } from "../types.js";
import { withKeyedLock } from "../state/keyed-mutex.js";
import { KV } from "../state/schema.js";
@@ -8,7 +9,9 @@ import { StateKV } from "../state/kv.js";
import { getLatestHealth } from "../health/monitor.js";
import type { MetricsStore } from "../eval/metrics-store.js";
import type { ResilientProvider } from "../providers/resilient.js";
-import { VERSION } from "../version.js";
+import { III_PINNED_VERSION, VERSION } from "../version.js";
+import { UNINDEXED_SCAN_REUSE_MS, evaluateStatus, prefersHtml, renderStatusHtml, singleFlight, type GraphStatsInput } from "../functions/status.js";
+import { findUnindexedObservations, getSearchIndex, getVectorIndex } from "../functions/search.js";
import { timingSafeCompare } from "../auth.js";
import { isSlotsEnabled, isReflectEnabled } from "../functions/slots.js";
import { renderViewerDocument } from "../viewer/document.js";
@@ -138,6 +141,55 @@ function parseOptionalPositiveInt(value: unknown): number | undefined | null {
return parsed;
}
+function buildConfigFlags() {
+ return [
+ {
+ key: "GRAPH_EXTRACTION_ENABLED",
+ label: "Knowledge graph extraction",
+ enabled: isGraphExtractionEnabled(),
+ default: false,
+ affects: ["Graph", "Dashboard"],
+ needsLlm: true,
+ description: "Extracts entities and relations from observations into a knowledge graph.",
+ enableHow: "Set GRAPH_EXTRACTION_ENABLED=true and provide an LLM key, then restart.",
+ docsHref: "https://github.com/rohitg00/agentmemory#knowledge-graph",
+ },
+ {
+ key: "CONSOLIDATION_ENABLED",
+ label: "Memory consolidation",
+ enabled: isConsolidationEnabled(),
+ default: false,
+ affects: ["Dashboard", "Memories", "Crystals"],
+ needsLlm: true,
+ description: "Periodically summarizes sessions into semantic facts + procedures.",
+ enableHow: "Set CONSOLIDATION_ENABLED=true and provide an LLM key, then restart.",
+ docsHref: "https://github.com/rohitg00/agentmemory#consolidation",
+ },
+ {
+ key: "AGENTMEMORY_AUTO_COMPRESS",
+ label: "LLM-powered observation compression",
+ enabled: isAutoCompressEnabled(),
+ default: false,
+ affects: ["Memories", "Timeline"],
+ needsLlm: true,
+ description: "Every observation is compressed by the LLM for richer summaries (costs tokens). OFF uses zero-LLM synthetic compression.",
+ enableHow: "Set AGENTMEMORY_AUTO_COMPRESS=true and provide an LLM key.",
+ docsHref: "https://github.com/rohitg00/agentmemory/issues/138",
+ },
+ {
+ key: "AGENTMEMORY_INJECT_CONTEXT",
+ label: "In-conversation context injection",
+ enabled: isContextInjectionEnabled(),
+ default: false,
+ affects: ["Hooks"],
+ needsLlm: false,
+ description: "Hooks write recalled context into Claude Code's conversation. OFF captures in the background without injecting.",
+ enableHow: "Set AGENTMEMORY_INJECT_CONTEXT=true and restart.",
+ docsHref: "https://github.com/rohitg00/agentmemory/issues/143",
+ },
+ ];
+}
+
export function registerApiTriggers(
sdk: IIIClient,
kv: StateKV,
@@ -197,52 +249,7 @@ export function registerApiTriggers(
if (authErr) return authErr;
const providerKind = detectLlmProviderKind();
const embeddingProvider = detectEmbeddingProvider() ? "embeddings" : "none";
- const flags = [
- {
- key: "GRAPH_EXTRACTION_ENABLED",
- label: "Knowledge graph extraction",
- enabled: isGraphExtractionEnabled(),
- default: false,
- affects: ["Graph", "Dashboard"],
- needsLlm: true,
- description: "Extracts entities and relations from observations into a knowledge graph.",
- enableHow: "Set GRAPH_EXTRACTION_ENABLED=true and provide an LLM key, then restart.",
- docsHref: "https://github.com/rohitg00/agentmemory#knowledge-graph",
- },
- {
- key: "CONSOLIDATION_ENABLED",
- label: "Memory consolidation",
- enabled: isConsolidationEnabled(),
- default: false,
- affects: ["Dashboard", "Memories", "Crystals"],
- needsLlm: true,
- description: "Periodically summarizes sessions into semantic facts + procedures.",
- enableHow: "Set CONSOLIDATION_ENABLED=true and provide an LLM key, then restart.",
- docsHref: "https://github.com/rohitg00/agentmemory#consolidation",
- },
- {
- key: "AGENTMEMORY_AUTO_COMPRESS",
- label: "LLM-powered observation compression",
- enabled: isAutoCompressEnabled(),
- default: false,
- affects: ["Memories", "Timeline"],
- needsLlm: true,
- description: "Every observation is compressed by the LLM for richer summaries (costs tokens). OFF uses zero-LLM synthetic compression.",
- enableHow: "Set AGENTMEMORY_AUTO_COMPRESS=true and provide an LLM key.",
- docsHref: "https://github.com/rohitg00/agentmemory/issues/138",
- },
- {
- key: "AGENTMEMORY_INJECT_CONTEXT",
- label: "In-conversation context injection",
- enabled: isContextInjectionEnabled(),
- default: false,
- affects: ["Hooks"],
- needsLlm: false,
- description: "Hooks write recalled context into Claude Code's conversation. OFF captures in the background without injecting.",
- enableHow: "Set AGENTMEMORY_INJECT_CONTEXT=true and restart.",
- docsHref: "https://github.com/rohitg00/agentmemory/issues/143",
- },
- ];
+ const flags = buildConfigFlags();
return {
status_code: 200,
body: {
@@ -298,6 +305,97 @@ export function registerApiTriggers(
},
});
+ const STATUS_CHECK_TIMEOUT_MS = 5000;
+
+ async function valueWithin<T>(work: Promise<T>, ms: number): Promise<T | null> {
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const expiry = new Promise<null>((resolve) => {
+ timer = setTimeout(() => resolve(null), ms);
+ });
+ try {
+ return await Promise.race([work.catch(() => null), expiry]);
+ } finally {
+ clearTimeout(timer);
+ }
+ }
+
+ const sharedUnindexedScan = singleFlight(() => findUnindexedObservations(kv), UNINDEXED_SCAN_REUSE_MS);
+
+ sdk.registerFunction("api::status",
+ async (req: HttpRequest): Promise<Response> => {
+ const authErr = checkAuth(req, secret);
+ if (authErr) return authErr;
+ const idx = getSearchIndex();
+ const [health, functionMetrics, graph, unindexed] = await Promise.all([
+ valueWithin(getLatestHealth(kv), STATUS_CHECK_TIMEOUT_MS),
+ metricsStore ? valueWithin(metricsStore.getAll(), STATUS_CHECK_TIMEOUT_MS) : Promise.resolve([]),
+ valueWithin(
+ sdk.trigger({ function_id: "mem::graph-stats", payload: {} }) as Promise<GraphStatsInput>,
+ STATUS_CHECK_TIMEOUT_MS,
+ ),
+ valueWithin(sharedUnindexedScan(), STATUS_CHECK_TIMEOUT_MS),
+ ]);
+ const observationsIndexed = [...idx.observationCountsBySession().values()].reduce((a, n) => a + n, 0);
+ const circuit =
+ provider && "circuitState" in provider
+ ? (provider.circuitState as { state?: string; failures?: number } | null)
+ : null;
+ const report = evaluateStatus({
+ now: new Date(),
+ version: VERSION,
+ engineVersion: III_PINNED_VERSION,
+ uptimeSeconds: Math.round(process.uptime()),
+ ports: {
+ rest: loadConfig().restPort ?? null,
+ streams: bootStreamsPort ?? null,
+ viewer: getViewerSkipped() ? null : (getBoundViewerPort() ?? null),
+ },
+ health: health
+ ? {
+ status: health.status,
+ alerts: health.alerts,
+ notes: health.notes,
+ connectionState: health.connectionState,
+ }
+ : null,
+ circuitBreaker: circuit,
+ functionMetrics: functionMetrics ?? [],
+ provider: detectLlmProviderKind(),
+ embeddingProvider: detectEmbeddingProvider() ? "embeddings" : "none",
+ flags: buildConfigFlags(),
+ index: {
+ bm25Documents: idx.size,
+ vectorDocuments: getVectorIndex()?.size ?? null,
+ observationsIndexed,
+ missingObservations: unindexed ? unindexed.missing.length : null,
+ sessions: unindexed ? unindexed.sessions : null,
+ },
+ graph,
+ graphExtractionEnabled: isGraphExtractionEnabled(),
+ });
+ const accept = req.headers?.["accept"] ?? req.headers?.["Accept"];
+ const format = req.query_params?.["format"];
+ if (prefersHtml(typeof accept === "string" ? accept : undefined, typeof format === "string" ? format : undefined)) {
+ const nonce = randomBytes(16).toString("base64");
+ return {
+ status_code: 200,
+ headers: {
+ "Content-Type": "text/html; charset=utf-8",
+ "Content-Security-Policy": `default-src 'none'; style-src 'nonce-${nonce}'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'`,
+ "Cache-Control": "no-store",
+ },
+ body: renderStatusHtml(report, nonce),
+ };
+ }
+ return { status_code: 200, headers: { "Cache-Control": "no-store" }, body: report };
+ },
+ );
+ sdk.registerTrigger({
+ type: "http",
+ function_id: "api::status",
+ config: { api_path: "/agentmemory/status", http_method: "GET" },
+ });
+
sdk.registerFunction("api::observe",
async (req: HttpRequest<HookPayload>): Promise<Response> => {
const body = (req.body ?? {}) as Record<string, unknown>;
diff --git a/src/version.ts b/src/version.ts
index 84d83bdc..2d78ca2d 100644
--- a/src/version.ts
+++ b/src/version.ts
@@ -1 +1,2 @@
export const VERSION = "0.9.29";
+export const III_PINNED_VERSION = "0.22.1";
diff --git a/src/viewer/index.html b/src/viewer/index.html
index de47f4f5..8fc60ade 100644
--- a/src/viewer/index.html
+++ b/src/viewer/index.html
@@ -193,7 +193,7 @@
background: none;
border: none;
color: var(--ink-muted);
- padding: 10px 20px;
+ padding: 10px 16px;
font-size: 11px;
cursor: pointer;
border-bottom: 2px solid transparent;
@@ -1053,6 +1053,7 @@
<button data-tab="activity">Activity</button>
<button data-tab="profile">Profile</button>
<button data-tab="replay">Replay</button>
+ <button data-tab="health">Health</button>
</div>
<div id="flag-banners" class="flag-banners"></div>
@@ -1070,6 +1071,7 @@
<div id="view-activity" class="view"></div>
<div id="view-profile" class="view"></div>
<div id="view-replay" class="view"></div>
+ <div id="view-health" class="view"></div>
<div id="modal-overlay" class="modal-overlay">
<div class="modal" id="modal"></div>
@@ -1158,7 +1160,7 @@
task: '&#9745;', other: '&#128196;'
};
var CB_STATE_COLORS = { closed: 'badge-green', open: 'badge-red', 'half-open': 'badge-yellow' };
- var TAB_IDS = ['dashboard', 'graph', 'memories', 'timeline', 'sessions', 'lessons', 'actions', 'crystals', 'audit', 'activity', 'profile', 'replay'];
+ var TAB_IDS = ['dashboard', 'graph', 'memories', 'timeline', 'sessions', 'lessons', 'actions', 'crystals', 'audit', 'activity', 'profile', 'replay', 'health'];
var VIEWER_TOKEN_STORAGE_KEY = 'agentmemory-viewer-token';
var state = {
@@ -1174,6 +1176,7 @@
actions: { loaded: false, items: [], frontier: [], statusFilter: '', search: '' },
crystals: { loaded: false, items: [], search: '', lessonMap: {} },
profile: { loaded: false, projects: [], selectedProject: '', data: null },
+ health: { report: null, error: null },
replay: { loaded: false, sessions: [], selectedId: '', timeline: null, cursor: 0, playing: false, speed: 1, timer: null, startAt: 0, offsetAt: 0 },
flagsConfig: null,
flagsDismissed: {},
@@ -1460,6 +1463,7 @@
case 'audit': await loadAudit(); break;
case 'activity': await loadActivity(); break;
case 'profile': await loadProfile(); break;
+ case 'health': await loadHealth(); break;
// Replay stays fetch-once: reloading it would reset playback
// timer and cursor state mid-session; its toolbar has an explicit
// Refresh button instead.
@@ -3656,6 +3660,110 @@
if (el) el.classList.toggle('open');
}
+ var HEALTH_LEVEL_BADGES = { ok: 'badge-green', info: 'badge-blue', warn: 'badge-yellow', error: 'badge-red' };
+
+ async function loadHealth() {
+ var el = document.getElementById('view-health');
+ if (!state.health.report) el.innerHTML = '<div class="loading">Checking agentmemory...</div>';
+ var report = await api('status', { headers: { Accept: 'application/json' } });
+ if (report && report.problems) {
+ state.health.report = report;
+ state.health.error = null;
+ } else {
+ state.health.error = 'The status check did not answer. The server may be restarting.';
+ }
+ renderHealth();
+ }
+
+ function healthRow(label, value) {
+ return '<div class="detail-row"><div class="dl">' + esc(label) + '</div><div class="dv">' + esc(value === null || value === undefined ? '' : String(value)) + '</div></div>';
+ }
+
+ function formatSeconds(seconds) {
+ if (seconds === null || seconds === undefined) return 'unknown';
+ if (seconds < 60) return seconds + 's';
+ var minutes = Math.floor(seconds / 60);
+ if (minutes < 60) return minutes + 'm';
+ var hours = Math.floor(minutes / 60);
+ return hours < 48 ? hours + 'h ' + (minutes % 60) + 'm' : Math.floor(hours / 24) + 'd';
+ }
+
+ function renderHealth() {
+ var el = document.getElementById('view-health');
+ var r = state.health.report;
+ var html = '';
+ if (state.health.error) {
+ html += '<div class="card" style="margin-bottom:14px;padding:10px 16px;font-size:12px;color:var(--ink-muted);border-left:3px solid var(--yellow);">' +
+ esc(state.health.error) + (r ? ' Showing the last result.' : '') + '</div>';
+ }
+ if (!r) {
+ el.innerHTML = html + '<div style="text-align:center;"><button class="btn btn-primary" data-action="refresh-health">Retry</button></div>';
+ return;
+ }
+ html += '<div class="card" style="margin-bottom:16px;"><div class="card-title">Status <span class="badge ' + (HEALTH_LEVEL_BADGES[r.status] || 'badge-muted') + '">' + esc(r.status) + '</span>' +
+ '<span style="float:right;font-size:10px;color:var(--ink-faint);font-family:var(--font-mono);">checked ' + esc(shortTime(r.checkedAt)) + '</span></div>';
+ if (!r.problems.length) {
+ html += '<p style="font-size:13px;color:var(--ink-muted);">No problems found.</p>';
+ }
+ r.problems.forEach(function(p) {
+ html += '<div style="padding:10px 0;border-bottom:1px solid var(--border-light);">';
+ html += '<span class="badge ' + (HEALTH_LEVEL_BADGES[p.level] || 'badge-muted') + '">' + esc(p.level) + '</span> ';
+ html += '<span style="font-size:13px;color:var(--ink);">' + esc(p.message) + '</span>';
+ if (p.fix) html += '<div style="font-size:12px;color:var(--ink-muted);margin-top:4px;">' + esc(p.fix) + '</div>';
+ html += '</div>';
+ });
+ html += '</div>';
+
+ var ports = r.service.ports || {};
+ var idx = r.index || {};
+ var cb = r.provider.circuitBreaker;
+ html += '<div class="two-col">';
+ html += '<div class="card"><div class="card-title">Service</div>' +
+ healthRow('Version', 'v' + r.service.version) +
+ healthRow('Engine', r.service.engineVersion) +
+ healthRow('Uptime', formatSeconds(r.service.uptimeSeconds)) +
+ healthRow('Ports', 'REST ' + (ports.rest || '?') + ' · streams ' + (ports.streams || '?') + ' · viewer ' + (ports.viewer || 'off')) +
+ healthRow('Engine connection', (r.health && r.health.connectionState) || 'unknown') +
+ healthRow('LLM provider', r.provider.llm) +
+ healthRow('Embeddings', r.provider.embeddings) +
+ healthRow('Circuit breaker', cb ? (cb.state + ' (' + (cb.failures || 0) + ' failures)') : 'not in use') +
+ '</div>';
+ html += '<div class="card"><div class="card-title">Search index &amp; graph</div>' +
+ healthRow('BM25 documents', idx.bm25Documents) +
+ healthRow('Vector documents', idx.vectorDocuments === null ? 'vector search off' : idx.vectorDocuments) +
+ healthRow('Observations indexed', idx.observationsIndexed) +
+ healthRow('Missing from index', idx.missingObservations === null ? 'not checked' : idx.missingObservations) +
+ healthRow('Sessions', idx.sessions === null ? 'unknown' : idx.sessions);
+ if (r.graph) {
+ html += healthRow('Graph extraction', r.graph.extractionEnabled ? 'on' : 'off') +
+ healthRow('Graph nodes / edges', (r.graph.totalNodes || 0) + ' / ' + (r.graph.totalEdges || 0)) +
+ healthRow('Graph snapshot age', r.graph.fromSnapshot ? formatSeconds(r.graph.ageSeconds) : 'no snapshot');
+ }
+ html += '</div></div>';
+
+ var fns = (r.functions || []).slice().sort(function(a, b) { return b.totalCalls - a.totalCalls; });
+ html += '<div class="card" style="margin-top:16px;"><div class="card-title">Functions</div>';
+ if (!fns.length) {
+ html += '<p style="font-size:13px;color:var(--ink-faint);">No function calls recorded yet.</p>';
+ } else {
+ html += '<table class="metric-table"><tr><th>Function</th><th style="text-align:right">Calls</th><th style="text-align:right">Failed</th><th style="text-align:right">Failure rate</th><th style="text-align:right">Avg latency</th></tr>';
+ fns.forEach(function(f) {
+ var bad = f.totalCalls >= 5 && f.failureRate >= 0.2;
+ html += '<tr><td class="metric-fn">' + esc(f.functionId) + '</td>' +
+ '<td class="metric-num">' + f.totalCalls + '</td>' +
+ '<td class="metric-num" style="color:' + (f.failureCount > 0 ? 'var(--red)' : 'var(--ink-faint)') + '">' + f.failureCount + '</td>' +
+ '<td class="metric-num" style="color:' + (bad ? 'var(--red)' : 'var(--ink-muted)') + '">' + Math.round(f.failureRate * 100) + '%</td>' +
+ '<td class="metric-num">' + Math.round(f.avgLatencyMs) + ' ms</td></tr>';
+ });
+ html += '</table>';
+ }
+ html += '</div>';
+
+ html += '<div style="text-align:center;margin-top:20px;"><button class="btn btn-primary" data-action="refresh-health">Check again</button>' +
+ '<span style="font-size:11px;color:var(--ink-faint);margin-left:10px;">Environment checks (keys, engine binary, pid files) run on your machine with <code>agentmemory doctor</code>.</span></div>';
+ el.innerHTML = html;
+ }
+
async function loadProfile() {
var el = document.getElementById('view-profile');
el.innerHTML = '<div class="loading">Loading profile...</div>';
@@ -4155,6 +4263,10 @@
refreshDashboard();
return;
}
+ if (action === 'refresh-health') {
+ loadHealth();
+ return;
+ }
if (action === 'zoom-graph') {
zoomGraph(parseInt(target.getAttribute('data-dir') || '0', 10));
return;
diff --git a/test/status.test.ts b/test/status.test.ts
new file mode 100644
index 00000000..6ecfb50c
--- /dev/null
+++ b/test/status.test.ts
@@ -0,0 +1,237 @@
+import { describe, it, expect } from "vitest";
+import { readFileSync } from "node:fs";
+import {
+ evaluateStatus,
+ prefersHtml,
+ renderStatusHtml,
+ singleFlight,
+ type StatusInputs,
+} from "../src/functions/status.js";
+
+function inputs(overrides: Partial<StatusInputs> = {}): StatusInputs {
+ return {
+ now: new Date("2026-09-24T12:00:00.000Z"),
+ version: "0.9.29",
+ engineVersion: "0.22.1",
+ uptimeSeconds: 125,
+ ports: { rest: 3111, streams: 3112, viewer: 3113 },
+ health: { status: "healthy", alerts: [], notes: [], connectionState: "connected" },
+ circuitBreaker: { state: "closed", failures: 0 },
+ functionMetrics: [],
+ provider: "llm",
+ embeddingProvider: "embeddings",
+ flags: [],
+ index: {
+ bm25Documents: 117,
+ vectorDocuments: 117,
+ observationsIndexed: 110,
+ missingObservations: 0,
+ sessions: 95,
+ },
+ graph: {
+ totalNodes: 55,
+ totalEdges: 1,
+ fromSnapshot: true,
+ updatedAt: "2026-09-24T11:59:00.000Z",
+ },
+ graphExtractionEnabled: true,
+ ...overrides,
+ };
+}
+
+function codes(report: ReturnType<typeof evaluateStatus>): string[] {
+ return report.problems.map((p) => p.code);
+}
+
+describe("evaluateStatus", () => {
+ it("reports ok with no problems on a healthy install", () => {
+ const report = evaluateStatus(inputs());
+ expect(report.status).toBe("ok");
+ expect(report.problems).toEqual([]);
+ expect(report.graph?.ageSeconds).toBe(60);
+ expect(report.service.engineVersion).toBe("0.22.1");
+ });
+
+ it("flags a function failing at least 20% of 5+ calls with a provider-specific fix", () => {
+ const report = evaluateStatus(
+ inputs({
+ functionMetrics: [
+ { functionId: "mem::summarize", totalCalls: 56, successCount: 20, failureCount: 36, avgLatencyMs: 38324 },
+ { functionId: "mem::observe", totalCalls: 4, successCount: 1, failureCount: 3, avgLatencyMs: 5 },
+ { functionId: "mem::search", totalCalls: 100, successCount: 90, failureCount: 10, avgLatencyMs: 5 },
+ ],
+ }),
+ );
+ expect(report.status).toBe("warn");
+ const failing = report.problems.filter((p) => p.code === "function-failing");
+ expect(failing).toHaveLength(1);
+ expect(failing[0].message).toBe("mem::summarize failed 36 of 56 calls (64%).");
+ expect(failing[0].fix).toMatch(/LLM provider/);
+ });
+
+ it("escalates to error when the provider circuit breaker is open or health is critical", () => {
+ expect(evaluateStatus(inputs({ circuitBreaker: { state: "open", failures: 5 } })).status).toBe("error");
+ expect(codes(evaluateStatus(inputs({ circuitBreaker: { state: "open", failures: 5 } })))).toContain(
+ "provider-circuit-open",
+ );
+ const critical = evaluateStatus(inputs({ health: { status: "critical", alerts: ["kv unreachable"] } }));
+ expect(critical.status).toBe("error");
+ expect(codes(critical)).toEqual(["health-critical", "health-alert"]);
+ });
+
+ it("warns about observations missing from the search index and says how to fix it", () => {
+ const report = evaluateStatus(inputs({ index: { ...inputs().index, missingObservations: 15 } }));
+ expect(report.status).toBe("warn");
+ const problem = report.problems.find((p) => p.code === "index-missing-observations");
+ expect(problem?.message).toMatch(/^15 stored observations/);
+ expect(problem?.fix).toMatch(/Restart agentmemory/);
+ });
+
+ it("notes when the index check timed out instead of claiming the index is fine", () => {
+ const report = evaluateStatus(inputs({ index: { ...inputs().index, missingObservations: null, sessions: null } }));
+ expect(codes(report)).toEqual(["index-check-unavailable"]);
+ expect(report.status).toBe("info");
+ });
+
+ it("checks snapshot presence when extraction is on, and snapshot age whenever a snapshot exists", () => {
+ const noSnapshot = { totalNodes: 0, totalEdges: 0, fromSnapshot: false };
+ expect(codes(evaluateStatus(inputs({ graph: noSnapshot })))).toEqual(["graph-no-snapshot"]);
+ expect(codes(evaluateStatus(inputs({ graph: noSnapshot, graphExtractionEnabled: false })))).toEqual([]);
+ const old = { ...inputs().graph, updatedAt: "2026-09-20T12:00:00.000Z" };
+ expect(evaluateStatus(inputs({ graph: old })).problems[0].message).toMatch(/4 days old/);
+ const dayOld = { ...inputs().graph, updatedAt: "2026-09-23T06:00:00.000Z" };
+ expect(evaluateStatus(inputs({ graph: dayOld })).problems[0].message).toMatch(/30 hours old/);
+ expect(codes(evaluateStatus(inputs({ graph: old, graphExtractionEnabled: false })))).toEqual([
+ "graph-snapshot-stale",
+ ]);
+ expect(codes(evaluateStatus(inputs({ graph: { ...inputs().graph, dirty: true } })))).toEqual([
+ "graph-snapshot-dirty",
+ ]);
+ });
+
+ it("tells keyless installs what they are missing without calling it a failure", () => {
+ const report = evaluateStatus(inputs({ provider: "noop" }));
+ expect(report.status).toBe("info");
+ expect(report.problems[0].code).toBe("no-llm-provider");
+ });
+});
+
+describe("missing health snapshot", () => {
+ it("says the health check was not run instead of reporting ok", () => {
+ const report = evaluateStatus(inputs({ health: null }));
+ expect(report.status).toBe("info");
+ expect(codes(report)).toEqual(["health-check-unavailable"]);
+ });
+});
+
+describe("singleFlight", () => {
+ it("shares one run between overlapping callers and reuses the result inside the window", async () => {
+ let clock = 0;
+ let runs = 0;
+ let finish: (v: number) => void = () => undefined;
+ const shared = singleFlight(
+ () => {
+ runs++;
+ return new Promise<number>((resolve) => {
+ finish = resolve;
+ });
+ },
+ 30_000,
+ () => clock,
+ );
+ const a = shared();
+ const b = shared();
+ expect(a).toBe(b);
+ finish(7);
+ await expect(a).resolves.toBe(7);
+ clock = 29_000;
+ await expect(shared()).resolves.toBe(7);
+ expect(runs).toBe(1);
+ clock = 31_000;
+ const c = shared();
+ finish(8);
+ await expect(c).resolves.toBe(8);
+ expect(runs).toBe(2);
+ });
+
+ it("starts a fresh run after a failure", async () => {
+ let runs = 0;
+ const shared = singleFlight(() => {
+ runs++;
+ return runs === 1 ? Promise.reject(new Error("store timeout")) : Promise.resolve("ok");
+ }, 30_000);
+ await expect(shared()).rejects.toThrow("store timeout");
+ await expect(shared()).resolves.toBe("ok");
+ expect(runs).toBe(2);
+ });
+});
+
+describe("renderStatusHtml", () => {
+ it("escapes every server-provided string and carries no script", () => {
+ const report = evaluateStatus(
+ inputs({
+ health: { status: "degraded", alerts: ['<img src=x onerror="alert(1)">'], connectionState: "connected" },
+ }),
+ );
+ const html = renderStatusHtml(report, "n0nce");
+ expect(html).not.toMatch(/<script/i);
+ expect(html).not.toContain('<img src=x onerror="alert(1)">');
+ expect(html).toContain("&lt;img src=x onerror=&quot;alert(1)&quot;&gt;");
+ expect(html).toContain('<style nonce="n0nce">');
+ expect(html).toContain('class="badge warn"');
+ });
+
+ it("shows the problems, the fix text and the core sections", () => {
+ const html = renderStatusHtml(
+ evaluateStatus(inputs({ index: { ...inputs().index, missingObservations: 3 } })),
+ "n",
+ );
+ expect(html).toContain("3 stored observations are not in the search index");
+ expect(html).toContain("boot reconcile re-indexes");
+ for (const heading of ["Problems", "Service", "Providers", "Search index", "Knowledge graph", "Functions", "Features"]) {
+ expect(html).toContain(`<h2>${heading}</h2>`);
+ }
+ });
+});
+
+describe("prefersHtml", () => {
+ it("serves HTML to browsers and JSON to everything else", () => {
+ expect(prefersHtml("text/html,application/xhtml+xml,*/*;q=0.8", undefined)).toBe(true);
+ expect(prefersHtml("application/json", undefined)).toBe(false);
+ expect(prefersHtml(undefined, undefined)).toBe(false);
+ expect(prefersHtml("*/*", undefined)).toBe(false);
+ expect(prefersHtml("text/html", "json")).toBe(false);
+ expect(prefersHtml("application/json", "html")).toBe(true);
+ });
+});
+
+describe("status wiring", () => {
+ const api = readFileSync("src/triggers/api.ts", "utf-8");
+ const viewer = readFileSync("src/viewer/index.html", "utf-8");
+
+ it("registers GET /agentmemory/status behind the same auth check as the other endpoints", () => {
+ expect(api).toMatch(/registerFunction\("api::status",\s*async \(req: HttpRequest\): Promise<Response> => \{\s*const authErr = checkAuth\(req, secret\);/);
+ expect(api).toMatch(/api_path: "\/agentmemory\/status", http_method: "GET"/);
+ expect(api).toMatch(/default-src 'none'; style-src 'nonce-\$\{nonce\}'/);
+ });
+
+ it("time-boxes every status probe so a slow store cannot hang the page", () => {
+ const handler = api.slice(api.indexOf('registerFunction("api::status"'), api.indexOf('function_id: "api::status"'));
+ expect(handler.match(/valueWithin\(/g)?.length).toBe(4);
+ expect(handler).toMatch(/valueWithin\(sharedUnindexedScan\(\), STATUS_CHECK_TIMEOUT_MS\)/);
+ expect(api).toMatch(/const sharedUnindexedScan = singleFlight\(\(\) => findUnindexedObservations\(kv\), UNINDEXED_SCAN_REUSE_MS\);/);
+ });
+
+ it("config flags and status share one flag list", () => {
+ expect(api.match(/buildConfigFlags\(\)(?! \{)/g)?.length).toBe(2);
+ expect(api.match(/key: "GRAPH_EXTRACTION_ENABLED"/g)?.length).toBe(1);
+ });
+
+ it("the viewer has a Health tab that reads the status report", () => {
+ expect(viewer).toContain('<button data-tab="health">Health</button>');
+ expect(viewer).toContain('<div id="view-health" class="view"></div>');
+ expect(viewer).toMatch(/'replay', 'health'\];/);
+ expect(viewer).toMatch(/case 'health': await loadHealth\(\); break;/);
+ expect(viewer).toMatch(/api\('status', \{ headers: \{ Accept: 'application\/json' \} \}\)/);
+ });
+});