#1 Persistent memory for AI coding agents based on real-world benchmarks
TypeScript agentmemoryagentsaiclaudeclaudecodecodexcopilotcursorgenaiharnesshermesmemoryompopenclawopencodepi
feat(viewer): stream every page and rebuild the viewer (#1433)
Rohit Ghumare0c4c56fd5aa8
diff --git a/AGENTS.md b/AGENTS.mdindex 45b0ce96..9145dfa2 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)-- 132 REST endpoints+- 134 REST endpoints- 6 MCP resources, 3 MCP prompts- 12 hooks, 17 skills- 260+ iii functionsdiff --git a/README.md b/README.mdindex 1a84a013..92254ae2 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>-132 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.+134 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.mdindex e98b8adf..75671c94 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.-132 registered endpoints:+134 registered endpoints:| Method | Path || --- | --- |@@ -57,6 +57,7 @@ The REST API is the primary surface. All paths are under `http://localhost:3111`| POST | `/agentmemory/graph/build` || POST | `/agentmemory/graph/extract` || POST | `/agentmemory/graph/import-graphify` |+| GET | `/agentmemory/graph/node` || POST | `/agentmemory/graph/query` || POST | `/agentmemory/graph/reset` || POST | `/agentmemory/graph/snapshot-rebuild` |@@ -84,6 +85,7 @@ The REST API is the primary surface. All paths are under `http://localhost:3111`| POST | `/agentmemory/migrate` || GET | `/agentmemory/next` || GET | `/agentmemory/observations` |+| GET | `/agentmemory/observations/locate` || POST | `/agentmemory/observe` || POST | `/agentmemory/obsidian/export` || POST | `/agentmemory/patterns` |diff --git a/src/config.ts b/src/config.tsindex f76fe19a..36f8c7b0 100644--- a/src/config.ts+++ b/src/config.ts@@ -235,8 +235,9 @@ export function isDropStaleIndexEnabled(): boolean {return getMergedEnv()["AGENTMEMORY_DROP_STALE_INDEX"] === "true";}-export function detectLlmProviderKind(): "llm" | "noop" {- const env = getMergedEnv();+export function detectLlmProviderKind(+ env: Record<string, string | undefined> = getMergedEnv(),+): "llm" | "noop" {if (hasRealValue(env["ANTHROPIC_API_KEY"]) ||hasRealValue(env["GEMINI_API_KEY"]) ||@@ -244,7 +245,8 @@ export function detectLlmProviderKind(): "llm" | "noop" {hasRealValue(env["OPENROUTER_API_KEY"]) ||hasRealValue(env["MINIMAX_API_KEY"]) ||(hasRealValue(env["OPENAI_API_KEY"]) &&- env["OPENAI_API_KEY_FOR_LLM"] !== "false")+ env["OPENAI_API_KEY_FOR_LLM"] !== "false") ||+ env["AGENTMEMORY_ALLOW_AGENT_SDK"] === "true") {return "llm";}@@ -424,25 +426,8 @@ export function isConsolidationEnabled(): boolean {const explicit = env["CONSOLIDATION_ENABLED"];if (explicit === "false" || explicit === "0") return false;if (explicit === "true" || explicit === "1") return true;- return hasLLMProviderConfigured(env);-}--function hasLLMProviderConfigured(env: Record<string, string | undefined>): boolean {- const provider = (env["AGENTMEMORY_PROVIDER"] || "").toLowerCase();- if (provider === "noop") return false;- const openaiKeyForLlm =- env["OPENAI_API_KEY"] &&- (env["OPENAI_API_KEY_FOR_LLM"] || "").toLowerCase() !== "false";- return Boolean(- env["ANTHROPIC_API_KEY"] ||- openaiKeyForLlm ||- env["OPENROUTER_API_KEY"] ||- env["GEMINI_API_KEY"] ||- env["GOOGLE_API_KEY"] ||- env["MINIMAX_API_KEY"] ||- env["OPENAI_BASE_URL"] ||- provider === "agent-sdk",- );+ if ((env["AGENTMEMORY_PROVIDER"] || "").toLowerCase() === "noop") return false;+ return detectLlmProviderKind(env) === "llm";}// Per-observation LLM compression is OFF by default as of 0.8.8.@@ -468,6 +453,13 @@ export function isContextInjectionEnabled(): boolean {return getMergedEnv()["AGENTMEMORY_INJECT_CONTEXT"] === "true";}+export const CONSOLIDATION_INTERVAL_DEFAULT_MS = 7200000;++export function getConsolidationIntervalMs(): number {+ const raw = parseInt(process.env.CONSOLIDATION_INTERVAL_MS || String(CONSOLIDATION_INTERVAL_DEFAULT_MS), 10);+ return Number.isFinite(raw) && raw > 0 ? raw : CONSOLIDATION_INTERVAL_DEFAULT_MS;+}+export function getConsolidationDecayDays(): number {return safeParseInt(getMergedEnv()["CONSOLIDATION_DECAY_DAYS"], 30);}diff --git a/src/functions/audit.ts b/src/functions/audit.tsindex 1e75b4b7..b5d48620 100644--- a/src/functions/audit.ts+++ b/src/functions/audit.ts@@ -83,6 +83,7 @@ export async function queryAudit(operation?: AuditEntry["operation"];dateFrom?: string;dateTo?: string;+ query?: string;limit?: number;},): Promise<AuditEntry[]> {@@ -108,6 +109,14 @@ export async function queryAudit(}entries = entries.filter((e) => new Date(e.timestamp).getTime() <= to);}+ const query = filter?.query?.trim().toLowerCase();+ if (query) {+ entries = entries.filter((e) =>+ [e.functionId, ...(e.targetIds || [])].some((v) =>+ String(v || "").toLowerCase().includes(query),+ ),+ );+ }return entries.slice(0, filter?.limit || 100);}diff --git a/src/functions/compress-synthetic.ts b/src/functions/compress-synthetic.tsindex 14f757ce..6c224bf5 100644--- a/src/functions/compress-synthetic.ts+++ b/src/functions/compress-synthetic.ts@@ -41,18 +41,20 @@ function inferType(return "other";}-function extractFiles(input: unknown): string[] {+const SEARCH_TOOL_PATTERN = /grep|glob|search|find|^ls$|list/i;++function extractFiles(toolName: string | undefined, input: unknown): string[] {if (!input || typeof input !== "object") return [];const o = input as Record<string, unknown>;+ const isSearch =+ (toolName !== undefined && SEARCH_TOOL_PATTERN.test(toolName)) ||+ typeof o["pattern"] === "string" ||+ typeof o["query"] === "string";+ const keys = isSearch+ ? ["file_path", "filepath", "filePath", "notebook_path"]+ : ["file_path", "filepath", "path", "filePath", "file", "notebook_path"];const out = new Set<string>();- for (const key of [- "file_path",- "filepath",- "path",- "filePath",- "file",- "pattern",- ]) {+ for (const key of keys) {const v = o[key];if (typeof v === "string" && v.length > 0 && v.length < 512) out.add(v);}@@ -95,7 +97,7 @@ export function buildSyntheticCompression(facts: [],narrative: truncate(narrativeParts.join(" | "), 400),concepts: [],- files: extractFiles(raw.toolInput),+ files: extractFiles(raw.toolName, raw.toolInput),importance: 5,confidence: 0.3,};diff --git a/src/functions/consolidation-pipeline.ts b/src/functions/consolidation-pipeline.tsindex 2a480dc9..99939843 100644--- a/src/functions/consolidation-pipeline.ts+++ b/src/functions/consolidation-pipeline.ts@@ -86,7 +86,7 @@ export function registerConsolidationPipelineFunction(sdk.registerFunction("mem::consolidate-pipeline",async (data?: { tier?: string; force?: boolean; project?: string }) => {if (!data?.force && !isConsolidationEnabled()) {- return { success: false, skipped: true, reason: "Consolidation disabled: set CONSOLIDATION_ENABLED=true or configure an LLM provider (ANTHROPIC_API_KEY / OPENAI_API_KEY / OPENROUTER_API_KEY / GEMINI_API_KEY / GOOGLE_API_KEY / MINIMAX_API_KEY / OPENAI_BASE_URL / AGENTMEMORY_PROVIDER=agent-sdk)" };+ return { success: false, skipped: true, reason: "Consolidation disabled: set CONSOLIDATION_ENABLED=true or configure an LLM provider (ANTHROPIC_API_KEY / OPENAI_API_KEY / OPENROUTER_API_KEY / GEMINI_API_KEY / GOOGLE_API_KEY / MINIMAX_API_KEY, or AGENTMEMORY_ALLOW_AGENT_SDK=true). OPENAI_BASE_URL alone only points an OpenAI key at another server; it is not a provider." };}const tier = data?.tier || "all";const decayDays = getConsolidationDecayDays();diff --git a/src/functions/consolidation-status.ts b/src/functions/consolidation-status.tsindex 48ee02f7..6ca50efb 100644--- a/src/functions/consolidation-status.ts+++ b/src/functions/consolidation-status.ts@@ -22,6 +22,13 @@ export interface ConsolidationStatusInput {procedures: number;relations: number;lastRun: ConsolidationRunRecord | null;+ schedule?: ConsolidationSchedule;+}++export interface ConsolidationSchedule {+ intervalMs: number;+ cooldownMs: number;+ decayDays: number;}export interface ConsolidationTier {@@ -37,6 +44,11 @@ export interface ConsolidationStatus {enabled: boolean;llmConfigured: boolean;lastRunAt: string | null;+ lastRun: ConsolidationRunRecord | null;+ summaries: number;+ recurringPatterns: number;+ schedule: ConsolidationSchedule | null;+ thresholds: { semanticMinSummaries: number; proceduralMinPatterns: number; proceduralMinSessionsPerPattern: number };tiers: ConsolidationTier[];}@@ -85,7 +97,7 @@ export function describeConsolidation(input: ConsolidationStatusInput): Consolid(semanticWaiting? {state: "waiting",- detail: `Waiting: ${input.summaries} of ${SEMANTIC_MIN_SUMMARIES} session summaries needed.`,+ detail: `Waiting: ${input.summaries} of ${SEMANTIC_MIN_SUMMARIES} session summaries needed. A summary is written when a session ends.`,}: { state: "ready", detail: "Ready: runs when the next session ends." }))};@@ -126,6 +138,15 @@ export function describeConsolidation(input: ConsolidationStatusInput): Consolidenabled: input.enabled,llmConfigured: input.llmConfigured,lastRunAt: input.lastRun?.at ?? null,+ lastRun: input.lastRun,+ summaries: input.summaries,+ recurringPatterns: input.recurringPatterns,+ schedule: input.schedule ?? null,+ thresholds: {+ semanticMinSummaries: SEMANTIC_MIN_SUMMARIES,+ proceduralMinPatterns: PROCEDURAL_MIN_PATTERNS,+ proceduralMinSessionsPerPattern: PROCEDURAL_MIN_SESSIONS_PER_PATTERN,+ },tiers: [semantic, procedural, relations],};}diff --git a/src/functions/governance.ts b/src/functions/governance.tsindex d8d0ab01..2b225a86 100644--- a/src/functions/governance.ts+++ b/src/functions/governance.ts@@ -169,6 +169,7 @@ export function registerGovernanceFunction(sdk: IIIClient, kv: StateKV): void {operation?: AuditEntry["operation"];dateFrom?: string;dateTo?: string;+ query?: string;limit?: number;}) => {return queryAudit(kv, data);diff --git a/src/functions/graph-node.ts b/src/functions/graph-node.tsnew file mode 100644index 00000000..98caea47--- /dev/null+++ b/src/functions/graph-node.ts@@ -0,0 +1,159 @@+import type { StateKV } from "../state/kv.js";+import { KV } from "../state/schema.js";+import type { CompressedObservation, GraphEdge, GraphNode, Memory, Session } from "../types.js";+import { getSearchIndex } from "./search.js";++const EDGE_SCAN_BUDGET_MS = 6000;+const MAX_RELATIONS = 200;+const MAX_OBSERVATIONS = 40;+const MAX_MEMORIES = 25;++export type GraphNodeRelation = {+ edgeId: string;+ type: string;+ direction: "out" | "in";+ weight: number;+ observationCount: number;+ neighbor: { id: string; name: string; type: string } | null;+};++export type GraphNodeDetail = {+ node: GraphNode;+ degree: number;+ relations: GraphNodeRelation[] | null;+ relationsTotal: number;+ relationsWarning?: string;+ provenance: {+ observationIds: string[];+ observations: Array<{ id: string; sessionId: string; title?: string; type?: string; timestamp?: string }>;+ sessions: Array<{ id: string; project?: string; agentId?: string; status?: string; startedAt?: string }>;+ projects: string[];+ memories: Array<{ id: string; title?: string; type?: string; project?: string; via: "observation" | "name" }>;+ structural: { source: string; sourceFile?: string } | null;+ };+};++function withBudget<T>(p: Promise<T>, ms: number): Promise<T | null> {+ return new Promise((resolve) => {+ const timer = setTimeout(() => resolve(null), ms);+ p.then(+ (v) => { clearTimeout(timer); resolve(v); },+ () => { clearTimeout(timer); resolve(null); },+ );+ });+}++function matchesName(values: string[] | undefined, name: string): boolean {+ if (!values || values.length === 0) return false;+ const lower = name.toLowerCase();+ return values.some((v) => {+ const s = String(v).toLowerCase();+ return s === lower || s.endsWith("/" + lower) || lower.endsWith("/" + s);+ });+}++export async function describeGraphNode(kv: StateKV, nodeId: string): Promise<GraphNodeDetail | null> {+ const node = await kv.get<GraphNode>(KV.graphNodes, nodeId);+ if (!node) return null;++ const edges = await withBudget(kv.list<GraphEdge>(KV.graphEdges), EDGE_SCAN_BUDGET_MS);+ let relations: GraphNodeRelation[] | null = null;+ let relationsTotal = 0;+ let relationsWarning: string | undefined;+ const edgeObsIds: string[] = [];+ if (edges) {+ const touching = edges.filter(+ (e) => !e.stale && e.isLatest !== false && (e.sourceNodeId === nodeId || e.targetNodeId === nodeId),+ );+ relationsTotal = touching.length;+ touching.sort((a, b) => (b.weight ?? 0) - (a.weight ?? 0));+ const kept = touching.slice(0, MAX_RELATIONS);+ const neighborIds = [...new Set(kept.map((e) => (e.sourceNodeId === nodeId ? e.targetNodeId : e.sourceNodeId)))];+ const neighbors = new Map<string, GraphNode | null>();+ await Promise.all(+ neighborIds.map(async (id) => neighbors.set(id, await kv.get<GraphNode>(KV.graphNodes, id).catch(() => null))),+ );+ relations = kept.map((e) => {+ const out = e.sourceNodeId === nodeId;+ const n = neighbors.get(out ? e.targetNodeId : e.sourceNodeId) ?? null;+ for (const id of e.sourceObservationIds ?? []) edgeObsIds.push(id);+ return {+ edgeId: e.id,+ type: e.type,+ direction: out ? "out" : "in",+ weight: typeof e.weight === "number" ? e.weight : 0.5,+ observationCount: (e.sourceObservationIds ?? []).length,+ neighbor: n ? { id: n.id, name: n.name, type: n.type } : null,+ };+ });+ } else {+ relationsWarning = "Listing relations took too long on this graph; showing the node without them.";+ }++ const storedDegree = await kv.get<number>(KV.graphNodeDegree, nodeId).catch(() => null);+ const degree = typeof storedDegree === "number" ? storedDegree : relationsTotal;++ const observationIds = [...new Set([...(node.sourceObservationIds ?? []), ...edgeObsIds])];+ const index = getSearchIndex();+ const observations: GraphNodeDetail["provenance"]["observations"] = [];+ const sessionIds = new Set<string>();+ for (const id of observationIds.slice(0, MAX_OBSERVATIONS)) {+ const sessionId = index.sessionOf(id);+ if (!sessionId || sessionId === "lesson" || id.startsWith("mem_")) continue;+ sessionIds.add(sessionId);+ const obs = await kv.get<CompressedObservation>(KV.observations(sessionId), id).catch(() => null);+ observations.push({+ id,+ sessionId,+ ...(obs?.title ? { title: obs.title } : {}),+ ...(obs?.type ? { type: obs.type } : {}),+ ...(obs?.timestamp ? { timestamp: obs.timestamp } : {}),+ });+ }++ const sessions: GraphNodeDetail["provenance"]["sessions"] = [];+ for (const sid of sessionIds) {+ const s = await kv.get<Session>(KV.sessions, sid).catch(() => null);+ sessions.push({+ id: sid,+ ...(s?.project ? { project: s.project } : {}),+ ...(s?.agentId ? { agentId: s.agentId } : {}),+ ...(s?.status ? { status: s.status } : {}),+ ...(s?.startedAt ? { startedAt: s.startedAt } : {}),+ });+ }+ const projects = [...new Set(sessions.map((s) => s.project).filter((p): p is string => !!p))].sort();++ const obsSet = new Set(observationIds);+ const memories: GraphNodeDetail["provenance"]["memories"] = [];+ const allMemories = await kv.list<Memory>(KV.memories).catch(() => [] as Memory[]);+ for (const m of allMemories) {+ if (!m || m.isLatest === false) continue;+ const viaObs = (m.sourceObservationIds ?? []).some((id) => obsSet.has(id));+ const viaName = !viaObs && (matchesName(m.concepts, node.name) || matchesName(m.files, node.name));+ if (!viaObs && !viaName) continue;+ memories.push({+ id: m.id,+ ...(m.title ? { title: m.title } : {}),+ type: m.type,+ ...(m.project ? { project: m.project } : {}),+ via: viaObs ? "observation" : "name",+ });+ if (memories.length >= MAX_MEMORIES) break;+ }++ const props = node.properties ?? {};+ const structural =+ typeof props.source === "string"+ ? { source: props.source, ...(typeof props.sourceFile === "string" ? { sourceFile: props.sourceFile } : {}) }+ : null;++ return {+ node,+ degree,+ relations,+ relationsTotal,+ ...(relationsWarning ? { relationsWarning } : {}),+ provenance: { observationIds, observations, sessions, projects, memories, structural },+ };+}diff --git a/src/functions/graph.ts b/src/functions/graph.tsindex 08188731..38add02b 100644--- a/src/functions/graph.ts+++ b/src/functions/graph.ts@@ -159,6 +159,11 @@ function paginateFromSnapshot(const pageEdges = snap.topEdges.filter((e) => pageIds.has(e.sourceNodeId) && pageIds.has(e.targetNodeId),);+ const degrees: Record<string, number> = {};+ for (const n of pageNodes) {+ const d = snap.topDegrees?.[n.id];+ if (typeof d === "number") degrees[n.id] = d;+ }return {nodes: pageNodes,edges: pageEdges,@@ -169,6 +174,7 @@ function paginateFromSnapshot(limit,offset,fromSnapshot: true,+ degrees,};}diff --git a/src/functions/lessons.ts b/src/functions/lessons.tsindex c750b1d6..cc238a9f 100644--- a/src/functions/lessons.ts+++ b/src/functions/lessons.ts@@ -63,6 +63,30 @@ function reinforceLesson(lesson: Lesson): void {lesson.updatedAt = now;}+export const LESSON_SOURCE_IDS_MAX = 50;+const LESSON_SOURCE_ID_MAX_LENGTH = 200;++export function normalizeLessonSourceIds(value: unknown): string[] | null {+ if (value === undefined || value === null) return [];+ if (!Array.isArray(value) || value.length > LESSON_SOURCE_IDS_MAX) return null;+ const ids: string[] = [];+ for (const raw of value) {+ if (typeof raw !== "string") return null;+ const id = raw.trim();+ if (!id || id.length > LESSON_SOURCE_ID_MAX_LENGTH || /\s/.test(id)) return null;+ if (!ids.includes(id)) ids.push(id);+ }+ return ids;+}++function mergeSourceIds(existing: string[] | undefined, incoming: string[] | undefined): string[] {+ const merged = [...(existing || [])];+ for (const id of incoming || []) {+ if (!merged.includes(id)) merged.push(id);+ }+ return merged.slice(-LESSON_SOURCE_IDS_MAX);+}+export function registerLessonsFunctions(sdk: IIIClient, kv: StateKV): void {sdk.registerFunction("mem::lesson-save",async (data: {@@ -88,6 +112,9 @@ export function registerLessonsFunctions(sdk: IIIClient, kv: StateKV): void {existing.context = data.context;indexedTextChanged = true;}+ if (data.sourceIds && data.sourceIds.length) {+ existing.sourceIds = mergeSourceIds(existing.sourceIds, data.sourceIds);+ }await kv.set(KV.lessons, existing.id, existing);lessonRecords.set(existing.id, existing);if (indexedTextChanged && lessonIndex) {diff --git a/src/functions/profile.ts b/src/functions/profile.tsindex a27a4463..127b6940 100644--- a/src/functions/profile.ts+++ b/src/functions/profile.ts@@ -1,12 +1,12 @@import type { IIIClient } from "iii-sdk";import type {CompressedObservation,+ Memory,Session,ProjectProfile,} from "../types.js";import { KV } from "../state/schema.js";import { StateKV } from "../state/kv.js";-import { recordAudit } from "./audit.js";import { logger } from "../logger.js";export function registerProfileFunction(sdk: IIIClient, kv: StateKV): void {@@ -24,7 +24,14 @@ export function registerProfileFunction(sdk: IIIClient, kv: StateKV): void {if (cached) {const age = Date.now() - new Date(cached.updatedAt).getTime();if (age < 3600_000) {- return { profile: cached, cached: true };+ const topFiles = cleanTopFiles(cached.topFiles || [], []);+ if (topFiles.length === (cached.topFiles || []).length) {+ return { profile: cached, cached: true };+ }+ return {+ profile: { ...cached, topFiles, conventions: extractConventions(cached.topConcepts || [], topFiles) },+ cached: true,+ };}}}@@ -85,15 +92,27 @@ export function registerProfileFunction(sdk: IIIClient, kv: StateKV): void {}}+ const memories = await kv+ .list<Memory>(KV.memories)+ .catch(() => [] as Memory[]);+ for (const memory of memories) {+ if (memory.project !== project || memory.isLatest === false) continue;+ for (const concept of memory.concepts || []) {+ conceptFreq.set(concept, (conceptFreq.get(concept) || 0) + 1);+ }+ }+const topConcepts = Array.from(conceptFreq.entries()).sort((a, b) => b[1] - a[1]).slice(0, 15).map(([concept, frequency]) => ({ concept, frequency }));- const topFiles = Array.from(fileFreq.entries())- .sort((a, b) => b[1] - a[1])- .slice(0, 15)- .map(([file, frequency]) => ({ file, frequency }));+ const topFiles = cleanTopFiles(+ Array.from(fileFreq.entries())+ .sort((a, b) => b[1] - a[1])+ .map(([file, frequency]) => ({ file, frequency })),+ projectSessions.map((s) => s.cwd),+ ).slice(0, 15);const uniqueErrors = [...new Set(errors)].slice(0, 10);@@ -110,10 +129,6 @@ export function registerProfileFunction(sdk: IIIClient, kv: StateKV): void {};await kv.set(KV.profiles, project, profile);- await recordAudit(kv, "share", "mem::profile", [project], {- sessionCount: projectSessions.length,- totalObservations: totalObs,- });logger.info("Profile generated", {project,@@ -125,6 +140,38 @@ export function registerProfileFunction(sdk: IIIClient, kv: StateKV): void {);}+const EXTENSIONLESS_FILES = new Set([+ "Makefile",+ "Dockerfile",+ "Containerfile",+ "Procfile",+ "Gemfile",+ "Rakefile",+ "Jenkinsfile",+ "Vagrantfile",+ "Justfile",+ "LICENSE",+ "README",+]);++export function isLikelyFilePath(value: string, cwds: Array<string | undefined>): boolean {+ const file = String(value || "").trim();+ if (!file || /[*?{}[\]]/.test(file) || /\s{2,}/.test(file)) return false;+ const bare = file.replace(/[/\\]+$/, "");+ if (cwds.some((cwd) => cwd && cwd.replace(/[/\\]+$/, "") === bare)) return false;+ const base = bare.split(/[/\\]/).pop() || "";+ if (!base || base === "." || base === "..") return false;+ if (EXTENSIONLESS_FILES.has(base)) return true;+ return /\.[A-Za-z0-9_-]{1,12}$/.test(base);+}++export function cleanTopFiles(+ files: Array<{ file: string; frequency: number }>,+ cwds: Array<string | undefined>,+): Array<{ file: string; frequency: number }> {+ return files.filter((f) => isLikelyFilePath(f.file, cwds));+}+function extractConventions(concepts: Array<{ concept: string; frequency: number }>,files: Array<{ file: string; frequency: number }>,diff --git a/src/functions/relations.ts b/src/functions/relations.tsindex 7bde404c..505697bd 100644--- a/src/functions/relations.ts+++ b/src/functions/relations.ts@@ -1,5 +1,13 @@-import type { IIIClient } from "iii-sdk";+import { TriggerAction, type IIIClient } from "iii-sdk";import type { Memory, MemoryRelation } from "../types.js";+import { memoryToObservation } from "../state/memory-utils.js";+import { memoryTitleFromContent } from "./remember.js";+import {+ getSearchIndex,+ scheduleIndexSave,+ vectorIndexAddGuarded,+ vectorIndexRemove,+} from "./search.js";import { KV, generateId } from "../state/schema.js";import { StateKV } from "../state/kv.js";import { withKeyedLock } from "../state/keyed-mutex.js";@@ -7,6 +15,15 @@ import { safeAudit } from "./audit.js";import { recordAccessBatch } from "./access-tracker.js";import { logger } from "../logger.js";+const MEMORY_TYPES = new Set([+ "pattern",+ "preference",+ "architecture",+ "bug",+ "workflow",+ "fact",+]);+function computeConfidence(source: Memory,target: Memory,@@ -131,64 +148,122 @@ export function registerRelationsFunction(sdk: IIIClient, kv: StateKV): void {memoryId: string;newContent: string;newTitle?: string;+ newType?: string;}) => {-- const existing = await kv.get<Memory>(KV.memories, data.memoryId);- if (!existing) {- return { success: false, error: "memory not found" };+ if (+ !data?.memoryId ||+ typeof data.newContent !== "string" ||+ !data.newContent.trim()+ ) {+ return { success: false, error: "memoryId and newContent are required" };+ }+ if (data.newType !== undefined && !MEMORY_TYPES.has(data.newType)) {+ return { success: false, error: `invalid type: ${data.newType}` };}+ return withKeyedLock("mem:remember", async () => {+ const existing = await kv.get<Memory>(KV.memories, data.memoryId);+ if (!existing) {+ return { success: false, error: "memory not found", code: "not_found" };+ }+ if (existing.isLatest === false) {+ return {+ success: false,+ error: "memory is not the latest version; edit the latest version instead",+ code: "not_latest",+ };+ }+ const newType = (data.newType ?? existing.type) as Memory["type"];+ if (+ data.newContent === existing.content &&+ newType === existing.type &&+ (!data.newTitle || data.newTitle === existing.title)+ ) {+ return { success: false, error: "nothing changed", code: "unchanged" };+ }- const now = new Date().toISOString();- const evolved: Memory = {- ...existing,- id: generateId("mem"),- createdAt: now,- updatedAt: now,- title: data.newTitle || existing.title,- content: data.newContent,- version: (existing.version || 1) + 1,- parentId: existing.id,- supersedes: [existing.id, ...(existing.supersedes || [])],- isLatest: true,- };-- existing.isLatest = false;- await kv.set(KV.memories, existing.id, existing);- await safeAudit(kv, "evolve", "mem::evolve", [existing.id], {- operation: "evolve",- action: "mark_non_latest",- newId: evolved.id,- });+ const titleWasDerived =+ existing.title === memoryTitleFromContent(existing.content);+ const now = new Date().toISOString();+ const evolved: Memory = {+ ...existing,+ id: generateId("mem"),+ createdAt: now,+ updatedAt: now,+ type: newType,+ title:+ data.newTitle ||+ (titleWasDerived ? memoryTitleFromContent(data.newContent) : existing.title),+ content: data.newContent,+ version: (existing.version || 1) + 1,+ parentId: existing.id,+ supersedes: [existing.id, ...(existing.supersedes || [])],+ isLatest: true,+ };- await kv.set(KV.memories, evolved.id, evolved);- await safeAudit(kv, "evolve", "mem::evolve", [evolved.id], {- operation: "evolve",- oldId: existing.id,- newId: evolved.id,- version: evolved.version,- });+ existing.isLatest = false;+ await kv.set(KV.memories, existing.id, existing);+ try {+ getSearchIndex().remove(existing.id);+ } catch {}+ vectorIndexRemove(existing.id);+ await safeAudit(kv, "evolve", "mem::evolve", [existing.id], {+ operation: "evolve",+ action: "mark_non_latest",+ newId: evolved.id,+ });- const relation: MemoryRelation = {- type: "supersedes",- sourceId: evolved.id,- targetId: existing.id,- createdAt: now,- confidence: 1.0,- };- const relationId = generateId("rel");- await kv.set(KV.relations, relationId, relation);- await safeAudit(kv, "evolve", "mem::evolve", [relationId], {- operation: "supersedes",- oldId: existing.id,- newId: evolved.id,- });+ await kv.set(KV.memories, evolved.id, evolved);+ try {+ getSearchIndex().add(memoryToObservation(evolved));+ scheduleIndexSave();+ } catch (err) {+ logger.warn("Failed to index evolved memory into BM25", {+ memId: evolved.id,+ error: err instanceof Error ? err.message : String(err),+ });+ }+ await vectorIndexAddGuarded(+ evolved.id,+ evolved.sessionIds?.[0] ?? "memory",+ evolved.title + " " + evolved.content,+ { kind: "memory", logId: evolved.id },+ );+ await safeAudit(kv, "evolve", "mem::evolve", [evolved.id], {+ operation: "evolve",+ oldId: existing.id,+ newId: evolved.id,+ version: evolved.version,+ });- logger.info("Memory evolved", {- oldId: existing.id,- newId: evolved.id,- version: evolved.version,+ const relation: MemoryRelation = {+ type: "supersedes",+ sourceId: evolved.id,+ targetId: existing.id,+ createdAt: now,+ confidence: 1.0,+ };+ const relationId = generateId("rel");+ await kv.set(KV.relations, relationId, relation);+ await safeAudit(kv, "evolve", "mem::evolve", [relationId], {+ operation: "supersedes",+ oldId: existing.id,+ newId: evolved.id,+ });++ logger.info("Memory evolved", {+ oldId: existing.id,+ newId: evolved.id,+ version: evolved.version,+ });+ await sdk+ .trigger({+ function_id: "mem::cascade-update",+ payload: { supersededMemoryId: existing.id },+ action: TriggerAction.Void(),+ })+ .catch(() => {});+ return { success: true, memory: evolved, previousId: existing.id };});- return { success: true, memory: evolved, previousId: existing.id };},);diff --git a/src/functions/remember.ts b/src/functions/remember.tsindex 4e0fcbf6..7acb7e59 100644--- a/src/functions/remember.ts+++ b/src/functions/remember.ts@@ -21,6 +21,10 @@ function safeSlice(text: string, length: number): string {return /[\uD800-\uDBFF]$/.test(sliced) ? sliced.slice(0, -1) : sliced;}+export function memoryTitleFromContent(content: string): string {+ return safeSlice(content, 80);+}+export function registerRememberFunction(sdk: IIIClient, kv: StateKV): void {sdk.registerFunction("mem::remember",async (data: {@@ -156,7 +160,7 @@ export function registerRememberFunction(sdk: IIIClient, kv: StateKV): void {createdAt: now,updatedAt: now,type: memType,- title: safeSlice(data.content, 80),+ title: memoryTitleFromContent(data.content),content: data.content,concepts: data.concepts || [],files: data.files || [],diff --git a/src/functions/replay.ts b/src/functions/replay.tsindex 95629653..4197e374 100644--- a/src/functions/replay.ts+++ b/src/functions/replay.ts@@ -50,16 +50,35 @@ async function isSymlink(path: string): Promise<boolean> {}}-function rawFromCompressed(obs: CompressedObservation): RawObservation {+function splitSyntheticNarrative(narrative: string): { input: unknown; output: string } | null {+ if (!narrative.startsWith("{")) return null;+ let at = narrative.indexOf("} | ");+ while (at >= 0) {+ try {+ return { input: JSON.parse(narrative.slice(0, at + 1)), output: narrative.slice(at + 4) };+ } catch {}+ at = narrative.indexOf("} | ", at + 1);+ }+ try {+ return { input: JSON.parse(narrative), output: "" };+ } catch {+ return null;+ }+}++export function rawFromCompressed(obs: CompressedObservation): RawObservation {+ const isPrompt = obs.type === "conversation";+ const narrative = obs.narrative || "";+ const split = isPrompt ? null : splitSyntheticNarrative(narrative);return {id: obs.id,sessionId: obs.sessionId,timestamp: obs.timestamp,- hookType: "post_tool_use",- toolName: undefined,- toolInput: undefined,- toolOutput: undefined,- userPrompt: obs.type === "conversation" ? obs.narrative : undefined,+ hookType: isPrompt ? "prompt_submit" : obs.type === "error" ? "post_tool_failure" : "post_tool_use",+ toolName: isPrompt ? undefined : obs.title || undefined,+ toolInput: isPrompt ? undefined : split ? split.input : obs.subtitle || undefined,+ toolOutput: isPrompt ? undefined : (split ? split.output : narrative) || undefined,+ userPrompt: isPrompt ? narrative : undefined,assistantResponse: undefined,raw: { title: obs.title, narrative: obs.narrative, facts: obs.facts },};diff --git a/src/functions/search.ts b/src/functions/search.tsindex 66be533b..7be779b6 100644--- a/src/functions/search.ts+++ b/src/functions/search.ts@@ -84,6 +84,45 @@ export function getEmbeddingProvider(): EmbeddingProvider | null {return currentEmbeddingProvider}+const MEMORY_ID_PREFIX = "mem_"+const RANK_FUSION_K = 60++export async function rankMemoryIds(+ query: string,+ limit: number,+): Promise<{ ids: string[]; mode: "hybrid" | "keyword" }> {+ const fetchLimit = Math.max(limit * 4, 50)+ const keyword = getSearchIndex()+ .search(query, fetchLimit)+ .filter((hit) => hit.obsId.startsWith(MEMORY_ID_PREFIX))+ let semantic: Array<{ obsId: string }> = []+ if (vectorIndex && vectorIndex.size > 0 && currentEmbeddingProvider) {+ try {+ const embedding = await currentEmbeddingProvider.embed(query)+ semantic = vectorIndex+ .search(embedding, fetchLimit)+ .filter((hit) => hit.obsId.startsWith(MEMORY_ID_PREFIX))+ } catch (err) {+ logger.warn("memory vector ranking failed, using keyword ranking", {+ error: err instanceof Error ? err.message : String(err),+ })+ }+ }+ const scores = new Map<string, number>()+ const addRanks = (hits: Array<{ obsId: string }>) => {+ hits.forEach((hit, rank) => {+ scores.set(hit.obsId, (scores.get(hit.obsId) ?? 0) + 1 / (RANK_FUSION_K + rank + 1))+ })+ }+ addRanks(keyword)+ addRanks(semantic)+ const ids = Array.from(scores.entries())+ .sort((a, b) => b[1] - a[1])+ .slice(0, limit)+ .map(([id]) => id)+ return { ids, mode: semantic.length > 0 ? "hybrid" : "keyword" }+}+export function vectorIndexRemove(id: string): void {vectorIndex?.remove(id);}diff --git a/src/functions/status.ts b/src/functions/status.tsindex c6577c44..234d7488 100644--- a/src/functions/status.ts+++ b/src/functions/status.ts@@ -45,6 +45,9 @@ export interface StatusInputs {alerts?: string[];notes?: string[];connectionState?: string;+ memory?: { heapUsed: number; heapTotal: number; heapLimit?: number; rss: number };+ eventLoopLagMs?: number;+ cpuPercent?: number;} | null;circuitBreaker: { state?: string; failures?: number } | null;functionMetrics: FunctionMetricInput[];@@ -55,6 +58,8 @@ export interface StatusInputs {bm25Documents: number;vectorDocuments: number | null;observationsIndexed: number;+ memoriesIndexed?: number;+ lessonsIndexed?: number;missingObservations: number | null;sessions: number | null;bm25Incomplete: boolean;@@ -65,8 +70,15 @@ export interface StatusInputs {indexPersistence?: IndexPersistenceStatus | null;}+export interface IndexBreakdown {+ observations: number;+ memories: number;+ lessons: number;+}+export interface StatusReport {status: StatusLevel;+ headline: string;checkedAt: string;service: {version: string;@@ -75,12 +87,17 @@ export interface StatusReport {ports: StatusInputs["ports"];};health: StatusInputs["health"];- provider: { llm: string; embeddings: string; circuitBreaker: StatusInputs["circuitBreaker"] };- index: StatusInputs["index"];+ provider: {+ llm: string;+ embeddings: string;+ circuitBreaker: StatusInputs["circuitBreaker"];+ offWithoutLlm: string[];+ };+ index: StatusInputs["index"] & { breakdown: IndexBreakdown | null };indexPersistence: IndexPersistenceStatus | null;graph: (GraphStatsInput & { ageSeconds: number | null; extractionEnabled: boolean }) | null;- functions: Array<FunctionMetricInput & { failureRate: number }>;- flags: StatusFlag[];+ functions: Array<FunctionMetricInput & { failureRate: number; offWithoutLlm: boolean }>;+ flags: Array<StatusFlag & { inactiveReason?: string }>;problems: StatusProblem[];}@@ -98,6 +115,71 @@ const FUNCTION_FIXES: Record<string, string> = {"Graph extraction calls your LLM provider. Check the provider key and model, or set GRAPH_EXTRACTION_ENABLED=false.",};+export const LLM_KEY_FIX =+ "Add one LLM provider key (for example ANTHROPIC_API_KEY or OPENAI_API_KEY) to ~/.agentmemory/.env and restart.";++export const OFF_WITHOUT_LLM = [+ "session summaries",+ "consolidation into semantic facts and procedures",+ "typed graph extraction",+ "LLM observation compression",+ "skill extraction from finished sessions",+];++export const BM25_EXPLAINER =+ "The keyword index holds observations, memories and lessons, so its total is larger than the observation count.";++export function describeHealthAlert(slug: string): { level: "warn" | "error"; message: string; fix: string } {+ let m: RegExpExecArray | null;+ if ((m = /^memory_(warn|critical)_(\d+)%_rss(\d+)mb$/.exec(slug))) {+ return {+ level: m[1] === "critical" ? "error" : "warn",+ message: `Memory ${m[1] === "critical" ? "critically high" : "high"}: ${m[2]}% of the heap limit in use, process memory ${m[3]} MB.`,+ fix: "Restart agentmemory to release memory. If it climbs back, raise the limit with NODE_OPTIONS=--max-old-space-size=4096.",+ };+ }+ if ((m = /^cpu_(warn|critical)_(\d+)%$/.exec(slug))) {+ return {+ level: m[1] === "critical" ? "error" : "warn",+ message: `CPU ${m[1] === "critical" ? "critically high" : "high"}: ${m[2]}%.`,+ fix: "Usually a burst of observations or a rebuild. If it stays high with no agent running, check the server log for a loop.",+ };+ }+ if ((m = /^event_loop_lag_(warn|critical)_(\d+)ms$/.exec(slug))) {+ return {+ level: m[1] === "critical" ? "error" : "warn",+ message: `The worker is ${m[2]} ms behind on its work (event loop delay), so requests answer slowly.`,+ fix: "It usually clears after an import or index rebuild finishes. If it persists, restart agentmemory.",+ };+ }+ if (slug === "connection_reconnecting") {+ return {+ level: "warn",+ message: "The connection to the iii engine dropped and is reconnecting.",+ fix: "Wait a few seconds. If it does not recover, check that the engine is running with npx @agentmemory/agentmemory status.",+ };+ }+ if ((m = /^connection_(.+)$/.exec(slug))) {+ return {+ level: "error",+ message: `The connection to the iii engine is ${m[1]}, so nothing can be stored or searched.`,+ fix: "Restart agentmemory. Run npx @agentmemory/agentmemory doctor if the engine does not start.",+ };+ }+ return { level: "warn", message: slug, fix: "Look for this alert in the server log." };+}++export function isOffWithoutLlm(functionId: string, providerKind: string): boolean {+ return providerKind === "noop" && functionId in FUNCTION_FIXES;+}++export function markLlmFunctions<T extends { functionId: string }>(+ metrics: T[],+ providerKind: string,+): Array<T & { offWithoutLlm: boolean }> {+ return metrics.map((m) => ({ ...m, offWithoutLlm: isOffWithoutLlm(m.functionId, providerKind) }));+}+function secondsBetween(later: Date, earlierIso: string | undefined): number | null {if (!earlierIso) return null;const earlier = Date.parse(earlierIso);@@ -113,16 +195,31 @@ export function evaluateStatus(input: StatusInputs): StatusReport {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.",+ fix: "The monitor writes a snapshot every 30 seconds after start. Wait a minute; if this stays, check the server log.",});}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." });+ const alerts = input.health?.alerts ?? [];+ if (alerts.length === 0 && healthStatus === "critical") {+ problems.push({+ level: "error",+ code: "health-critical",+ message: "The health monitor reports a critical state.",+ fix: "Check the server log, then restart agentmemory.",+ });+ } else if (alerts.length === 0 && healthStatus === "degraded") {+ problems.push({+ level: "warn",+ code: "health-degraded",+ message: "The health monitor reports a degraded state.",+ fix: "Check the server log for the cause.",+ });}- for (const alert of input.health?.alerts ?? []) {- problems.push({ level: "warn", code: "health-alert", message: alert });+ const described = alerts.map(describeHealthAlert);+ if (healthStatus !== "critical") for (const d of described) d.level = "warn";+ else if (described.length && !described.some((d) => d.level === "error")) described[0].level = "error";+ for (const d of described) {+ problems.push({ level: d.level, code: "health-alert", message: d.message, fix: d.fix });}if (input.circuitBreaker?.state === "open") {@@ -139,15 +236,17 @@ export function evaluateStatus(input: StatusInputs): StatusReport {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.",+ fix: LLM_KEY_FIX,});}- const functions = input.functionMetrics.map((m) => ({+ const noLlm = input.provider === "noop";+ const functions = markLlmFunctions(input.functionMetrics, input.provider).map((m) => ({...m,failureRate: m.totalCalls > 0 ? m.failureCount / m.totalCalls : 0,}));for (const fn of functions) {+ if (fn.offWithoutLlm) continue;if (fn.totalCalls < FAILURE_MIN_CALLS || fn.failureRate < FAILURE_RATE_THRESHOLD) continue;problems.push({level: "warn",@@ -171,6 +270,7 @@ export function evaluateStatus(input: StatusInputs): StatusReport {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.",+ fix: "The check runs again on the next health update. If it keeps timing out, the store is overloaded: check the server log.",});}@@ -248,6 +348,7 @@ export function evaluateStatus(input: StatusInputs): StatusReport {level: "info",code: "graph-snapshot-dirty",message: "The graph snapshot was read while a write was in flight; counts are eventually consistent.",+ fix: "No action needed: the next graph write settles the counts.",});}}@@ -259,6 +360,7 @@ export function evaluateStatus(input: StatusInputs): StatusReport {return {status,+ headline: statusHeadline(status, problems),checkedAt: input.now.toISOString(),service: {version: input.version,@@ -271,16 +373,78 @@ export function evaluateStatus(input: StatusInputs): StatusReport {llm: input.provider,embeddings: input.embeddingProvider,circuitBreaker: input.circuitBreaker,+ offWithoutLlm: noLlm ? OFF_WITHOUT_LLM : [],},- index: input.index,+ index: { ...input.index, breakdown: indexBreakdown(input.index) },indexPersistence: persistence,graph,functions,- flags: input.flags,+ flags: input.flags.map((flag) =>+ flag.enabled && flag.needsLlm && noLlm+ ? { ...flag, inactiveReason: "needs an LLM provider, none is configured" }+ : flag,+ ),problems,};}+function statusHeadline(status: StatusLevel, problems: StatusProblem[]): string {+ if (status === "ok") return "Every check passed. Capture, search and the stream are working.";+ if (status === "info") {+ return `Working normally. ${plural(problems.length, "note")} below about features that are off or checks that did not run.`;+ }+ const worst = problems.find((p) => p.level === status) ?? problems[0];+ const rest = problems.length - 1;+ const lead = status === "error" ? "Not working correctly" : "Working, but needs attention";+ return `${lead}: ${worst.message}${rest > 0 ? ` (${plural(rest, "more item")} below.)` : ""}`;+}++function indexBreakdown(idx: StatusInputs["index"]): IndexBreakdown | null {+ if (idx.memoriesIndexed === undefined && idx.lessonsIndexed === undefined) return null;+ const lessons = idx.lessonsIndexed ?? 0;+ return {+ observations: Math.max(0, idx.observationsIndexed - lessons),+ memories: idx.memoriesIndexed ?? 0,+ lessons,+ };+}++function plural(count: number, word: string): string {+ return `${count} ${word}${count === 1 ? "" : "s"}`;+}++function documentBreakdown(idx: StatusReport["index"]): string {+ const b = idx.breakdown;+ if (!b) return String(idx.bm25Documents);+ const parts = [+ plural(b.observations, "observation"),+ `${b.memories} ${b.memories === 1 ? "memory" : "memories"}`,+ plural(b.lessons, "lesson"),+ ];+ return `${idx.bm25Documents} (${parts.join(", ")})`;+}++function flagState(flag: StatusReport["flags"][number]): string {+ if (!flag.enabled) return "off";+ if (flag.inactiveReason) return `on, inactive: ${flag.inactiveReason}`;+ return "on";+}++function flagHowTo(flag: StatusReport["flags"][number]): string {+ if (!flag.enabled) return flag.enableHow;+ if (flag.inactiveReason) return LLM_KEY_FIX;+ return `Set ${flag.key}=false and restart to turn it off.`;+}++function processHealth(report: StatusReport): string {+ const status = report.health?.status;+ if (!status) return "no data yet";+ if (status === "healthy" && report.status !== "ok") {+ return "healthy (memory, CPU and engine checks only; the badge at the top covers every problem on this page)";+ }+ return status;+}+function escapeHtml(value: unknown): string {return String(value ?? "").replace(/&/g, "&")@@ -318,13 +482,48 @@ function indexPersistenceRows(report: StatusReport): string {rows += row("Vector save", escapeHtml(legSummary(report, persistence.vector)));rows += row("Vector storage",- escapeHtml(`${persistence.buckets} buckets, ${persistence.pendingChanges} unsaved changes`),+ escapeHtml(`${plural(persistence.buckets, "bucket")}, ${plural(persistence.pendingChanges, "unsaved change")}`),+ );+ }+ return rows;+}++function mb(bytes: number): string {+ return `${Math.round(bytes / (1024 * 1024))} MB`;+}++function processRows(report: StatusReport): string {+ const h = report.health;+ let rows = row("Process health", escapeHtml(processHealth(report)));+ if (h?.memory) {+ const limit = h.memory.heapLimit || h.memory.heapTotal;+ const pct = limit > 0 ? Math.round((h.memory.heapUsed / limit) * 100) : 0;+ rows += row(+ "Heap",+ escapeHtml(`${mb(h.memory.heapUsed)} of ${mb(limit)} (${pct}%)`) ++ '<p class="note">JavaScript memory in use against the most it may grow to. Only a concern above 80% while RSS is also over 512 MB.</p>',+ );+ rows += row(+ "RSS",+ escapeHtml(mb(h.memory.rss)) + '<p class="note">Everything the process holds from the operating system, including code and buffers.</p>',+ );+ }+ if (typeof h?.eventLoopLagMs === "number") {+ rows += row(+ "Event loop delay",+ escapeHtml(`${h.eventLoopLagMs.toFixed(1)} ms`) ++ '<p class="note">How far behind the worker is. Under 100 ms is fine; above that requests answer slowly.</p>',);}return rows;}-export function renderStatusHtml(report: StatusReport, styleNonce: string): string {+export function renderStatusHtml(+ report: StatusReport,+ styleNonce: string,+ options: { viewerUrl?: string } = {},+): string {+ const viewerUrl = options.viewerUrl ?? "/agentmemory/viewer#health";const problems = report.problems.length? report.problems.map(@@ -342,9 +541,9 @@ export function renderStatusHtml(report: StatusReport, styleNonce: string): stri.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>`,+ `<tr${!f.offWithoutLlm && f.failureRate >= FAILURE_RATE_THRESHOLD && f.totalCalls >= FAILURE_MIN_CALLS ? ' class="bad"' : ""}>` ++ `<td>${escapeHtml(f.functionId)}</td><td>${f.totalCalls}</td><td>${f.offWithoutLlm ? "-" : f.failureCount}</td>` ++ `<td>${f.offWithoutLlm ? "off, no LLM provider" : `${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>`;@@ -352,8 +551,8 @@ export function renderStatusHtml(report: StatusReport, styleNonce: string): striconst 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>`,+ `<tr><td>${escapeHtml(f.label)}</td><td><code>${escapeHtml(f.key)}</code></td><td${f.inactiveReason ? ' class="warn"' : ""}>${escapeHtml(flagState(f))}</td>` ++ `<td>${escapeHtml(flagHowTo(f))}</td></tr>`,).join("");@@ -365,48 +564,54 @@ export function renderStatusHtml(report: StatusReport, styleNonce: string): stri<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}+:root{--bg:#F9F9F7;--bg-alt:#F0F0EC;--ink:#111111;--ink-muted:#666666;--line:#D4D4CF;--rule:#111111;--ok:#2D6A4F;--info:#1D4E89;--warn:#B8860B;--error:#CC0000;--font-display:'Playfair Display',Georgia,'Times New Roman',serif;--font-body:'Lora',Georgia,serif;--font-ui:'Inter',-apple-system,system-ui,sans-serif;--font-mono:'JetBrains Mono','SF Mono','Fira Code',ui-monospace,monospace}+@media (prefers-color-scheme:dark){:root{--bg:#121316;--bg-alt:#1a1c20;--ink:#eef0f3;--ink-muted:#94979d;--line:#26282c;--rule:#c9cbd1;--ok:#4ade80;--info:#93c5fd;--warn:#fbbf24;--error:#f2555a}}+*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--ink);font:14px/1.55 var(--font-body)}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}+header{display:flex;align-items:baseline;gap:12px;flex-wrap:wrap;border-bottom:3px double var(--rule);padding-bottom:12px;margin-bottom:24px}+h1{font:700 26px/1.2 var(--font-display);margin:0}h2{font:600 11px/1.4 var(--font-ui);letter-spacing:.12em;text-transform:uppercase;color:var(--ink-muted);margin:32px 0 8px;padding-bottom:4px;border-bottom:1px solid var(--rule)}+.badge{font:700 11px/1.4 var(--font-ui);text-transform:uppercase;letter-spacing:.08em;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}+.meta{color:var(--ink-muted);font:12px/1.4 var(--font-ui);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}+li.p p{margin:0;color:var(--ink)}li.p .fix{color:var(--ink-muted);margin-top:4px;font-size:13px}+.lvl{font:700 11px/1.4 var(--font-ui);text-transform:uppercase;letter-spacing:.08em;padding-top:2px}+table{width:100%;border-collapse:collapse;font:13px/1.5 var(--font-ui)}th,td{text-align:left;padding:6px 8px;border-bottom:1px solid var(--line);vertical-align:top;overflow-wrap:anywhere}+th{color:var(--ink-muted);font-weight:500;width:220px}+table.list th{width:auto;font-size:11px;text-transform:uppercase;letter-spacing:.06em;overflow-wrap:normal}table.list td{overflow-wrap:break-word}table.list td code{overflow-wrap:break-word;word-break:normal}tr.bad td{color:var(--error)}+tr:nth-child(even) td{background:var(--bg-alt)}+code{font:12px var(--font-mono);overflow-wrap:anywhere}+.lead{font:600 16px/1.45 var(--font-body);margin:0 0 8px}.live{font:13px/1.5 var(--font-ui);color:var(--ink-muted);margin:0 0 8px}+.note{margin:2px 0 0;color:var(--ink-muted);font-size:12px}a{color:inherit}+@media (max-width:640px){th{width:110px}table.list{table-layout:fixed}table.list th,table.list td{padding:6px 4px;font-size:12px}}</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>+<span class="meta">v${escapeHtml(report.service.version)} · engine ${escapeHtml(report.service.engineVersion)} · checked ${escapeHtml(report.checkedAt)} · <a href="?format=json">json</a></span></header>+<p class="lead ${report.status}">${escapeHtml(report.headline)}</p>+<p class="live">A snapshot from when this page loaded. <a href="${escapeHtml(viewerUrl)}">Open the live version in the viewer →</a> From a terminal: <code>curl -s ${ports.rest ? `http://localhost:${escapeHtml(ports.rest)}` : ""}/agentmemory/status</code> returns this report as JSON.</p><h2>Problems</h2><ul class="problems">${problems}</ul>-<h2>Service</h2><table>+<h2>Engine and connection</h2><table>+${row("Engine connection", escapeHtml(report.health?.connectionState ?? "unknown"))}${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))}+<h2>LLM and embeddings</h2><table>+${row("LLM", escapeHtml(report.provider.llm === "noop" ? "none configured" : report.provider.llm))}+${report.provider.offWithoutLlm.length ? row("Off without an LLM", escapeHtml(report.provider.offWithoutLlm.join(", ")) + `<p class="note">${escapeHtml(LLM_KEY_FIX)}</p>`) : ""}+${row("Embeddings", escapeHtml(report.provider.embeddings === "none" ? "none (keyword search only)" : 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("Keyword index (BM25)", escapeHtml(documentBreakdown(idx)) + `<p class="note">${escapeHtml(BM25_EXPLAINER)}</p>`)}${row("Vector documents", escapeHtml(idx.vectorDocuments ?? "vector search off"))}-${row("Observations indexed", escapeHtml(idx.observationsIndexed))}+${row("Observations searchable", escapeHtml(idx.breakdown ? idx.breakdown.observations : idx.observationsIndexed))}${row("Missing from index", escapeHtml(idx.missingObservations ?? "not checked"))}${row("Sessions", escapeHtml(idx.sessions ?? "unknown"))}-${row("BM25 rebuild", idx.bm25Incomplete ? '<span class="warn">incomplete</span>' : "complete")}+${row("Keyword index rebuild", idx.bm25Incomplete ? '<span class="warn">incomplete</span>' : "complete")}${row("Pending vector backfill", escapeHtml(idx.pendingVectorBackfill))}${indexPersistenceRows(report)}</table>@@ -417,9 +622,12 @@ ${graphrow("Snapshot age", escapeHtml(graph.fromSnapshot ? formatDuration(graph.ageSeconds) : "no snapshot")): row("Graph", "unavailable")}</table>+<h2>Features</h2><table class="list"><tr><th>Feature</th><th>Setting</th><th>State</th><th>How to change</th></tr>${flags}</table>+<h2>Process</h2><table>+${processRows(report)}+</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>+<h2>More</h2><p>Environment checks (keys, engine binary, stale pid files) run on your machine with <code>npx @agentmemory/agentmemory doctor</code>. JSON: <code>GET /agentmemory/status</code> with <code>Accept: application/json</code>, or add <code>?format=json</code>.</p></main></body></html>`;}diff --git a/src/functions/summarize.ts b/src/functions/summarize.tsindex b3ade48d..5ed6e232 100644--- a/src/functions/summarize.ts+++ b/src/functions/summarize.ts@@ -17,6 +17,7 @@ import { getXmlTag, getXmlChildren } from "../prompts/xml.js";import { SummaryOutputSchema } from "../eval/schemas.js";import { validateOutput } from "../eval/validator.js";import { scoreSummary } from "../eval/quality.js";+import { isNoopProvider } from "../providers/noop.js";import type { MetricsStore } from "../eval/metrics-store.js";import { safeAudit } from "./audit.js";import { logger } from "../logger.js";@@ -260,7 +261,7 @@ export function registerSummarizeFunction(return { success: false, error: "no_observations" };}- if (provider.name === "noop") {+ if (isNoopProvider(provider)) {logger.info("Summarize skipped — no LLM provider configured", {sessionId,});diff --git a/src/index.ts b/src/index.tsindex cf8154a0..df92cb93 100644--- a/src/index.ts+++ b/src/index.ts@@ -11,6 +11,7 @@ import {isGraphExtractionEnabled,isAutoCompressEnabled,isConsolidationEnabled,+ getConsolidationIntervalMs,isContextInjectionEnabled,isDropStaleIndexEnabled,} from "./config.js";@@ -98,6 +99,7 @@ import { registerCompressFileFunction } from "./functions/compress-file.js";import { registerReplayFunctions } from "./functions/replay.js";import { registerApiTriggers } from "./triggers/api.js";import { registerEventTriggers } from "./triggers/events.js";+import { registerViewerStreamTriggers } from "./triggers/viewer-streams.js";import { registerMcpEndpoints } from "./mcp/server.js";import { getAllTools } from "./mcp/tools-registry.js";import { startViewerServer } from "./viewer/server.js";@@ -406,6 +408,7 @@ async function main() {registerApiTriggers(sdk, kv, secret, metricsStore, provider);registerEventTriggers(sdk, kv);+ registerViewerStreamTriggers(sdk, kv, { secret, metricsStore, provider });registerMcpEndpoints(sdk, kv, secret);const healthMonitor = registerHealthMonitor(sdk, kv);@@ -518,7 +521,7 @@ async function main() {`Ready. ${embeddingProvider ? "Triple-stream (BM25+Vector+Graph)" : "BM25+Graph"} search active.`,);bootLog(- `REST API: 132 endpoints at http://localhost:${config.restPort}/agentmemory/*`,+ `REST API: 134 endpoints at http://localhost:${config.restPort}/agentmemory/*`,);bootLog(`MCP surface (opt-in via \`npx @agentmemory/mcp\`): ${getAllTools().length} tools · 6 resources · 3 prompts`,@@ -533,7 +536,7 @@ async function main() {);const autoForgetIntervalMs = parseInt(process.env.AUTO_FORGET_INTERVAL_MS || "3600000", 10);- const consolidationIntervalMs = parseInt(process.env.CONSOLIDATION_INTERVAL_MS || "7200000", 10);+ const consolidationIntervalMs = getConsolidationIntervalMs();if (process.env.AUTO_FORGET_ENABLED !== "false") {const autoForgetTimer = setInterval(async () => {diff --git a/src/providers/noop.ts b/src/providers/noop.tsindex 6e74f9aa..63ef083e 100644--- a/src/providers/noop.ts+++ b/src/providers/noop.ts@@ -7,6 +7,10 @@ import type { MemoryProvider } from "../types.js";* detect the empty result and short-circuit instead of spawning a* provider session (#149 / Stop-hook recursion loop fix).*/+export function isNoopProvider(provider: { name: string }): boolean {+ return provider.name === "noop" || provider.name === "resilient(noop)";+}+export class NoopProvider implements MemoryProvider {name = "noop";diff --git a/src/state/list-query.ts b/src/state/list-query.tsnew file mode 100644index 00000000..0f015963--- /dev/null+++ b/src/state/list-query.ts@@ -0,0 +1,112 @@+export const LIST_PAGE_MAX = 500;++export interface ListQuery {+ limit?: number;+ cursor?: string;+ project?: string;+ type?: string;+ status?: string;+ q?: string;+}++type QueryParams = Record<string, string | string[] | undefined> | undefined;++function firstParam(params: QueryParams, name: string): string | undefined {+ const raw = params?.[name];+ const value = Array.isArray(raw) ? raw[0] : raw;+ if (typeof value !== "string") return undefined;+ const trimmed = value.trim();+ return trimmed.length > 0 ? trimmed : undefined;+}++export function parseListQuery(params: QueryParams): ListQuery {+ const rawLimit = firstParam(params, "limit");+ const parsedLimit = rawLimit === undefined ? Number.NaN : Number(rawLimit);+ return {+ limit:+ Number.isFinite(parsedLimit) && parsedLimit >= 1+ ? Math.min(Math.floor(parsedLimit), LIST_PAGE_MAX)+ : undefined,+ cursor: firstParam(params, "cursor"),+ project: firstParam(params, "project"),+ type: firstParam(params, "type"),+ status: firstParam(params, "status"),+ q: firstParam(params, "q"),+ };+}++interface CursorPosition {+ key?: string;+ id?: string;+ offset?: number;+}++export function encodeCursor(position: CursorPosition): string {+ return Buffer.from(JSON.stringify(position), "utf-8").toString("base64url");+}++export function decodeCursor(cursor: string | undefined): CursorPosition | null {+ if (!cursor) return null;+ try {+ const parsed = JSON.parse(Buffer.from(cursor, "base64url").toString("utf-8"));+ if (!parsed || typeof parsed !== "object") return null;+ const position: CursorPosition = {};+ if (typeof parsed.key === "string") position.key = parsed.key;+ if (typeof parsed.id === "string") position.id = parsed.id;+ if (Number.isInteger(parsed.offset) && parsed.offset >= 0) position.offset = parsed.offset;+ return position;+ } catch {+ return null;+ }+}++function compareDesc(aKey: string, aId: string, bKey: string, bId: string): number {+ if (aKey !== bKey) return aKey < bKey ? 1 : -1;+ if (aId === bId) return 0;+ return aId < bId ? 1 : -1;+}++export function sortByKeyDesc<T>(items: T[], keyOf: (item: T) => string, idOf: (item: T) => string): T[] {+ return items.sort((a, b) => compareDesc(keyOf(a), idOf(a), keyOf(b), idOf(b)));+}++export function pageAfterCursor<T>(+ sortedDesc: T[],+ keyOf: (item: T) => string,+ idOf: (item: T) => string,+ cursor: string | undefined,+ limit: number,+): { page: T[]; nextCursor: string | null } {+ const position = decodeCursor(cursor);+ let start = 0;+ if (position?.key !== undefined && position.id !== undefined) {+ const { key, id } = position;+ start = sortedDesc.findIndex((item) => compareDesc(keyOf(item), idOf(item), key, id) > 0);+ if (start < 0) start = sortedDesc.length;+ }+ const page = sortedDesc.slice(start, start + limit);+ const last = page[page.length - 1];+ const nextCursor =+ last !== undefined && start + limit < sortedDesc.length+ ? encodeCursor({ key: keyOf(last), id: idOf(last) })+ : null;+ return { page, nextCursor };+}++export function pageByOffset<T>(+ ordered: T[],+ cursor: string | undefined,+ limit: number,+): { page: T[]; nextCursor: string | null } {+ const start = decodeCursor(cursor)?.offset ?? 0;+ const page = ordered.slice(start, start + limit);+ const nextCursor =+ start + limit < ordered.length ? encodeCursor({ offset: start + limit }) : null;+ return { page, nextCursor };+}++export function matchesText(q: string | undefined, ...fields: Array<string | undefined | null>): boolean {+ if (!q) return true;+ const needle = q.toLowerCase();+ return fields.some((field) => typeof field === "string" && field.toLowerCase().includes(needle));+}diff --git a/src/state/search-index.ts b/src/state/search-index.tsindex a1ae6cf2..c7e8b65d 100644--- a/src/state/search-index.ts+++ b/src/state/search-index.ts@@ -52,6 +52,10 @@ export class SearchIndex {return this.entries.has(id);}+ sessionOf(id: string): string | undefined {+ return this.entries.get(id)?.sessionId;+ }+observationCountsBySession(): Map<string, number> {const counts = new Map<string, number>();for (const entry of this.entries.values()) {@@ -61,6 +65,16 @@ export class SearchIndex {return counts;}+ documentKindCounts(): { memories: number; lessons: number } {+ let memories = 0;+ let lessons = 0;+ for (const entry of this.entries.values()) {+ if (entry.obsId.startsWith("mem_")) memories++;+ else if (entry.sessionId === "lesson") lessons++;+ }+ return { memories, lessons };+ }+remove(id: string): void {const entry = this.entries.get(id);if (!entry) return;diff --git a/src/state/viewer-counts.ts b/src/state/viewer-counts.tsnew file mode 100644index 00000000..76a6b020--- /dev/null+++ b/src/state/viewer-counts.ts@@ -0,0 +1,186 @@+import type { StateKV } from "./kv.js";+import { KV } from "./schema.js";+import { getAgentId, isAgentScopeIsolated } from "../config.js";+import type {+ GraphSnapshot,+ Lesson,+ Memory,+ Session,+} from "../types.js";++export interface ViewerCounts {+ sessions: number;+ activeSessions: number;+ observations: number;+ memories: number;+ latestMemories: number;+ lessons: number;+ actions: number;+ crystals: number;+ semantic: number;+ procedural: number;+ graphNodes: number;+ graphEdges: number;+ updatedAt: string;+}++export type CountedKind = "lessons" | "actions" | "crystals" | "semantic" | "procedural";++const GRAPH_SNAPSHOT_KEY = "current";+const EMIT_DELAY_MS = 500;+const MAX_LOAD_ATTEMPTS = 2;++let counts: ViewerCounts | null = null;+let loading: Promise<ViewerCounts> | null = null;+let changedWhileLoading = false;+let emitter: ((counts: ViewerCounts) => void) | null = null;+let emitTimer: ReturnType<typeof setTimeout> | null = null;++export function setViewerCountsEmitter(fn: ((counts: ViewerCounts) => void) | null): void {+ emitter = fn;+}++function inAgentScope(record: { agentId?: string } | null | undefined): boolean {+ if (!record) return false;+ return !isAgentScopeIsolated() || record.agentId === getAgentId();+}++function isLiveLesson(lesson: Lesson | null | undefined): boolean {+ return Boolean(lesson) && lesson!.deleted !== true;+}++async function listOrEmpty<T>(kv: StateKV, scope: string): Promise<T[]> {+ const rows = await kv.list<T>(scope).catch(() => [] as T[]);+ return Array.isArray(rows) ? rows : [];+}++async function readCounts(kv: StateKV): Promise<ViewerCounts> {+ const [sessions, memories, lessons, actions, crystals, semantic, procedural, snapshot] =+ await Promise.all([+ listOrEmpty<Session>(kv, KV.sessions),+ listOrEmpty<Memory>(kv, KV.memories),+ listOrEmpty<Lesson>(kv, KV.lessons),+ listOrEmpty<unknown>(kv, KV.actions),+ listOrEmpty<unknown>(kv, KV.crystals),+ listOrEmpty<unknown>(kv, KV.semantic),+ listOrEmpty<unknown>(kv, KV.procedural),+ kv.get<GraphSnapshot>(KV.graphSnapshot, GRAPH_SNAPSHOT_KEY).catch(() => null),+ ]);+ const scopedSessions = sessions.filter(inAgentScope);+ const scopedMemories = memories.filter(inAgentScope);+ return {+ sessions: scopedSessions.length,+ activeSessions: scopedSessions.filter((s) => s.status === "active").length,+ observations: scopedSessions.reduce((sum, s) => sum + (s.observationCount || 0), 0),+ memories: scopedMemories.length,+ latestMemories: scopedMemories.filter((m) => m.isLatest !== false).length,+ lessons: lessons.filter(isLiveLesson).length,+ actions: actions.length,+ crystals: crystals.length,+ semantic: semantic.length,+ procedural: procedural.length,+ graphNodes: snapshot?.stats?.totalNodes ?? 0,+ graphEdges: snapshot?.stats?.totalEdges ?? 0,+ updatedAt: new Date().toISOString(),+ };+}++export async function getViewerCounts(kv: StateKV): Promise<ViewerCounts> {+ if (counts) return { ...counts };+ if (!loading) {+ loading = (async () => {+ let result = await readCounts(kv);+ for (let attempt = 1; attempt < MAX_LOAD_ATTEMPTS && changedWhileLoading; attempt++) {+ changedWhileLoading = false;+ result = await readCounts(kv);+ }+ changedWhileLoading = false;+ counts = result;+ return result;+ })().finally(() => {+ loading = null;+ });+ }+ return { ...(await loading) };+}++function scheduleEmit(): void {+ if (!emitter || emitTimer) return;+ emitTimer = setTimeout(() => {+ emitTimer = null;+ if (counts && emitter) emitter({ ...counts });+ }, EMIT_DELAY_MS);+ if (typeof emitTimer === "object" && emitTimer && "unref" in emitTimer) emitTimer.unref();+}++function applyDelta(apply: (current: ViewerCounts) => boolean): void {+ if (!counts) {+ if (loading) changedWhileLoading = true;+ return;+ }+ if (!apply(counts)) return;+ counts.updatedAt = new Date().toISOString();+ scheduleEmit();+}++function presence(before: unknown, after: unknown): number {+ return (after ? 1 : 0) - (before ? 1 : 0);+}++export function noteSessionChange(before: Session | null | undefined, after: Session | null | undefined): void {+ const prev = inAgentScope(before) ? before : null;+ const next = inAgentScope(after) ? after : null;+ applyDelta((c) => {+ const sessions = presence(prev, next);+ const active = presence(prev?.status === "active", next?.status === "active");+ const observations = (next?.observationCount || 0) - (prev?.observationCount || 0);+ if (sessions === 0 && active === 0 && observations === 0) return false;+ c.sessions += sessions;+ c.activeSessions += active;+ c.observations += observations;+ return true;+ });+}++export function noteMemoryChange(before: Memory | null | undefined, after: Memory | null | undefined): void {+ const prev = inAgentScope(before) ? before : null;+ const next = inAgentScope(after) ? after : null;+ applyDelta((c) => {+ const total = presence(prev, next);+ const latest = presence(prev && prev.isLatest !== false, next && next.isLatest !== false);+ if (total === 0 && latest === 0) return false;+ c.memories += total;+ c.latestMemories += latest;+ return true;+ });+}++export function noteRowChange(kind: CountedKind, before: unknown, after: unknown): void {+ const alive = (row: unknown) =>+ kind === "lessons" ? isLiveLesson(row as Lesson | null | undefined) : Boolean(row);+ applyDelta((c) => {+ const delta = presence(alive(before), alive(after));+ if (delta === 0) return false;+ c[kind] += delta;+ return true;+ });+}++export function noteGraphStats(stats: GraphSnapshot["stats"] | null | undefined): void {+ if (!stats) return;+ applyDelta((c) => {+ if (c.graphNodes === stats.totalNodes && c.graphEdges === stats.totalEdges) return false;+ c.graphNodes = stats.totalNodes;+ c.graphEdges = stats.totalEdges;+ return true;+ });+}++export function resetViewerCounts(): void {+ counts = null;+ loading = null;+ changedWhileLoading = false;+ emitter = null;+ if (emitTimer) clearTimeout(emitTimer);+ emitTimer = null;+}diff --git a/src/triggers/api.ts b/src/triggers/api.tsindex d8831057..5fa9c7a1 100644--- a/src/triggers/api.ts+++ b/src/triggers/api.ts@@ -1,7 +1,7 @@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 type { Session, CompressedObservation, HookPayload, CommitLink, SessionSummary, HealthSnapshot } from "../types.js";import { withKeyedLock } from "../state/keyed-mutex.js";import { KV } from "../state/schema.js";import { checkPayloadFrameSize } from "../state/frame-guard.js";@@ -11,25 +11,41 @@ import { getLatestHealth } from "../health/monitor.js";import type { MetricsStore } from "../eval/metrics-store.js";import type { ResilientProvider } from "../providers/resilient.js";import { III_PINNED_VERSION, VERSION } from "../version.js";-import { CONSOLIDATION_COUNTS_REUSE_MS, CONSOLIDATION_LAST_RUN_KEY, PROCEDURAL_MIN_SESSIONS_PER_PATTERN, describeConsolidation, type ConsolidationRunRecord } from "../functions/consolidation-status.js";-import { UNINDEXED_SCAN_REUSE_MS, evaluateStatus, prefersHtml, renderStatusHtml, singleFlight, type GraphStatsInput } from "../functions/status.js";+import { CONSOLIDATION_COUNTS_REUSE_MS, CONSOLIDATION_LAST_RUN_KEY, PROCEDURAL_MIN_SESSIONS_PER_PATTERN, describeConsolidation, type ConsolidationRunRecord, type ConsolidationStatus } from "../functions/consolidation-status.js";+import { UNINDEXED_SCAN_REUSE_MS, evaluateStatus, prefersHtml, renderStatusHtml, singleFlight, type GraphStatsInput, type StatusReport } from "../functions/status.js";import {findUnindexedObservations,getIndexPersistenceStatus,+ getEmbeddingProvider,getPendingVectorBackfillCount,getSearchIndex,getVectorIndex,isBm25RebuildIncomplete,+ rankMemoryIds,} from "../functions/search.js";+import {+ LIST_PAGE_MAX,+ encodeCursor,+ matchesText,+ pageAfterCursor,+ pageByOffset,+ parseListQuery,+ sortByKeyDesc,+} from "../state/list-query.js";import { timingSafeCompare } from "../auth.js";import { isSlotsEnabled, isReflectEnabled } from "../functions/slots.js";import { renderViewerDocument } from "../viewer/document.js";import { getBoundViewerPort, getViewerSkipped } from "../viewer/server.js";import { MAX_FILES_UPPER_BOUND } from "../functions/replay.js";+import { describeGraphNode } from "../functions/graph-node.js";+import { LESSON_SOURCE_IDS_MAX, normalizeLessonSourceIds } from "../functions/lessons.js";import { logger } from "../logger.js";import {isGraphExtractionEnabled,isConsolidationEnabled,+ getConsolidationIntervalMs,+ getConsolidationCooldownMs,+ getConsolidationDecayDays,isAutoCompressEnabled,isContextInjectionEnabled,detectEmbeddingProvider,@@ -51,7 +67,7 @@ function parseOptionalInt(raw: unknown): number | undefined {return Number.isFinite(n) ? n : undefined;}-function checkAuth(+export function checkAuth(req: HttpRequest,secret: string | undefined,): Response | null {@@ -150,7 +166,7 @@ function parseOptionalPositiveInt(value: unknown): number | undefined | null {return parsed;}-function buildConfigFlags() {+export function buildConfigFlags() {return [{key: "GRAPH_EXTRACTION_ENABLED",@@ -199,6 +215,223 @@ function buildConfigFlags() {];}+function sessionSortKey(s: Session): string {+ return s.startedAt || "";+}++function observationSortKey(o: CompressedObservation): string {+ return o.timestamp || "";+}++function memorySortKey(m: { updatedAt?: string; createdAt?: string }): string {+ return m.updatedAt || m.createdAt || "";+}++type FacetCount = { value: string; count: number };++function memoryFacets(+ memories: Array<{ isLatest?: boolean; project?: string; agentId?: string; type?: string }>,+): { projects: FacetCount[]; agents: FacetCount[]; types: FacetCount[] } {+ const tally = (pick: (m: (typeof memories)[number]) => string | undefined) => {+ const counts = new Map<string, number>();+ for (const m of memories) {+ if (m.isLatest === false) continue;+ const value = pick(m);+ if (value) counts.set(value, (counts.get(value) ?? 0) + 1);+ }+ return [...counts.entries()]+ .map(([value, count]) => ({ value, count }))+ .sort((a, b) => b.count - a.count || a.value.localeCompare(b.value));+ };+ return {+ projects: tally((m) => m.project),+ agents: tally((m) => m.agentId),+ types: tally((m) => m.type),+ };+}++function sessionFacets(+ sessions: Array<{ project?: string; agentId?: string; status?: string }>,+): { projects: FacetCount[]; agents: FacetCount[]; statuses: FacetCount[] } {+ const tally = (pick: (s: (typeof sessions)[number]) => string | undefined) => {+ const counts = new Map<string, number>();+ for (const s of sessions) {+ const value = pick(s);+ if (value) counts.set(value, (counts.get(value) ?? 0) + 1);+ }+ return [...counts.entries()]+ .map(([value, count]) => ({ value, count }))+ .sort((a, b) => b.count - a.count || a.value.localeCompare(b.value));+ };+ return {+ projects: tally((s) => s.project),+ agents: tally((s) => s.agentId),+ statuses: tally((s) => s.status),+ };+}++function describeEmbeddingProvider(): string {+ const active = getEmbeddingProvider();+ if (active) return `${active.name} (${active.dimensions} dims)`;+ return detectEmbeddingProvider() ?? "none";+}++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);+ }+}++type UnindexedScan = Awaited<ReturnType<typeof findUnindexedObservations>>;+const unindexedScans = new WeakMap<StateKV, { run: () => Promise<UnindexedScan>; last: { at: number; value: UnindexedScan } | null }>();++function unindexedScanFor(kv: StateKV) {+ let entry = unindexedScans.get(kv);+ if (!entry) {+ const created: { run: () => Promise<UnindexedScan>; last: { at: number; value: UnindexedScan } | null } = {+ run: singleFlight(async () => {+ const value = await findUnindexedObservations(kv);+ created.last = { at: Date.now(), value };+ return value;+ }, UNINDEXED_SCAN_REUSE_MS),+ last: null,+ };+ unindexedScans.set(kv, created);+ entry = created;+ }+ return entry;+}++export interface StatusReporterDeps {+ metricsStore?: MetricsStore;+ provider?: ResilientProvider | { circuitState?: unknown };+}++export function createStatusReporter(sdk: IIIClient, kv: StateKV, deps: StatusReporterDeps) {+ const scan = unindexedScanFor(kv);+ return async function statusReport(options: { health?: HealthSnapshot | null; scanMaxAgeMs?: number } = {}): Promise<StatusReport> {+ const idx = getSearchIndex();+ const cached = scan.last && options.scanMaxAgeMs !== undefined && Date.now() - scan.last.at < options.scanMaxAgeMs+ ? scan.last.value+ : null;+ const [health, functionMetrics, graph, unindexed] = await Promise.all([+ options.health !== undefined ? Promise.resolve(options.health) : valueWithin(getLatestHealth(kv), STATUS_CHECK_TIMEOUT_MS),+ deps.metricsStore ? valueWithin(deps.metricsStore.getAll(), STATUS_CHECK_TIMEOUT_MS) : Promise.resolve([]),+ valueWithin(+ sdk.trigger({ function_id: "mem::graph-stats", payload: {} }) as Promise<GraphStatsInput>,+ STATUS_CHECK_TIMEOUT_MS,+ ),+ cached ? Promise.resolve(cached) : valueWithin(scan.run(), STATUS_CHECK_TIMEOUT_MS),+ ]);+ const observationsIndexed = [...idx.observationCountsBySession().values()].reduce((a, n) => a + n, 0);+ const documentKinds = idx.documentKindCounts();+ const circuit =+ deps.provider && "circuitState" in deps.provider+ ? (deps.provider.circuitState as { state?: string; failures?: number } | null)+ : null;+ return evaluateStatus({+ now: new Date(),+ version: VERSION,+ engineVersion: III_PINNED_VERSION,+ uptimeSeconds: Math.round(process.uptime()),+ ports: {+ rest: loadConfig().restPort ?? null,+ streams: loadConfig().streamsPort ?? null,+ viewer: getViewerSkipped() ? null : (getBoundViewerPort() ?? null),+ },+ health: health+ ? {+ status: health.status,+ alerts: health.alerts,+ notes: health.notes,+ connectionState: health.connectionState,+ memory: health.memory,+ eventLoopLagMs: health.eventLoopLagMs,+ cpuPercent: health.cpu?.percent,+ }+ : null,+ circuitBreaker: circuit,+ functionMetrics: functionMetrics ?? [],+ provider: detectLlmProviderKind(),+ embeddingProvider: describeEmbeddingProvider(),+ flags: buildConfigFlags(),+ index: {+ bm25Documents: idx.size,+ vectorDocuments: getVectorIndex()?.size ?? null,+ observationsIndexed,+ memoriesIndexed: documentKinds.memories,+ lessonsIndexed: documentKinds.lessons,+ missingObservations: unindexed ? unindexed.missing.length : null,+ sessions: unindexed ? unindexed.sessions : null,+ bm25Incomplete: isBm25RebuildIncomplete(),+ pendingVectorBackfill: getPendingVectorBackfillCount(),+ },+ graph,+ graphExtractionEnabled: isGraphExtractionEnabled(),+ indexPersistence: getIndexPersistenceStatus(),+ });+ };+}++export function createConsolidationStatusReader(kv: StateKV) {+ const counts = singleFlight(async () => {+ const [summaries, memories, semantic, procedural, relations] = await Promise.all([+ kv.list(KV.summaries).catch(() => []),+ kv.list<import("../types.js").Memory>(KV.memories).catch(() => []),+ kv.list(KV.semantic).catch(() => []),+ kv.list(KV.procedural).catch(() => []),+ kv.list(KV.relations).catch(() => []),+ ]);+ return {+ summaries: summaries.length,+ recurringPatterns: memories.filter(+ (m) =>+ m.isLatest &&+ m.type === "pattern" &&+ (m.sessionIds?.length ?? 0) >= PROCEDURAL_MIN_SESSIONS_PER_PATTERN,+ ).length,+ semanticFacts: semantic.length,+ procedures: procedural.length,+ relations: relations.length,+ };+ }, CONSOLIDATION_COUNTS_REUSE_MS);+ return async function consolidationStatus(known: { lastRun?: ConsolidationRunRecord | null } = {}): Promise<ConsolidationStatus> {+ const [current, lastRun] = await Promise.all([+ counts(),+ known.lastRun !== undefined+ ? Promise.resolve(known.lastRun)+ : kv.get<ConsolidationRunRecord>(KV.config, CONSOLIDATION_LAST_RUN_KEY).catch(() => null),+ ]);+ return describeConsolidation({+ now: new Date(),+ enabled: isConsolidationEnabled(),+ llmConfigured: detectLlmProviderKind() === "llm",+ ...current,+ lastRun: lastRun ?? null,+ schedule: {+ intervalMs: getConsolidationIntervalMs(),+ cooldownMs: getConsolidationCooldownMs(),+ decayDays: getConsolidationDecayDays(),+ },+ });+ };+}++function statusViewerUrl(req: HttpRequest, viewerPort: number | null): string {+ const hostHeader = req.headers?.["host"] ?? req.headers?.["Host"];+ const host = typeof hostHeader === "string" ? hostHeader.replace(/:\d+$/, "") : "";+ if (viewerPort && host && /^[A-Za-z0-9.\-[\]:]+$/.test(host)) return `http://${host}:${viewerPort}/#health`;+ return "/agentmemory/viewer#health";+}+export function registerApiTriggers(sdk: IIIClient,kv: StateKV,@@ -257,7 +490,7 @@ export function registerApiTriggers(const authErr = checkAuth(req, secret);if (authErr) return authErr;const providerKind = detectLlmProviderKind();- const embeddingProvider = detectEmbeddingProvider() ? "embeddings" : "none";+ const embeddingProvider = describeEmbeddingProvider();const flags = buildConfigFlags();return {status_code: 200,@@ -314,77 +547,13 @@ 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);+ const statusReport = createStatusReporter(sdk, kv, { metricsStore, provider });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,- bm25Incomplete: isBm25RebuildIncomplete(),- pendingVectorBackfill: getPendingVectorBackfillCount(),- },- graph,- graphExtractionEnabled: isGraphExtractionEnabled(),- indexPersistence: getIndexPersistenceStatus(),- });+ const report = await statusReport();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)) {@@ -396,7 +565,7 @@ export function registerApiTriggers("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),+ body: renderStatusHtml(report, nonce, { viewerUrl: statusViewerUrl(req, report.service.ports.viewer) }),};}return { status_code: 200, headers: { "Cache-Control": "no-store" }, body: report };@@ -996,9 +1165,37 @@ export function registerApiTriggers(? undefined: explicitAgentId ??(isAgentScopeIsolated() ? getAgentId() : undefined);- const filtered = filterAgentId+ const listQuery = parseListQuery(req.query_params);+ let filtered = filterAgentId? sessions.filter((s) => s.agentId === filterAgentId): sessions;+ const facets =+ req.query_params?.["facets"] === "true"+ ? sessionFacets(+ !wildcardAgent && isAgentScopeIsolated()+ ? sessions.filter((s) => s.agentId === getAgentId())+ : sessions,+ )+ : undefined;+ if (listQuery.project) filtered = filtered.filter((s) => s.project === listQuery.project);+ if (listQuery.status) filtered = filtered.filter((s) => s.status === listQuery.status);+ if (listQuery.q) {+ filtered = filtered.filter((s) =>+ matchesText(listQuery.q, s.id, s.project, s.cwd, s.firstPrompt, s.agentId),+ );+ }+ let nextCursor: string | null = null;+ if (listQuery.limit !== undefined || listQuery.cursor) {+ const paged = pageAfterCursor(+ sortByKeyDesc(filtered, sessionSortKey, (s) => s.id),+ sessionSortKey,+ (s) => s.id,+ listQuery.cursor,+ listQuery.limit ?? LIST_PAGE_MAX,+ );+ filtered = paged.page;+ nextCursor = paged.nextCursor;+ }// Bounded fan-out: each kv.get is a full engine invocation, so// Promise.all over hundreds of sessions saturates the invocation// pool. Batch in chunks of 10 (parallel within a chunk, sequential@@ -1017,7 +1214,10 @@ export function registerApiTriggers(const withSummary = filtered.map((s, i) =>summaries[i] ? { ...s, summary: summaries[i] } : s,);- return { status_code: 200, body: { sessions: withSummary } };+ return {+ status_code: 200,+ body: { sessions: withSummary, nextCursor, ...(facets ? { facets } : {}) },+ };},);sdk.registerTrigger({@@ -1047,10 +1247,35 @@ export function registerApiTriggers(? undefined: explicitAgentId ??(isAgentScopeIsolated() ? getAgentId() : undefined);- const filtered = filterAgentId+ const listQuery = parseListQuery(req.query_params);+ let filtered = filterAgentId? observations.filter((o) => o.agentId === filterAgentId): observations;- return { status_code: 200, body: { observations: filtered } };+ if (listQuery.type) filtered = filtered.filter((o) => o.type === listQuery.type);+ if (listQuery.q) {+ filtered = filtered.filter((o) =>+ matchesText(listQuery.q, o.title, o.subtitle, o.narrative, ...(o.facts ?? []), ...(o.files ?? [])),+ );+ }+ const minImportance = Number(req.query_params?.["minImportance"]);+ if (Number.isFinite(minImportance)) {+ filtered = filtered.filter((o) => (o.importance ?? 0) >= minImportance);+ }+ if (listQuery.limit === undefined && !listQuery.cursor) {+ return { status_code: 200, body: { observations: filtered, total: filtered.length, nextCursor: null } };+ }+ const total = filtered.length;+ const paged = pageAfterCursor(+ sortByKeyDesc(filtered, observationSortKey, (o) => o.id),+ observationSortKey,+ (o) => o.id,+ listQuery.cursor,+ listQuery.limit ?? LIST_PAGE_MAX,+ );+ return {+ status_code: 200,+ body: { observations: paged.page, total, nextCursor: paged.nextCursor },+ };},);sdk.registerTrigger({@@ -1059,6 +1284,32 @@ export function registerApiTriggers(config: { api_path: "/agentmemory/observations", http_method: "GET" },});+ sdk.registerFunction("api::observations-locate",+ async (req: HttpRequest): Promise<Response> => {+ const authErr = checkAuth(req, secret);+ if (authErr) return authErr;+ const raw = req.query_params?.["ids"];+ const ids = (Array.isArray(raw) ? raw.join(",") : String(raw ?? ""))+ .split(",")+ .map((id) => id.trim())+ .filter(Boolean)+ .slice(0, 200);+ if (ids.length === 0) return { status_code: 400, body: { error: "ids required" } };+ const index = getSearchIndex();+ const sessions: Record<string, string> = {};+ for (const id of ids) {+ const sessionId = index.sessionOf(id);+ if (sessionId && !id.startsWith("mem_") && sessionId !== "lesson") sessions[id] = sessionId;+ }+ return { status_code: 200, body: { sessions } };+ },+ );+ sdk.registerTrigger({+ type: "http",+ function_id: "api::observations-locate",+ config: { api_path: "/agentmemory/observations/locate", http_method: "GET" },+ });+sdk.registerFunction("api::file-context",async (req: HttpRequest<{ sessionId: string; files: string[] }>,@@ -1434,7 +1685,8 @@ export function registerApiTriggers(body: { error: "project query param is required" },};}- const result = await sdk.trigger({ function_id: "mem::profile", payload: { project } });+ const refresh = req.query_params["refresh"] === "true";+ const result = await sdk.trigger({ function_id: "mem::profile", payload: { project, refresh } });return { status_code: 200, body: result };},);@@ -1531,6 +1783,7 @@ export function registerApiTriggers(memoryId: string;newContent: string;newTitle?: string;+ newType?: string;}>,): Promise<Response> => {const authErr = checkAuth(req, secret);@@ -1541,7 +1794,15 @@ export function registerApiTriggers(body: { error: "memoryId and newContent are required" },};}- const result = await sdk.trigger({ function_id: "mem::evolve", payload: req.body });+ const result = await sdk.trigger<unknown, { success?: boolean; code?: string }>({+ function_id: "mem::evolve",+ payload: req.body,+ });+ if (result && result.success === false) {+ const status =+ result.code === "not_found" ? 404 : result.code === "not_latest" ? 409 : 400;+ return { status_code: status, body: result };+ }return { status_code: 200, body: result };},);@@ -1667,6 +1928,23 @@ export function registerApiTriggers(config: { api_path: "/agentmemory/graph/stats", http_method: "GET" },});+ sdk.registerFunction("api::graph-node",+ async (req: HttpRequest): Promise<Response> => {+ const authErr = checkAuth(req, secret);+ if (authErr) return authErr;+ const id = asNonEmptyString(req.query_params?.["id"]);+ if (!id) return { status_code: 400, body: { error: "id required" } };+ const detail = await describeGraphNode(kv, id);+ if (!detail) return { status_code: 404, body: { error: "graph node not found", id } };+ return { status_code: 200, body: detail };+ },+ );+ sdk.registerTrigger({+ type: "http",+ function_id: "api::graph-node",+ config: { api_path: "/agentmemory/graph/node", http_method: "GET" },+ });+// #814: explicit snapshot rebuild endpoint. Pays the full graph// enumeration once and persists a top-degree subgraph + aggregate// counts so subsequent /graph/query and /graph/stats calls skip the@@ -1937,10 +2215,21 @@ export function registerApiTriggers(async (req: HttpRequest): Promise<Response> => {const authErr = checkAuth(req, secret);if (authErr) return authErr;- const parsedLimit = parseOptionalInt(req.query_params?.["limit"]);+ const params = req.query_params || {};+ const parsedLimit = parseOptionalInt(params["limit"]);+ const dateFrom = asNonEmptyString(params["dateFrom"]);+ const dateTo = asNonEmptyString(params["dateTo"]);+ for (const [name, value] of [["dateFrom", dateFrom], ["dateTo", dateTo]] as const) {+ if (value && Number.isNaN(new Date(value).getTime())) {+ return { status_code: 400, body: { error: `invalid date: ${name}` } };+ }+ }const entries = await sdk.trigger({ function_id: "mem::audit-query", payload: {- operation: req.query_params?.["operation"],- limit: parsedLimit ?? 50,+ operation: asNonEmptyString(params["operation"]),+ dateFrom,+ dateTo,+ query: asNonEmptyString(params["q"]),+ limit: Math.min(Math.max(parsedLimit ?? 50, 1), 1000),} });return { status_code: 200, body: { entries, success: true } };},@@ -2090,6 +2379,37 @@ export function registerApiTriggers((includeOrphans && m.agentId === undefined),);}+ const facets =+ req.query_params?.["facets"] === "true" ? memoryFacets(filtered) : undefined;+ const listQuery = parseListQuery(req.query_params);+ if (listQuery.project) filtered = filtered.filter((m) => m.project === listQuery.project);+ if (listQuery.type) filtered = filtered.filter((m) => m.type === listQuery.type);+ const fromSession = asNonEmptyString(req.query_params?.["sessionId"]);+ if (fromSession) {+ const needsObservations = filtered.some(+ (m) => !(m.sessionIds ?? []).includes(fromSession) && (m.sourceObservationIds?.length ?? 0) > 0,+ );+ const sessionObsIds = needsObservations+ ? new Set(+ (await kv.list<CompressedObservation>(KV.observations(fromSession)).catch(() => []))+ .map((o) => o.id),+ )+ : new Set<string>();+ filtered = filtered.filter(+ (m) =>+ (m.sessionIds ?? []).includes(fromSession) ||+ (m.sourceObservationIds ?? []).some((id) => sessionObsIds.has(id)),+ );+ }+ let searchMode: "hybrid" | "keyword" | undefined;+ if (listQuery.q) {+ const ranked = await rankMemoryIds(listQuery.q, LIST_PAGE_MAX);+ searchMode = ranked.mode;+ const byId = new Map(filtered.map((m) => [m.id, m]));+ filtered = ranked.ids+ .map((id) => byId.get(id))+ .filter((m): m is import("../types.js").Memory => m !== undefined);+ }// viewer + `agentmemory status` were hitting this endpoint to// count memories. On a real corpus (8K+ memories) the unbounded@@ -2123,13 +2443,39 @@ export function registerApiTriggers(: undefined;const offset =Number.isInteger(parsedOffset) && parsedOffset >= 0 ? parsedOffset : 0;- filtered.sort((a, b) =>- (b.updatedAt || b.createdAt || "").localeCompare(- a.updatedAt || a.createdAt || "",- ),- );- const sliced =- limit !== undefined ? filtered.slice(offset, offset + limit) : filtered;+ let sliced = filtered;+ let nextCursor: string | null = null;+ if (listQuery.q) {+ if (limit !== undefined || listQuery.cursor) {+ const paged = pageByOffset(+ filtered,+ listQuery.cursor ?? (offset > 0 ? encodeCursor({ offset }) : undefined),+ limit ?? LIST_PAGE_MAX,+ );+ sliced = paged.page;+ nextCursor = paged.nextCursor;+ }+ } else {+ sortByKeyDesc(filtered, memorySortKey, (m) => m.id);+ if (listQuery.cursor) {+ const paged = pageAfterCursor(+ filtered,+ memorySortKey,+ (m) => m.id,+ listQuery.cursor,+ limit ?? LIST_PAGE_MAX,+ );+ sliced = paged.page;+ nextCursor = paged.nextCursor;+ } else if (limit !== undefined) {+ sliced = filtered.slice(offset, offset + limit);+ const last = sliced[sliced.length - 1];+ nextCursor =+ last && offset + limit < filtered.length+ ? encodeCursor({ key: memorySortKey(last), id: last.id })+ : null;+ }+ }return {status_code: 200,@@ -2138,6 +2484,9 @@ export function registerApiTriggers(total: filtered.length,offset,limit: limit ?? null,+ nextCursor,+ ...(searchMode ? { search: { query: listQuery.q, mode: searchMode } } : {}),+ ...(facets ? { facets } : {}),},};},@@ -2197,46 +2546,13 @@ export function registerApiTriggers(config: { api_path: "/agentmemory/procedural", http_method: "GET" },});- const sharedConsolidationCounts = singleFlight(async () => {- const [summaries, memories, semantic, procedural, relations] = await Promise.all([- kv.list(KV.summaries).catch(() => []),- kv.list<import("../types.js").Memory>(KV.memories).catch(() => []),- kv.list(KV.semantic).catch(() => []),- kv.list(KV.procedural).catch(() => []),- kv.list(KV.relations).catch(() => []),- ]);- return {- summaries: summaries.length,- recurringPatterns: memories.filter(- (m) =>- m.isLatest &&- m.type === "pattern" &&- (m.sessionIds?.length ?? 0) >= PROCEDURAL_MIN_SESSIONS_PER_PATTERN,- ).length,- semanticFacts: semantic.length,- procedures: procedural.length,- relations: relations.length,- };- }, CONSOLIDATION_COUNTS_REUSE_MS);+ const consolidationStatus = createConsolidationStatusReader(kv);sdk.registerFunction("api::consolidation-status",async (req: HttpRequest): Promise<Response> => {const authErr = checkAuth(req, secret);if (authErr) return authErr;- const [counts, lastRun] = await Promise.all([- sharedConsolidationCounts(),- kv.get<ConsolidationRunRecord>(KV.config, CONSOLIDATION_LAST_RUN_KEY).catch(() => null),- ]);- return {- status_code: 200,- body: describeConsolidation({- now: new Date(),- enabled: isConsolidationEnabled(),- llmConfigured: detectLlmProviderKind() === "llm",- ...counts,- lastRun,- }),- };+ return { status_code: 200, body: await consolidationStatus() };},);sdk.registerTrigger({@@ -3354,6 +3670,10 @@ export function registerApiTriggers(const body = req.body as Record<string, unknown>;if (!body?.content || typeof body.content !== "string") return { status_code: 400, body: { error: "content is required" } };const tags = typeof body.tags === "string" ? (body.tags as string).split(",").map((t: string) => t.trim()).filter(Boolean) : Array.isArray(body.tags) ? body.tags : [];+ const sourceIds = normalizeLessonSourceIds(body.sourceIds);+ if (!sourceIds) {+ return { status_code: 400, body: { error: `sourceIds must be an array of at most ${LESSON_SOURCE_IDS_MAX} ids (session, memory, observation or crystal ids) without spaces` } };+ }const result = (await sdk.trigger({function_id: "mem::lesson-save",payload: {@@ -3363,6 +3683,7 @@ export function registerApiTriggers(project: typeof body.project === "string" ? body.project : undefined,tags,source: "manual",+ sourceIds,},})) as { action?: string };const statusCode = result?.action === "created" ? 201 : 200;diff --git a/src/triggers/events.ts b/src/triggers/events.tsindex 88ee2433..42c058c8 100644--- a/src/triggers/events.ts+++ b/src/triggers/events.ts@@ -13,6 +13,7 @@ import {isConsolidationEnabled,} from "../config.js";import { logger } from "../logger.js";+import { noteMemoryChange, noteSessionChange } from "../state/viewer-counts.js";// Global marker recording when corpus consolidation last ran, used to debounce// the per-turn session-stop fan-out.@@ -207,6 +208,7 @@ export function registerEventTriggers(sdk: IIIClient, kv: StateKV): void {old_value?: Session;new_value?: Session;}) => {+ noteSessionChange(payload.old_value, isStateDelete(payload) ? null : payload.new_value);if (isOutOfAgentScope(payload.new_value ?? payload.old_value)) {return { emitted: false };}@@ -249,23 +251,29 @@ export function registerEventTriggers(sdk: IIIClient, kv: StateKV): void {old_value?: Memory;new_value?: Memory;}) => {+ const deleted = isStateDelete(payload);+ noteMemoryChange(payload.old_value, deleted ? null : payload.new_value);if (isOutOfAgentScope(payload.new_value ?? payload.old_value)) {return { emitted: false };}- const deleted = isStateDelete(payload);const memory = payload.new_value;+ const created = !deleted && !payload.old_value;+ let type = "memory.updated";+ if (deleted) type = "memory.deleted";+ else if (created) type = "memory.created";await sendViewerEvent(sdk,- `memory-${deleted ? "deleted" : "updated"}-${payload.key}-${Date.now()}`,- deleted ? "memory.deleted" : "memory.updated",+ `${type.replace(".", "-")}-${payload.key}-${Date.now()}`,+ type,deleted- ? { memoryId: payload.key }+ ? { memoryId: payload.key, isLatest: payload.old_value?.isLatest }: {memoryId: payload.key,type: memory?.type,title: memory?.title,isLatest: memory?.isLatest,updatedAt: memory?.updatedAt,+ memory,},);return { emitted: true };@@ -278,15 +286,15 @@ export function registerEventTriggers(sdk: IIIClient, kv: StateKV): void {});}-function isStateDelete(payload: { event_type: string; new_value?: unknown }): boolean {+export function isStateDelete(payload: { event_type: string; new_value?: unknown }): boolean {return payload.event_type === "state:deleted" || !payload.new_value;}-function isOutOfAgentScope(record: { agentId?: string } | undefined): boolean {+export function isOutOfAgentScope(record: { agentId?: string } | undefined): boolean {return isAgentScopeIsolated() && record?.agentId !== getAgentId();}-async function sendViewerEvent(+export async function sendViewerEvent(sdk: IIIClient,id: string,type: string,diff --git a/src/triggers/viewer-streams.ts b/src/triggers/viewer-streams.tsnew file mode 100644index 00000000..c9595896--- /dev/null+++ b/src/triggers/viewer-streams.ts@@ -0,0 +1,355 @@+import type { IIIClient } from "iii-sdk";+import type { HttpRequest } from "@iii-dev/helpers/http";+import type { StateKV } from "../state/kv.js";+import { KV } from "../state/schema.js";+import type {+ Action,+ AuditEntry,+ Crystal,+ GraphSnapshot,+ HealthSnapshot,+ Lesson,+ ProceduralMemory,+ SemanticMemory,+} from "../types.js";+import type { MetricsStore } from "../eval/metrics-store.js";+import type { ResilientProvider } from "../providers/resilient.js";+import { VERSION } from "../version.js";+import { getLatestHealth } from "../health/monitor.js";+import { UNINDEXED_SCAN_REUSE_MS, markLlmFunctions } from "../functions/status.js";+import { CONSOLIDATION_LAST_RUN_KEY, type ConsolidationRunRecord } from "../functions/consolidation-status.js";+import {+ getEmbeddingProvider,+ getIndexPersistenceStatus,+ getPendingVectorBackfillCount,+ getSearchIndex,+ getVectorIndex,+} from "../functions/search.js";+import {+ getViewerCounts,+ noteGraphStats,+ noteRowChange,+ setViewerCountsEmitter,+ type CountedKind,+ type ViewerCounts,+} from "../state/viewer-counts.js";+import { detectLlmProviderKind, loadConfig } from "../config.js";+import { getBoundViewerPort, getViewerSkipped } from "../viewer/server.js";+import { buildConfigFlags, checkAuth, createConsolidationStatusReader, createStatusReporter } from "./api.js";+import { isStateDelete, sendViewerEvent } from "./events.js";++type Response = {+ status_code: number;+ headers?: Record<string, string>;+ body: unknown;+};++type StatePayload<T> = {+ key: string;+ event_type: string;+ old_value?: T | null;+ new_value?: T | null;+};++const GRAPH_SNAPSHOT_KEY = "current";+const HEALTH_LATEST_KEY = "latest";+const GRAPH_ITEMS_COALESCE_MS = 1000;+const HEALTH_TICK_SCAN_MAX_AGE_MS = 2 * 60_000;++export interface ViewerStreamDeps {+ secret?: string;+ metricsStore?: MetricsStore;+ provider?: ResilientProvider | { circuitState?: unknown };+}++function eventId(prefix: string, key: string): string {+ return `${prefix}-${key}-${Date.now()}`;+}++const GRAPH_DELTA_MAX_NODES = 200;+const GRAPH_DELTA_MAX_EDGES = 500;++type GraphSnapshotDelta = {+ full: boolean;+ nodes: GraphSnapshot["topNodes"];+ edges: GraphSnapshot["topEdges"];+ removedNodeIds: string[];+ removedEdgeIds: string[];+ degrees: Record<string, number>;+};++function rowsChanged<T extends { id: string }>(+ before: T[] | undefined,+ after: T[] | undefined,+): { upserted: T[]; removed: string[] } {+ const prev = new Map<string, string>();+ for (const row of before ?? []) prev.set(row.id, JSON.stringify(row));+ const seen = new Set<string>();+ const upserted: T[] = [];+ for (const row of after ?? []) {+ seen.add(row.id);+ if (prev.get(row.id) !== JSON.stringify(row)) upserted.push(row);+ }+ const removed = [...prev.keys()].filter((id) => !seen.has(id));+ return { upserted, removed };+}++export function graphSnapshotDelta(+ before: GraphSnapshot | null,+ after: GraphSnapshot | null,+): GraphSnapshotDelta | null {+ if (!after) return null;+ const nodes = rowsChanged(before?.topNodes, after.topNodes);+ const edges = rowsChanged(before?.topEdges, after.topEdges);+ if (nodes.upserted.length > GRAPH_DELTA_MAX_NODES || edges.upserted.length > GRAPH_DELTA_MAX_EDGES) return null;+ const degrees: Record<string, number> = {};+ const prevDegrees = before?.topDegrees ?? {};+ for (const [id, d] of Object.entries(after.topDegrees ?? {})) {+ if (prevDegrees[id] !== d) degrees[id] = d;+ }+ return {+ full: !before,+ nodes: nodes.upserted,+ edges: edges.upserted,+ removedNodeIds: nodes.removed,+ removedEdgeIds: edges.removed,+ degrees,+ };+}++function indexStats() {+ return {+ bm25Documents: getSearchIndex().size,+ vectorDocuments: getVectorIndex()?.size ?? 0,+ pendingVectorBackfill: getPendingVectorBackfillCount(),+ persistence: getIndexPersistenceStatus(),+ };+}++export function registerViewerStreamTriggers(+ sdk: IIIClient,+ kv: StateKV,+ deps: ViewerStreamDeps = {},+): void {+ const circuitBreaker = () =>+ deps.provider && "circuitState" in deps.provider ? deps.provider.circuitState ?? null : null;++ const statusReport = createStatusReporter(sdk, kv, { metricsStore: deps.metricsStore, provider: deps.provider });+ const consolidationStatus = createConsolidationStatusReader(kv);++ async function healthPayload(snapshot: HealthSnapshot | null, scanMaxAgeMs: number) {+ const [functionMetrics, counts, report] = await Promise.all([+ deps.metricsStore ? deps.metricsStore.getAll().catch(() => []) : Promise.resolve([]),+ getViewerCounts(kv),+ statusReport({ health: snapshot, scanMaxAgeMs }).catch(() => null),+ ]);+ return {+ status: snapshot?.status ?? "healthy",+ health: snapshot,+ circuitBreaker: circuitBreaker(),+ functionMetrics: markLlmFunctions(functionMetrics, detectLlmProviderKind()),+ counts,+ indexes: indexStats(),+ report,+ generatedAt: new Date().toISOString(),+ };+ }++ setViewerCountsEmitter((counts: ViewerCounts) => {+ void sendViewerEvent(sdk, eventId("counts", "all"), "counts.changed", { counts }).catch(() => {});+ });++ function registerRowStream<T extends { id?: string }>(options: {+ functionId: string;+ scope: string;+ entity: string;+ countKind?: CountedKind;+ }): void {+ sdk.registerFunction(options.functionId, async (payload: StatePayload<T>) => {+ const deleted = isStateDelete(payload);+ const row = deleted ? null : payload.new_value ?? null;+ if (options.countKind) noteRowChange(options.countKind, payload.old_value, row);+ let type = `${options.entity}.updated`;+ if (deleted) type = `${options.entity}.deleted`;+ else if (!payload.old_value) type = `${options.entity}.created`;+ await sendViewerEvent(sdk, eventId(options.entity, payload.key), type, {+ id: payload.key,+ [options.entity]: row,+ });+ return { emitted: true };+ });+ sdk.registerTrigger({+ type: "state",+ function_id: options.functionId,+ config: { scope: options.scope },+ });+ }++ registerRowStream<Lesson>({ functionId: "event::viewer::lesson-changed", scope: KV.lessons, entity: "lesson", countKind: "lessons" });+ registerRowStream<Action>({ functionId: "event::viewer::action-changed", scope: KV.actions, entity: "action", countKind: "actions" });+ registerRowStream<Crystal>({ functionId: "event::viewer::crystal-changed", scope: KV.crystals, entity: "crystal", countKind: "crystals" });+ registerRowStream<SemanticMemory>({ functionId: "event::viewer::semantic-changed", scope: KV.semantic, entity: "semantic", countKind: "semantic" });+ registerRowStream<ProceduralMemory>({ functionId: "event::viewer::procedural-changed", scope: KV.procedural, entity: "procedural", countKind: "procedural" });+ registerRowStream<AuditEntry>({ functionId: "event::viewer::audit-changed", scope: KV.audit, entity: "audit" });++ let lastGraphSnapshotEventAt = 0;+ sdk.registerFunction(+ "event::viewer::graph-snapshot-changed",+ async (payload: StatePayload<GraphSnapshot>) => {+ if (payload.key !== GRAPH_SNAPSHOT_KEY) return { emitted: false };+ const snapshot = isStateDelete(payload) ? null : payload.new_value ?? null;+ noteGraphStats(snapshot?.stats ?? { totalNodes: 0, totalEdges: 0, nodesByType: {}, edgesByType: {} });+ lastGraphSnapshotEventAt = Date.now();+ await sendViewerEvent(sdk, eventId("graph", "snapshot"), "graph.changed", {+ source: "snapshot",+ stats: snapshot?.stats ?? null,+ updatedAt: snapshot?.updatedAt ?? new Date().toISOString(),+ resetAt: snapshot?.resetAt ?? null,+ delta: graphSnapshotDelta(payload.old_value ?? null, snapshot),+ });+ return { emitted: true };+ },+ );+ sdk.registerTrigger({+ type: "state",+ function_id: "event::viewer::graph-snapshot-changed",+ config: { scope: KV.graphSnapshot },+ });++ const pendingGraphItems = { nodes: 0, edges: 0, since: 0 };+ let graphItemsTimer: ReturnType<typeof setTimeout> | null = null;+ function flushGraphItems(): void {+ graphItemsTimer = null;+ const nodesChanged = pendingGraphItems.nodes;+ const edgesChanged = pendingGraphItems.edges;+ const coveredBySnapshot = lastGraphSnapshotEventAt >= pendingGraphItems.since - GRAPH_ITEMS_COALESCE_MS;+ pendingGraphItems.nodes = 0;+ pendingGraphItems.edges = 0;+ if (nodesChanged === 0 && edgesChanged === 0) return;+ void sendViewerEvent(sdk, eventId("graph", "items"), "graph.changed", {+ source: "items",+ nodesChanged,+ edgesChanged,+ coveredBySnapshot,+ updatedAt: new Date().toISOString(),+ }).catch(() => {});+ }+ function noteGraphItem(kind: "nodes" | "edges"): void {+ pendingGraphItems[kind] += 1;+ if (graphItemsTimer) return;+ pendingGraphItems.since = Date.now();+ graphItemsTimer = setTimeout(flushGraphItems, GRAPH_ITEMS_COALESCE_MS);+ if (typeof graphItemsTimer === "object" && "unref" in graphItemsTimer) graphItemsTimer.unref();+ }+ for (const [kind, scope] of [["nodes", KV.graphNodes], ["edges", KV.graphEdges]] as const) {+ const functionId = `event::viewer::graph-${kind}-changed`;+ sdk.registerFunction(functionId, async () => {+ noteGraphItem(kind);+ return { emitted: true };+ });+ sdk.registerTrigger({ type: "state", function_id: functionId, config: { scope } });+ }++ sdk.registerFunction(+ "event::viewer::consolidation-changed",+ async (payload: StatePayload<ConsolidationRunRecord>) => {+ if (payload.key !== CONSOLIDATION_LAST_RUN_KEY || isStateDelete(payload)) {+ return { emitted: false };+ }+ const lastRun = payload.new_value ?? null;+ await sendViewerEvent(sdk, eventId("consolidation", "run"), "consolidation.run", {+ lastRun,+ status: await consolidationStatus({ lastRun }).catch(() => null),+ });+ return { emitted: true };+ },+ );+ sdk.registerTrigger({+ type: "state",+ function_id: "event::viewer::consolidation-changed",+ config: { scope: KV.config },+ });++ sdk.registerFunction(+ "event::viewer::health-changed",+ async (payload: StatePayload<HealthSnapshot>) => {+ if (payload.key !== HEALTH_LATEST_KEY || isStateDelete(payload)) {+ return { emitted: false };+ }+ await sendViewerEvent(+ sdk,+ eventId("health", "latest"),+ "health",+ await healthPayload(payload.new_value ?? null, HEALTH_TICK_SCAN_MAX_AGE_MS),+ );+ return { emitted: true };+ },+ );+ sdk.registerTrigger({+ type: "state",+ function_id: "event::viewer::health-changed",+ config: { scope: KV.health },+ });++ const { streamsPort, restPort } = loadConfig();++ sdk.registerFunction("api::viewer-snapshot",+ async (req: HttpRequest): Promise<Response> => {+ const authErr = checkAuth(req, deps.secret);+ if (authErr) return authErr;+ const [health, graph, lastRun] = await Promise.all([+ getLatestHealth(kv).catch(() => null),+ kv.get<GraphSnapshot>(KV.graphSnapshot, GRAPH_SNAPSHOT_KEY).catch(() => null),+ kv.get<ConsolidationRunRecord>(KV.config, CONSOLIDATION_LAST_RUN_KEY).catch(() => null),+ ]);+ return {+ status_code: 200,+ body: {+ version: VERSION,+ service: "agentmemory",+ viewerPort: getBoundViewerPort(),+ viewerSkipped: getViewerSkipped(),+ streamsPort,+ restPort,+ provider: detectLlmProviderKind(),+ embeddingProvider: getEmbeddingProvider()?.name ?? "none",+ flags: buildConfigFlags(),+ graph: graph+ ? { stats: graph.stats, updatedAt: graph.updatedAt, resetAt: graph.resetAt ?? null }+ : null,+ consolidation: {+ lastRun: lastRun ?? null,+ status: await consolidationStatus({ lastRun: lastRun ?? null }).catch(() => null),+ },+ ...(await healthPayload(health ?? null, UNINDEXED_SCAN_REUSE_MS)),+ },+ };+ },+ );+ sdk.registerTrigger({+ type: "http",+ function_id: "api::viewer-snapshot",+ config: {+ api_path: "/agentmemory/viewer/snapshot",+ http_method: "GET",+ middleware_function_ids: ["middleware::api-auth"],+ },+ });++ sdk.registerFunction("api::counts",+ async (req: HttpRequest): Promise<Response> => {+ const authErr = checkAuth(req, deps.secret);+ if (authErr) return authErr;+ return { status_code: 200, body: { counts: await getViewerCounts(kv) } };+ },+ );+ sdk.registerTrigger({+ type: "http",+ function_id: "api::counts",+ config: {+ api_path: "/agentmemory/counts",+ http_method: "GET",+ middleware_function_ids: ["middleware::api-auth"],+ },+ });+}diff --git a/src/types.ts b/src/types.tsindex 7b3a312a..dff2bc59 100644--- a/src/types.ts+++ b/src/types.ts@@ -483,6 +483,7 @@ export interface GraphQueryResult {// empty-body / nodeType-only branch on large corpora where the// unbounded enumeration would exceed the iii invocation timeout.fromSnapshot?: boolean;+ degrees?: Record<string, number>;// #814: when the snapshot is stale or absent and the live fallback// also failed, expose an explanatory note so the viewer can surface// an actionable banner instead of a blank graph.diff --git a/src/viewer/index.html b/src/viewer/index.htmlindex ea63a973..39a97b6f 100644--- a/src/viewer/index.html+++ b/src/viewer/index.html@@ -64,19 +64,13 @@--accent: #f2555a;--accent-light: #ff7a70;--cream: #2a2520;- }- html[data-theme="dark"] .graph-tooltip {- background: rgba(30,30,35,0.92);- border-color: rgba(255,255,255,0.1);- box-shadow: 0 8px 32px rgba(0,0,0,0.4);- }- html[data-theme="dark"] .graph-controls button {- background: rgba(30,30,35,0.92);- border-color: rgba(255,255,255,0.1);- }- html[data-theme="dark"] .graph-controls button:hover {- background: var(--ink);- color: var(--bg);+ --green: #5cc08f;+ --blue: #7fa9e3;+ --yellow: #dcae45;+ --red: #f2555a;+ --purple: #ae92dc;+ --orange: #e8905a;+ --cyan: #4ec0d2;}* { margin: 0; padding: 0; box-sizing: border-box; }#bg-dither {@@ -88,7 +82,7 @@pointer-events: none;opacity: 0.5;}- .app-header, .tab-bar, .view, .flags-banner, footer, .app-footer { position: relative; z-index: 1; }+ .app-header, .tab-bar, .views, .view, .flags-panel, .offline-banner, footer, .app-footer { position: relative; z-index: 1; }body {font-family: var(--font-body);background: var(--bg);@@ -105,9 +99,10 @@::-webkit-scrollbar-thumb:hover { background: var(--ink-muted); }.app-header {- padding: 10px 24px;+ padding: 10px 24px 0;border-bottom: 4px solid var(--border-heavy);display: flex;+ flex-wrap: wrap;align-items: center;justify-content: space-between;background: var(--bg);@@ -115,6 +110,11 @@position: relative;z-index: 3;}+ .app-header > .tab-bar { flex: 1 1 100%; order: 10; margin: 8px -24px 0; border-bottom: none; border-top: 1px solid var(--border-light); }+ @media (max-width: 720px) {+ .app-header { padding-bottom: 8px; }+ .app-header > .tab-bar { margin: 0; border-top: none; }+ }.app-header .brand {display: flex;align-items: baseline;@@ -147,9 +147,8 @@gap: 12px;}@media (max-width: 720px) {- .app-header { flex-wrap: wrap; row-gap: 6px; padding: 10px 16px; }+ .app-header { flex-wrap: wrap; row-gap: 6px; padding: 8px 16px; }.app-header .dateline { display: none; }- .view { overflow-x: auto; }}.ws-status {font-size: 10px;@@ -175,12 +174,19 @@0%, 100% { opacity: 1; }50% { opacity: 0.35; }}- .ws-status.disconnected { border-color: var(--ink-faint); color: var(--ink-faint); }- .ws-status.disconnected::before { background: var(--ink-faint); }+ .ws-status.disconnected, .ws-status.connecting { border-color: var(--ink-faint); color: var(--ink-faint); }+ .ws-status.disconnected::before, .ws-status.connecting::before { background: var(--ink-faint); }+ .ws-status.reconnecting { border-color: var(--yellow); color: var(--yellow); }+ .ws-status.reconnecting::before { background: var(--yellow); }+ .ws-status.offline { border-color: var(--accent); color: var(--accent); }+ .ws-status.offline::before { background: var(--accent); }+ .ws-status.stale-health { border-color: var(--yellow); color: var(--yellow); }+ .ws-status.stale-health::before { background: var(--yellow); }.tab-bar {display: flex;- height: 48px;+ align-items: stretch;+ height: 44px;flex-shrink: 0;border-bottom: 1px solid var(--border-light);background: var(--bg);@@ -188,30 +194,82 @@flex: 0 0 auto;position: relative;z-index: 2;+ padding: 0 12px;+ scrollbar-width: none;+ }+ .tab-bar::-webkit-scrollbar { display: none; }+ .tab-group { display: flex; align-items: stretch; border-left: 1px solid var(--border-light); padding-left: 6px; margin-left: 6px; }+ .tab-group-label {+ align-self: center;+ font-family: var(--font-ui);+ font-size: 8px;+ font-weight: 700;+ letter-spacing: 0.18em;+ text-transform: uppercase;+ color: var(--ink-faint);+ padding: 0 6px 0 4px;+ white-space: nowrap;}.tab-bar button {background: none;border: none;color: var(--ink-muted);- padding: 10px 16px;+ padding: 8px 12px;font-size: 11px;cursor: pointer;border-bottom: 2px solid transparent;white-space: nowrap;font-family: var(--font-ui);text-transform: uppercase;- letter-spacing: 0.12em;+ letter-spacing: 0.1em;font-weight: 600;transition: color 0.15s, border-color 0.15s;}.tab-bar button:hover { color: var(--ink); }+ .tab-bar button:focus-visible { outline: 2px solid var(--accent); outline-offset: -4px; }.tab-bar button.active {color: var(--ink);border-bottom-color: var(--accent);}-- .view { display: none; flex: 1 1 auto; min-height: 0; overflow-y: auto; padding: 24px; }+ .tab-bar button .tab-count {+ font-family: var(--font-mono);+ font-size: 9px;+ letter-spacing: 0;+ color: var(--ink-faint);+ margin-left: 5px;+ font-weight: 500;+ }+ .nav-toggle { display: none; }+ @media (max-width: 720px) {+ .nav-toggle { display: inline-flex; align-items: center; gap: 6px; order: 3; flex: 1 1 100%; justify-content: space-between; }+ .tab-bar {+ display: none;+ position: absolute;+ top: 100%;+ left: 0;+ right: 0;+ height: auto;+ max-height: 70vh;+ overflow-y: auto;+ flex-direction: column;+ padding: 6px 12px 12px;+ border-bottom: 2px solid var(--border);+ box-shadow: 0 12px 24px rgba(0,0,0,0.12);+ z-index: 20;+ }+ .tab-bar.open { display: flex; }+ .tab-group { flex-direction: column; border-left: none; margin-left: 0; padding-left: 0; border-top: 1px solid var(--border-light); padding-top: 4px; margin-top: 4px; }+ .tab-group-label { align-self: flex-start; padding: 6px 12px 2px; }+ .tab-bar button { text-align: left; border-bottom: none; border-left: 2px solid transparent; padding: 9px 12px; }+ .tab-bar button.active { border-left-color: var(--accent); background: var(--bg-alt); }+ .app-shell-nav { position: relative; }+ }++ .views { flex: 1 1 auto; min-height: 0; display: flex; flex-direction: column; }+ .view { display: none; flex: 1 1 auto; min-height: 0; overflow-y: auto; padding: 20px 24px; }.view.active { display: block; animation: view-in 160ms ease-out; }+ #view-graph.active { display: flex; flex-direction: column; padding: 0; overflow: hidden; }+ body.is-stale .view { filter: saturate(0.6); }@keyframes view-in {from { opacity: 0; transform: translateY(4px); }to { opacity: 1; transform: translateY(0); }@@ -230,20 +288,64 @@.layer-detail { font-size: 12px; color: var(--ink-faint); margin-top: 4px; line-height: 1.5; }.layer-preview { margin: 6px 0 0; padding-left: 16px; font-size: 12px; color: var(--ink-muted); }.layer-preview li { margin-bottom: 2px; }+ .verdict { display: flex; gap: 14px; align-items: flex-start; }+ .verdict-badge { font-family: var(--font-ui); font-size: 12px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.08em; padding: 4px 10px; border: 2px solid currentColor; flex-shrink: 0; }+ .verdict-badge.ok { color: var(--green); } .verdict-badge.info { color: var(--blue); } .verdict-badge.warn { color: var(--yellow); } .verdict-badge.error { color: var(--accent); } .verdict-badge.unknown { color: var(--ink-faint); }+ .verdict-text { font-family: var(--font-display); font-size: 17px; line-height: 1.4; color: var(--ink); }+ .verdict-meta { font-family: var(--font-ui); font-size: 11px; color: var(--ink-faint); margin-top: 4px; }+ .hstale { font-family: var(--font-ui); font-size: 12px; color: var(--ink); padding: 8px 12px; border-left: 3px solid var(--yellow); background: var(--bg-subtle); margin: 12px 0 0; line-height: 1.5; }+ .hstale.offline { border-left-color: var(--accent); }+ .problem { display: grid; grid-template-columns: 56px 1fr; gap: 10px; padding: 10px 0; border-bottom: 1px solid var(--border-light); }+ .problem:last-child { border-bottom: none; }+ .problem .pm { font-size: 13px; color: var(--ink); line-height: 1.5; }+ .problem .pf { font-family: var(--font-ui); font-size: 12px; color: var(--ink-muted); margin-top: 3px; line-height: 1.5; }+ .problem .pf::before { content: 'Fix: '; font-weight: 700; color: var(--ink-secondary); }+ .hgrid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 16px; margin-top: 16px; }+ .hgrid .card { margin: 0; min-width: 0; }+ .hnote { font-family: var(--font-ui); font-size: 11px; color: var(--ink-faint); line-height: 1.5; margin-top: 2px; }+ .hbar { height: 6px; background: var(--bg-inset); margin-top: 5px; position: relative; max-width: 260px; }+ .hbar > span { position: absolute; left: 0; top: 0; bottom: 0; background: var(--green); }+ .hbar.warn > span { background: var(--yellow); } .hbar.bad > span { background: var(--accent); }+ .flag-row { padding: 9px 0; border-bottom: 1px solid var(--bg-inset); }+ .flag-row:last-child { border-bottom: none; }+ .flag-head { display: flex; gap: 8px; align-items: baseline; flex-wrap: wrap; font-size: 13px; }+ .flag-head code, .env-chip { font-family: var(--font-mono); font-size: 11px; color: var(--ink-secondary); background: var(--bg-inset); padding: 1px 5px; }+ .flag-how { font-family: var(--font-ui); font-size: 12px; color: var(--ink-muted); margin-top: 3px; line-height: 1.5; }+ .cflow { display: grid; grid-template-columns: repeat(5, minmax(0, 1fr)); gap: 0; margin: 12px 0 4px; border: 1px solid var(--border-light); }+ .cstep { padding: 10px 12px; border-right: 1px solid var(--border-light); position: relative; min-width: 0; }+ .cstep:last-child { border-right: none; }+ .cstep-n { font-family: var(--font-ui); font-size: 10px; font-weight: 700; letter-spacing: 0.1em; text-transform: uppercase; color: var(--ink-faint); }+ .cstep-t { font-family: var(--font-display); font-weight: 700; font-size: 14px; color: var(--ink); margin: 2px 0 4px; }+ .cstep-d { font-family: var(--font-ui); font-size: 11px; color: var(--ink-muted); line-height: 1.5; }+ .cstep-c { font-family: var(--font-mono); font-size: 12px; color: var(--ink); margin-top: 6px; }+ .ccols { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 20px; margin-top: 14px; }+ .ccols h4 { font-family: var(--font-ui); font-size: 10px; font-weight: 700; letter-spacing: 0.1em; text-transform: uppercase; color: var(--ink-muted); margin-bottom: 6px; }+ .ckv { display: flex; gap: 10px; font-size: 12px; padding: 4px 0; border-bottom: 1px solid var(--bg-inset); font-family: var(--font-ui); }+ .ckv > span:first-child { color: var(--ink-muted); width: 150px; flex-shrink: 0; }+ .ckv > span:last-child { color: var(--ink); min-width: 0; overflow-wrap: anywhere; }+ @media (max-width: 900px) {+ .hgrid, .ccols { grid-template-columns: 1fr; }+ .cflow { grid-template-columns: 1fr; }+ .cstep { border-right: none; border-bottom: 1px solid var(--border-light); }+ .cstep:last-child { border-bottom: none; }+ .verdict { flex-direction: column; gap: 8px; }+ .ckv > span:first-child { width: 120px; }+ }.stats-grid {- display: grid;- grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));- gap: 0;- margin-bottom: 24px;+ display: flex;+ flex-wrap: wrap;+ gap: 1px;+ margin-bottom: 16px;border: 1px solid var(--border);+ background: var(--border-light);}.stat-card {background: var(--bg);- padding: 16px 20px;- border-right: 1px solid var(--border-light);- border-bottom: 1px solid var(--border-light);+ padding: 12px 16px;+ flex: 1 1 150px;+ min-width: 0;}- .stat-card:last-child { border-right: none; }+ .stat-card .label .help { margin-left: 4px; }.stat-card[data-action] {cursor: pointer;transition: background 0.15s ease-out;@@ -410,73 +512,111 @@.btn-primary { background: var(--ink); color: var(--bg); border-color: var(--ink); }.btn-primary:hover { background: var(--ink-secondary); box-shadow: 3px 3px 0px 0px var(--ink-muted); }- .graph-container {- display: flex;- height: calc(100vh - 178px);- min-height: 460px;- margin: -24px;- border-top: 1px solid var(--border-light);- }- .graph-canvas-wrap {- flex: 1;- position: relative;- overflow: hidden;- background: var(--bg);- }- .graph-canvas-wrap canvas {- display: block;- width: 100%;- height: 100%;- }- .graph-sidebar {- width: 260px;- border-left: 2px solid var(--border);- padding: 20px;- overflow-y: auto;- background: var(--bg);- }- .graph-sidebar h3 {- font-size: 9px;- color: var(--ink);- text-transform: uppercase;- letter-spacing: 0.15em;- margin-bottom: 12px;- font-family: var(--font-ui);- font-weight: 600;- padding-bottom: 6px;- border-bottom: 1px solid var(--border-light);- }- .filter-item {- display: flex;- align-items: center;- gap: 6px;- padding: 4px 0;- font-size: 12px;- cursor: pointer;- font-family: var(--font-ui);- }- .filter-item input[type="checkbox"] {- accent-color: var(--ink);- }- .filter-dot {- width: 8px;- height: 8px;- display: inline-block;- }- .graph-info {- margin-top: 16px;- padding-top: 16px;- border-top: 1px solid var(--border-light);+ .graph-page { display: flex; flex-direction: column; flex: 1 1 auto; min-height: 0; height: 100%; }+ .graph-toolbar { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; padding: 10px 16px; border-bottom: 1px solid var(--border-light); background: var(--bg); position: relative; z-index: 6; }+ .graph-search-wrap { position: relative; flex: 1 1 260px; max-width: 420px; min-width: 0; }+ .graph-search { width: 100%; background: var(--bg); color: var(--ink); border: 1px solid var(--border); padding: 7px 10px; font-size: 13px; font-family: var(--font-ui); outline: none; }+ .graph-search:focus { box-shadow: 2px 2px 0 0 var(--border); }+ .graph-search-results { position: absolute; top: calc(100% + 4px); left: 0; right: 0; background: var(--bg); border: 1px solid var(--border); box-shadow: 4px 4px 0 0 var(--border-light); z-index: 20; max-height: 320px; overflow-y: auto; }+ .gs-hit { display: flex; align-items: center; gap: 8px; width: 100%; padding: 7px 10px; border: none; border-bottom: 1px solid var(--border-light); background: none; color: var(--ink); font-family: var(--font-ui); font-size: 12px; text-align: left; cursor: pointer; }+ .gs-hit:hover, .gs-hit.active, .gs-hit:focus-visible { background: var(--bg-alt); outline: none; }+ .gs-hit .gs-name { flex: 1 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+ .gs-hit .gs-meta { color: var(--ink-faint); font-family: var(--font-mono); font-size: 10px; white-space: nowrap; }+ .gs-remote { color: var(--blue); font-weight: 600; }+ .gs-empty { padding: 8px 10px; font-family: var(--font-ui); font-size: 12px; color: var(--ink-muted); }+ .graph-toolbar select { background: var(--bg); color: var(--ink); border: 1px solid var(--border); padding: 7px 8px; font-family: var(--font-ui); font-size: 12px; max-width: 220px; }+ .graph-summary { font-family: var(--font-ui); font-size: 12px; color: var(--ink-muted); margin-left: auto; display: inline-flex; align-items: center; gap: 4px; flex-wrap: wrap; }+ .graph-build { padding: 6px 12px; font-size: 10px; }+ .graph-body { display: grid; grid-template-columns: minmax(0, 1fr) 360px; flex: 1 1 auto; min-height: 0; }+ .graph-stage { position: relative; overflow: hidden; background: var(--bg); min-height: 0; min-width: 0; }+ .graph-stage canvas { display: block; width: 100%; height: 100%; touch-action: none; cursor: grab; outline: none; }+ .graph-stage canvas:focus-visible { box-shadow: inset 0 0 0 2px var(--accent); }+ .graph-zoom { position: absolute; top: 12px; right: 12px; display: flex; flex-direction: column; gap: 4px; z-index: 5; }+ .graph-zoom button { width: 34px; height: 30px; background: var(--bg); color: var(--ink); border: 1px solid var(--border); font-family: var(--font-ui); font-size: 15px; font-weight: 600; cursor: pointer; line-height: 1; }+ .graph-zoom button:last-child { font-size: 10px; text-transform: uppercase; letter-spacing: 0.06em; }+ .graph-zoom button:hover, .graph-zoom button:focus-visible { background: var(--ink); color: var(--bg); outline: none; }+ .graph-stage-msg { position: absolute; inset: 0; overflow-y: auto; padding: 24px; background: var(--bg); z-index: 7; }+ .graph-stage-msg .empty-state { max-width: 760px; margin: 0 auto; }+ .graph-msg-actions { max-width: 760px; margin: 12px auto 0; display: flex; gap: 8px; }+ .graph-loading { max-width: 520px; margin: 40px auto; }+ .graph-page.is-empty .graph-body { grid-template-columns: minmax(0, 1fr); }+ .graph-page.is-empty .graph-side, .graph-page.is-empty .graph-zoom { display: none; }+ .graph-side { border-left: 2px solid var(--border); overflow-y: auto; background: var(--bg); min-width: 0; }+ .graph-side .detail-panel { margin: 0; border: none; border-bottom: 2px solid var(--border); box-shadow: none; }+ .detail-panel h3.gd-name { font-family: var(--font-display); font-size: 17px; line-height: 1.3; color: var(--ink); overflow-wrap: anywhere; margin: 2px 0 4px; outline: none; text-transform: none; letter-spacing: 0; padding: 0; border: none; }+ .gd-typetext { font-family: var(--font-ui); font-size: 12px; color: var(--ink-muted); }+ .gd-type { text-transform: lowercase; }+ .gd-count { margin-left: auto; font-weight: 500; letter-spacing: 0.04em; text-transform: none; color: var(--ink-faint); font-size: 10px; }+ .gd-rels, .gd-obs, .go-top, .go-legend { list-style: none; margin: 0; padding: 0; font-family: var(--font-ui); font-size: 12px; }+ .gd-rels li { display: grid; grid-template-columns: 14px 92px minmax(0, 1fr); gap: 6px; align-items: center; padding: 3px 0; border-bottom: 1px dotted var(--border-light); }+ .gd-dir { color: var(--ink-faint); font-family: var(--font-mono); }+ .gd-etype { font-family: var(--font-mono); font-size: 10px; color: var(--ink-muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }+ .gd-neighbor { display: flex; align-items: center; gap: 6px; min-width: 0; width: 100%; background: none; border: none; padding: 2px 0; color: var(--blue); font-family: var(--font-ui); font-size: 12px; text-align: left; cursor: pointer; }+ .gd-neighbor span { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+ .gd-neighbor:hover span, .gd-neighbor:focus-visible span { text-decoration: underline; }+ .gd-neighbor:focus-visible { outline: 1px solid var(--ink); outline-offset: 1px; }+ .gd-neighbor[aria-current="true"] { font-weight: 700; color: var(--ink); }+ .gd-missing { color: var(--ink-faint); font-style: italic; }+ .gd-sub { font-family: var(--font-ui); font-size: 10px; text-transform: uppercase; letter-spacing: 0.08em; font-weight: 600; color: var(--ink-faint); margin: 10px 0 4px; display: flex; gap: 6px; }+ .gd-obs li { display: flex; align-items: baseline; gap: 6px; padding: 3px 0; border-bottom: 1px dotted var(--border-light); min-width: 0; }+ .gd-obs li .entity-link { flex: 0 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+ .gd-obs-meta { color: var(--ink-faint); font-size: 11px; white-space: nowrap; margin-left: auto; }+ .gd-raw { margin-top: 8px; padding: 10px; background: var(--bg); border: 1px solid var(--border); font-size: 11px; line-height: 1.5; overflow-x: auto; white-space: pre-wrap; overflow-wrap: anywhere; }+ .linkish { background: none; border: none; padding: 0; color: var(--blue); font: inherit; text-decoration: underline; cursor: pointer; }+ .go { padding: 16px 18px 20px; }+ .go-intro { font-family: var(--font-ui); font-size: 12px; line-height: 1.5; color: var(--ink-muted); }+ .go-intro strong { color: var(--ink); }+ .go-stats { display: grid; grid-template-columns: repeat(3, 1fr); border: 1px solid var(--border-light); margin: 12px 0; }+ .go-stats > div { padding: 8px 10px; border-left: 1px solid var(--border-light); }+ .go-stats > div:first-child { border-left: none; }+ .go-stats b { display: block; font-family: var(--font-display); font-size: 22px; line-height: 1.1; color: var(--ink); }+ .go-stats span { font-family: var(--font-ui); font-size: 10px; text-transform: uppercase; letter-spacing: 0.08em; color: var(--ink-faint); display: inline-flex; align-items: center; gap: 4px; }+ .go-sparse .cmd-block { margin-top: 8px; }+ .go-legend li { padding: 2px 0; }+ .go-type { display: flex; align-items: center; gap: 8px; width: 100%; background: none; border: 1px solid transparent; padding: 4px 6px; color: var(--ink); font-family: var(--font-ui); font-size: 12px; text-align: left; cursor: pointer; }+ .go-type.static { cursor: default; padding-left: 0; }+ .go-edges .go-type { color: var(--ink-secondary); }+ button.go-type:hover, button.go-type:focus-visible { border-color: var(--border); outline: none; }+ .go-type.off { color: var(--ink-faint); text-decoration: line-through; }+ .go-type.off .g-shape { opacity: 0.35; }+ .go-name { flex: 1 1 auto; font-weight: 600; }+ .go-num { font-family: var(--font-mono); font-size: 11px; color: var(--ink-muted); margin-left: auto; }+ .go-desc { font-family: var(--font-ui); font-size: 11px; color: var(--ink-faint); padding: 0 6px 4px 28px; line-height: 1.4; }+ .go-edges .go-desc { padding-left: 36px; }+ .go-top li { padding: 1px 0; }+ .go-top .gd-neighbor { color: var(--ink); }+ .go-top .gd-neighbor span:nth-child(2) { flex: 1 1 auto; }+ .go-live { margin-top: 14px; font-family: var(--font-ui); font-size: 11px; color: var(--ink-faint); display: flex; align-items: center; gap: 4px; flex-wrap: wrap; }+ .g-shape, .g-edge { flex: 0 0 auto; display: inline-block; vertical-align: middle; }+ .graph-tooltip { position: absolute; background: var(--bg); border: 1px solid var(--border); box-shadow: 3px 3px 0 0 var(--border-light); padding: 8px 10px; font-family: var(--font-ui); font-size: 11px; pointer-events: none; z-index: 8; max-width: 240px; display: none; }+ .graph-tooltip.visible { display: block; }+ .graph-tooltip .tt-name { font-weight: 700; color: var(--ink); font-size: 12px; overflow-wrap: anywhere; margin-bottom: 3px; }+ .graph-tooltip .tt-meta { color: var(--ink-muted); display: flex; align-items: center; gap: 5px; }+ .graph-tooltip .tt-hint { color: var(--ink-faint); margin-top: 3px; font-size: 10px; }+ @media (max-width: 1100px) {+ .graph-body { grid-template-columns: minmax(0, 1fr) 300px; }}- .graph-info .info-row {- display: flex;- justify-content: space-between;- font-size: 12px;- padding: 3px 0;- font-family: var(--font-ui);+ @media (max-width: 720px) {+ #view-graph.active { overflow-y: auto; }+ .graph-page { height: auto; flex: 0 0 auto; }+ .graph-toolbar { padding: 10px 16px; }+ .graph-body { flex: 0 0 auto; }+ #graph-detail, #graph-overview { flex: 0 0 auto; }+ .graph-side .gd > .mem-detail-head { position: sticky; top: 0; margin: -14px -14px 10px; padding: 10px 14px; background: var(--bg); z-index: 2; border-bottom: 1px solid var(--border-light); }+ .graph-search-wrap { flex: 1 1 100%; max-width: none; }+ .graph-toolbar select { flex: 1 1 auto; max-width: none; }+ .graph-summary { margin-left: 0; flex: 1 1 100%; order: 3; }+ .graph-body { display: flex; flex-direction: column; }+ .graph-stage { height: 62vh; min-height: 320px; flex: 0 0 auto; }+ .graph-page.is-empty .graph-stage { height: auto; min-height: 0; }+ .graph-page.is-empty .graph-stage canvas { display: none; }+ .graph-stage-msg { position: static; padding: 16px; }+ .graph-side { border-left: none; border-top: 2px solid var(--border); overflow: visible; display: contents; }+ #graph-detail:not(:empty) { position: sticky; bottom: 0; z-index: 9; max-height: 45vh; overflow-y: auto; border-top: 2px solid var(--border); background: var(--bg); box-shadow: 0 -8px 24px rgba(0,0,0,0.12); order: 2; }+ #graph-overview { order: 3; border-top: 2px solid var(--border); }+ .go { padding: 14px 16px 20px; }+ .gd-rels li { grid-template-columns: 14px 78px minmax(0, 1fr); }}- .graph-info .info-row .info-label { color: var(--ink-muted); }- .graph-info .info-row .info-value { color: var(--ink); font-weight: 600; font-family: var(--font-mono); }.obs-card {background: var(--bg);@@ -569,17 +709,87 @@/* Two-pane sessions: list left, detail pinned right on wide screens.The detail panel previously rendered below the full list — selectinga session on any real corpus put the response off-screen. */- .sessions-layout {- display: grid;- grid-template-columns: minmax(300px, 400px) minmax(0, 1fr);- gap: 20px;- align-items: start;- }- .sessions-layout #session-detail { position: sticky; top: 0; min-width: 0; }+ .sessions-layout { display: grid; grid-template-columns: minmax(0, 1fr); gap: 20px; align-items: start; }+ .sessions-layout.has-detail { grid-template-columns: minmax(300px, 380px) minmax(0, 1fr); }+ .sessions-layout #session-detail { min-width: 0; }+ .sessions-layout.has-detail #session-detail { position: sticky; top: 0; max-height: calc(100vh - 150px); overflow-y: auto; }.sessions-layout #session-detail .detail-panel { margin-top: 0; }@media (max-width: 1100px) {- .sessions-layout { grid-template-columns: 1fr; }- .sessions-layout #session-detail { position: static; }+ .sessions-layout.has-detail { grid-template-columns: minmax(0, 1fr); }+ .sessions-layout.has-detail #session-detail { position: static; max-height: none; overflow: visible; order: -1; }+ }+ .memories-layout { display: grid; grid-template-columns: minmax(0, 1fr); gap: 20px; align-items: start; }+ .memories-layout.has-detail { grid-template-columns: minmax(0, 1fr) minmax(360px, 460px); }+ #memory-detail { min-width: 0; }+ .memories-layout.has-detail #memory-detail { position: sticky; top: 0; max-height: calc(100vh - 150px); overflow-y: auto; }+ #memory-detail:empty { display: none; }+ @media (max-width: 1100px) {+ .memories-layout.has-detail { grid-template-columns: minmax(0, 1fr); }+ .memories-layout.has-detail #memory-detail { position: static; order: -1; max-height: none; overflow: visible; }+ }+ .mem-table td.mem-check, .mem-table th.mem-check { width: 28px; padding-right: 0; }+ .mem-table input[type="checkbox"] { width: 15px; height: 15px; accent-color: var(--ink); cursor: pointer; margin-top: 2px; }+ .memory-row.selected td { background: var(--bg-alt); }+ .memory-row.selected td:first-child { box-shadow: inset 3px 0 0 var(--accent); }+ .memory-row.checked td { background: var(--bg-subtle); }+ .mem-head { color: var(--ink); font-weight: 600; line-height: 1.4; }+ .mem-excerpt { font-size: 12px; color: var(--ink-muted); margin-top: 2px; line-height: 1.4; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 100%; }+ .mem-chips { margin-top: 5px; display: flex; gap: 4px; flex-wrap: wrap; align-items: center; font-family: var(--font-ui); font-size: 11px; color: var(--ink-faint); }+ .mem-chip { font-family: var(--font-ui); font-size: 10px; line-height: 16px; padding: 0 6px; border: 1px solid var(--border-light); background: var(--bg-subtle); color: var(--ink-secondary); cursor: pointer; max-width: 180px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+ .mem-chip:hover, .mem-chip:focus-visible { border-color: var(--ink); color: var(--ink); outline: none; }+ .mem-chip.on { border-color: var(--ink); background: var(--ink); color: var(--bg); }+ .ver-badge { font-family: var(--font-mono); font-size: 10px; line-height: 16px; padding: 0 5px; border: 1px solid var(--purple); color: var(--purple); white-space: nowrap; }+ .strength-num { font-size: 10px; color: var(--ink-faint); font-family: var(--font-mono); }+ .mob-only { display: none; }+ .bulk-bar { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; padding: 8px 12px; margin-bottom: 10px; border: 1px solid var(--border); background: var(--bg-alt); font-family: var(--font-ui); font-size: 12px; color: var(--ink); position: sticky; top: 0; z-index: 5; }+ .bulk-bar .bulk-count { font-weight: 700; margin-right: auto; }+ .bulk-bar .btn { padding: 4px 10px; font-size: 10px; }+ .mem-filter-note { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; margin: -10px 0 10px; font-family: var(--font-ui); font-size: 11px; color: var(--ink-faint); }+ .mem-filter-note .btn { padding: 2px 8px; font-size: 9px; }+ .mem-detail { margin-top: 0; padding: 18px 20px; }+ .mem-detail-head { display: flex; gap: 6px; align-items: center; flex-wrap: wrap; margin-bottom: 10px; font-family: var(--font-ui); font-size: 11px; color: var(--ink-muted); }+ .mem-detail-head .icon-close { margin-left: auto; }+ .mem-detail-content { font-size: 14px; color: var(--ink); white-space: pre-wrap; overflow-wrap: anywhere; line-height: 1.55; margin-bottom: 12px; font-family: var(--font-body); }+ .mem-section { border-top: 1px solid var(--border-light); padding-top: 10px; margin-top: 12px; }+ .mem-section-title { font-family: var(--font-ui); font-size: 9px; letter-spacing: 0.14em; text-transform: uppercase; color: var(--ink-faint); font-weight: 700; margin-bottom: 6px; display: flex; align-items: center; gap: 6px; }+ .mem-meta { display: grid; grid-template-columns: max-content minmax(0, 1fr); gap: 4px 12px; font-size: 12px; font-family: var(--font-ui); color: var(--ink-secondary); align-items: baseline; }+ .mem-meta dt { color: var(--ink-faint); font-size: 10px; text-transform: uppercase; letter-spacing: 0.08em; font-weight: 600; white-space: nowrap; }+ .mem-meta dd { min-width: 0; overflow-wrap: anywhere; }+ .mem-actions { display: flex; gap: 6px; flex-wrap: wrap; align-items: center; margin-top: 12px; }+ .mem-actions .btn { padding: 4px 10px; font-size: 10px; }+ .mem-actions .btn-danger { margin-left: auto; }+ .ver-list { list-style: none; margin: 0; padding: 0; font-family: var(--font-ui); font-size: 12px; }+ .ver-item { display: grid; grid-template-columns: 40px minmax(0, 1fr) auto; gap: 8px; align-items: baseline; padding: 5px 6px; border-left: 2px solid var(--border-light); }+ .ver-item.current { border-left-color: var(--accent); background: var(--bg-alt); }+ .ver-item .ver-text { color: var(--ink-secondary); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }+ .ver-item a { color: inherit; text-decoration: none; display: block; min-width: 0; overflow: hidden; }+ .ver-item .ver-text { display: block; }+ .ver-item .ver-tools { white-space: nowrap; }+ .ver-item a:hover .ver-text, .ver-item a:focus-visible .ver-text { color: var(--accent); }+ .ver-item .ver-tools { display: flex; gap: 6px; align-items: baseline; }+ .ver-item button.linkish { background: none; border: none; padding: 0; font-family: var(--font-ui); font-size: 10px; text-transform: uppercase; letter-spacing: 0.08em; font-weight: 700; color: var(--blue); cursor: pointer; }+ .ver-item button.linkish[aria-pressed="true"] { color: var(--accent); }+ .mem-diff { margin-top: 8px; padding: 10px 12px; border: 1px solid var(--border-light); background: var(--bg); font-size: 13px; line-height: 1.6; white-space: pre-wrap; overflow-wrap: anywhere; font-family: var(--font-body); color: var(--ink-secondary); }+ .mem-diff del { color: var(--red); text-decoration: line-through; background: rgba(204, 0, 0, 0.08); }+ .mem-diff ins { color: var(--green); text-decoration: none; background: rgba(45, 106, 79, 0.14); font-weight: 600; }+ html[data-theme="dark"] .mem-diff del { background: rgba(242, 85, 90, 0.14); }+ html[data-theme="dark"] .mem-diff ins { background: rgba(92, 192, 143, 0.16); }+ .mem-diff-sum { font-family: var(--font-ui); font-size: 11px; color: var(--ink-faint); margin-top: 6px; }+ .mem-edit textarea { width: 100%; min-height: 150px; resize: vertical; padding: 10px; font-family: var(--font-body); font-size: 13px; line-height: 1.5; background: var(--bg); color: var(--ink); border: 1px solid var(--border); }+ .mem-edit textarea:focus { outline: none; box-shadow: 2px 2px 0 0 var(--border); }+ .mem-edit select { background: var(--bg); color: var(--ink); border: 1px solid var(--border); padding: 4px 8px; font-family: var(--font-ui); font-size: 12px; }+ .mem-edit-row { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; margin-top: 8px; font-family: var(--font-ui); font-size: 11px; color: var(--ink-muted); }+ .mem-note { font-family: var(--font-ui); font-size: 12px; color: var(--ink-muted); padding: 6px 10px; border-left: 3px solid var(--yellow); background: var(--bg-subtle); margin-bottom: 10px; }+ .mem-note.err { border-left-color: var(--accent); color: var(--ink); }+ .modal .modal-list { margin: 0 0 14px; padding-left: 18px; font-size: 12px; color: var(--ink-secondary); max-height: 160px; overflow-y: auto; }+ .modal label.modal-check { display: flex; gap: 8px; align-items: flex-start; font-size: 12px; color: var(--ink-secondary); margin-bottom: 14px; font-family: var(--font-ui); }+ .modal .mem-diff { max-height: 220px; overflow-y: auto; margin: 0 0 14px; }+ @media (max-width: 720px) {+ .mob-only { display: inline; }+ .mem-detail { padding: 14px; }+ .mem-actions .btn-danger { margin-left: 0; }+ .mem-filters input { flex: 1 1 100%; }+ .mem-filters select { flex: 1 1 30%; min-width: 0; }}.session-list { display: flex; flex-direction: column; gap: 0; }.session-item {@@ -637,7 +847,7 @@font-size: 13px;border-bottom: 1px solid var(--bg-inset);}- .detail-row .dl { color: var(--ink-muted); width: 140px; flex-shrink: 0; font-family: var(--font-ui); font-size: 10px; text-transform: uppercase; letter-spacing: 0.1em; font-weight: 600; padding-top: 2px; }+ .detail-row .dl { color: var(--ink-muted); width: 190px; flex-shrink: 0; font-family: var(--font-ui); font-size: 10px; text-transform: uppercase; letter-spacing: 0.1em; font-weight: 600; padding-top: 2px; }.detail-row .dv { color: var(--ink); font-family: var(--font-body); }.audit-entry {@@ -699,80 +909,8 @@.empty-state .empty-icon { font-size: 36px; margin-bottom: 10px; opacity: 0.4; }.empty-state p { font-size: 14px; font-family: var(--font-body); font-style: italic; }.empty-state .empty-title { font-size: 16px; font-weight: 600; font-style: normal; color: var(--ink-muted); margin-bottom: 8px; }- .empty-state .empty-lead { font-style: normal; font-size: 14px; color: var(--ink-muted); max-width: 520px; margin: 0 auto 14px; line-height: 1.5; }- .empty-state pre.empty-cmd {- display: inline-block; margin: 10px auto 12px; padding: 10px 14px;- background: var(--bg-alt); border: 1px solid var(--border);- border-radius: 4px; font-family: var(--font-mono); font-size: 12px;- color: var(--ink); text-align: left; font-style: normal; white-space: pre;- }.empty-state .empty-link { color: var(--accent); text-decoration: underline; font-size: 13px; font-style: normal; }-- /* Feature flag banner system — compact collapsed by default */- .flag-banners {- padding: 0 12px 10px 12px;- background: var(--bg);- flex: 0 0 auto;- position: relative;- z-index: 1;- }- .flag-banners:empty { display: none; }- button.flag-summary {- display: flex; align-items: center; gap: 12px;- padding: 8px 14px; border-radius: 4px;- border: 1px solid var(--border);- background: var(--bg-subtle);- font-family: var(--font-ui); font-size: 12px;- color: var(--ink-muted);- cursor: pointer; user-select: none;- width: 100%; text-align: left;- appearance: none;- flex: 1 1 auto;- }- 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;- background: #f59e0b20; color: #d97706; font-size: 11px; font-weight: 600;- margin-right: 6px;- }- .flag-summary .flag-pill.info { background: var(--border-light); color: var(--ink-muted); }- .flag-summary .flag-toggle { margin-left: auto; font-size: 11px; opacity: 0.7; }- .flag-list {- display: none; flex-direction: column; gap: 6px;- margin-top: 6px;- max-height: min(30vh, 260px);- overflow-y: auto;- }- .flag-list.open { display: flex; }- .flag-banner {- display: flex; align-items: flex-start; gap: 10px;- padding: 10px 14px; border-radius: 3px;- border: 1px solid var(--border);- background: var(--bg-subtle);- font-family: var(--font-ui); font-size: 12px;- }- .flag-banner.warn { border-left: 3px solid #f59e0b; }- .flag-banner.info { border-left: 3px solid var(--ink-muted); }- .flag-banner .flag-icon { flex-shrink: 0; font-size: 14px; line-height: 1.3; }- .flag-banner .flag-body { flex: 1; min-width: 0; }- .flag-banner .flag-title { font-weight: 600; color: var(--ink); margin-bottom: 2px; font-size: 12px; }- .flag-banner .flag-title code { font-family: var(--font-mono); font-size: 10px; color: var(--ink-muted); font-weight: 400; margin-left: 4px; }- .flag-banner .flag-desc { color: var(--ink-muted); margin-bottom: 4px; line-height: 1.4; font-size: 12px; }- .flag-banner .flag-enable {- display: block; margin-top: 2px; padding: 5px 8px;- background: var(--bg); border: 1px solid var(--border); border-radius: 3px;- font-family: var(--font-mono); font-size: 10px; color: var(--ink);- white-space: pre-wrap; word-break: break-all;- }- .flag-close {- background: none; border: none; color: var(--ink-faint); cursor: pointer;- font-size: 16px; line-height: 1; padding: 0 4px; font-family: inherit;- flex: 0 0 auto;- }- .flag-close:hover,- .flag-close:focus-visible { color: var(--ink); outline: 2px solid var(--border); outline-offset: 1px; }+ a.empty-link { color: var(--blue); text-decoration: underline; }.viewer-auth {display: none;@@ -814,14 +952,20 @@.viewer-auth-panel { grid-template-columns: 1fr; }}- /* Viewer footer */.viewer-footer {- margin-top: 48px; padding: 16px 0 24px;+ flex: 0 0 auto;+ padding: 5px 24px;border-top: 1px solid var(--border-light);- display: flex; align-items: center; gap: 10px;- font-family: var(--font-ui); font-size: 11px;+ background: var(--bg);+ display: flex; align-items: center; gap: 10px; flex-wrap: wrap;+ font-family: var(--font-ui); font-size: 10px;color: var(--ink-faint); letter-spacing: 0.05em;}+ .viewer-footer .footer-keys { margin-left: auto; }+ @media (max-width: 720px) {+ .viewer-footer { padding: 5px 16px; }+ .viewer-footer .footer-keys, .viewer-footer #footer-sync, .viewer-footer #footer-sync + .footer-sep { display: none; }+ }.viewer-footer a { color: var(--ink-muted); text-decoration: none; }.viewer-footer a:hover { color: var(--ink); text-decoration: underline; }.viewer-footer .footer-sep { color: var(--ink-faint); opacity: 0.5; }@@ -930,24 +1074,6 @@justify-content: flex-end;gap: 8px;}- .selected-node-info {- margin-top: 16px;- padding-top: 16px;- border-top: 1px solid var(--border-light);- }- .selected-node-info h4 {- font-size: 13px;- font-weight: 700;- color: var(--ink);- margin-bottom: 6px;- font-family: var(--font-display);- }- .selected-node-info .prop {- font-size: 12px;- color: var(--ink-muted);- padding: 2px 0;- font-family: var(--font-ui);- }.two-col {display: grid;grid-template-columns: 1fr 1fr;@@ -955,7 +1081,6 @@}@media (max-width: 768px) {.two-col { grid-template-columns: 1fr; }- .graph-sidebar { width: 200px; }.stats-grid { grid-template-columns: repeat(auto-fit, minmax(140px, 1fr)); }}@@ -972,22 +1097,67 @@letter-spacing: 0.1em;}- .timeline-container { position: relative; padding: 20px 0; }- .timeline-container::before { content: ''; position: absolute; left: 50%; top: 0; bottom: 0; width: 2px; background: var(--border-light); transform: translateX(-50%); }- .timeline-item { position: relative; width: 45%; margin-bottom: 20px; min-width: 0; }- .timeline-item.tl-left { margin-left: 0; margin-right: auto; text-align: right; padding-right: 30px; }- .timeline-item.tl-right { margin-left: auto; margin-right: 0; padding-left: 30px; }- .timeline-dot { position: absolute; width: 12px; height: 12px; border-radius: 50%; top: 16px; z-index: 1; border: 2px solid var(--bg); }- .timeline-item.tl-left .timeline-dot { right: -6px; transform: translateX(50%); }- .timeline-item.tl-right .timeline-dot { left: -6px; transform: translateX(-50%); }- .timeline-connector { position: absolute; top: 21px; height: 1px; background: var(--border-light); width: 24px; }- .timeline-item.tl-left .timeline-connector { right: 0; }- .timeline-item.tl-right .timeline-connector { left: 0; }- .timeline-date-marker { text-align: center; position: relative; margin: 24px 0 16px; z-index: 2; }- .timeline-date-marker span { background: var(--bg); padding: 4px 16px; font-size: 10px; font-family: var(--font-mono); text-transform: uppercase; letter-spacing: 0.1em; color: var(--ink-muted); border: 1px solid var(--border-light); }+ .ses-detail { margin-top: 0; padding: 18px 20px; }+ .ses-prompt { font-family: var(--font-display); font-size: 15px; font-weight: 600; }+ .ses-prompt.none, .session-preview.none { color: var(--ink-faint); font-weight: 400; font-style: italic; }+ .ses-danger-actions { margin-left: auto; display: inline-flex; gap: 6px; flex-wrap: wrap; }+ .mem-actions a.btn { text-decoration: none; padding: 4px 10px; font-size: 10px; }+ .ses-stats { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 8px; margin-top: 14px; }+ .ses-stats > div { border: 1px solid var(--border-light); padding: 8px 10px; font-family: var(--font-ui); font-size: 10px; letter-spacing: 0.08em; text-transform: uppercase; color: var(--ink-muted); display: flex; flex-direction: column; gap: 2px; min-width: 0; }+ .ses-stats > div > span { font-family: var(--font-display); font-size: 20px; font-weight: 700; color: var(--ink); letter-spacing: 0; text-transform: none; }+ .ses-stats small { font-size: 10px; display: inline-flex; gap: 4px; align-items: center; }+ .ses-foot { font-family: var(--font-ui); font-size: 11px; color: var(--ink-faint); margin-top: 6px; }+ .ses-summary { font-size: 13px; line-height: 1.5; color: var(--ink-secondary); margin-bottom: 4px; white-space: pre-wrap; }+ .ses-links { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 4px; }+ .ses-links li { font-size: 12px; line-height: 1.4; display: flex; gap: 6px; align-items: baseline; min-width: 0; }+ .ses-links .badge { flex: 0 0 auto; font-size: 8px; }+ .ses-live-note { font-weight: 500; letter-spacing: 0.06em; text-transform: none; display: inline-flex; gap: 4px; align-items: center; }+ .session-preview { font-size: 13px; color: var(--ink); margin: 4px 0 2px; line-height: 1.4; }+ .ses-id-mini { margin-left: auto; font-family: var(--font-mono); font-size: 10px; color: var(--ink-faint); }+ .running-dot { color: var(--green); font-weight: 600; }+ .running-dot::before { content: ''; display: inline-block; width: 6px; height: 6px; border-radius: 50%; background: var(--green); margin-right: 4px; vertical-align: 1px; }+ .ses-detail .type-chips { align-items: center; margin-bottom: 12px; }+ .ses-detail .type-chips select { margin-left: auto; font-family: var(--font-ui); font-size: 11px; padding: 3px 6px; background: var(--bg); color: var(--ink); border: 1px solid var(--border-light); }+ .obs-timeline { list-style: none; margin: 0; padding: 0 0 0 14px; position: relative; }+ .obs-timeline::before { content: ''; position: absolute; left: 4px; top: 4px; bottom: 4px; width: 1px; background: var(--border-light); }+ .obs-item { position: relative; border: 1px solid var(--border-light); border-left: 3px solid var(--obs-color, var(--border-light)); background: var(--bg); padding: 8px 12px; margin-bottom: 8px; min-width: 0; }+ .obs-item::before { content: ''; position: absolute; left: -15px; top: 13px; width: 9px; height: 9px; border-radius: 50%; background: var(--obs-color, var(--ink-faint)); border: 2px solid var(--bg); }+ .obs-item.focus { box-shadow: 0 0 0 2px var(--accent); }+ .obs-item.fresh { animation: feed-in 2.5s ease-out; }+ .obs-item-head { display: flex; align-items: center; gap: 8px; min-width: 0; flex-wrap: wrap; }+ .obs-type-chip { font-family: var(--font-ui); font-size: 9px; font-weight: 700; letter-spacing: 0.08em; text-transform: uppercase; color: var(--obs-color); border: 1px solid var(--obs-color); padding: 0 5px; line-height: 16px; flex: 0 0 auto; }+ .obs-item-title { font-family: var(--font-display); font-size: 14px; font-weight: 700; color: var(--ink); flex: 0 0 auto; }+ .obs-item-sub { font-family: var(--font-mono); font-size: 11px; color: var(--ink-muted); min-width: 0; flex: 1 1 120px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+ .obs-item-meta { margin-left: auto; display: inline-flex; gap: 8px; align-items: center; flex: 0 0 auto; }+ .obs-item-meta .obs-importance { width: 20px; height: 20px; font-size: 10px; }+ .obs-importance.raw { border-color: var(--border-light); color: var(--ink-faint); }+ .obs-item-meta .obs-time { font-family: var(--font-mono); font-size: 10px; color: var(--ink-faint); text-decoration: none; }+ .obs-item-meta .obs-time:hover { color: var(--ink); text-decoration: underline; }+ .obs-item-body { margin-top: 6px; min-width: 0; }+ .obs-item-body .obs-narrative { font-size: 13px; color: var(--ink-muted); overflow-wrap: anywhere; }+ .obs-item-body .obs-facts { margin: 6px 0 0 16px; font-size: 12px; color: var(--ink-muted); }+ .obs-prompt { font-size: 13px; line-height: 1.5; color: var(--ink); padding: 6px 10px; border-left: 2px solid var(--border); background: var(--bg-subtle); white-space: pre-wrap; overflow-wrap: anywhere; }+ .obs-fields { display: grid; grid-template-columns: max-content minmax(0, 1fr); gap: 2px 10px; margin: 0; font-size: 12px; align-items: baseline; }+ .obs-fields dt { font-family: var(--font-ui); font-size: 10px; text-transform: uppercase; letter-spacing: 0.08em; color: var(--ink-faint); font-weight: 600; }+ .obs-fields dd { min-width: 0; margin: 0; overflow-wrap: anywhere; }+ .obs-fields code { font-family: var(--font-mono); font-size: 12px; color: var(--ink); }+ .obs-block { margin-top: 6px; min-width: 0; }+ .obs-block-label { font-family: var(--font-ui); font-size: 10px; text-transform: uppercase; letter-spacing: 0.08em; color: var(--ink-faint); font-weight: 600; margin-bottom: 2px; }+ .obs-block-label span { text-transform: none; letter-spacing: 0; font-weight: 400; }+ .obs-code { margin: 0; font-family: var(--font-mono); font-size: 11px; line-height: 1.5; color: var(--ink-secondary); background: var(--bg-alt); border: 1px solid var(--border-light); padding: 6px 8px; max-height: 220px; overflow: auto; white-space: pre-wrap; overflow-wrap: anywhere; }+ .obs-item-meta .copy-btn { opacity: 0.5; }+ .obs-item:hover .obs-item-meta .copy-btn, .obs-item-meta .copy-btn:focus-visible { opacity: 1; }+ @media (max-width: 720px) {+ .ses-detail { padding: 14px; }+ .ses-stats { grid-template-columns: repeat(2, minmax(0, 1fr)); }+ .ses-danger-actions { margin-left: 0; }+ .obs-item-meta { margin-left: 0; }+ .ses-id-mini { display: none; }+ }.heatmap-wrap { overflow-x: auto; padding: 8px 0; }- .heatmap-grid { display: grid; grid-template-rows: repeat(7, 1fr); grid-auto-flow: column; grid-auto-columns: 12px; gap: 2px; }+ .heatmap-grid { display: grid; grid-template-rows: repeat(7, 14px); grid-auto-flow: column; grid-auto-columns: minmax(10px, 1fr); gap: 3px; }+ .heatmap-grid .heatmap-cell { width: auto; height: 14px; }.heatmap-cell { width: 10px; height: 10px; background: var(--bg-inset); cursor: default; }.heatmap-cell[title] { cursor: pointer; }.heatmap-cell.level-1 { background: rgba(45,106,79,0.2); }@@ -996,21 +1166,6 @@.heatmap-cell.level-4 { background: var(--green); }.heatmap-labels { display: flex; gap: 2px; font-size: 9px; color: var(--ink-faint); font-family: var(--font-mono); margin-bottom: 4px; }- .graph-search { width: 100%; background: var(--bg); border: 1px solid var(--border); padding: 7px 12px; font-size: 12px; font-family: var(--font-ui); margin-bottom: 12px; outline: none; }- .graph-search:focus { border-color: var(--ink); box-shadow: 2px 2px 0px 0px var(--border); }- .graph-legend { margin-top: 16px; padding-top: 16px; border-top: 1px solid var(--border-light); }- .graph-legend-item { display: flex; align-items: center; gap: 6px; padding: 3px 0; font-size: 11px; font-family: var(--font-ui); color: var(--ink-muted); }- .graph-legend-shape { width: 16px; height: 16px; display: flex; align-items: center; justify-content: center; }- .graph-tooltip { position: absolute; background: rgba(255,255,255,0.88); backdrop-filter: blur(12px); -webkit-backdrop-filter: blur(12px); border: 1px solid rgba(17,17,17,0.08); padding: 12px 16px; font-size: 11px; font-family: var(--font-ui); pointer-events: none; z-index: 10; box-shadow: 0 8px 32px rgba(0,0,0,0.12), 0 2px 8px rgba(0,0,0,0.06); max-width: 260px; display: none; border-radius: 8px; transition: opacity 0.15s ease; }- .graph-tooltip.visible { display: block; opacity: 1; }- .graph-tooltip .tt-name { font-weight: 700; color: var(--ink); margin-bottom: 4px; font-family: var(--font-display); font-size: 13px; }- .graph-tooltip .tt-type { font-size: 9px; text-transform: uppercase; letter-spacing: 0.1em; margin-bottom: 6px; font-weight: 600; padding: 2px 6px; border-radius: 3px; display: inline-block; }- .graph-tooltip .tt-prop { font-size: 10px; color: var(--ink-muted); padding: 1px 0; }- .graph-tooltip .tt-conns { font-size: 10px; color: var(--ink-faint); margin-top: 6px; border-top: 1px solid rgba(17,17,17,0.08); padding-top: 6px; font-family: var(--font-mono); }- .graph-controls { position: absolute; bottom: 16px; right: 16px; display: flex; flex-direction: column; gap: 2px; z-index: 5; }- .graph-controls button { width: 36px; height: 36px; font-size: 18px; cursor: pointer; background: rgba(255,255,255,0.92); backdrop-filter: blur(8px); -webkit-backdrop-filter: blur(8px); border: 1px solid rgba(17,17,17,0.1); color: var(--ink); display: flex; align-items: center; justify-content: center; font-weight: 500; font-family: var(--font-ui); border-radius: 6px; transition: all 0.15s ease; box-shadow: 0 2px 8px rgba(0,0,0,0.06); }- .graph-controls button:hover { background: var(--ink); color: var(--bg); transform: scale(1.05); box-shadow: 0 4px 12px rgba(0,0,0,0.15); }- .graph-controls .ctrl-divider { height: 1px; background: var(--border-light); margin: 2px 4px; }.type-chips { display: flex; gap: 6px; flex-wrap: wrap; margin-bottom: 16px; }.type-chip { font-size: 10px; padding: 3px 10px; border: 1px solid var(--border-light); cursor: pointer; font-family: var(--font-ui); text-transform: uppercase; letter-spacing: 0.06em; font-weight: 600; transition: all 0.15s; background: var(--bg); }@@ -1030,67 +1185,344 @@.activity-feed-body { flex: 1; min-width: 0; }.activity-feed-title { font-weight: 600; color: var(--ink); font-family: var(--font-display); font-size: 13px; }.activity-feed-meta { font-size: 10px; color: var(--ink-faint); font-family: var(--font-mono); margin-top: 2px; }++ .icon-btn {+ background: var(--bg);+ border: 1px solid var(--border-light);+ color: var(--ink-muted);+ font-family: var(--font-ui);+ font-size: 10px;+ font-weight: 700;+ letter-spacing: 0.08em;+ padding: 3px 9px;+ cursor: pointer;+ line-height: 1.4;+ }+ .icon-btn:hover, .icon-btn:focus-visible { color: var(--ink); border-color: var(--ink); outline: none; }+ .chip {+ display: inline-flex; align-items: center; gap: 6px;+ font-family: var(--font-ui); font-size: 10px; font-weight: 600;+ letter-spacing: 0.06em; text-transform: uppercase;+ padding: 3px 9px; border: 1px solid var(--border-light);+ background: var(--bg); color: var(--ink-muted); cursor: pointer;+ }+ .chip:hover, .chip:focus-visible { border-color: var(--ink); color: var(--ink); outline: none; }+ .chip.chip-warn { border-color: var(--yellow); color: var(--yellow); }+ .chip.chip-ok { border-color: var(--green); color: var(--green); }++ .flags-panel {+ flex: 0 0 auto;+ background: var(--bg-subtle);+ border-bottom: 1px solid var(--border);+ padding: 12px 24px;+ max-height: 45vh;+ overflow-y: auto;+ font-family: var(--font-ui);+ }+ .flags-panel[hidden] { display: none; }+ .flags-panel-head { display: flex; align-items: baseline; gap: 10px; margin-bottom: 8px; }+ .flags-panel-head h2 { font-size: 13px; font-family: var(--font-display); color: var(--ink); }+ .flags-panel-head p { font-size: 12px; color: var(--ink-muted); flex: 1; }+ .flags-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(320px, 1fr)); gap: 8px; }+ .flag-item { border: 1px solid var(--border-light); background: var(--bg); padding: 10px 12px; font-size: 12px; min-width: 0; }+ .flag-item.off { border-left: 3px solid var(--yellow); }+ .flag-item.on { border-left: 3px solid var(--green); }+ .flag-item .flag-item-title { display: flex; align-items: center; gap: 6px; font-weight: 600; color: var(--ink); margin-bottom: 3px; }+ .flag-item .flag-item-desc { color: var(--ink-muted); line-height: 1.45; margin-bottom: 4px; }+ .flag-item .flag-item-meta { color: var(--ink-faint); font-size: 11px; }++ .offline-banner {+ flex: 0 0 auto;+ display: flex; align-items: center; gap: 10px; flex-wrap: wrap;+ padding: 7px 24px;+ background: var(--bg-alt);+ border-bottom: 1px solid var(--yellow);+ font-family: var(--font-ui); font-size: 12px; color: var(--ink-secondary);+ }+ .offline-banner[hidden] { display: none; }+ .offline-banner.offline { border-bottom-color: var(--accent); }+ .offline-banner strong { color: var(--ink); }++ .help {+ display: inline-flex; align-items: center; justify-content: center;+ width: 14px; height: 14px; border-radius: 50%;+ border: 1px solid var(--border-light);+ background: var(--bg);+ color: var(--ink-faint);+ font-family: var(--font-ui); font-size: 9px; font-weight: 700;+ line-height: 1; padding: 0; cursor: help; vertical-align: middle;+ text-transform: none; letter-spacing: 0;+ }+ .help:hover, .help:focus-visible { color: var(--bg); background: var(--ink); border-color: var(--ink); outline: none; }+ .help-pop {+ position: fixed;+ z-index: 200;+ max-width: 300px;+ background: var(--bg);+ border: 1px solid var(--border);+ box-shadow: 4px 4px 0 0 var(--border);+ padding: 10px 12px;+ font-family: var(--font-ui);+ font-size: 12px;+ line-height: 1.5;+ color: var(--ink-secondary);+ }+ .help-pop[hidden] { display: none; }+ .help-pop .help-pop-term { font-weight: 700; color: var(--ink); margin-bottom: 3px; font-family: var(--font-display); font-size: 13px; }++ .copy-btn {+ background: none; border: 1px solid var(--border-light); color: var(--ink-muted);+ font-family: var(--font-ui); font-size: 9px; font-weight: 700; letter-spacing: 0.08em;+ text-transform: uppercase; padding: 1px 6px; cursor: pointer; vertical-align: middle; white-space: nowrap; flex-shrink: 0;+ }+ .copy-btn:hover, .copy-btn:focus-visible { color: var(--ink); border-color: var(--ink); outline: none; }+ .copy-btn.copied { color: var(--green); border-color: var(--green); }+ .entity-link {+ font-family: var(--font-mono); font-size: 11px; color: var(--blue);+ text-decoration: none; border-bottom: 1px dotted var(--blue);+ }+ .entity-link:hover, .entity-link:focus-visible { color: var(--accent); border-bottom-color: var(--accent); outline: none; }+ html[data-theme="dark"] .entity-link { color: #8fb4e8; border-bottom-color: #8fb4e8; }+ .id-chip { display: inline-flex; align-items: center; gap: 4px; }+ .rel-time { font-family: var(--font-mono); font-size: 11px; color: var(--ink-faint); white-space: nowrap; }++ .cmd-block { display: flex; align-items: flex-start; gap: 6px; margin: 4px 0 0; max-width: 100%; }+ .cmd-block pre {+ flex: 1 1 auto; min-width: 0; margin: 0; padding: 8px 10px;+ background: var(--bg-alt); border: 1px solid var(--border-light);+ font-family: var(--font-mono); font-size: 11px; color: var(--ink);+ white-space: pre-wrap; overflow-wrap: anywhere; text-align: left; font-style: normal;+ }+ .empty-state.v2 { text-align: left; padding: 20px 22px; border: 1px dashed var(--border-light); background: var(--bg-subtle); color: var(--ink-secondary); }+ .empty-state.v2 .empty-head { display: flex; align-items: center; gap: 10px; margin-bottom: 10px; }+ .empty-state.v2 .empty-icon { font-size: 22px; margin: 0; opacity: 0.7; }+ .empty-state.v2 .empty-title { margin: 0; font-size: 15px; color: var(--ink); font-family: var(--font-display); font-weight: 700; }+ .empty-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 10px 20px; margin: 0 0 12px; }+ .empty-grid dt { font-family: var(--font-ui); font-size: 9px; letter-spacing: 0.14em; text-transform: uppercase; color: var(--ink-faint); font-weight: 700; margin-bottom: 2px; }+ .empty-grid dd { font-size: 13px; line-height: 1.5; color: var(--ink-secondary); font-family: var(--font-body); }+ .empty-steps-title { font-family: var(--font-ui); font-size: 9px; letter-spacing: 0.14em; text-transform: uppercase; color: var(--ink-faint); font-weight: 700; margin-bottom: 4px; }+ .empty-step { margin-bottom: 8px; }+ .first-run-steps { display: grid; grid-template-columns: repeat(auto-fit, minmax(260px, 1fr)); gap: 14px 24px; }+ .first-run-steps .empty-step-label { line-height: 1.5; margin-bottom: 4px; }+ .empty-step-label { font-size: 12px; color: var(--ink-muted); font-family: var(--font-ui); }+ .empty-state.v2.compact { padding: 12px 14px; }+ .empty-state.v2.compact .empty-grid { margin-bottom: 6px; }++ .skeleton { display: flex; flex-direction: column; gap: 10px; padding: 4px 0; }+ .skeleton-row { height: 14px; background: linear-gradient(90deg, var(--bg-inset) 0%, var(--bg-alt) 50%, var(--bg-inset) 100%); background-size: 200% 100%; animation: sk-shimmer 1.2s ease-in-out infinite; }+ .skeleton-row.short { width: 45%; }+ .skeleton-row.mid { width: 70%; }+ @keyframes sk-shimmer { from { background-position: 200% 0; } to { background-position: -200% 0; } }+ @media (prefers-reduced-motion: reduce) { .skeleton-row { animation: none; } }++ .section-head { display: flex; align-items: baseline; gap: 8px; margin: 4px 0 8px; font-family: var(--font-ui); }+ .section-head h2 { font-size: 10px; letter-spacing: 0.16em; text-transform: uppercase; color: var(--ink-muted); font-weight: 700; }+ .section-head .section-sub { font-size: 11px; color: var(--ink-faint); }+ .dash-cols { display: grid; grid-template-columns: minmax(0, 1.1fr) minmax(0, 1fr); gap: 16px; align-items: stretch; margin-bottom: 16px; }+ .dash-cols > .card { margin-bottom: 0; display: flex; flex-direction: column; min-height: 0; }+ .dash-cols .card-scroll { flex: 1 1 auto; overflow-y: auto; max-height: 340px; }+ @media (max-width: 900px) { .dash-cols { grid-template-columns: 1fr; } }+ .clamp-2 { display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; overflow-wrap: anywhere; }+ .feed-item .badge { max-width: 120px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+ .feed-item { display: grid; grid-template-columns: max-content minmax(0, 1fr) auto; gap: 8px; align-items: baseline; padding: 6px 0; border-bottom: 1px solid var(--border-light); font-size: 12px; }+ .feed-item:last-child { border-bottom: none; }+ a.feed-text:hover, a.feed-text:focus-visible { color: var(--accent); outline: none; }+ .feed-item .feed-text { color: var(--ink); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+ .feed-item.fresh { animation: feed-in 900ms ease-out; }+ @keyframes feed-in { from { background: rgba(45,106,79,0.18); } to { background: transparent; } }+ @media (prefers-reduced-motion: reduce) { .feed-item.fresh { animation: none; } }+ .mini-table td, .mini-table th { padding: 6px 8px; }+ .table-wrap { width: 100%; overflow-x: auto; }+ @media (max-width: 720px) {+ .col-opt { display: none; }+ .toolbar input { min-width: 0; }+ .sessions-layout { grid-template-columns: 1fr; }+ .replay-grid { grid-template-columns: 1fr; }+ .detail-row { flex-direction: column; }+ .detail-row .dl { width: auto; }+ }+ .overlay-panel { max-width: 760px; width: 94%; max-height: 84vh; overflow-y: auto; }+ .glossary-list { display: grid; grid-template-columns: repeat(auto-fill, minmax(240px, 1fr)); gap: 8px 18px; margin: 8px 0 16px; }+ .glossary-list div { font-size: 12px; line-height: 1.45; color: var(--ink-muted); font-family: var(--font-ui); }+ .glossary-list b { color: var(--ink); display: block; font-size: 12px; }+ .kbd-list { display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 4px 18px; font-family: var(--font-ui); font-size: 12px; color: var(--ink-muted); margin: 8px 0 14px; }+ kbd { font-family: var(--font-mono); font-size: 10px; border: 1px solid var(--border-light); border-bottom-width: 2px; padding: 0 5px; background: var(--bg-alt); color: var(--ink); }+ .skip-link { position: absolute; left: -999px; top: 0; z-index: 300; background: var(--ink); color: var(--bg); padding: 6px 10px; font-family: var(--font-ui); font-size: 12px; }+ .skip-link:focus { left: 8px; top: 8px; }+ .load-more { display: flex; justify-content: center; align-items: center; gap: 10px; margin: 14px 0 4px; font-family: var(--font-ui); font-size: 11px; color: var(--ink-faint); }+ .usage-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(260px, 1fr)); gap: 12px 18px; }+ .inline-note { font-family: var(--font-ui); font-size: 12px; color: var(--ink-muted); padding: 8px 12px; border-left: 3px solid var(--blue); background: var(--bg-subtle); margin-bottom: 12px; }+ @media (max-width: 720px) {+ .view { overflow-x: hidden; padding: 14px 16px; }+ .viewer-auth { padding: 0 16px 10px; }+ .flags-panel { padding: 12px 16px; }+ .offline-banner { padding: 7px 16px; }+ }+ .list-detail { display: grid; grid-template-columns: minmax(0, 1fr); gap: 20px; align-items: start; }+ .list-detail.has-detail { grid-template-columns: minmax(0, 1fr) minmax(340px, 440px); }+ .list-detail > .ld-detail { min-width: 0; }+ .list-detail > .ld-detail:empty { display: none; }+ .list-detail.has-detail > .ld-detail { position: sticky; top: 0; max-height: calc(100vh - 150px); overflow-y: auto; }+ @media (max-width: 1100px) {+ .list-detail.has-detail { grid-template-columns: minmax(0, 1fr); }+ .list-detail.has-detail > .ld-detail { position: static; order: -1; max-height: none; overflow: visible; }+ }+ .row-select td:first-child { box-shadow: inset 3px 0 0 var(--accent); }+ .row-select td { background: var(--bg-alt); }+ .toolbar label.tb-label { display: inline-flex; align-items: center; gap: 6px; font-family: var(--font-ui); font-size: 11px; color: var(--ink-muted); }+ .toolbar input[type="date"] { flex: 0 0 auto; min-width: 0; padding: 6px 8px; }+ .toolbar .tb-count { font-family: var(--font-ui); font-size: 12px; color: var(--ink-faint); margin-left: auto; }+ .audit-list { border: 1px solid var(--border); background: var(--bg); }+ .audit-row { display: grid; grid-template-columns: 132px minmax(0, 1fr) auto; gap: 4px 12px; align-items: baseline; padding: 10px 14px; border-bottom: 1px solid var(--border-light); font-family: var(--font-ui); font-size: 12px; }+ .audit-row:last-child { border-bottom: none; }+ .audit-row.fresh { animation: feed-in 2.5s ease-out; }+ .audit-row.open { background: var(--bg-subtle); }+ .audit-op { justify-self: start; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+ .audit-sum { color: var(--ink); font-size: 13px; line-height: 1.45; min-width: 0; overflow-wrap: anywhere; }+ .audit-fn { font-family: var(--font-mono); font-size: 10px; color: var(--ink-faint); margin-left: 6px; }+ .audit-when { display: inline-flex; gap: 8px; align-items: baseline; white-space: nowrap; }+ .audit-targets { grid-column: 2 / 4; display: flex; gap: 6px; flex-wrap: wrap; align-items: baseline; color: var(--ink-faint); font-size: 11px; }+ .audit-more { grid-column: 1 / -1; margin-top: 6px; padding: 10px 12px; border: 1px solid var(--border-light); background: var(--bg); }+ .kind-tag { font-family: var(--font-ui); font-size: 9px; text-transform: uppercase; letter-spacing: 0.08em; color: var(--ink-faint); }+ @media (max-width: 720px) {+ .audit-row { grid-template-columns: minmax(0, 1fr) auto; }+ .audit-op { grid-column: 1 / 2; }+ .audit-when { grid-column: 2 / 3; grid-row: 1; justify-self: end; }+ .audit-sum { grid-column: 1 / -1; }+ .audit-targets { grid-column: 1 / -1; }+ .toolbar .tb-count { margin-left: 0; flex: 1 1 100%; }+ .toolbar #audit-op-filter { flex: 1 1 100%; }+ .toolbar label.tb-label { flex: 1 1 40%; min-width: 0; }+ .toolbar label.tb-label input { flex: 1 1 auto; }+ }+ .hm { display: grid; grid-template-columns: 26px minmax(0, 1fr); gap: 4px 6px; }+ .hm-days { display: grid; grid-template-rows: repeat(7, 1fr); gap: 3px; font-family: var(--font-mono); font-size: 9px; color: var(--ink-faint); }+ .hm-days span { line-height: 1; display: flex; align-items: center; }+ .hm-months { grid-column: 2; display: grid; grid-auto-flow: column; grid-auto-columns: minmax(0, 1fr); gap: 3px; font-family: var(--font-mono); font-size: 9px; color: var(--ink-faint); height: 12px; }+ .hm-months span { white-space: nowrap; overflow: visible; }+ .hm-grid { display: grid; grid-template-rows: repeat(7, minmax(12px, 1fr)); grid-auto-flow: column; grid-auto-columns: minmax(0, 1fr); gap: 3px; aspect-ratio: auto; }+ .hm-cell { border: none; padding: 0; min-height: 12px; background: var(--bg-inset); cursor: default; }+ .hm-cell.future { background: transparent; }+ button.hm-cell { cursor: pointer; }+ button.hm-cell:hover { outline: 1px solid var(--ink); }+ .hm-cell.on { outline: 2px solid var(--accent); outline-offset: 1px; }+ .hm-cell.level-1 { background: rgba(45,106,79,0.25); }+ .hm-cell.level-2 { background: rgba(45,106,79,0.45); }+ .hm-cell.level-3 { background: rgba(45,106,79,0.7); }+ .hm-cell.level-4 { background: var(--green); }+ html[data-theme="dark"] .hm-cell.level-1 { background: rgba(92,192,143,0.22); }+ html[data-theme="dark"] .hm-cell.level-2 { background: rgba(92,192,143,0.42); }+ html[data-theme="dark"] .hm-cell.level-3 { background: rgba(92,192,143,0.66); }+ .hm-foot { display: flex; gap: 12px; align-items: center; flex-wrap: wrap; margin-top: 8px; font-family: var(--font-ui); font-size: 11px; color: var(--ink-faint); }+ .hm-legend { margin-left: auto; display: inline-flex; gap: 3px; align-items: center; }+ .hm-legend .hm-cell { width: 11px; height: 11px; min-height: 0; display: inline-block; }+ .hm-stats { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 8px; margin-bottom: 12px; }+ .hm-stats > div { border: 1px solid var(--border-light); padding: 6px 10px; font-family: var(--font-ui); font-size: 10px; text-transform: uppercase; letter-spacing: 0.08em; color: var(--ink-muted); }+ .hm-stats b { display: block; font-family: var(--font-display); font-size: 18px; color: var(--ink); letter-spacing: 0; text-transform: none; }+ .day-panel { margin-top: 12px; border-top: 1px solid var(--border-light); padding-top: 10px; }+ .bar-row.linkrow { cursor: pointer; background: none; border: none; width: 100%; padding: 2px 0; text-align: left; color: inherit; font: inherit; }+ .bar-row.linkrow:hover .bar-label, .bar-row.linkrow.on .bar-label { color: var(--ink); text-decoration: underline; }+ .bar-row.linkrow.on .bar-label { font-weight: 700; }+ .feed-session { display: flex; gap: 6px; align-items: baseline; flex-wrap: wrap; font-family: var(--font-ui); font-size: 11px; color: var(--ink-muted); margin: 10px 0 6px -14px; }+ .feed-session:first-child { margin-top: 0; }+ .act-filter { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; font-family: var(--font-ui); font-size: 11px; color: var(--ink-muted); margin-bottom: 10px; }+ .act-filter .btn { padding: 2px 8px; font-size: 9px; }+ .src-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 4px; font-family: var(--font-ui); font-size: 12px; }+ .src-list li { display: flex; gap: 6px; align-items: baseline; min-width: 0; flex-wrap: wrap; }+ .src-list .src-text { color: var(--ink-muted); min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1 1 140px; }+ .conf-line { display: flex; gap: 10px; align-items: center; }+ .conf-line .hbar { flex: 1 1 auto; max-width: 180px; margin: 0; }+ .ready-badge { font-family: var(--font-ui); font-size: 9px; font-weight: 700; letter-spacing: 0.08em; text-transform: uppercase; color: var(--green); border: 1px solid var(--green); padding: 0 5px; line-height: 16px; white-space: nowrap; }+ .crystal-card.selected { box-shadow: 0 0 0 2px var(--accent); }+ tr.fresh td, .crystal-card.fresh { animation: feed-in 2.5s ease-out; }+ .mem-table th { white-space: nowrap; }+ @media (prefers-reduced-motion: reduce) { tr.fresh td, .crystal-card.fresh, .audit-row.fresh, .obs-item.fresh { animation: none; } }+ .inline-status { font-family: var(--font-ui); font-size: 12px; padding: 8px 12px; border-left: 3px solid var(--blue); background: var(--bg-subtle); margin: 0 0 12px; color: var(--ink-secondary); line-height: 1.5; }+ .inline-status.ok { border-left-color: var(--green); }+ .inline-status.err { border-left-color: var(--accent); color: var(--ink); }+ .replay-event { width: 100%; background: none; border: none; border-bottom: 1px solid var(--border-light); text-align: left; color: var(--ink); cursor: pointer; }+ .replay-controls button[aria-pressed="true"] { background: var(--ink); color: var(--bg); }+ .prof-cols { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 16px; }+ .prof-cols > .card { margin-bottom: 0; min-width: 0; }+ @media (max-width: 900px) { .prof-cols { grid-template-columns: 1fr; } .hm-stats { grid-template-columns: repeat(2, minmax(0, 1fr)); } }+ .sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; border: 0; }+ :where(a, button, select, input, textarea, summary, [tabindex], [role="button"], [role="link"], [role="tab"]):focus-visible { outline: 2px solid var(--accent) !important; outline-offset: 2px; }+ .tab-bar button:focus-visible, .graph-stage canvas:focus-visible, .stat-card[data-action]:focus-visible, .session-item:focus-visible, .memory-row:focus-visible, .lesson-row:focus-visible { outline-offset: -3px; }</style></head><body><canvas id="bg-dither" aria-hidden="true"></canvas>- <div class="app-header">- <a class="brand" href="#dashboard" data-tab-link="dashboard" aria-label="Open dashboard">+ <a class="skip-link" href="#main">Skip to content</a>+ <header class="app-header">+ <a class="brand" href="#dashboard" data-tab-link="dashboard" aria-label="Open overview"><h1>agentmemory</h1><span class="version">v__AGENTMEMORY_VERSION__</span></a>+ <button type="button" class="btn nav-toggle" id="nav-toggle" data-action="toggle-nav" aria-expanded="false" aria-controls="tab-bar"><span id="nav-current">Overview</span><span aria-hidden="true">▾</span></button><div class="header-right"><span class="dateline" id="dateline"></span>- <button id="theme-toggle" class="btn" style="font-size:9px;padding:3px 10px;letter-spacing:0.1em;margin-right:8px;" data-action="toggle-theme">DARK</button>- <span id="ws-status" class="ws-status disconnected">live updates off</span>+ <span id="flags-chip"></span>+ <span id="ws-status" class="ws-status connecting" role="status" aria-live="polite">connecting</span>+ <button type="button" class="icon-btn" data-action="open-help" aria-label="Glossary and keyboard shortcuts" title="Glossary and keyboard shortcuts (?)">?</button>+ <button type="button" id="theme-toggle" class="icon-btn" data-action="toggle-theme">DARK</button></div>- </div>-- <div class="tab-bar" id="tab-bar">- <button class="active" data-tab="dashboard" aria-current="page">Dashboard</button>- <button data-tab="graph">Graph</button>- <button data-tab="memories">Memories</button>- <button data-tab="timeline">Timeline</button>- <button data-tab="sessions">Sessions</button>- <button data-tab="lessons">Lessons</button>- <button data-tab="actions">Actions</button>- <button data-tab="crystals">Crystals</button>- <button data-tab="audit">Audit</button>- <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>+ <nav class="tab-bar" id="tab-bar" role="tablist" aria-label="Viewer sections">+ <button type="button" role="tab" class="active" data-tab="dashboard" aria-selected="true" aria-controls="view-dashboard">Overview</button>+ <div class="tab-group" role="presentation"><span class="tab-group-label" aria-hidden="true">Memory</span>+ <button type="button" role="tab" data-tab="memories" aria-selected="false" aria-controls="view-memories">Memories<span class="tab-count" data-count="latestMemories"></span></button>+ <button type="button" role="tab" data-tab="lessons" aria-selected="false" aria-controls="view-lessons">Lessons<span class="tab-count" data-count="lessons"></span></button>+ <button type="button" role="tab" data-tab="crystals" aria-selected="false" aria-controls="view-crystals">Crystals<span class="tab-count" data-count="crystals"></span></button>+ <button type="button" role="tab" data-tab="graph" aria-selected="false" aria-controls="view-graph">Graph<span class="tab-count" data-count="graphNodes"></span></button>+ </div>+ <div class="tab-group" role="presentation"><span class="tab-group-label" aria-hidden="true">Work</span>+ <button type="button" role="tab" data-tab="sessions" aria-selected="false" aria-controls="view-sessions">Sessions<span class="tab-count" data-count="sessions"></span></button>+ <button type="button" role="tab" data-tab="actions" aria-selected="false" aria-controls="view-actions">Actions<span class="tab-count" data-count="actions"></span></button>+ <button type="button" role="tab" data-tab="replay" aria-selected="false" aria-controls="view-replay">Replay</button>+ </div>+ <div class="tab-group" role="presentation"><span class="tab-group-label" aria-hidden="true">Insight</span>+ <button type="button" role="tab" data-tab="activity" aria-selected="false" aria-controls="view-activity">Activity</button>+ <button type="button" role="tab" data-tab="profile" aria-selected="false" aria-controls="view-profile">Profile</button>+ </div>+ <div class="tab-group" role="presentation"><span class="tab-group-label" aria-hidden="true">System</span>+ <button type="button" role="tab" data-tab="health" aria-selected="false" aria-controls="view-health">Health</button>+ <button type="button" role="tab" data-tab="audit" aria-selected="false" aria-controls="view-audit">Audit</button>+ </div>+ </nav>+ </header>++ <div id="flags-panel" class="flags-panel" hidden></div>+ <div id="offline-banner" class="offline-banner" role="status" hidden></div><div id="viewer-auth" class="viewer-auth"></div>- <div id="view-dashboard" class="view active"></div>- <div id="view-graph" class="view"></div>- <div id="view-memories" class="view"></div>- <div id="view-lessons" class="view"></div>- <div id="view-actions" class="view"></div>- <div id="view-crystals" class="view"></div>- <div id="view-timeline" class="view"></div>- <div id="view-sessions" class="view"></div>- <div id="view-audit" class="view"></div>- <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>+ <main id="main" class="views" tabindex="-1">+ <div id="view-dashboard" class="view active" role="tabpanel" aria-label="Overview"></div>+ <div id="view-graph" class="view" role="tabpanel" aria-label="Graph"></div>+ <div id="view-memories" class="view" role="tabpanel" aria-label="Memories"></div>+ <div id="view-lessons" class="view" role="tabpanel" aria-label="Lessons"></div>+ <div id="view-actions" class="view" role="tabpanel" aria-label="Actions"></div>+ <div id="view-crystals" class="view" role="tabpanel" aria-label="Crystals"></div>+ <div id="view-sessions" class="view" role="tabpanel" aria-label="Sessions"></div>+ <div id="view-audit" class="view" role="tabpanel" aria-label="Audit"></div>+ <div id="view-activity" class="view" role="tabpanel" aria-label="Activity"></div>+ <div id="view-profile" class="view" role="tabpanel" aria-label="Profile"></div>+ <div id="view-replay" class="view" role="tabpanel" aria-label="Replay"></div>+ <div id="view-health" class="view" role="tabpanel" aria-label="Health"></div>+ </main><div id="modal-overlay" class="modal-overlay">- <div class="modal" id="modal"></div>+ <div class="modal" id="modal" role="dialog" aria-modal="true"></div></div>+ <div id="help-pop" class="help-pop" role="tooltip" hidden></div><footer id="viewer-footer" class="viewer-footer">- <span>agentmemory viewer · <span id="footer-version">loading...</span></span>+ <span>agentmemory · <span id="footer-version">v__AGENTMEMORY_VERSION__</span></span><span class="footer-sep">·</span>- <a href="https://github.com/rohitg00/agentmemory" target="_blank" rel="noopener">github</a>+ <span id="footer-sync">waiting for first sync</span><span class="footer-sep">·</span><a href="https://github.com/rohitg00/agentmemory#readme" target="_blank" rel="noopener">docs</a><span class="footer-sep">·</span>- <a id="footer-feedback" href="#" target="_blank" rel="noopener">report issue →</a>+ <a id="footer-feedback" href="https://github.com/rohitg00/agentmemory/issues/new" target="_blank" rel="noopener">report issue →</a>+ <span class="footer-keys"><kbd>/</kbd> search · <kbd>g</kbd> then a letter to jump · <kbd>?</kbd> glossary</span></footer><script nonce="__AGENTMEMORY_VIEWER_NONCE__">@@ -1140,7 +1572,8 @@var NODE_COLORS = {file: '#2D6A4F', function: '#1D4E89', concept: '#B8860B', error: '#CC0000',- decision: '#6B3FA0', pattern: '#2563EB', library: '#C2410C', person: '#111111'+ decision: '#6B3FA0', pattern: '#2563EB', library: '#C2410C', person: '#111111',+ project: '#0E7490', preference: '#BE185D', location: '#4D7C0F', organization: '#475569', event: '#A16207'};var OP_BADGES = {observe: 'badge-blue', compress: 'badge-cyan', remember: 'badge-green',@@ -1154,7 +1587,7 @@var OBS_TYPE_COLORS = {file_read: '#1D4E89', file_write: '#2D6A4F', file_edit: '#B8860B',command_run: '#C2410C', search: '#2563EB', web_fetch: '#6B3FA0',- conversation: '#111111', error: '#CC0000', decision: '#B8860B',+ conversation: '#5b6068', error: '#CC0000', decision: '#B8860B',discovery: '#2D6A4F', subagent: '#6B3FA0', notification: '#0E7490',task: '#1D4E89', other: '#666666'};@@ -1166,29 +1599,142 @@task: '☑', other: '📄'};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', 'health'];+ var TAB_IDS = ['dashboard', 'memories', 'lessons', 'crystals', 'graph', 'sessions', 'actions', 'replay', 'activity', 'profile', 'health', 'audit'];+ var TAB_LABELS = {+ dashboard: 'Overview', memories: 'Memories', lessons: 'Lessons', crystals: 'Crystals', graph: 'Graph',+ sessions: 'Sessions', actions: 'Actions', replay: 'Replay',+ activity: 'Activity', profile: 'Profile', health: 'Health', audit: 'Audit'+ };+ var TAB_SHORTCUTS = {+ o: 'dashboard', m: 'memories', l: 'lessons', c: 'crystals', g: 'graph',+ s: 'sessions', a: 'actions', r: 'replay',+ v: 'activity', p: 'profile', h: 'health', u: 'audit'+ };+ var ENTITY_TABS = { memory: 'memories', session: 'sessions', lesson: 'lessons', action: 'actions', crystal: 'crystals', audit: 'audit', node: 'graph' };var VIEWER_TOKEN_STORAGE_KEY = 'agentmemory-viewer-token';+ var GLOSSARY = {+ observation: { term: 'Observation', text: 'One thing an agent did during a session: a file read or edit, a command, a search, an error, a decision. Hooks capture them automatically.' },+ memory: { term: 'Memory', text: 'A durable fact the agent should keep across sessions, such as an architecture note, a convention or a preference. Saved with memory_save or distilled from observations.' },+ lesson: { term: 'Lesson', text: 'A short rule learned from past work ("always run tsc before commit"). Its confidence grows when the agent re-confirms it and decays when unused.' },+ crystal: { term: 'Crystal', text: 'A compact summary of one finished piece of work: what happened, tools used, files touched and lessons found. Kept after raw observations are pruned.' },+ action: { term: 'Action', text: 'A follow-up the agent tracked: a task, a decision to revisit, something blocked on input. Moves pending, active, done or blocked.' },+ frontier: { term: 'Frontier', text: 'Actions that are unblocked and ready to pick up next. Everything they depend on is done.' },+ session: { term: 'Session', text: 'One run of an agent in a project, from start to end. Observations belong to a session.' },+ sessionStatus: { term: 'Session status', text: 'Active means the agent is still running and sending observations. Completed means the session ended.' },+ project: { term: 'Project', text: 'The working directory an agent ran in. Memories, sessions and lessons are grouped by project.' },+ agent: { term: 'Agent', text: 'Which agent or role wrote a record (for example coder or reviewer). Used to keep multi-agent memories apart.' },+ consolidation: { term: 'Consolidation', text: 'A background step that turns many raw observations into fewer, longer-lived records: semantic facts and procedures. It needs an LLM provider.' },+ semantic: { term: 'Semantic facts', text: 'General facts distilled from many sessions ("the API uses jose for JWT"). Produced by consolidation.' },+ procedural: { term: 'Procedures', text: 'Step-by-step workflows the agent repeated successfully ("to release: bump, tag, publish"). Produced by consolidation from finished sessions with a summary; it stays empty until enough such sessions exist.' },+ decay: { term: 'Decay', text: 'Records that are never used lose strength or confidence over time, so stale knowledge stops crowding out fresh knowledge.' },+ strength: { term: 'Strength', text: 'How important a memory is, from 1 to 10. memory_save and the REST API store 7; consolidation rates each distilled memory itself. Stronger memories go first into the context agents get at session start, and bulk cleanup can target weak ones.' },+ importance: { term: 'Importance', text: 'A 1 to 10 score for how much an observation matters: 1 to 3 low (green), 4 to 6 medium (yellow), 7 to 10 high (red). With an LLM provider the compressor rates each observation; without one every observation gets the default 5. Session-start context uses observations rated 5 or higher, highest first, and old low-rated ones are evicted first.' },+ confidence: { term: 'Confidence', text: 'How battle-tested a lesson is, from 0 to 100%. New lessons start at 50% unless the saver sets it. Each use closes 10% of the gap to 100% (50% becomes 55%). A lesson not used for a week loses 5 points per week, down to 5%; one that falls to 10% without ever being used is dropped. Recall ranks higher-confidence lessons first.' },+ reinforcements: { term: 'Uses', text: 'How many times the lesson was confirmed again: saved again with the same text by any agent, or strengthened with memory_lesson_strengthen. Each use raises confidence and restarts the decay clock.' },+ lessonSources: { term: 'Sources', text: 'The sessions, memories, observations or crystals a lesson was learned from. Crystal and import lessons record them automatically; pass sourceIds to POST /lessons to link a lesson you save by hand.' },+ auditTargets: { term: 'Targets', text: 'The records the change touched. Memory, session, observation, lesson, action, crystal and graph ids open that record; other ids can be copied.' },+ conventions: { term: 'Conventions', text: 'Rules agentmemory infers from the files and concepts above: TypeScript when .ts files outnumber .js, a src/ layout when most files sit under src/, tests when test or spec files appear, and any concept that came up 3 or more times.' },+ frontierReady: { term: 'Ready', text: 'Unblocked and ready to pick up next: every action it depends on is done. memory_frontier returns these first.' },+ version: { term: 'Version', text: 'Saving a near-duplicate of a memory, or editing it here, creates a new version instead of changing it in place. v3 means two earlier versions exist. Only the latest version is searched; older ones stay as history.' },+ provenance: { term: 'Provenance', text: 'Where a memory came from: the sessions and observations it was distilled from. Memories saved directly with memory_save or the REST API have none.' },+ diff: { term: 'Changes', text: 'What changed from the previous version. Struck-through words were removed, highlighted words were added.' },+ supersedes: { term: 'Supersedes', text: 'The older memory this one replaced. The old version is kept for history but no longer returned by search.' },+ origin: { term: 'Origin', text: 'Where a record came from: an agent tool call, an automatic hook, an import or a user action.' },+ bm25: { term: 'Keyword index (BM25)', text: 'The full-text index used for keyword search. It holds observations, memories and lessons, so its document count is usually higher than the observation count.' },+ vector: { term: 'Vector index', text: 'Embeddings used for meaning-based search. It needs an embedding provider; without one, search is keyword only.' },+ observationsIndexed: { term: 'Observations indexed', text: 'Observations that are searchable. The keyword index also contains memories and lessons, which is why its total is larger.' },+ missingFromIndex: { term: 'Missing from index', text: 'Stored observations that are not searchable yet. They are added in the background; a large number that does not shrink means indexing is stuck.' },+ pendingBackfill: { term: 'Pending vector backfill', text: 'Records waiting for an embedding so they can be found by meaning, not only by keywords.' },+ graph: { term: 'Knowledge graph', text: 'Entities (files, functions, concepts, errors, decisions) and the relations between them. When a session ends, the files and concepts in its observations become nodes, and ones that appear in the same observation get a "related to" relation; no LLM is needed for that. With GRAPH_EXTRACTION_ENABLED=true and an LLM provider, an LLM also adds typed entities and relations such as "uses" or "fixes". A structural code graph can be imported with POST /graph/import-graphify.' },+ graphDegree: { term: 'Relations (degree)', text: 'How many relations touch this node. Nodes with more relations are drawn larger and get their labels first.' },+ graphProvenance: { term: 'Where it came from', text: 'The observations that mentioned this entity, the sessions and projects they belong to, and memories distilled from the same observations or naming this entity. Imported code-graph nodes show the import instead.' },+ graphIsolated: { term: 'Unlinked nodes', text: 'Nodes with no relation yet. They sit in the dashed box under the graph until an observation mentions them together with another entity.' },+ graphNode: { term: 'Node', text: 'One entity in the knowledge graph, such as a file, a function, a library or a concept.' },+ graphEdge: { term: 'Edge', text: 'A relation between two entities, such as "uses", "fixes" or "depends on".' },+ circuitBreaker: { term: 'LLM circuit breaker', text: 'Protects against a failing LLM provider. Closed means calls go through normally. Open means too many recent failures, so calls are paused briefly. Half-open means it is testing whether the provider recovered.' },+ functionCalls: { term: 'Function calls', text: 'How many times agentmemory functions (observe, search, remember, summarize and so on) ran since the worker started, with their failure counts.' },+ contextSaved: { term: 'Context saved (estimate)', text: 'A rough estimate of prompt tokens saved by injecting a compact memory context instead of replaying every observation. It assumes about 80 tokens per observation and a 2,000 token budget per session.' },+ heap: { term: 'Heap', text: 'JavaScript memory the worker is using, compared with the limit it may grow to. Warnings only matter when the process is also large overall.' },+ rss: { term: 'RSS', text: 'Total memory the worker process holds from the operating system, including code and buffers.' },+ eventLoop: { term: 'Event loop delay', text: 'How far behind the worker is in handling work. Under 20 ms is healthy; a large value means it is busy or blocked.' },+ uptime: { term: 'Uptime', text: 'How long the agentmemory worker has been running since it last started.' },+ health: { term: 'Health status', text: 'Healthy means everything is normal. Degraded means something needs attention but memory still works. Critical means a core part is failing.' },+ engineConnection: { term: 'Engine connection', text: 'Whether the agentmemory worker is connected to the iii engine that stores its data and runs its functions.' },+ live: { term: 'Live updates', text: 'The viewer keeps one streaming connection open and updates every page the moment data changes. Nothing is refreshed on a timer.' },+ flags: { term: 'Feature flags', text: 'Optional features that are on or off in this install. Off features leave some pages empty; each one lists the setting that turns it on.' },+ audit: { term: 'Audit log', text: 'A record of every change agentmemory made to stored data: saves, deletes, imports, consolidation runs. Use it to see who changed what and when.' },+ workers: { term: 'Workers', text: 'Processes connected to the iii engine. agentmemory runs as one worker.' },+ latency: { term: 'Average latency', text: 'Average time one call of the function took to finish.' },+ failureRate: { term: 'Failure rate', text: 'Share of calls that failed. Functions that need an LLM show as off, not failing, when no LLM provider is set.' },+ replay: { term: 'Replay', text: 'Plays back a past session step by step: prompts, responses and tool calls in the order they happened, with their real timing. Works for any session agentmemory recorded, from any connected agent.' },+ profile: { term: 'Project profile', text: 'What agentmemory has learned about one project: the concepts and files that come up most and the conventions it noticed.' },+ heatmap: { term: 'Activity heatmap', text: 'One square per day. The shade is how many observations the sessions that started that day recorded; darker means more. Only the sessions loaded in this viewer are counted, and the note under the grid says how many that is.' }+ };+var state = {activeTab: 'dashboard',- dashboard: { loaded: false, health: null, sessions: [], memories: [], graphStats: null, recentAudit: [], lessons: [], crystals: [] },- graph: { loaded: false, nodes: [], edges: [], stats: null, filters: {}, selectedNode: null, queryError: null, truncated: false, totalNodes: 0, totalEdges: 0 },- memories: { loaded: false, items: [], search: '', typeFilter: '', selectedId: null },- timeline: { loaded: false, observations: [], sessionId: '', minImportance: 0, page: 0, pageSize: 50 },- sessions: { loaded: false, items: [], selectedId: null },- audit: { loaded: false, entries: [], opFilter: '' },- activity: { loaded: false, observations: [], sessions: [], typeFilter: '' },- lessons: { loaded: false, items: [], search: '', selectedId: null },- 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: {},+ dashboard: { loaded: false },+ graph: { loaded: false, loading: false, dirty: false, nodeMap: {}, edgeMap: {}, degrees: {}, rev: 0, localDegree: null, localDegreeRev: -1, stats: null, hidden: {}, search: '', searchOpen: false, searchIndex: 0, selectedId: null, detail: null, queryError: null, disabledInfo: null, warning: '', truncated: false, totalNodes: 0, totalEdges: 0, requestSeq: 0, fetches: 0, patches: 0, lastPatchAt: 0, fresh: {}, simStale: false, rebuildResult: '' },+ memories: { search: '', typeFilter: '', projectFilter: '', agentFilter: '', selectedId: null, nextCursor: null, loadingMore: false, searchIds: null, searchMode: '', searching: false, query: null, facets: null, checked: {}, editing: null, saving: false, pendingId: null, fetches: {}, diffId: null, error: '' },+ sessions: { selectedId: null, autoSelected: false, closed: false, nextCursor: null, loadingMore: false, filters: { q: '', project: '', agent: '', status: '' }, query: null, facets: null, detail: null, pendingObs: null, notice: null, summarizing: '' },+ audit: { opFilter: '', selectedIdx: null, from: '', to: '', q: '', query: null, loadingMore: false, exhausted: {}, fresh: {} },+ activity: { loaded: false, observations: [], sessionCount: 0, typeFilter: '', fileFilter: '', day: '' },+ lessons: { search: '', selectedId: null, projectFilter: '', notice: null, busy: '' },+ actions: { frontier: [], statusFilter: '', search: '', selectedId: null, notice: null, busy: '' },+ crystals: { search: '', selectedId: null },+ profile: { loaded: false, selectedProject: '', data: null, dataProject: '', userPicked: false, notice: null },+ health: { error: null, checking: false, consolidating: false, reveal: '' },+ replay: { loaded: false, selectedId: '', timeline: null, cursor: 0, playing: false, speed: 1, timer: null, startAt: 0, offsetAt: 0, loadingTimeline: false, loadError: '', importPath: '', importing: false, importOpen: false, importStatus: null },+ flagsOpen: false,+ freshRows: {},ws: null};+ var store = {+ snapshot: null,+ counts: null,+ health: null,+ status: '',+ circuitBreaker: null,+ functionMetrics: [],+ indexes: null,+ flags: [],+ provider: '',+ embeddingProvider: '',+ version: '',+ graph: null,+ consolidation: null,+ consolidationStatus: null,+ report: null,+ entities: { memory: {}, session: {}, lesson: {}, action: {}, crystal: {}, semantic: {}, procedural: {}, audit: {} },+ loaded: {},+ loading: {},+ feed: [],+ snapshotAt: 0,+ lastHealthAt: 0,+ lastEventAt: 0+ };+ var ENTITY_ENDPOINTS = {+ memory: { path: 'memories?latest=true&limit=100&facets=true', key: 'memories' },+ session: { path: 'sessions?limit=100&facets=true', key: 'sessions' },+ lesson: { path: 'lessons', key: 'lessons' },+ action: { path: 'actions', key: 'actions' },+ crystal: { path: 'crystals', key: 'crystals' },+ semantic: { path: 'semantic', key: 'facts', fallbackKey: 'semantic' },+ procedural: { path: 'procedural', key: 'procedures', fallbackKey: 'procedural' },+ audit: { path: 'audit?limit=100', key: 'entries' }+ };+ var bootGateOpen = null;+ var bootGate = new Promise(function(resolve) { bootGateOpen = resolve; });+ function openBootGate() {+ if (bootGateOpen) { bootGateOpen(); bootGateOpen = null; }+ }+ var FEED_MAX = 40;+ var EVENT_LOG_MAX = 500;+ var eventLog = [];+ var eventSeq = 0;+function esc(s) {if (!s) return '';var d = document.createElement('div');@@ -1242,6 +1788,11 @@return s;}+ function humanizeNarrative(n) {+ if (typeof n !== 'string') return '';+ return n.split(' | ').map(function(part) { return humanizeSubtitle(part); }).join(' · ');+ }+function summaryText(v) {if (!v) return '';if (typeof v === 'string') return v;@@ -1291,6 +1842,148 @@var name = sessionDisplayName(s);return id ? name + ' (' + id + ')' : name + ' (missing id)';}+ function sessionPickerLabel(s) {+ var name = sessionDisplayName(s);+ var when = s && s.startedAt ? timeAgo(s.startedAt) : '';+ var prompt = s && (s.firstPrompt || summaryText(s.summary)) ? truncate(String(s.firstPrompt || summaryText(s.summary)).replace(/\s+/g, ' '), 48) : '';+ var parts = [name];+ if (when) parts.push(when);+ parts.push((s && s.observationCount || 0) + ' obs');+ if (prompt) parts.push(prompt);+ return parts.join(' · ');+ }++ function help(key) {+ var g = GLOSSARY[key];+ if (!g) return '';+ return '<button type="button" class="help" data-help="' + key + '" aria-label="What is ' + esc(g.term) + '?">?</button>';+ }+ function copyBtn(text, label) {+ if (text === undefined || text === null || text === '') return '';+ return '<button type="button" class="copy-btn" data-copy="' + esc(String(text)) + '" aria-label="Copy ' + esc(label || 'value') + '" title="Copy ' + esc(label || 'value') + '">copy</button>';+ }+ function shortId(id, n) {+ var s = String(id || '');+ var max = n || 14;+ if (s.length <= max) return s;+ return s.slice(0, Math.max(4, max - 7)) + '…' + s.slice(-6);+ }+ function entityHref(kind, id) {+ var tab = ENTITY_TABS[kind];+ if (!tab || !id) return '';+ return '#' + tab + '/' + encodeURIComponent(String(id));+ }+ function entityLink(kind, id, label) {+ if (!id) return '';+ var href = entityHref(kind, id);+ var text = esc(label || shortId(id));+ if (!href) return '<span class="entity-link" title="' + esc(id) + '">' + text + '</span>';+ return '<a class="entity-link" href="' + href + '" title="Open ' + esc(kind) + ' ' + esc(id) + '">' + text + '</a>';+ }+ function idChip(kind, id) {+ if (!id) return '';+ return '<span class="id-chip">' + entityLink(kind, id) + copyBtn(id, kind + ' id') + '</span>';+ }+ function timeAgo(ts) {+ if (!ts) return '';+ var t = new Date(ts).getTime();+ if (!isFinite(t)) return '';+ var diff = Math.round((Date.now() - t) / 1000);+ if (diff < 0) diff = 0;+ if (diff < 45) return 'just now';+ if (diff < 3600) return Math.round(diff / 60) + 'm ago';+ if (diff < 86400) return Math.round(diff / 3600) + 'h ago';+ if (diff < 86400 * 30) return Math.round(diff / 86400) + 'd ago';+ try { return new Date(ts).toLocaleDateString(); } catch (_) { return ''; }+ }+ function relTime(ts) {+ if (!ts) return '<span class="rel-time">-</span>';+ return '<time class="rel-time" datetime="' + esc(ts) + '" title="' + esc(formatTime(ts)) + '">' + esc(timeAgo(ts)) + '</time>';+ }+ function apiBase() {+ return REST + '/agentmemory';+ }+ function statusSummary(report) {+ var first = String(report.headline || '').split('. ')[0].replace(/\.$/, '');+ var n = (report.problems || []).length;+ return first + (n ? '. ' + n + (n === 1 ? ' note' : ' notes') + ' on the Health page' : '');+ }+ function restPort() {+ return (store.snapshot && store.snapshot.restPort) || 0;+ }+ function agentUrl() {+ var p = restPort();+ return p ? window.location.protocol + '//' + window.location.hostname + ':' + p : REST;+ }+ function customPort() {+ var p = restPort();+ return p && p !== 3111;+ }+ function connectCmd(agent) {+ var cmd = 'npx @agentmemory/agentmemory connect ' + (agent || 'claude-code --with-hooks');+ return customPort() ? 'export AGENTMEMORY_URL=' + agentUrl() + '\n' + cmd : cmd;+ }+ function cmdBlock(cmd) {+ return '<div class="cmd-block"><pre>' + esc(cmd) + '</pre>' + copyBtn(cmd, 'command') + '</div>';+ }+ function emptyState(o) {+ var html = '<div class="empty-state v2' + (o.compact ? ' compact' : '') + '">';+ html += '<div class="empty-head">' + (o.icon ? '<span class="empty-icon" aria-hidden="true">' + o.icon + '</span>' : '') + '<div class="empty-title">' + esc(o.title) + '</div></div>';+ html += '<dl class="empty-grid">';+ if (o.what) html += '<div><dt>What this is</dt><dd>' + o.what + '</dd></div>';+ if (o.why) html += '<div><dt>Why it is empty</dt><dd>' + o.why + '</dd></div>';+ html += '</dl>';+ if (o.steps && o.steps.length) {+ html += '<div class="empty-steps"><div class="empty-steps-title">How to fill it</div>';+ o.steps.forEach(function(step) {+ html += '<div class="empty-step">' + (step.label ? '<div class="empty-step-label">' + step.label + '</div>' : '') + (step.cmd ? cmdBlock(step.cmd) : '') + '</div>';+ });+ html += '</div>';+ }+ if (o.link) html += '<a class="empty-link" href="' + esc(o.link.href) + '" target="_blank" rel="noopener">' + esc(o.link.text) + ' →</a>';+ html += '</div>';+ return html;+ }+ function usageCard(kind) {+ var cards = {+ memory: { title: 'Use memories from an agent or a terminal', steps: [+ ['Recall the memories relevant to a task:', 'memory_recall { "query": "how is auth handled" }'],+ ['Search by meaning and keyword together:', 'memory_smart_search { "query": "checkout totals" }'],+ ['Save a new memory from a terminal:', curlPost('remember', { content: 'Coupons apply before shipping thresholds', type: 'bug' })]+ ] },+ lesson: { title: 'Use lessons from an agent or a terminal', steps: [+ ['Recall the lessons that match a task:', 'memory_lesson_recall { "query": "deploy" }'],+ ['Save a lesson when you correct the agent:', 'memory_lesson_save { "content": "Run tsc before committing", "context": "CI failed on types" }'],+ ['Search lessons from a terminal:', curlPost('lessons/search', { query: 'deploy' })]+ ] },+ action: { title: 'Work with actions from an agent or a terminal', steps: [+ ['Ask for the next unblocked actions:', 'memory_frontier { "limit": 5 }'],+ ['Mark an action done:', 'memory_action_update { "actionId": "act_...", "status": "done" }'],+ ['List every action from a terminal:', curlGet('actions')]+ ] }+ };+ var c = cards[kind];+ if (!c) return '';+ var html = '<div class="card usage-card" style="margin-top:16px;"><div class="card-title">' + esc(c.title) + '</div><div class="usage-grid">';+ c.steps.forEach(function(st) {+ html += '<div><div class="empty-step-label">' + esc(st[0]) + '</div>' + cmdBlock(st[1]) + '</div>';+ });+ return html + '</div></div>';+ }++ function skeleton(rows) {+ var html = '<div class="skeleton" aria-busy="true" aria-label="Loading">';+ for (var i = 0; i < (rows || 6); i++) {+ html += '<div class="skeleton-row' + (i % 3 === 1 ? ' mid' : i % 3 === 2 ? ' short' : '') + '"></div>';+ }+ return html + '</div>';+ }+ function curlPost(path, body) {+ return 'curl -X POST ' + apiBase() + '/' + path + " \\\n -H 'Content-Type: application/json' \\\n -d '" + JSON.stringify(body) + "'";+ }+ function curlGet(path) {+ return 'curl ' + apiBase() + '/' + path;+ }function debounce(fn, ms) {var t;return function() {@@ -1415,21 +2108,43 @@});}+ var TAB_ALIASES = { timeline: 'sessions' };+function normalizeTab(tab) {var normalized = String(tab || '').replace(/^#/, '').toLowerCase();+ if (TAB_ALIASES[normalized]) normalized = TAB_ALIASES[normalized];return TAB_IDS.indexOf(normalized) >= 0 ? normalized : 'dashboard';}- function tabFromRoute() {- try {- return normalizeTab(decodeURIComponent(window.location.hash.slice(1)));- } catch (_) {- return 'dashboard';+ function decodePart(part) {+ try { return part ? decodeURIComponent(part) : ''; } catch (_) { return part; }+ }++ function parseRoute(hash) {+ var raw = String(hash || '').replace(/^#/, '');+ var slash = raw.indexOf('/');+ var tabPart = slash >= 0 ? raw.slice(0, slash) : raw;+ var idPart = slash >= 0 ? raw.slice(slash + 1) : '';+ var query = '';+ var qm = idPart.indexOf('?');+ if (qm >= 0) {+ query = idPart.slice(qm + 1);+ idPart = idPart.slice(0, qm);}+ var obs = '';+ query.split('&').forEach(function(pair) {+ if (pair.indexOf('obs=') === 0) obs = decodePart(pair.slice(4));+ });+ var alias = !!TAB_ALIASES[tabPart.toLowerCase()];+ return { tab: normalizeTab(tabPart), id: decodePart(idPart), obs: obs, redirect: alias };+ }++ function tabFromRoute() {+ return parseRoute(window.location.hash).tab;}- function updateTabRoute(tab, replace) {- var target = '#' + tab;+ function updateTabRoute(tab, replace, id) {+ var target = '#' + tab + (id ? '/' + encodeURIComponent(id) : '');if (window.location.hash === target) return;if (replace) {history.replaceState(null, '', target);@@ -1438,86 +2153,143 @@}}+ function setRouteEntity(tab, id) {+ if (state.activeTab !== tab) return;+ updateTabRoute(tab, true, id || '');+ }++ function applyRouteEntity(tab, id, obs) {+ if (!id) return;+ if (tab === 'memories') state.memories.selectedId = id;+ else if (tab === 'lessons') state.lessons.selectedId = id;+ else if (tab === 'actions') state.actions.selectedId = id;+ else if (tab === 'crystals') state.crystals.selectedId = id;+ else if (tab === 'audit') state.audit.selectedIdx = id;+ else if (tab === 'health') state.health.reveal = id;+ else if (tab === 'graph') {+ if (state.graph.loaded && graphSim.canvas) selectGraphNode(id, { fromRoute: true, keepRoute: true });+ else state.graph.selectedId = id;+ }+ else if (tab === 'sessions') {+ state.sessions.selectedId = id;+ state.sessions.autoSelected = false;+ state.sessions.closed = false;+ if (obs) focusSessionObservation(id, obs);+ }+ }+function switchTab(tab, opts) {opts = opts || {};tab = normalizeTab(tab);if (state.activeTab === 'replay' && tab !== 'replay' && typeof stopReplayTimer === 'function') {stopReplayTimer();}+ applyRouteEntity(tab, opts.id, opts.obs);if (!opts.skipRoute) {- updateTabRoute(tab, !!opts.replaceRoute);+ updateTabRoute(tab, !!opts.replaceRoute, opts.id);}state.activeTab = tab;- document.querySelectorAll('.tab-bar button').forEach(function(b) {+ document.querySelectorAll('.tab-bar button[data-tab]').forEach(function(b) {var isActive = b.dataset.tab === tab;b.classList.toggle('active', isActive);- if (isActive) {- b.setAttribute('aria-current', 'page');- } else {- b.removeAttribute('aria-current');- }+ b.setAttribute('aria-selected', isActive ? 'true' : 'false');+ b.tabIndex = isActive ? 0 : -1;});document.querySelectorAll('.view').forEach(function(v) {v.classList.toggle('active', v.id === 'view-' + tab);});- if (state.flagsConfig) renderFlagBanners(state.flagsConfig);- loadTab(tab);+ var current = document.getElementById('nav-current');+ if (current) current.textContent = TAB_LABELS[tab] || tab;+ closeNav();+ hideHelpPop();+ showTab(tab, opts);+ }++ var tabRendered = {};+ var tabDirty = {};++ function renderTab(tab) {+ switch (tab) {+ case 'dashboard': renderDashboard(); break;+ case 'memories': renderMemories(); break;+ case 'lessons': renderLessons(); break;+ case 'crystals': renderCrystals(); break;+ case 'actions': renderActions(); break;+ case 'audit': renderAudit(); break;+ case 'sessions': renderSessions(); break;+ case 'health': renderHealth(); break;+ case 'profile': renderProfilePage(); break;+ case 'activity': if (state.activity.loaded) renderActivity(); break;+ case 'graph': renderGraphView(); break;+ case 'replay': if (state.replay.loaded) renderReplay(); break;+ }+ tabRendered[tab] = true;+ tabDirty[tab] = false;+ }++ function tabNeeds(tab) {+ switch (tab) {+ case 'dashboard': return ['session', 'audit', 'semantic', 'procedural'];+ case 'memories': return ['memory'];+ case 'lessons': return ['lesson', 'session'];+ case 'crystals': return ['crystal', 'lesson'];+ case 'actions': return ['action'];+ case 'audit': return ['audit', 'lesson', 'action'];+ case 'sessions': return ['session'];+ case 'profile': return ['session', 'lesson', 'memory'];+ case 'activity': return ['session'];+ case 'replay': return ['session'];+ default: return [];+ }+ }++ async function showTab(tab, opts) {+ opts = opts || {};+ var needs = tabNeeds(tab);+ var missing = needs.filter(function(kind) { return !store.loaded[kind]; });+ if (!tabRendered[tab] || tabDirty[tab] || missing.length === 0) renderTab(tab);+ if (missing.length > 0) {+ await Promise.all(missing.map(ensureLoaded));+ if (state.activeTab === tab) renderTab(tab);+ }+ if (tab === 'dashboard') ensureConsolidationStatus();+ if (tab === 'actions') ensureFrontier();+ if (tab === 'graph') {+ if (!state.graph.loaded && !state.graph.loading) await loadGraph();+ else if (state.graph.dirty) scheduleGraphReload();+ else if (state.graph.simStale) { syncGraphSim(false); requestGraphDraw(); }+ }+ if (tab === 'profile') ensureProfileData();+ if (tab === 'activity' && !state.activity.loaded) await loadActivity();+ if (tab === 'replay' && !state.replay.loaded) await loadReplay();+ if (opts.id) revealRouteEntity(tab, opts.id);}- // Per-tab freshness stamps. Tabs refetch on entry (the loaded-once- // model went stale the moment anything wrote through the API), but a- // short window stops rapid tab flipping from re-issuing the full- // fan-out (dashboard alone is ~10 requests) on every click.- var tabFetchedAt = {};- var TAB_FRESH_MS = 5000;-- async function loadTab(tab) {- var now = Date.now();- if (tab !== 'replay' && tabFetchedAt[tab] && now - tabFetchedAt[tab] < TAB_FRESH_MS) {- return;+ function revealRouteEntity(tab, id) {+ var sel = null;+ if (tab === 'memories') sel = '[data-memory-id="' + cssEscape(id) + '"]';+ else if (tab === 'sessions') {+ if (state.sessions.detail && state.sessions.detail.focusObs) return;+ sel = window.matchMedia('(max-width: 1100px)').matches ? '#session-detail' : '#session-list [data-session-id="' + cssEscape(id) + '"]';}- tabFetchedAt[tab] = now;- switch(tab) {- case 'dashboard': await loadDashboard(); break;- case 'graph': await loadGraph(); break;- case 'memories': await loadMemories(); break;- case 'timeline': await loadTimeline(); break;- case 'sessions': await loadSessions(); break;- case 'lessons': await loadLessons(); break;- case 'actions': await loadActions(); break;- case 'crystals': await loadCrystals(); break;- 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.- case 'replay': if (!state.replay.loaded) await loadReplay(); break;- }- }-- var dashboardLoading = false;- var dashboardReloadPending = false;- var dashboardReloadTimer = null;- var DASHBOARD_RELOAD_COALESCE_MS = 2000;-- function scheduleDashboardReload() {- if (dashboardReloadTimer) return;- dashboardReloadTimer = setTimeout(function() {- dashboardReloadTimer = null;- if (state.activeTab === 'dashboard') loadDashboard();- }, DASHBOARD_RELOAD_COALESCE_MS);- }-- var STALE_RETRY_MS = 15000;- var staleRetryTimer = null;- function scheduleStaleRetry() {- if (staleRetryTimer) return;- staleRetryTimer = setTimeout(function() {- staleRetryTimer = null;- if (state.activeTab === 'dashboard' && state.dashboard.stale) loadDashboard();- }, STALE_RETRY_MS);+ else if (tab === 'lessons') sel = window.matchMedia('(max-width: 1100px)').matches ? '#lesson-detail' : '[data-lesson-id="' + cssEscape(id) + '"]';+ else if (tab === 'actions') sel = window.matchMedia('(max-width: 1100px)').matches ? '#action-detail' : '[data-action-id="' + cssEscape(id) + '"]';+ else if (tab === 'crystals') sel = '[data-crystal-id="' + cssEscape(id) + '"]';+ else if (tab === 'audit') sel = '[data-audit-row="' + cssEscape(id) + '"]';+ else if (tab === 'health') sel = '#health-' + cssEscape(id);+ if (!sel) return;+ var el = document.querySelector('#view-' + tab + ' ' + sel);+ if (el && el.scrollIntoView) el.scrollIntoView({ block: sel.charAt(0) === '#' ? 'start' : 'center' });+ if (tab === 'memories' && !el) renderMemories();+ }++ function cssEscape(s) {+ return String(s).replace(/["\\]/g, '\\$&');+ }++ function markDirty(tabs) {+ tabs.forEach(function(t) { tabDirty[t] = true; });+ if (tabs.indexOf(state.activeTab) >= 0) scheduleLiveRender();}function listOr(previous, result, key, fallbackKey) {@@ -1525,81 +2297,132 @@return result[key] || (fallbackKey && result[fallbackKey]) || [];}- async function loadDashboard() {- if (dashboardLoading) {- dashboardReloadPending = true;- return;- }- dashboardLoading = true;- var el = document.getElementById('view-dashboard');- var d = state.dashboard;- if (!d.loaded) el.innerHTML = '<div class="loading">Loading dashboard...</div>';- var seqAtStart = liveSessionSeq;- var countToken = ++memoryCountRequest;- try {- var results = await Promise.all([- api('health', { readErrorBody: true }),- apiGet('sessions'),- apiGet('memories?latest=true&count=true'),- apiGet('graph/stats'),- apiGet('audit?limit=5'),- apiGet('semantic'),- apiGet('procedural'),- apiGet('relations'),- apiGet('lessons'),- apiGet('crystals'),- apiGet('consolidation/status')- ]);- var sessionsOk = !!(results[1] && Array.isArray(results[1].sessions));- if (!sessionsOk && !d.loaded) {- el.innerHTML =- '<div class="loading" style="color:var(--accent);">Could not reach the agentmemory API. ' +- 'The server may be restarting.<br><br>' +- '<button class="btn btn-primary" data-action="refresh-dashboard">Retry</button></div>';- return;+ function entityList(kind) {+ var bucket = store.entities[kind] || {};+ return Object.keys(bucket).map(function(k) { return bucket[k]; });+ }++ function sortByTimeDesc(list, keys) {+ function ts(item) {+ for (var i = 0; i < keys.length; i++) {+ if (item && item[keys[i]]) return String(item[keys[i]]);}- d.stale = results.some(function(r) { return r === null; });- if (d.stale) scheduleStaleRetry();- if (results[0]) d.health = results[0];- if (sessionsOk) d.sessions = replaySessionEvents(results[1].sessions, seqAtStart);- if (countToken === memoryCountRequest && results[2] && typeof results[2].total === 'number') {- d.memoryTotal = results[2].total;+ return '';+ }+ return list.slice().sort(function(a, b) { return ts(b).localeCompare(ts(a)); });+ }++ function replaceBucket(kind, rows) {+ var bucket = {};+ (rows || []).forEach(function(row) {+ var id = entityKey(kind, row);+ if (id) bucket[id] = row;+ });+ store.entities[kind] = bucket;+ }++ async function ensureLoaded(kind) {+ if (store.loaded[kind]) return;+ if (store.loading[kind]) return store.loading[kind];+ var spec = ENTITY_ENDPOINTS[kind];+ if (!spec) return;+ store.loading[kind] = (async function() {+ try {+ await bootGate;+ var seqAtStart = eventSeq;+ var result = await apiGet(spec.path);+ if (result === null) return;+ replaceBucket(kind, listOr([], result, spec.key, spec.fallbackKey));+ if (kind === 'memory') {+ state.memories.nextCursor = result.nextCursor || null;+ state.memories.facets = result.facets || null;+ state.memories.fetches = {};+ if (memoryFiltersActive() || state.memories.searchIds) setTimeout(applyMemoryFilters, 0);+ }+ if (kind === 'session') {+ state.sessions.nextCursor = result.nextCursor || null;+ state.sessions.facets = result.facets || null;+ }+ if (kind === 'audit') {+ state.audit.exhausted = {};+ if ((result[spec.key] || []).length < 100) state.audit.exhausted['|||'] = true;+ seedFeedFromAudit();+ }+ replayEventsSince(seqAtStart, kind);+ store.loaded[kind] = true;+ } finally {+ store.loading[kind] = null;}- if (results[3]) d.graphStats = results[3];- d.recentAudit = listOr(d.recentAudit, results[4], 'entries');- d.semantic = listOr(d.semantic, results[5], 'facts', 'semantic');- d.procedural = listOr(d.procedural, results[6], 'procedures', 'procedural');- d.relations = listOr(d.relations, results[7], 'relations');- d.lessons = listOr(d.lessons, results[8], 'lessons');- d.crystals = listOr(d.crystals, results[9], 'crystals');- if (results[10] && results[10].tiers) d.consolidation = results[10];- d.loaded = true;- renderDashboard();- } catch (err) {- // Without this catch, any uncaught error in the await Promise.all- // or the renderDashboard call leaves the dashboard stuck on- // "Loading dashboard..." forever with no indication to the user- // (#323). apiGet() already swallows network/HTTP errors and- // returns null, but renderDashboard can still throw on shape- // surprises (CSP-blocked event handler binding, undefined fields).- // Surface the error in the panel + log full detail to console.- var msg = (err && err.message) ? err.message : String(err);- console.error('[viewer] loadDashboard failed:', err);- el.innerHTML =- '<div class="loading" style="color:var(--accent);">' +- 'Dashboard failed to load: ' + msg +- '<br><br><span style="font-size:12px;color:var(--ink-muted);">' +- 'Check the browser console for the full error. If you see CSP ' +- 'violations, please open an issue with the agentmemory version ' +- '(top-right of the viewer) and the violation text.' +- '</span></div>';- } finally {- dashboardLoading = false;- if (dashboardReloadPending) {- dashboardReloadPending = false;- scheduleDashboardReload();+ })();+ return store.loading[kind];+ }++ function replayEventsSince(seq, onlyKind) {+ eventLog.forEach(function(entry) {+ if (entry.seq <= seq) return;+ if (onlyKind && entry.kind !== onlyKind) return;+ reduceLiveEvent(store, entry.type, entry.data);+ });+ }++ async function loadSnapshot() {+ var snap = await apiGet('viewer/snapshot');+ if (!snap) return false;+ var graphBefore = store.graph && store.graph.updatedAt;+ var reconnect = !!store.snapshotAt;+ applySnapshot(store, snap);+ renderFlagsChip();+ renderFlagsPanel();+ updateCountBadges();+ updateFooter();+ markDirty(['dashboard', 'health', 'graph']);+ if (reconnect && state.graph.loaded && (!store.graph || store.graph.updatedAt !== graphBefore)) scheduleGraphReload();+ if (!tabRendered[state.activeTab] || state.activeTab === 'dashboard' || state.activeTab === 'health') renderTab(state.activeTab);+ return true;+ }++ function applySnapshot(s, snap) {+ s.snapshot = snap;+ s.version = snap.version || s.version;+ s.provider = snap.provider || '';+ s.embeddingProvider = snap.embeddingProvider || '';+ s.flags = Array.isArray(snap.flags) ? snap.flags : [];+ s.graph = snap.graph || null;+ s.consolidation = snap.consolidation || null;+ if (snap.consolidation && snap.consolidation.status) s.consolidationStatus = snap.consolidation.status;+ s.report = snap.report || s.report;+ s.status = snap.status || '';+ s.health = snap.health || null;+ s.circuitBreaker = snap.circuitBreaker || null;+ s.functionMetrics = Array.isArray(snap.functionMetrics) ? snap.functionMetrics : [];+ s.counts = snap.counts || s.counts;+ s.indexes = snap.indexes || null;+ s.snapshotAt = Date.now();+ s.lastHealthAt = Date.now();+ }++ var consolidationStatusRequest = null;+ function ensureConsolidationStatus(force) {+ if (!force && (store.consolidationStatus || consolidationStatusRequest)) return;+ consolidationStatusRequest = apiGet('consolidation/status').then(function(res) {+ consolidationStatusRequest = null;+ if (res && res.tiers) {+ store.consolidationStatus = res;+ markDirty(['dashboard']);}- }+ });+ }++ var frontierRequest = null;+ var frontierStale = true;+ function ensureFrontier() {+ if (!frontierStale || frontierRequest) return;+ frontierStale = false;+ frontierRequest = apiGet('frontier').then(function(res) {+ frontierRequest = null;+ if (res) state.actions.frontier = res.frontier || res.actions || [];+ markDirty(['actions']);+ });}function estimateTokenSavings(sessions, tokenBudget) {@@ -1634,16 +2457,16 @@}function renderMemoryLayers(status, semFacts, procItems) {- var html = '<div class="card" style="margin-top:16px;"><div class="card-title">Memory layers';+ var html = '<div class="card" style="margin-top:0;"><div class="card-title">Memory layers ' + help('consolidation');if (status && status.lastRunAt) {- html += '<span style="float:right;font-size:10px;color:var(--ink-faint);font-family:var(--font-mono);">consolidated ' + esc(formatTime(status.lastRunAt)) + '</span>';+ html += '<span style="float:right;font-size:10px;color:var(--ink-faint);font-family:var(--font-mono);text-transform:none;letter-spacing:0;">consolidated ' + esc(formatTime(status.lastRunAt)) + '</span>';}html += '</div>';if (!status || !status.tiers) {- html += '<div style="font-size:13px;color:var(--ink-faint);">Consolidation status did not load. Semantic facts: ' + semFacts.length + ', procedures: ' + procItems.length + '.</div></div>';+ html += skeleton(4) + '</div>';return html;}- html += '<div style="font-size:12px;color:var(--ink-muted);margin-bottom:8px;line-height:1.5;">Raw observations stay searchable as they are. Consolidation turns them into these longer-lived layers.</div>';+ html += '<div style="font-size:12px;color:var(--ink-muted);margin-bottom:8px;line-height:1.5;">Raw observations stay searchable as they are. Consolidation ' + help('consolidation') + ' turns them into longer-lived layers: semantic facts ' + help('semantic') + ' and procedures ' + help('procedural') + '. Each layer below says why it is empty or what it is waiting for. <a class="empty-link" href="#health/consolidation">How consolidation works, its schedule and last run →</a></div>';status.tiers.forEach(function(t) {html += '<div class="layer-row">' +'<div class="layer-head"><span class="layer-name">' + esc(t.label) + '</span>' +@@ -1658,2367 +2481,5101 @@return html;}+ function statCard(o) {+ var attrs = o.tab ? ' data-action="goto-tab" data-tab="' + o.tab + '" role="link" tabindex="0"' : '';+ return '<div class="stat-card"' + attrs + '>' ++ '<div class="label">' + esc(o.label) + (o.help ? help(o.help) : '') + '</div>' ++ '<div class="value">' + o.value + '</div>' ++ '<div class="sub">' + (o.sub || ' ') + '</div>' ++ '</div>';+ }++ function fmtNum(n) {+ if (n === null || n === undefined || !isFinite(n)) return '-';+ return Number(n).toLocaleString();+ }++ function mb(bytes) {+ return Math.round((bytes || 0) / 1024 / 1024);+ }++ function formatUptime(seconds) {+ if (!seconds && seconds !== 0) return '-';+ var mins = Math.floor(seconds / 60);+ var hrs = Math.floor(mins / 60);+ if (hrs >= 48) return Math.floor(hrs / 24) + 'd';+ return hrs > 0 ? hrs + 'h ' + (mins % 60) + 'm' : mins + 'm';+ }++ function healthDotClass(status) {+ return status === 'healthy' ? 'healthy' : status === 'degraded' ? 'degraded' : status === 'critical' ? 'critical' : '';+ }+function renderDashboard() {var el = document.getElementById('view-dashboard');- var d = state.dashboard;- var h = d.health || {};- var snap = h.health || {};- var healthStatus = h.status || 'unknown';- 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.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 || [];-+ if (!store.snapshot) {+ setViewHtml(el, '<div class="section-head"><h2>Connecting to agentmemory</h2></div>' + skeleton(8));+ return;+ }+ var c = store.counts || {};+ var snap = store.health || {};+ var healthStatus = store.status || snap.status || 'unknown';+ var cb = store.circuitBreaker;+ var fMetrics = store.functionMetrics || [];+ var idx = store.indexes || {};+ var sessions = sortByTimeDesc(entityList('session'), ['startedAt']);var html = '';- // First-run hero: empty dashboard = guided next step- if (d.sessions.length === 0) {- html += '<div class="card" style="margin-bottom:14px;padding:24px 28px;background:var(--bg-subtle);border-left:3px solid var(--accent);">' +- '<div style="font-family:var(--font-ui);font-size:11px;letter-spacing:0.15em;text-transform:uppercase;color:var(--accent);font-weight:700;margin-bottom:8px;">First run → magical moment in 10 seconds</div>' +- '<div style="font-family:var(--font-display,Lora,Georgia,serif);font-size:22px;font-weight:700;color:var(--ink);margin-bottom:8px;">Seed sample data + prove semantic recall works</div>' +- '<div style="font-size:13px;color:var(--ink-muted);margin-bottom:12px;line-height:1.5;max-width:640px;">agentmemory is running but hasn’t seen any sessions yet. Run the demo command in a second terminal: it seeds 3 realistic coding sessions and proves the hybrid search finds semantically-related memories that keyword search would miss.</div>' +- '<pre style="display:inline-block;margin:0;padding:10px 14px;background:var(--bg);border:1px solid var(--border);border-radius:4px;font-family:var(--font-mono);font-size:12px;color:var(--ink);">npx @agentmemory/agentmemory demo</pre>' +- '<div style="margin-top:10px;"><a class="empty-link" href="https://github.com/rohitg00/agentmemory#quick-start" target="_blank" rel="noopener" style="font-size:12px;">Or: wire up your real agent →</a></div>' +- '</div>';- }- if (d.stale) {- html += '<div class="card" style="margin-bottom:14px;padding:10px 16px;font-size:12px;color:var(--ink-muted);border-left:3px solid var(--yellow);">' +- 'Some panels could not refresh; showing the last data that loaded. Retrying automatically.</div>';- }- html += '<div class="stats-grid">';- html += '<div class="stat-card" data-action="goto-tab" data-tab="sessions" role="link" tabindex="0"><div class="label">Sessions</div><div class="value">' + d.sessions.length + '</div><div class="sub">' + activeSessions + ' active</div></div>';- html += '<div class="stat-card" data-action="goto-tab" data-tab="memories" role="link" tabindex="0"><div class="label">Memories</div><div class="value">' + (d.memoryTotal || 0) + '</div><div class="sub">latest versions</div></div>';- var lessonCount = (d.lessons || []).length;- var crystalCount = (d.crystals || []).length;- html += '<div class="stat-card" data-action="goto-tab" data-tab="lessons" role="link" tabindex="0"><div class="label">Lessons</div><div class="value">' + lessonCount + '</div><div class="sub">confidence-scored</div></div>';- html += '<div class="stat-card" data-action="goto-tab" data-tab="crystals" role="link" tabindex="0"><div class="label">Crystals</div><div class="value">' + crystalCount + '</div><div class="sub">action digests</div></div>';- html += '<div class="stat-card" data-action="goto-tab" data-tab="graph" role="link" tabindex="0"><div class="label">Graph Nodes</div><div class="value">' + nodeCount + '</div><div class="sub">' + edgeCount + ' edges' + (gs.fromSnapshot && gs.updatedAt ? ' · snapshot ' + esc(shortTime(gs.updatedAt)) : '') + '</div></div>';- html += '<div class="stat-card"><div class="label">Health</div><div class="value"><div class="health-bar"><span class="health-dot ' + dotClass + '"></span> ' + esc(healthStatus) + '</div></div>';- html += '<div class="sub">' + esc(snap.connectionState || 'unknown') + '</div></div>';- var totalCalls = fMetrics.reduce(function(a, m) { return a + (m.totalCalls || 0); }, 0);- html += '<div class="stat-card"><div class="label">Function Calls</div><div class="value">' + totalCalls + '</div><div class="sub">' + fMetrics.length + ' functions tracked</div></div>';- if (cb) {- var cbClass = cb.state === 'closed' ? 'cb-closed' : cb.state === 'open' ? 'cb-open' : 'cb-half-open';- html += '<div class="stat-card"><div class="label">Circuit Breaker</div><div class="value"><span class="cb-indicator ' + cbClass + '">' + esc(cb.state) + '</span></div>';- html += '<div class="sub">' + (cb.failures || 0) + ' failures</div></div>';- }- var tokenBudget = parseInt(new URLSearchParams(window.location.search).get('tokenBudget') || '2000', 10) || 2000;- var tokenEstimate = estimateTokenSavings(d.sessions, tokenBudget);- var savings = tokenEstimate.percent;- var tokensSaved = tokenEstimate.saved;- // Rate: $0.30 per 1K tokens (mid-tier model baseline)- var costDollars = tokensSaved / 1000 * 0.3;- var costCents = Math.round(costDollars * 100);- var costStr = costCents >= 100 ? '$' + (costCents / 100).toFixed(2) : costCents + 'ct';- html += '<div class="stat-card"><div class="label">Token Savings</div><div class="value">' + savings + '%</div><div class="sub">~' + tokensSaved.toLocaleString() + ' tokens · ' + costStr + ' saved</div></div>';- html += '</div>';- if (snap.memory || snap.cpu) {- html += '<div class="card" style="margin-bottom:16px"><div class="card-title">System Resources</div>';- if (snap.memory) {- var heapUsed = Math.round((snap.memory.heapUsed || 0) / 1024 / 1024);- var heapLimit = Math.round((snap.memory.heapLimit || snap.memory.heapTotal || 0) / 1024 / 1024);- var rss = Math.round((snap.memory.rss || 0) / 1024 / 1024);- var heapPct = heapLimit > 0 ? Math.round((heapUsed / heapLimit) * 100) : 0;- var rssAboveFloor = rss >= 512;- var heapColor = (heapPct > 80 && rssAboveFloor) ? 'var(--red)' : (heapPct > 60 && rssAboveFloor) ? 'var(--yellow)' : 'var(--green)';- html += '<div class="gauge"><span class="gauge-label">Heap</span><div class="gauge-bar"><div class="gauge-fill" style="width:' + heapPct + '%;background:' + heapColor + '"></div></div><span class="gauge-value">' + heapUsed + ' / ' + heapLimit + ' MB</span></div>';- html += '<div class="gauge"><span class="gauge-label">RSS</span><div class="gauge-bar"><div class="gauge-fill" style="width:' + Math.min(100, Math.round(rss / 512 * 100)) + '%;background:var(--blue)"></div></div><span class="gauge-value">' + rss + ' MB</span></div>';- if (snap.memory.external) {- var ext = Math.round(snap.memory.external / 1024 / 1024);- html += '<div class="gauge"><span class="gauge-label">External</span><div class="gauge-bar"><div class="gauge-fill" style="width:' + Math.min(100, Math.round(ext / 128 * 100)) + '%;background:var(--purple)"></div></div><span class="gauge-value">' + ext + ' MB</span></div>';- }- }- if (snap.cpu) {- var cpuPct = snap.cpu.percent || 0;- var cpuColor = cpuPct > 80 ? 'var(--red)' : cpuPct > 50 ? 'var(--yellow)' : 'var(--green)';- html += '<div class="gauge"><span class="gauge-label">CPU</span><div class="gauge-bar"><div class="gauge-fill" style="width:' + Math.min(100, cpuPct) + '%;background:' + cpuColor + '"></div></div><span class="gauge-value">' + cpuPct.toFixed(1) + '%</span></div>';- }- if (snap.eventLoopLagMs !== undefined) {- var lag = snap.eventLoopLagMs;- var lagColor = lag > 100 ? 'var(--red)' : lag > 20 ? 'var(--yellow)' : 'var(--green)';- html += '<div class="gauge"><span class="gauge-label">Event Loop</span><div class="gauge-bar"><div class="gauge-fill" style="width:' + Math.min(100, lag) + '%;background:' + lagColor + '"></div></div><span class="gauge-value">' + lag.toFixed(1) + ' ms</span></div>';- }- if (snap.uptimeSeconds) {- var mins = Math.floor(snap.uptimeSeconds / 60);- var hrs = Math.floor(mins / 60);- var upStr = hrs > 0 ? hrs + 'h ' + (mins % 60) + 'm' : mins + 'm';- html += '<div style="font-size:10px;color:var(--ink-faint);margin-top:6px;font-family:var(--font-mono);letter-spacing:0.04em;">UPTIME: ' + upStr + '</div>';- }- html += '</div>';+ if ((c.sessions || 0) === 0 && (c.memories || 0) === 0) {+ html += '<div class="card" style="margin-bottom:14px;padding:20px 24px;background:var(--bg-subtle);border-left:3px solid var(--accent);">' ++ '<div style="font-family:var(--font-ui);font-size:11px;letter-spacing:0.15em;text-transform:uppercase;color:var(--accent);font-weight:700;margin-bottom:6px;">First run</div>' ++ '<div style="font-family:var(--font-display);font-size:20px;font-weight:700;color:var(--ink);margin-bottom:6px;">agentmemory is running and waiting for its first session</div>' ++ '<div style="font-size:13px;color:var(--ink-muted);margin-bottom:10px;line-height:1.5;max-width:760px;">This server is listening at <code>' + esc(agentUrl()) + '</code>. Every page fills in live, without a reload, as soon as an agent with agentmemory hooks runs.</div>' ++ '<div class="first-run-steps">' ++ '<div><div class="empty-steps-title">1 · Connect your agent</div><div class="empty-step-label">Wires hooks and the MCP server into Claude Code (or pick codex, cursor, gemini-cli and others from the list when you drop the name)' + (customPort() ? '. This server is not on the default port 3111, so export its URL in the shell you start the agent from' : '') + ':</div>' + cmdBlock(connectCmd()) + '</div>' ++ '<div><div class="empty-steps-title">2 · Start a session</div><div class="empty-step-label">Open your agent in a project and ask it anything. Sessions, observations and memories appear here as they are written.</div></div>' ++ '<div><div class="empty-steps-title">Or try it with sample data</div><div class="empty-step-label">Seeds three sample coding sessions and runs a search demo against this server:</div>' + cmdBlock('npx @agentmemory/agentmemory demo' + (customPort() ? ' --port ' + restPort() : '')) + '</div>' ++ '</div>' ++ '<div style="margin-top:8px;"><a class="empty-link" href="https://github.com/rohitg00/agentmemory#quick-start" target="_blank" rel="noopener" style="font-size:12px;">Supported agents and manual setup →</a></div>' ++ '</div>';}if (snap.alerts && snap.alerts.length > 0) {- html += '<div class="card" style="margin-bottom:16px;border-color:var(--accent);border-width:2px;"><div class="card-title" style="color:var(--accent);border-bottom-color:var(--accent);">Alerts (' + snap.alerts.length + ')</div>';- snap.alerts.forEach(function(alRaw) {- var al = humanizeHealthFlag(alRaw);- html += '<div style="font-size:12px;color:var(--accent);padding:4px 0;border-bottom:1px solid var(--border-light);font-family:var(--font-ui);">' + esc(al) + '</div>';+ html += '<div class="card" style="margin-bottom:14px;border-color:var(--accent);border-width:2px;padding:12px 16px;"><div class="card-title" style="color:var(--accent);border-bottom-color:var(--accent);margin-bottom:6px;">Needs attention (' + snap.alerts.length + ')</div>';+ snap.alerts.forEach(function(al) {+ html += '<div style="font-size:12px;color:var(--accent);padding:3px 0;font-family:var(--font-ui);">' + esc(humanizeHealthFlag(al)) + '</div>';});html += '</div>';}- if (snap.notes && snap.notes.length > 0) {- html += '<div class="card" style="margin-bottom:16px;"><div class="card-title" style="color:var(--ink-muted);">Notes (' + snap.notes.length + ')</div>';- snap.notes.forEach(function(n) {- html += '<div style="font-size:12px;color:var(--ink-muted);padding:4px 0;border-bottom:1px solid var(--border-light);font-family:var(--font-ui);">' + esc(humanizeHealthFlag(n)) + '</div>';- });- html += '</div>';- }+ html += '<div class="section-head"><h2>What your agents remember</h2><span class="section-sub">updates live</span></div>';+ html += '<div class="stats-grid">';+ html += statCard({ label: 'Memories', help: 'memory', tab: 'memories', value: fmtNum(c.latestMemories), sub: fmtNum(c.memories) + ' incl. older versions' });+ html += statCard({ label: 'Observations', help: 'observation', tab: 'sessions', value: fmtNum(c.observations), sub: 'across ' + fmtNum(c.sessions) + ' sessions' });+ html += statCard({ label: 'Sessions', help: 'session', tab: 'sessions', value: fmtNum(c.sessions), sub: fmtNum(c.activeSessions) + ' running now' });+ html += statCard({ label: 'Lessons', help: 'lesson', tab: 'lessons', value: fmtNum(c.lessons), sub: 'rules learned from past work' });+ html += statCard({ label: 'Crystals', help: 'crystal', tab: 'crystals', value: fmtNum(c.crystals), sub: 'summaries of finished work' });+ html += statCard({ label: 'Actions', help: 'action', tab: 'actions', value: fmtNum(c.actions), sub: 'tracked follow-ups' });+ html += statCard({ label: 'Graph', help: 'graph', tab: 'graph', value: fmtNum(c.graphNodes), sub: fmtNum(c.graphEdges) + ' relations' });+ var tokenBudget = parseInt(new URLSearchParams(window.location.search).get('tokenBudget') || '2000', 10) || 2000;+ var est = estimateTokenSavings(sessions, tokenBudget);+ html += statCard({ label: 'Context saved', help: 'contextSaved', tab: 'sessions', value: est.percent + '%', sub: '~' + fmtNum(est.saved) + ' tokens (estimate)' });+ html += '</div>';- html += '<div class="two-col">';+ html += '<div class="section-head"><h2>Is it healthy</h2><span class="section-sub">' + (store.lastHealthAt ? 'checked ' + relTime(new Date(store.lastHealthAt).toISOString()) : '') + '</span></div>';+ html += '<div class="stats-grid">';+ var verdict = store.report ? store.report.status : healthStatus;+ var verdictDot = { ok: 'healthy', info: 'healthy', warn: 'degraded', error: 'critical' }[verdict] || healthDotClass(verdict);+ html += statCard({ label: 'Status', help: 'health', tab: 'health', value: '<span class="health-bar" style="margin:0;"><span class="health-dot ' + verdictDot + '"></span>' + esc(verdict) + '</span>', sub: store.report ? esc(statusSummary(store.report)) : 'engine ' + esc(snap.connectionState || 'unknown') });+ html += statCard({ label: 'Search index', help: 'bm25', tab: 'health', value: fmtNum(idx.bm25Documents), sub: (store.embeddingProvider && store.embeddingProvider !== 'none' ? fmtNum(idx.vectorDocuments) + ' with vectors' : 'keyword only, no embeddings') + (idx.pendingVectorBackfill ? ' · ' + fmtNum(idx.pendingVectorBackfill) + ' waiting' : '') });+ if (snap.memory) {+ var heapUsed = mb(snap.memory.heapUsed);+ var heapLimit = mb(snap.memory.heapLimit || snap.memory.heapTotal);+ html += statCard({ label: 'Memory use', help: 'heap', tab: 'health', value: heapUsed + ' MB', sub: 'of ' + heapLimit + ' MB heap · RSS ' + mb(snap.memory.rss) + ' MB' });+ }+ html += statCard({ label: 'Uptime', help: 'uptime', tab: 'health', value: formatUptime(snap.uptimeSeconds), sub: snap.eventLoopLagMs !== undefined ? 'event loop ' + Number(snap.eventLoopLagMs).toFixed(1) + ' ms behind' : ' ' });+ var liveMetrics = fMetrics.filter(function(m) { return !m.offWithoutLlm; });+ var offCount = fMetrics.length - liveMetrics.length;+ var totalCalls = liveMetrics.reduce(function(a, m) { return a + (m.totalCalls || 0); }, 0);+ var totalFails = liveMetrics.reduce(function(a, m) { return a + (m.failureCount || 0); }, 0);+ var callsSub = liveMetrics.length ? (totalFails ? fmtNum(totalFails) + ' failed' : 'no failures') + ' across ' + liveMetrics.length + ' function' + (liveMetrics.length === 1 ? '' : 's') : 'none recorded yet';+ if (offCount) callsSub += ' · ' + offCount + ' off, no LLM';+ html += statCard({ label: 'Function calls', help: 'functionCalls', tab: 'health', value: fmtNum(totalCalls), sub: callsSub });+ var cbState = cb && cb.state ? cb.state : 'not in use';+ html += statCard({ label: 'LLM breaker', help: 'circuitBreaker', tab: 'health', value: '<span class="cb-indicator ' + (cbState === 'closed' ? 'cb-closed' : cbState === 'open' ? 'cb-open' : cbState === 'half-open' ? 'cb-half-open' : '') + '">' + esc(cbState) + '</span>', sub: cb ? (cb.state === 'closed' ? 'LLM calls flowing normally' : (cb.failures || 0) + ' recent failures') : (store.provider === 'noop' ? 'no LLM provider configured' : ' ') });+ html += '</div>';- html += '<div class="card"><div class="card-title">Recent Sessions</div>';- if (d.sessions.length === 0) {- html += '<div class="empty-state"><p>No sessions yet. Start a coding session with agentmemory hooks enabled.</p></div>';+ html += '<div class="dash-cols">';+ html += '<div class="card"><div class="card-title">Recent sessions ' + help('session') + '</div><div class="card-scroll">';+ if (!store.loaded.session) {+ html += skeleton(5);+ } else if (sessions.length === 0) {+ html += emptyState({+ compact: true,+ title: 'No sessions yet',+ what: 'Each run of an agent in a project becomes a session with its own observations.',+ why: 'No agent with agentmemory hooks has started yet.',+ steps: [{ label: 'Start one by hand to see it appear here instantly:', cmd: curlPost('session/start', { sessionId: 'demo-1', project: 'my-project', cwd: '/path/to/project' }) }]+ });} else {- var recent = d.sessions.slice().sort(function(a, b) { return (b.startedAt || '').localeCompare(a.startedAt || ''); }).slice(0, 5);- html += '<table><tr><th>Project</th><th>Status</th><th>Obs</th><th>Started</th></tr>';- recent.forEach(function(s) {+ html += '<table class="mini-table"><tr><th>Project</th><th>Status</th><th>Obs</th><th>Started</th></tr>';+ sessions.slice(0, 8).forEach(function(s) {+ var id = sessionId(s);var statusBadge = s.status === 'active' ? 'badge-green' : s.status === 'completed' ? 'badge-blue' : 'badge-muted';- html += '<tr><td style="color:var(--ink);font-weight:500;">' + esc(sessionDisplayName(s)) + '</td>';- html += '<td><span class="badge ' + statusBadge + '">' + esc(s.status) + '</span></td>';- html += '<td style="color:var(--ink-muted);font-family:var(--font-mono);font-size:12px;">' + (s.observationCount || 0) + '</td>';- html += '<td style="font-family:var(--font-mono);font-size:11px;color:var(--ink-faint);">' + esc(shortTime(s.startedAt)) + '</td></tr>';+ html += '<tr><td>' + (id ? '<a class="entity-link" href="' + entityHref('session', id) + '" style="font-family:var(--font-body);font-size:13px;">' + esc(sessionDisplayName(s)) + '</a>' : esc(sessionDisplayName(s))) ++ (s.firstPrompt ? '<div style="font-size:11px;color:var(--ink-faint);">' + esc(truncate(s.firstPrompt, 70)) + '</div>' : '') + '</td>';+ html += '<td><span class="badge ' + statusBadge + '">' + esc(s.status || 'unknown') + '</span></td>';+ html += '<td style="font-family:var(--font-mono);font-size:12px;">' + (s.observationCount || 0) + '</td>';+ html += '<td>' + relTime(s.startedAt) + '</td></tr>';});html += '</table>';}- html += '</div>';+ html += '</div></div>';- html += '<div class="card"><div class="card-title">Recent Activity</div>';- if (d.recentAudit.length === 0) {- html += '<div class="empty-state"><p>No activity recorded yet</p></div>';- } else {- d.recentAudit.forEach(function(a) {- var badgeClass = OP_BADGES[a.operation] || 'badge-muted';- html += '<div style="padding:6px 0;border-bottom:1px solid var(--border-light);font-size:13px;">';- html += '<span class="badge ' + badgeClass + '">' + esc(a.operation) + '</span> ';- if (a.functionId) html += '<span style="font-size:11px;color:var(--ink-muted);font-family:var(--font-mono);">' + esc(a.functionId) + '</span> ';- html += '<span style="color:var(--ink-faint);font-size:10px;font-family:var(--font-mono);">' + esc(shortTime(a.timestamp)) + '</span>';- if (a.targetIds && a.targetIds.length) html += '<span style="font-size:10px;color:var(--ink-faint);margin-left:4px;">(' + a.targetIds.length + ' targets)</span>';- html += '</div>';- });- }+ html += '<div class="card"><div class="card-title">Live feed ' + help('live') + '</div><div class="card-scroll" id="dash-feed">';+ html += renderFeedItems();+ html += '</div></div>';html += '</div>';- html += '</div>';+ html += renderMemoryLayers(store.consolidationStatus, entityList('semantic'), entityList('procedural'));+ html += '<details class="card" style="margin-top:16px;"><summary class="card-title" style="cursor:pointer;margin-bottom:0;border-bottom:none;">Function metrics and workers ' + help('functionCalls') + '</summary>';if (fMetrics.length > 0) {var sorted = fMetrics.slice().sort(function(a, b) { return (b.totalCalls || 0) - (a.totalCalls || 0); });- html += '<div class="card" style="margin-top:16px"><div class="card-title">Function Metrics (OTel)</div>';- html += '<table class="metric-table"><tr><th>Function</th><th style="text-align:right">Calls</th><th style="text-align:right">Success</th><th style="text-align:right">Fail</th><th style="text-align:right">Avg Latency</th><th style="text-align:right">Quality</th></tr>';+ html += '<div class="table-wrap" style="margin-top:10px;"><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">Avg latency ' + help('latency') + '</th></tr>';sorted.forEach(function(m) {- var successRate = m.totalCalls > 0 ? Math.round((m.successCount / m.totalCalls) * 100) : 0;- var rateColor = successRate >= 95 ? 'var(--green)' : successRate >= 80 ? 'var(--yellow)' : 'var(--red)';var latencyColor = m.avgLatencyMs > 1000 ? 'var(--red)' : m.avgLatencyMs > 200 ? 'var(--yellow)' : 'var(--green)';- html += '<tr>';- html += '<td class="metric-fn">' + esc(m.functionId) + '</td>';- html += '<td class="metric-num">' + m.totalCalls + '</td>';- html += '<td class="metric-num" style="color:' + rateColor + '">' + m.successCount + ' (' + successRate + '%)</td>';- html += '<td class="metric-num" style="color:' + (m.failureCount > 0 ? 'var(--red)' : 'var(--ink-faint)') + '">' + m.failureCount + '</td>';- html += '<td class="metric-num" style="color:' + latencyColor + '">' + Math.round(m.avgLatencyMs) + ' ms</td>';- html += '<td class="metric-num">' + (m.avgQualityScore > 0 ? m.avgQualityScore.toFixed(2) : '-') + '</td>';- html += '</tr>';+ html += '<tr><td class="metric-fn">' + esc(m.functionId) + '</td>' ++ '<td class="metric-num">' + fmtNum(m.totalCalls) + '</td>' ++ '<td class="metric-num" style="color:' + (m.failureCount > 0 ? 'var(--red)' : 'var(--ink-faint)') + '">' + fmtNum(m.failureCount) + '</td>' ++ '<td class="metric-num" style="color:' + latencyColor + '">' + Math.round(m.avgLatencyMs || 0) + ' ms</td></tr>';});html += '</table></div>';+ } else {+ html += '<p style="font-size:12px;color:var(--ink-muted);margin-top:10px;">No function has run since the worker started. Calls appear here as agents observe, search and save.</p>';}-+ var workers = snap.workers || [];if (workers.length > 0) {- html += '<div class="card" style="margin-top:16px"><div class="card-title">Workers</div>';+ html += '<div style="margin-top:12px;font-family:var(--font-ui);font-size:10px;letter-spacing:0.12em;text-transform:uppercase;color:var(--ink-muted);font-weight:700;">Workers ' + help('workers') + '</div>';workers.forEach(function(w) {var statusClass = w.status === 'running' ? 'running' : w.status === 'starting' ? 'starting' : 'stopped';- html += '<div class="worker-row"><span class="worker-dot ' + statusClass + '"></span>';- html += '<span style="color:var(--ink);font-weight:600;font-family:var(--font-ui);font-size:12px;">' + esc(w.name) + '</span>';- html += '<span class="badge ' + (w.status === 'running' ? 'badge-green' : 'badge-muted') + '">' + esc(w.status) + '</span>';- html += '<span style="font-size:10px;color:var(--ink-faint);font-family:var(--font-mono);">' + esc(w.id) + '</span></div>';- });- html += '</div>';- }-- if (cb && cb.state !== 'closed') {- html += '<div class="card" style="margin-top:16px;border-color:var(--accent);border-width:2px;"><div class="card-title" style="color:var(--accent);">Circuit Breaker Details</div>';- html += '<div class="detail-row"><div class="dl">State</div><div class="dv"><span class="cb-indicator ' + (cb.state === 'open' ? 'cb-open' : 'cb-half-open') + '">' + esc(cb.state) + '</span></div></div>';- html += '<div class="detail-row"><div class="dl">Failures</div><div class="dv" style="color:var(--accent);font-family:var(--font-mono);">' + (cb.failures || 0) + '</div></div>';- if (cb.lastFailureAt) html += '<div class="detail-row"><div class="dl">Last Failure</div><div class="dv" style="font-family:var(--font-mono);font-size:12px;">' + esc(formatTime(cb.lastFailureAt)) + '</div></div>';- if (cb.openedAt) html += '<div class="detail-row"><div class="dl">Opened At</div><div class="dv" style="font-family:var(--font-mono);font-size:12px;">' + esc(formatTime(cb.openedAt)) + '</div></div>';- html += '</div>';- }-- var semFacts = d.semantic || [];- var procItems = d.procedural || [];- var relItems = d.relations || [];-- html += '<hr class="section-rule">';- html += renderMemoryLayers(d.consolidation, semFacts, procItems);-- if (relItems.length > 0) {- html += '<div class="card" style="margin-top:16px;"><div class="card-title">Memory Relations</div>';- relItems.slice(0, 8).forEach(function(r) {- var relType = r.type || r.relationType || 'related';- var badgeClass = relType === 'supersedes' ? 'badge-red' : relType === 'extends' ? 'badge-green' : relType === 'contradicts' ? 'badge-yellow' : 'badge-muted';- html += '<div style="padding:4px 0;border-bottom:1px solid var(--border-light);font-size:12px;display:flex;align-items:center;gap:6px;">';- html += '<span style="font-family:var(--font-mono);color:var(--blue);font-size:11px;">' + esc(truncate(r.sourceId || r.fromId || '', 8)) + '</span>';- html += '<span class="badge ' + badgeClass + '">' + esc(relType) + '</span>';- html += '<span style="font-family:var(--font-mono);color:var(--blue);font-size:11px;">' + esc(truncate(r.targetId || r.toId || '', 8)) + '</span>';- html += '</div>';+ html += '<div class="worker-row"><span class="worker-dot ' + statusClass + '"></span><span style="color:var(--ink);font-weight:600;">' + esc(w.name) + '</span><span class="badge ' + (w.status === 'running' ? 'badge-green' : 'badge-muted') + '">' + esc(w.status) + '</span></div>';});- html += '</div>';}-- html += '<div style="text-align:center;margin-top:20px;"><button class="btn btn-primary" data-action="refresh-dashboard">Refresh</button>';- html += '</div>';+ html += '</details>';setViewHtml(el, html);}- function refreshDashboard() {- loadDashboard();- }-- var graphSim = { nodes: [], edges: [], running: false, canvas: null, ctx: null, raf: null, panX: 0, panY: 0, zoom: 1, dragNode: null, mouseX: 0, mouseY: 0, tickCount: 0, quietTicks: 0 };- function wakeGraphSim() {- graphSim.quietTicks = 0;- if (graphSim.running && !graphSim.raf) {- graphSim.raf = requestAnimationFrame(runSimulation);- }- }-- // #753: previously POST'd `{}` and let the engine return the full- // graph. On 10k+ nodes the payload exceeded the iii state channel- // limit and the engine returned HTTP 500, leaving the tab blank- // with no signal. Now we pass an explicit `limit`, distinguish- // server error from empty-corpus, and render an actionable banner- // when the request itself fails instead of falling silent.- var GRAPH_INITIAL_LIMIT = 500;-- async function loadGraph() {- var el = document.getElementById('view-graph');- el.innerHTML = '<div class="graph-container"><div class="graph-canvas-wrap"><canvas id="graph-canvas"></canvas><div class="graph-controls"><button title="Zoom In" data-action="zoom-graph" data-dir="1">+</button><button title="Zoom Out" data-action="zoom-graph" data-dir="-1">−</button><div class="ctrl-divider"></div><button title="Recenter" data-action="recenter-graph">⌖</button></div><div class="graph-tooltip" id="graph-tooltip"></div></div><div class="graph-sidebar" id="graph-sidebar"></div></div>';-- var results = await Promise.all([- apiPost('graph/query', { limit: GRAPH_INITIAL_LIMIT }),- api('graph/stats', { readErrorBody: true })- ]);- var queryResult = results[0];- var statsResult = results[1];- if (statsResult && statsResult.error && statsResult.flag) {- // 503 with a structured body = the feature is off, not broken.- // Rendering this as "query failed / Retry" sends users hunting- // through server logs for an error that isn't one.- state.graph.disabledInfo = statsResult;- state.graph.queryError = null;- state.graph.nodes = [];- state.graph.edges = [];- state.graph.stats = {};- state.graph.loaded = true;- renderGraphSidebar();- return;- }- state.graph.disabledInfo = null;- if (queryResult === null) {- // api() returns null only on non-2xx or a transport error; an- // empty graph would come back as { nodes: [], edges: [] }.- // Surface as an error state so #753-class failures don't read- // as "no data yet" — and so "Rebuild Graph" stays available.- state.graph.queryError = 'graph/query failed (check server logs for HTTP error)';- state.graph.nodes = [];- state.graph.edges = [];- state.graph.stats = results[1] || {};- state.graph.loaded = true;- renderGraphSidebar();- return;- }- state.graph.queryError = null;- state.graph.nodes = queryResult.nodes || [];- state.graph.edges = queryResult.edges || [];- state.graph.truncated = queryResult.truncated === true;- state.graph.totalNodes = typeof queryResult.totalNodes === 'number' ? queryResult.totalNodes : state.graph.nodes.length;- state.graph.totalEdges = typeof queryResult.totalEdges === 'number' ? queryResult.totalEdges : state.graph.edges.length;- state.graph.stats = results[1] || {};-- if (state.graph.nodes.length === 0 && (state.graph.stats.totalNodes || state.graph.stats.nodes || 0) === 0) {- var sb = document.getElementById('graph-sidebar');- if (sb) sb.innerHTML = '<h3>Graph</h3><p style="font-size:12px;color:var(--ink-faint);margin:8px 0;font-style:italic;">No graph data yet. Building from observations and memories...</p>';- var buildResult = await apiPost('graph/build', {});- if (buildResult && buildResult.success && buildResult.nodes > 0) {- var freshResults = await Promise.all([- apiPost('graph/query', { limit: GRAPH_INITIAL_LIMIT }),- apiGet('graph/stats')- ]);- var freshQuery = freshResults[0];- if (freshQuery) {- state.graph.nodes = freshQuery.nodes || [];- state.graph.edges = freshQuery.edges || [];- state.graph.truncated = freshQuery.truncated === true;- state.graph.totalNodes = typeof freshQuery.totalNodes === 'number' ? freshQuery.totalNodes : state.graph.nodes.length;- state.graph.totalEdges = typeof freshQuery.totalEdges === 'number' ? freshQuery.totalEdges : state.graph.edges.length;- }- state.graph.stats = freshResults[1] || {};- }+ function renderFeedItems() {+ if (store.feed.length === 0) {+ if (!store.loaded.audit) return skeleton(5);+ return emptyState({+ compact: true,+ title: 'Waiting for activity',+ what: 'Everything agentmemory does appears here the moment it happens: new sessions, observations, saved memories, lessons and deletes.',+ why: 'Nothing has changed since this page connected, and the audit log is empty.',+ steps: [{ label: 'Save a memory and watch it arrive:', cmd: curlPost('remember', { content: 'The API uses jose for JWT validation', type: 'architecture' }) }]+ });}-- state.graph.loaded = true;- var types = {};- state.graph.nodes.forEach(function(n) { types[n.type] = true; });- state.graph.filters = types;-- renderGraphSidebar();- initGraph();+ var html = '';+ store.feed.forEach(function(f) {+ var href = f.kind && f.id ? entityHref(f.kind, f.id) : '';+ var text = href+ ? '<a class="feed-text" href="' + href + '" title="' + esc(f.text) + '" style="text-decoration:none;">' + esc(f.text) + '</a>'+ : '<span class="feed-text" title="' + esc(f.text) + '">' + esc(f.text) + '</span>';+ html += '<div class="feed-item' + (f.fresh ? ' fresh' : '') + '">' ++ '<span class="badge ' + (f.badge || 'badge-muted') + '" style="justify-self:start;">' + esc(f.tag) + '</span>' ++ text + relTime(f.at) + '</div>';+ f.fresh = false;+ });+ return html;}+ var GRAPH_LIMIT = 500;+ var GRAPH_TYPE_ORDER = ['file', 'function', 'concept', 'error', 'decision', 'pattern', 'library', 'person', 'project', 'preference', 'location', 'organization', 'event'];var NODE_SHAPES = {- file: 'rect', function: 'circle', concept: 'circle', error: 'diamond',- decision: 'diamond', pattern: 'circle', library: 'hexagon', person: 'circle'+ file: 'square', function: 'circle', concept: 'hexagon', error: 'triangle', decision: 'diamond',+ pattern: 'pentagon', library: 'ring', person: 'triangleDown', project: 'star', preference: 'plus',+ location: 'cross', organization: 'squareRing', event: 'diamondRing'};- var graphSearchTerm = '';-- function renderGraphSidebar() {- var sb = document.getElementById('graph-sidebar');- if (!sb) return;- var gs = state.graph.stats || {};- 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 = '';-- if (state.graph.disabledInfo) {- html += '<div style="margin:8px 0;padding:10px 12px;border:1px solid var(--border);background:var(--bg-alt);font-size:12px;color:var(--ink);line-height:1.5;">';- html += '<div style="font-weight:600;margin-bottom:4px;">Knowledge graph is off</div>';- html += '<div style="font-size:11px;color:var(--ink-muted);">' + esc(state.graph.disabledInfo.enableHow || 'Set ' + (state.graph.disabledInfo.flag || 'GRAPH_EXTRACTION_ENABLED') + '=true and restart.') + '</div>';- if (state.graph.disabledInfo.docsHref) {- html += '<a href="' + esc(state.graph.disabledInfo.docsHref) + '" target="_blank" rel="noopener" style="font-size:11px;">docs →</a>';- }- html += '</div>';- sb.innerHTML = html;- return;- }- // #753: error banner stays above the search box so a failed- // graph/query doesn't read as "0 nodes".- if (state.graph.queryError) {- html += '<div style="margin:8px 0;padding:10px 12px;border:1px solid var(--accent);background:var(--bg-alt);font-size:12px;color:var(--ink);line-height:1.4;">';- html += '<div style="font-weight:600;margin-bottom:4px;">Graph query failed</div>';- html += '<div style="font-size:11px;color:var(--ink-muted);">' + esc(state.graph.queryError) + '</div>';- html += '<button class="btn" data-action="rebuild-graph" style="margin-top:8px;font-size:11px;">Retry</button>';- html += '</div>';- } else if (state.graph.truncated) {- // #753: surface the cap so operators know they're not seeing- // the whole graph. Densest-first ranking on the server makes- // this the meaningful subset, not an arbitrary head.- html += '<div style="margin:8px 0;padding:10px 12px;border:1px solid var(--border);background:var(--bg-alt);font-size:11px;color:var(--ink-muted);line-height:1.4;">';- html += 'Showing ' + state.graph.nodes.length + ' of ' + state.graph.totalNodes + ' nodes (most-connected first). The full graph is too large to render at once.';- html += '</div>';- }-- html += '<input type="text" class="graph-search" id="graph-search" placeholder="Search nodes...">';-- html += '<h3 style="margin-top:16px;font-size:10px;text-transform:uppercase;letter-spacing:0.12em;color:var(--ink-muted);font-family:var(--font-ui);font-weight:700;">Graph Stats</h3>';- html += '<div style="display:flex;gap:20px;margin:10px 0 16px;padding:12px;background:var(--bg-alt);border:1px solid var(--border-light);border-radius:4px;">';- html += '<div style="text-align:center;flex:1;"><span style="font-size:28px;font-weight:900;font-family:var(--font-display);color:var(--ink);line-height:1;">' + nodeCount + '</span><div style="font-size:8px;color:var(--ink-faint);text-transform:uppercase;letter-spacing:0.12em;font-family:var(--font-ui);font-weight:600;margin-top:4px;">Nodes</div></div>';- html += '<div style="width:1px;background:var(--border-light);"></div>';- html += '<div style="text-align:center;flex:1;"><span style="font-size:28px;font-weight:900;font-family:var(--font-display);color:var(--ink);line-height:1;">' + edgeCount + '</span><div style="font-size:8px;color:var(--ink-faint);text-transform:uppercase;letter-spacing:0.12em;font-family:var(--font-ui);font-weight:600;margin-top:4px;">Edges</div></div>';- html += '</div>';-- html += '<h3 style="margin-top:12px;font-size:10px;text-transform:uppercase;letter-spacing:0.12em;color:var(--ink-muted);font-family:var(--font-ui);font-weight:700;">Filter by Type</h3>';- Object.keys(state.graph.filters).forEach(function(type) {- var color = NODE_COLORS[type] || '#666666';- html += '<label class="filter-item"><input type="checkbox" checked data-type="' + esc(type) + '"><span class="filter-dot" style="background:' + color + '"></span>' + esc(type) + '</label>';+ var NODE_COLORS_DARK = {+ file: '#5cc08f', function: '#7fa9e3', concept: '#dcae45', error: '#f2555a', decision: '#ae92dc',+ pattern: '#6f9bff', library: '#e8905a', person: '#d8dadf', project: '#4ec0d2', preference: '#f07ab0',+ location: '#a3cf5a', organization: '#a4adbb', event: '#d9a23a'+ };+ var NODE_TYPE_TEXT = {+ file: 'A file the agent read, edited or that a code import found.',+ function: 'A function, class or other code symbol.',+ concept: 'A topic that came up in the work, such as pricing or auth.',+ error: 'An error or bug the agent ran into.',+ decision: 'A decision or the reasoning behind one.',+ pattern: 'A convention or approach that keeps coming back.',+ library: 'A library, framework or tool.',+ person: 'A person named in the work.',+ project: 'A project or repository.',+ preference: 'A preference someone stated.',+ location: 'A place, host or environment.',+ organization: 'A team or company.',+ event: 'Something that happened at a point in time, such as a release.'+ };+ var EDGE_TYPE_TEXT = {+ related_to: 'The two appeared in the same observation. Added without an LLM.',+ uses: 'One calls or uses the other.',+ imports: 'One imports or loads the other.',+ modifies: 'One changes the other.',+ causes: 'One led to the other.',+ caused_by: 'One was caused by the other.',+ fixes: 'One fixes the other.',+ depends_on: 'One needs the other to work.',+ blocked_by: 'One is waiting on the other.',+ works_at: 'A person works at an organization.',+ prefers: 'Someone prefers this option.',+ optimizes_for: 'A choice made to favor this goal.',+ rejected: 'An option that was considered and turned down.',+ avoids: 'Something deliberately kept away from.'+ };+ var EDGE_DASHES = [[], [7, 4], [2, 3], [9, 3, 2, 3], [1, 4], [4, 2]];+ var EDGE_TYPE_ORDER = ['uses', 'imports', 'related_to', 'depends_on', 'modifies', 'fixes', 'causes', 'caused_by', 'blocked_by', 'prefers', 'optimizes_for', 'rejected', 'works_at', 'avoids'];++ function graphState() { return state.graph; }+ function nodeColor(type) {+ var dark = isDarkMode();+ return (dark ? NODE_COLORS_DARK[type] : NODE_COLORS[type]) || (dark ? '#b8bbc1' : '#555a63');+ }+ function edgeDash(type) {+ var i = EDGE_TYPE_ORDER.indexOf(type);+ if (i < 0) i = EDGE_TYPE_ORDER.length;+ return EDGE_DASHES[i % EDGE_DASHES.length];+ }+ function graphTypeRank(t) {+ var i = GRAPH_TYPE_ORDER.indexOf(t);+ return i < 0 ? 99 : i;+ }+ function graphNodeLabel(n, max) {+ var name = String(n.name || n.id || '');+ if (n.type === 'file' && name.indexOf('/') >= 0) name = name.replace(/\/+$/, '').split('/').pop() || name;+ return truncate(name, max || 28);+ }+ function graphNodeList() {+ var map = state.graph.nodeMap;+ return Object.keys(map).map(function(k) { return map[k]; });+ }+ function graphEdgeList() {+ var map = state.graph.edgeMap;+ return Object.keys(map).map(function(k) { return map[k]; });+ }+ function graphLocalDegrees() {+ var g = state.graph;+ if (g.localDegreeRev === g.rev && g.localDegree) return g.localDegree;+ var d = {};+ graphEdgeList().forEach(function(e) {+ d[e.sourceNodeId] = (d[e.sourceNodeId] || 0) + 1;+ d[e.targetNodeId] = (d[e.targetNodeId] || 0) + 1;});-- if (state.graph.nodes.length > 0 && state.graph.edges.length === 0) {- html += '<div style="margin:10px 0;padding:10px 12px;border:1px solid var(--border-light);background:var(--bg-subtle);font-size:11px;color:var(--ink-muted);line-height:1.5;">Entities extracted, no relations between them yet. Nodes are grouped by kind; edges appear as extraction sees entities acting on each other across more sessions (larger models find them faster).</div>';- }- html += '<div class="graph-legend" style="display:none"><h3>Legend</h3>';- var shapeLabels = { rect: '▭', circle: '●', diamond: '◆', hexagon: '⬢' };- var shownShapes = {};- Object.keys(NODE_COLORS).forEach(function(type) {- var shape = NODE_SHAPES[type] || 'circle';- var color = NODE_COLORS[type];- var key = type;- if (shownShapes[key]) return;- shownShapes[key] = true;- html += '<div class="graph-legend-item"><span class="graph-legend-shape" style="color:' + color + ';font-size:14px;">' + (shapeLabels[shape] || '●') + '</span><span>' + esc(type) + '</span></div>';+ g.localDegree = d;+ g.localDegreeRev = g.rev;+ return d;+ }+ function graphDegree(id) {+ var d = state.graph.degrees[id];+ if (typeof d === 'number') return d;+ return graphLocalDegrees()[id] || 0;+ }+ function graphTypeVisible(type) {+ return !state.graph.hidden[type];+ }+ function graphNodeVisible(n) {+ return !!n && graphTypeVisible(n.type);+ }+ function graphSearchMatches(limit) {+ var q = state.graph.search.trim().toLowerCase();+ if (!q) return [];+ return graphNodeList().filter(function(n) {+ return String(n.name || '').toLowerCase().indexOf(q) >= 0 || String(n.id).toLowerCase() === q;+ }).sort(function(a, b) { return graphDegree(b.id) - graphDegree(a.id) || String(a.name).localeCompare(String(b.name)); }).slice(0, limit || 500);+ }+ function graphTypeCounts() {+ var local = {};+ graphNodeList().forEach(function(n) { local[n.type] = (local[n.type] || 0) + 1; });+ var stats = graphStats();+ var total = stats && stats.nodesByType ? stats.nodesByType : {};+ var types = {};+ Object.keys(local).concat(Object.keys(total)).forEach(function(t) { types[t] = true; });+ return Object.keys(types).sort(function(a, b) { return graphTypeRank(a) - graphTypeRank(b) || a.localeCompare(b); }).map(function(t) {+ return { type: t, shown: local[t] || 0, total: typeof total[t] === 'number' ? total[t] : (local[t] || 0) };});- html += '</div>';-- html += '<button class="btn" style="margin-top:14px;width:100%;font-size:11px;padding:8px;letter-spacing:0.06em;transition:all 0.15s ease;" data-action="rebuild-graph">↻ Rebuild Graph</button>';- html += '<div id="selected-node-panel"></div>';- var __focus = captureSearchFocus(['graph-search']);- sb.innerHTML = html;-- sb.querySelectorAll('input[type="checkbox"]').forEach(function(cb) {- cb.addEventListener('change', function() {- state.graph.filters[this.dataset.type] = this.checked;- renderGraph();- });+ }+ function graphEdgeTypeCounts() {+ var local = {};+ graphEdgeList().forEach(function(e) { local[e.type] = (local[e.type] || 0) + 1; });+ var stats = graphStats();+ var total = stats && stats.edgesByType ? stats.edgesByType : {};+ var types = {};+ Object.keys(local).concat(Object.keys(total)).forEach(function(t) { types[t] = true; });+ return Object.keys(types).sort(function(a, b) { return (total[b] || local[b] || 0) - (total[a] || local[a] || 0) || a.localeCompare(b); }).map(function(t) {+ return { type: t, shown: local[t] || 0, total: typeof total[t] === 'number' ? total[t] : (local[t] || 0) };});-- var searchInput = document.getElementById('graph-search');- if (searchInput) {- bindImeSafeSearch(searchInput, 200, function(v){ graphSearchTerm = v.toLowerCase(); renderGraph(); });- }- restoreSearchFocus(__focus);+ }+ function graphStats() {+ return (store.graph && store.graph.stats) || state.graph.stats || null;+ }+ function graphTotals() {+ var s = graphStats();+ var g = state.graph;+ return {+ nodes: s && typeof s.totalNodes === 'number' ? s.totalNodes : (g.totalNodes || graphNodeList().length),+ edges: s && typeof s.totalEdges === 'number' ? s.totalEdges : (g.totalEdges || graphEdgeList().length)+ };+ }+ function graphIsolatedCount() {+ var deg = graphLocalDegrees();+ return graphNodeList().filter(function(n) { return !deg[n.id]; }).length;}- function initGraph() {- var canvas = document.getElementById('graph-canvas');- if (!canvas) return;- graphSim.canvas = canvas;- graphSim.ctx = canvas.getContext('2d');-- function resize() {- var r = canvas.parentElement.getBoundingClientRect();- canvas.width = r.width * window.devicePixelRatio;- canvas.height = r.height * window.devicePixelRatio;- canvas.style.width = r.width + 'px';- canvas.style.height = r.height + 'px';- graphSim.ctx.setTransform(window.devicePixelRatio, 0, 0, window.devicePixelRatio, 0, 0);- }- resize();- window.addEventListener('resize', resize);-- var cw = canvas.width / window.devicePixelRatio;- var ch = canvas.height / window.devicePixelRatio;- graphSim.panX = cw / 2;- graphSim.panY = ch / 2;-+ function setGraphData(result) {+ var g = state.graph;+ var nodeMap = {};var edgeMap = {};- state.graph.edges.forEach(function(e) {- edgeMap[e.sourceNodeId] = (edgeMap[e.sourceNodeId] || 0) + 1;- edgeMap[e.targetNodeId] = (edgeMap[e.targetNodeId] || 0) + 1;- });-- // With no (or few) edges a pure force layout is a meaningless- // scatter. Anchor each type to its own cluster center so the- // picture reads as "here is what memory knows, grouped by kind";- // once real relations exist the edge springs dominate instead.- var types = [];- state.graph.nodes.forEach(function(n) {- if (types.indexOf(n.type) === -1) types.push(n.type);- });- var typeCenters = {};- types.forEach(function(t, ti) {- var a = (2 * Math.PI * ti) / Math.max(types.length, 1) - Math.PI / 2;- var cr = types.length > 1 ? Math.min(cw, ch) * 0.28 : 0;- typeCenters[t] = { x: Math.cos(a) * cr, y: Math.sin(a) * cr };- });- graphSim.typeCenters = typeCenters;- graphSim.clustered = state.graph.edges.length < state.graph.nodes.length / 2;-- graphSim.nodes = state.graph.nodes.map(function(n, i) {- var deg = edgeMap[n.id] || 0;- var c = typeCenters[n.type] || { x: 0, y: 0 };- return {- id: n.id, type: n.type, name: n.name, properties: n.properties,- x: c.x + (Math.random() - 0.5) * 150,- y: c.y + (Math.random() - 0.5) * 150,- vx: 0, vy: 0,- r: Math.max(11, Math.min(22, 11 + deg * 2.5))- };- });- graphSim.edges = state.graph.edges.slice();- graphSim.running = true;- graphSim.dragNode = null;- graphSim.autoFitPending = true;-- setupGraphInteraction(canvas);- runSimulation();- }-- function setupGraphInteraction(canvas) {- var isPanning = false;- var lastMX = 0, lastMY = 0;-- function canvasCoords(e) {- var rect = canvas.getBoundingClientRect();- return {- x: (e.clientX - rect.left - graphSim.panX) / graphSim.zoom,- y: (e.clientY - rect.top - graphSim.panY) / graphSim.zoom- };- }- function findNode(cx, cy) {- for (var i = graphSim.nodes.length - 1; i >= 0; i--) {- var n = graphSim.nodes[i];- if (!state.graph.filters[n.type]) continue;- var dx = n.x - cx, dy = n.y - cy;- if (dx * dx + dy * dy < n.r * n.r + 25) return n;- }- return null;- }-- canvas.addEventListener('mousedown', function(e) {- var c = canvasCoords(e);- var node = findNode(c.x, c.y);- if (node) {- graphSim.dragNode = node;+ (result.nodes || []).forEach(function(n) { if (n && n.id) nodeMap[n.id] = n; });+ (result.edges || []).forEach(function(e) { if (e && e.id && nodeMap[e.sourceNodeId] && nodeMap[e.targetNodeId]) edgeMap[e.id] = e; });+ if (g.selectedId && !nodeMap[g.selectedId] && g.nodeMap[g.selectedId]) nodeMap[g.selectedId] = g.nodeMap[g.selectedId];+ g.nodeMap = nodeMap;+ g.edgeMap = edgeMap;+ g.degrees = Object.assign({}, result.degrees || {});+ g.truncated = result.truncated === true;+ g.totalNodes = typeof result.totalNodes === 'number' ? result.totalNodes : Object.keys(nodeMap).length;+ g.totalEdges = typeof result.totalEdges === 'number' ? result.totalEdges : Object.keys(edgeMap).length;+ g.rev++;+ }++ function mergeGraphRows(nodes, edges) {+ var g = state.graph;+ (nodes || []).forEach(function(n) { if (n && n.id) g.nodeMap[n.id] = Object.assign({}, g.nodeMap[n.id] || {}, n); });+ (edges || []).forEach(function(e) { if (e && e.id && g.nodeMap[e.sourceNodeId] && g.nodeMap[e.targetNodeId]) g.edgeMap[e.id] = e; });+ g.rev++;+ }++ async function loadGraph(opts) {+ opts = opts || {};+ var g = state.graph;+ g.dirty = false;+ if (!opts.quiet) g.loading = true;+ if (!opts.quiet) renderGraphView();+ var seq = ++g.requestSeq;+ var result = await apiPost('graph/query', { limit: GRAPH_LIMIT });+ if (seq !== g.requestSeq) return;+ g.loading = false;+ if (result === null) {+ var stats = await api('graph/stats', { readErrorBody: true });+ if (stats && stats.error && stats.flag) {+ g.disabledInfo = stats;+ g.queryError = null;} else {- isPanning = true;- }- lastMX = e.clientX;- lastMY = e.clientY;- // wake the simulation if it parked itself after settling- wakeGraphSim();- });- canvas.addEventListener('mousemove', function(e) {- var dx = e.clientX - lastMX;- var dy = e.clientY - lastMY;- if (graphSim.dragNode) {- graphSim.dragNode.x += dx / graphSim.zoom;- graphSim.dragNode.y += dy / graphSim.zoom;- graphSim.dragNode.vx = 0;- graphSim.dragNode.vy = 0;- } else if (isPanning) {- graphSim.panX += dx;- graphSim.panY += dy;- }- lastMX = e.clientX;- lastMY = e.clientY;- graphSim.mouseX = e.clientX;- graphSim.mouseY = e.clientY;-- var c = canvasCoords(e);- var hoverNode = findNode(c.x, c.y);- var tooltip = document.getElementById('graph-tooltip');- if (tooltip) {- if (hoverNode && !graphSim.dragNode && !isPanning) {- var conns = graphSim.edges.filter(function(ed) { return ed.sourceNodeId === hoverNode.id || ed.targetNodeId === hoverNode.id; }).length;- var ttHtml = '<div class="tt-name">' + esc(hoverNode.name) + '</div>';- ttHtml += '<div class="tt-type" style="color:' + (NODE_COLORS[hoverNode.type] || '#666') + '">' + esc(hoverNode.type) + '</div>';- if (hoverNode.properties) {- var propKeys = Object.keys(hoverNode.properties).slice(0, 3);- propKeys.forEach(function(k) {- ttHtml += '<div class="tt-prop">' + esc(k) + ': ' + esc(truncate(String(hoverNode.properties[k]), 30)) + '</div>';- });- }- ttHtml += '<div class="tt-conns">' + conns + ' connection' + (conns !== 1 ? 's' : '') + '</div>';- tooltip.innerHTML = ttHtml;- var rect = canvas.getBoundingClientRect();- tooltip.style.left = (e.clientX - rect.left + 12) + 'px';- tooltip.style.top = (e.clientY - rect.top + 12) + 'px';- tooltip.classList.add('visible');- canvas.style.cursor = 'pointer';- } else {- tooltip.classList.remove('visible');- canvas.style.cursor = graphSim.dragNode || isPanning ? 'grabbing' : 'grab';- }+ g.disabledInfo = null;+ g.queryError = 'POST /agentmemory/graph/query failed. The server log has the HTTP error.';}+ g.loaded = true;+ renderGraphView();+ return;+ }+ g.disabledInfo = null;+ g.queryError = null;+ g.warning = result.warning || '';+ setGraphData(result);+ g.loaded = true;+ g.fetches++;+ syncGraphSim(!opts.quiet);+ renderGraphView();+ if (g.selectedId) selectGraphNode(g.selectedId, { fromRoute: true, keepRoute: true });+ }++ function applyGraphDelta(delta) {+ var g = state.graph;+ if (!g.loaded || !delta) return false;+ if (delta.full) {+ var keepNodes = {};+ (delta.nodes || []).forEach(function(n) { keepNodes[n.id] = true; });+ Object.keys(g.nodeMap).forEach(function(id) { if (!keepNodes[id] && id !== g.selectedId) delete g.nodeMap[id]; });+ var keepEdges = {};+ (delta.edges || []).forEach(function(e) { keepEdges[e.id] = true; });+ Object.keys(g.edgeMap).forEach(function(id) { if (!keepEdges[id]) delete g.edgeMap[id]; });+ }+ (delta.removedEdgeIds || []).forEach(function(id) { delete g.edgeMap[id]; });+ (delta.removedNodeIds || []).forEach(function(id) {+ if (id === g.selectedId) return;+ delete g.nodeMap[id];+ delete g.degrees[id];});- canvas.addEventListener('mouseup', function(e) {- if (graphSim.dragNode && !isPanning) {- selectGraphNode(graphSim.dragNode);- }- graphSim.dragNode = null;- isPanning = false;+ Object.keys(g.edgeMap).forEach(function(id) {+ var e = g.edgeMap[id];+ if (!g.nodeMap[e.sourceNodeId] || !g.nodeMap[e.targetNodeId]) delete g.edgeMap[id];});- canvas.addEventListener('wheel', function(e) {- e.preventDefault();- var factor = e.deltaY > 0 ? 0.9 : 1.1;- graphSim.zoom = Math.max(0.1, Math.min(5, graphSim.zoom * factor));- // zoom is visually meaningless if the rAF loop is parked —- // wake the simulation so the next frame redraws at the new scale.- wakeGraphSim();- }, { passive: false });- canvas.addEventListener('dblclick', function(e) {- var c = canvasCoords(e);- var node = findNode(c.x, c.y);- if (node) {- selectGraphNode(node);- expandNode(node.id);+ var touched = {};+ (delta.nodes || []).forEach(function(n) { touched[n.id] = true; });+ (delta.edges || []).forEach(function(e) { touched[e.sourceNodeId] = true; touched[e.targetNodeId] = true; });+ mergeGraphRows(delta.nodes, delta.edges);+ Object.keys(delta.degrees || {}).forEach(function(id) { g.degrees[id] = delta.degrees[id]; });+ g.patches++;+ g.lastPatchAt = Date.now();+ Object.keys(touched).forEach(function(id) { g.fresh[id] = Date.now(); });+ if (g.selectedId && touched[g.selectedId] && g.detail && g.detail.id === g.selectedId) g.detail.stale = true;+ return true;+ }++ function handleGraphChange(data) {+ var g = state.graph;+ if (!data) return;+ if (!g.loaded) { g.dirty = true; return; }+ if (data.source === 'snapshot') {+ if (data.delta && applyGraphDelta(data.delta)) {+ if (graphSim.canvas && state.activeTab === 'graph') { syncGraphSim(false); requestGraphDraw(); setTimeout(requestGraphDraw, 4200); }+ else g.simStale = true;+ return;}- });+ scheduleGraphReload();+ return;+ }+ if (data.source === 'items' && !data.coveredBySnapshot) scheduleGraphReload();}- window.zoomGraph = function(dir) {- var factor = dir > 0 ? 1.25 : 0.8;- graphSim.zoom = Math.max(0.1, Math.min(5, graphSim.zoom * factor));- wakeGraphSim();- };- window.recenterGraph = function() {- graphSim.zoom = 1;- if (graphSim.canvas) {- var cw = graphSim.canvas.width / window.devicePixelRatio;- var ch = graphSim.canvas.height / window.devicePixelRatio;- graphSim.panX = cw / 2;- graphSim.panY = ch / 2;- }- wakeGraphSim();- };-- function selectGraphNode(simNode) {- state.graph.selectedNode = simNode;- var panel = document.getElementById('selected-node-panel');- if (!panel) return;- var color = NODE_COLORS[simNode.type] || '#666666';- var html = '<div class="selected-node-info">';- html += '<h4 style="color:' + color + '">' + esc(simNode.name) + '</h4>';- html += '<div class="prop">Type: ' + esc(simNode.type) + '</div>';- if (simNode.properties) {- Object.keys(simNode.properties).forEach(function(k) {- html += '<div class="prop">' + esc(k) + ': ' + esc(truncate(simNode.properties[k], 50)) + '</div>';- });- }- var conns = graphSim.edges.filter(function(e) { return e.sourceNodeId === simNode.id || e.targetNodeId === simNode.id; }).length;- html += '<div class="prop">Connections: ' + conns + '</div>';- html += '<button class="btn btn-primary" style="margin-top:8px;width:100%;" data-action="expand-node" data-node-id="' + esc(simNode.id) + '">Expand neighbors</button>';- html += '</div>';- panel.innerHTML = html;+ var graphReloadTimer = null;+ function scheduleGraphReload() {+ state.graph.dirty = true;+ if (state.activeTab !== 'graph') return;+ if (graphReloadTimer) clearTimeout(graphReloadTimer);+ graphReloadTimer = setTimeout(function() {+ graphReloadTimer = null;+ if (state.activeTab === 'graph' && state.graph.dirty) loadGraph({ quiet: true });+ }, 1200);}- async function expandNode(nodeId) {- var result = await apiPost('graph/query', { startNodeId: nodeId, maxDepth: 1 });- if (!result) return;- var existingIds = {};- graphSim.nodes.forEach(function(n) { existingIds[n.id] = true; });- var parentNode = graphSim.nodes.find(function(n) { return n.id === nodeId; });- var px = parentNode ? parentNode.x : 0;- var py = parentNode ? parentNode.y : 0;-- (result.nodes || []).forEach(function(n) {- if (!existingIds[n.id]) {- state.graph.nodes.push(n);- if (!state.graph.filters.hasOwnProperty(n.type)) state.graph.filters[n.type] = true;- var angle = Math.random() * Math.PI * 2;- graphSim.nodes.push({- id: n.id, type: n.type, name: n.name, properties: n.properties,- x: px + Math.cos(angle) * 80,- y: py + Math.sin(angle) * 80,- vx: 0, vy: 0, r: 8+ async function fetchGraphDetail(id) {+ var g = state.graph;+ g.detail = { id: id, loading: true, data: null, error: '', stale: false };+ renderGraphDetail();+ var res = await api('graph/node?id=' + encodeURIComponent(id), { readErrorBody: true });+ if (!g.detail || g.detail.id !== id) return;+ if (!res || res.error) {+ g.detail = { id: id, loading: false, data: null, error: res && res.error ? res.error : 'request failed', stale: false };+ } else {+ g.detail = { id: id, loading: false, data: res, error: '', stale: false };+ if (res.node && !g.nodeMap[id]) {+ var extraNodes = [res.node];+ var extraEdges = [];+ (res.relations || []).slice(0, 40).forEach(function(r) {+ if (!r.neighbor) return;+ if (!g.nodeMap[r.neighbor.id]) extraNodes.push({ id: r.neighbor.id, name: r.neighbor.name, type: r.neighbor.type, properties: {}, sourceObservationIds: [] });+ extraEdges.push({ id: r.edgeId, type: r.type, sourceNodeId: r.direction === 'out' ? id : r.neighbor.id, targetNodeId: r.direction === 'out' ? r.neighbor.id : id, weight: r.weight, sourceObservationIds: [] });});+ mergeGraphRows(extraNodes, extraEdges);+ if (typeof res.degree === 'number') g.degrees[id] = res.degree;+ syncGraphSim(false);+ centerGraphOn(id);}- });+ }+ renderGraphDetail();+ renderGraphOverview();+ requestGraphDraw();+ }- var existingEdges = {};- graphSim.edges.forEach(function(e) { existingEdges[e.id] = true; });- (result.edges || []).forEach(function(e) {- if (!existingEdges[e.id]) {- state.graph.edges.push(e);- graphSim.edges.push(e);+ function selectGraphNode(id, opts) {+ opts = opts || {};+ var g = state.graph;+ if (!id) {+ g.selectedId = null;+ g.detail = null;+ if (!opts.keepRoute) setRouteEntity('graph', '');+ renderGraphDetail();+ requestGraphDraw();+ return;+ }+ var changed = g.selectedId !== id;+ g.selectedId = id;+ if (!opts.keepRoute) setRouteEntity('graph', id);+ if (changed || !g.detail || g.detail.id !== id) fetchGraphDetail(id);+ else renderGraphDetail();+ if (opts.center || opts.fromRoute) centerGraphOn(id);+ requestGraphDraw();+ if (opts.focusDetail) {+ var panel = document.getElementById('graph-detail');+ if (panel) {+ if (panel.scrollIntoView && window.matchMedia('(max-width: 720px)').matches) panel.scrollIntoView({ block: 'nearest' });+ var head = panel.querySelector('.gd-name');+ if (head) head.focus({ preventScroll: true });}- });- renderGraphSidebar();+ }}- function runSimulation() {- if (!graphSim.running) return;- var nodes = graphSim.nodes;- var edges = graphSim.edges;- var nodeCount = nodes.length;- graphSim.tickCount = (graphSim.tickCount || 0) + 1;- // dense graphs (>1000 nodes) used to oscillate forever- // because the per-node force pile-up exceeded what 0.9 damping- // could bleed off each tick. Tick-decay tightens damping over- // time so the layout actually settles; a per-node velocity cap- // prevents any single node from being launched off-screen by an- // accumulated kick before damping catches up.- var coolBoost = Math.min(0.4, graphSim.tickCount / 1500);- var damping = 0.9 - coolBoost;- var repulsion = nodeCount > 1000 ? 3000 : nodeCount > 100 ? 2000 : nodeCount > 50 ? 1200 : 800;- var attraction = nodeCount > 100 ? 0.002 : 0.005;- var centerGravity = nodeCount > 1000 ? 0.012 : nodeCount > 100 ? 0.005 : 0.01;- var velocityCap = nodeCount > 1000 ? 6 : nodeCount > 200 ? 12 : 24;+ var graphSim = { nodes: [], byId: {}, edges: [], canvas: null, ctx: null, raf: null, drawQueued: false, panX: 0, panY: 0, zoom: 1, dpr: 1, w: 0, h: 0, alpha: 0, drag: null, hoverId: null, fitted: false, isolatedBox: null, pointers: {}, ro: null };- var nodeMap = {};- nodes.forEach(function(n) { nodeMap[n.id] = n; });-- for (var i = 0; i < nodes.length; i++) {- if (graphSim.dragNode === nodes[i]) continue;- var n = nodes[i];- var fx = 0, fy = 0;- for (var j = 0; j < nodes.length; j++) {- if (i === j) continue;- var dx = n.x - nodes[j].x;- var dy = n.y - nodes[j].y;- var dist = Math.sqrt(dx * dx + dy * dy) || 1;- var force = repulsion / (dist * dist);- fx += (dx / dist) * force;- fy += (dy / dist) * force;- }- if (graphSim.clustered && graphSim.typeCenters && graphSim.typeCenters[n.type]) {- var tc = graphSim.typeCenters[n.type];- fx += (tc.x - n.x) * 0.006;- fy += (tc.y - n.y) * 0.006;- } else {- fx -= n.x * centerGravity;- fy -= n.y * centerGravity;- }- var nvx = (n.vx + fx) * damping;- var nvy = (n.vy + fy) * damping;- // Velocity cap (#563): keep any single node from being launched- // off-screen by a one-tick force spike.- if (nvx > velocityCap) nvx = velocityCap; else if (nvx < -velocityCap) nvx = -velocityCap;- if (nvy > velocityCap) nvy = velocityCap; else if (nvy < -velocityCap) nvy = -velocityCap;- n.vx = nvx;- n.vy = nvy;- }+ function hashUnit(str, salt) {+ var h = 2166136261 ^ (salt || 0);+ var s = String(str);+ for (var i = 0; i < s.length; i++) { h ^= s.charCodeAt(i); h = Math.imul(h, 16777619); }+ return ((h >>> 0) % 100000) / 100000;+ }+ function graphNodeRadius(id) {+ var d = graphDegree(id);+ return Math.min(18, 6 + Math.sqrt(d) * 3.2);+ }- edges.forEach(function(e) {- var s = nodeMap[e.sourceNodeId];- var t = nodeMap[e.targetNodeId];- if (!s || !t) return;- var dx = t.x - s.x;- var dy = t.y - s.y;- var dist = Math.sqrt(dx * dx + dy * dy) || 1;- var f = (dist - 100) * attraction;- var fx = (dx / dist) * f;- var fy = (dy / dist) * f;- if (graphSim.dragNode !== s) { s.vx += fx; s.vy += fy; }- if (graphSim.dragNode !== t) { t.vx -= fx; t.vy -= fy; }+ function syncGraphSim(fresh) {+ var g = state.graph;+ var prev = fresh ? {} : graphSim.byId;+ var deg = graphLocalDegrees();+ var byId = {};+ var nodes = [];+ graphNodeList().forEach(function(n) {+ var s = prev[n.id];+ if (!s) s = { id: n.id, x: NaN, y: NaN, vx: 0, vy: 0, pinned: false };+ s.type = n.type;+ s.r = graphNodeRadius(n.id);+ s.isolated = !deg[n.id];+ byId[n.id] = s;+ nodes.push(s);});-- var totalKineticEnergy = 0;- nodes.forEach(function(n) {- if (graphSim.dragNode === n) return;- n.x += n.vx;- n.y += n.vy;- totalKineticEnergy += n.vx * n.vx + n.vy * n.vy;+ graphSim.byId = byId;+ graphSim.nodes = nodes;+ graphSim.edges = graphEdgeList().filter(function(e) { return byId[e.sourceNodeId] && byId[e.targetNodeId] && e.sourceNodeId !== e.targetNodeId; });+ var newcomers = nodes.filter(function(s) { return !s.isolated && isNaN(s.x); });+ newcomers.forEach(function(s) {+ var anchor = null;+ graphSim.edges.some(function(e) {+ var other = e.sourceNodeId === s.id ? byId[e.targetNodeId] : e.targetNodeId === s.id ? byId[e.sourceNodeId] : null;+ if (other && !isNaN(other.x) && !other.isolated) { anchor = other; return true; }+ return false;+ });+ var a = hashUnit(s.id, 1) * Math.PI * 2;+ var rad = anchor ? 60 : 40 + hashUnit(s.id, 2) * 220;+ s.x = (anchor ? anchor.x : 0) + Math.cos(a) * rad;+ s.y = (anchor ? anchor.y : 0) + Math.sin(a) * rad;});-- if (graphSim.autoFitPending && graphSim.tickCount > 45) {- graphSim.autoFitPending = false;- fitGraphToView();- }- // park the simulation when the layout is quiet to save CPU.- // Pick up again when a drag/interaction wakes the loop.- var rmsVelocity = nodes.length > 0 ? Math.sqrt(totalKineticEnergy / nodes.length) : 0;- if (rmsVelocity < 0.05 && graphSim.tickCount > 60 && !graphSim.dragNode) {- graphSim.quietTicks = (graphSim.quietTicks || 0) + 1;+ nodes.forEach(function(s) { if (!s.isolated && s.wasIsolated) { s.pinned = false; } s.wasIsolated = s.isolated; });+ if (fresh || !graphSim.fitted) {+ graphSim.alpha = 1;+ for (var i = 0; i < 320 && graphSim.alpha > 0.004; i++) graphTick();+ layoutIsolated();+ graphSim.fitted = false;+ fitGraph();} else {- graphSim.quietTicks = 0;+ layoutIsolated();+ if (newcomers.length || g.simStale) reheatGraph(0.35);}-- renderGraph();- if (graphSim.quietTicks > 30) {- graphSim.raf = null;- return;- }- graphSim.raf = requestAnimationFrame(runSimulation);+ g.simStale = false;}- var graphRebuilding = false;+ function layoutIsolated() {+ var conn = graphSim.nodes.filter(function(s) { return !s.isolated; });+ var iso = graphSim.nodes.filter(function(s) { return s.isolated; });+ iso.sort(function(a, b) {+ var na = state.graph.nodeMap[a.id] || {}, nb = state.graph.nodeMap[b.id] || {};+ return graphTypeRank(a.type) - graphTypeRank(b.type) || graphDegree(b.id) - graphDegree(a.id) || String(graphNodeLabel(na)).localeCompare(String(graphNodeLabel(nb)));+ });+ if (!iso.length) { graphSim.isolatedBox = null; return; }+ var minX = Infinity, maxX = -Infinity, maxY = -Infinity, minY = Infinity;+ conn.forEach(function(s) {+ minX = Math.min(minX, s.x - s.r); maxX = Math.max(maxX, s.x + s.r);+ minY = Math.min(minY, s.y - s.r); maxY = Math.max(maxY, s.y + s.r);+ });+ var cellW = 118, cellH = 46;+ var aspect = graphSim.w && graphSim.h ? graphSim.w / graphSim.h : 1.6;+ var cols = Math.max(2, Math.round(Math.sqrt(iso.length * aspect * cellH / cellW) * 1.3));+ if (conn.length && aspect > 1) cols = Math.max(cols, Math.min(14, Math.floor((maxX - minX) / cellW) + 1));+ cols = Math.min(cols, iso.length);+ var width = (cols - 1) * cellW;+ var cx = conn.length ? (minX + maxX) / 2 : 0;+ var top = conn.length ? maxY + 90 : 0;+ var x0 = cx - width / 2;+ iso.forEach(function(s, i) {+ if (s.pinned === 'user') return;+ s.x = x0 + (i % cols) * cellW;+ s.y = top + Math.floor(i / cols) * cellH;+ s.vx = 0; s.vy = 0;+ s.pinned = true;+ });+ var rows = Math.ceil(iso.length / cols);+ graphSim.isolatedBox = { x: x0 - 24, y: top - 30, w: width + 48, h: (rows - 1) * cellH + 50, count: iso.length };+ }- async function rebuildGraph() {- if (graphRebuilding) return;- var ok = window.confirm(- 'Rebuild the knowledge graph from every stored observation?\n\n' +- 'This replays the whole corpus and can take several minutes on a large store. ' +- 'With an LLM provider configured it also spends provider tokens.'- );- if (!ok) return;- graphRebuilding = true;- var sb = document.getElementById('graph-sidebar');- if (sb) sb.innerHTML = '<h3>Graph</h3><p style="font-size:12px;color:var(--ink-faint);font-style:italic;">Rebuilding graph from observations...</p>';- try {- var result = await apiPost('graph/build', {});- state.graph.rebuildResult = result && result.success- ? 'Rebuilt from ' + (result.sessions || 0) + ' sessions: ' + (result.nodes || 0) + ' nodes, ' + (result.edges || 0) + ' edges.'- : 'Graph rebuild failed or graph extraction is disabled. Check the server log.';- } finally {- graphRebuilding = false;- state.graph.loaded = false;- await loadGraph();- if (state.graph.queryError && state.graph.rebuildResult) {- state.graph.rebuildResult = 'The rebuild finished, but the graph could not be refreshed. Reload the Graph tab.';- }- var sidebar = document.getElementById('graph-sidebar');- if (sidebar && state.graph.rebuildResult) {- var note = document.createElement('p');- note.style.cssText = 'font-size:12px;color:var(--ink-muted);margin:8px 0;';- note.textContent = state.graph.rebuildResult;- sidebar.insertBefore(note, sidebar.firstChild);+ function graphTick() {+ var nodes = graphSim.nodes;+ var edges = graphSim.edges;+ var alpha = graphSim.alpha;+ var byId = graphSim.byId;+ var active = nodes.filter(function(s) { return !s.isolated; });+ var n = active.length;+ var repulse = n > 300 ? 1400 : 2200;+ for (var i = 0; i < n; i++) {+ var a = active[i];+ for (var j = i + 1; j < n; j++) {+ var b = active[j];+ var dx = a.x - b.x, dy = a.y - b.y;+ var d2 = dx * dx + dy * dy;+ if (d2 < 1) { dx = hashUnit(a.id + b.id, 3) - 0.5; dy = hashUnit(b.id + a.id, 4) - 0.5; d2 = dx * dx + dy * dy + 0.01; }+ if (d2 > 250000) continue;+ var f = (repulse * alpha) / d2;+ var d = Math.sqrt(d2);+ var fx = (dx / d) * f, fy = (dy / d) * f;+ a.vx += fx; a.vy += fy;+ b.vx -= fx; b.vy -= fy;}}+ edges.forEach(function(e) {+ var s = byId[e.sourceNodeId], t = byId[e.targetNodeId];+ if (!s || !t || s.isolated || t.isolated) return;+ var dx = t.x - s.x, dy = t.y - s.y;+ var d = Math.sqrt(dx * dx + dy * dy) || 1;+ var rest = 70 + s.r + t.r;+ var k = ((d - rest) / d) * 0.08 * alpha;+ s.vx += dx * k; s.vy += dy * k;+ t.vx -= dx * k; t.vy -= dy * k;+ });+ var moved = 0;+ active.forEach(function(s) {+ s.vx -= s.x * 0.012 * alpha;+ s.vy -= s.y * 0.012 * alpha;+ if (s.pinned || (graphSim.drag && graphSim.drag.id === s.id)) { s.vx = 0; s.vy = 0; return; }+ s.vx *= 0.55; s.vy *= 0.55;+ var sp = Math.sqrt(s.vx * s.vx + s.vy * s.vy);+ if (sp > 30) { s.vx *= 30 / sp; s.vy *= 30 / sp; }+ s.x += s.vx; s.y += s.vy;+ moved += sp;+ });+ graphSim.alpha *= 0.975;+ return moved;+ }++ function reheatGraph(alpha) {+ graphSim.alpha = Math.max(graphSim.alpha, alpha);+ if (!graphSim.raf) graphSim.raf = requestAnimationFrame(graphFrame);+ }+ function graphFrame() {+ graphSim.raf = null;+ if (!graphSim.canvas || !graphSim.canvas.isConnected) return;+ graphTick();+ layoutIsolated();+ drawGraph();+ if (graphSim.alpha > 0.01 || graphSim.drag) graphSim.raf = requestAnimationFrame(graphFrame);+ }+ function requestGraphDraw() {+ if (graphSim.drawQueued || graphSim.raf) return;+ graphSim.drawQueued = true;+ requestAnimationFrame(function() {+ graphSim.drawQueued = false;+ drawGraph();+ });}- function drawNodeShape(ctx, x, y, r, type) {- var shape = NODE_SHAPES[type] || 'circle';- switch(shape) {- case 'rect':- ctx.beginPath();- ctx.rect(x - r, y - r * 0.75, r * 2, r * 1.5);- break;- case 'diamond':- ctx.beginPath();- ctx.moveTo(x, y - r);- ctx.lineTo(x + r, y);- ctx.lineTo(x, y + r);- ctx.lineTo(x - r, y);- ctx.closePath();- break;+ function graphBounds(onlyVisible) {+ var minX = Infinity, maxX = -Infinity, minY = Infinity, maxY = -Infinity;+ graphSim.nodes.forEach(function(s) {+ if (onlyVisible && !graphTypeVisible(s.type)) return;+ minX = Math.min(minX, s.x - s.r); maxX = Math.max(maxX, s.x + s.r);+ minY = Math.min(minY, s.y - s.r); maxY = Math.max(maxY, s.y + s.r + 16);+ });+ if (!isFinite(minX)) return null;+ return { minX: minX, maxX: maxX, minY: minY, maxY: maxY };+ }+ function fitGraph() {+ if (!graphSim.w || !graphSim.h) return;+ var b = graphBounds(true) || graphBounds(false);+ if (!b) return;+ var narrow = graphSim.w < 600;+ var padX = narrow ? 46 : 70, padTop = narrow ? 40 : 70, padBottom = narrow ? 24 : 40;+ var spanX = Math.max(1, b.maxX - b.minX);+ var spanY = Math.max(1, b.maxY - b.minY);+ var z = Math.min((graphSim.w - padX * 2) / spanX, (graphSim.h - padTop - padBottom) / spanY);+ graphSim.zoom = Math.max(0.2, Math.min(1.6, z));+ graphSim.panX = graphSim.w / 2 - ((b.minX + b.maxX) / 2) * graphSim.zoom;+ graphSim.panY = padTop + (graphSim.h - padTop - padBottom) / 2 - ((b.minY + b.maxY) / 2) * graphSim.zoom;+ graphSim.fitted = true;+ requestGraphDraw();+ }+ function zoomGraphAt(factor, sx, sy) {+ var z = Math.max(0.15, Math.min(4, graphSim.zoom * factor));+ if (sx === undefined) { sx = graphSim.w / 2; sy = graphSim.h / 2; }+ var wx = (sx - graphSim.panX) / graphSim.zoom;+ var wy = (sy - graphSim.panY) / graphSim.zoom;+ graphSim.zoom = z;+ graphSim.panX = sx - wx * z;+ graphSim.panY = sy - wy * z;+ requestGraphDraw();+ }+ function centerGraphOn(id) {+ var s = graphSim.byId[id];+ if (!s || !graphSim.w) return;+ if (graphSim.zoom < 0.9) graphSim.zoom = 1.1;+ graphSim.panX = graphSim.w / 2 - s.x * graphSim.zoom;+ var narrow = window.matchMedia('(max-width: 720px)').matches && state.graph.selectedId;+ graphSim.panY = (narrow ? Math.max(40, (graphSim.h - window.innerHeight * 0.45) / 2) : graphSim.h / 2) - s.y * graphSim.zoom;+ requestGraphDraw();+ }+ function toScreen(s) {+ return { x: s.x * graphSim.zoom + graphSim.panX, y: s.y * graphSim.zoom + graphSim.panY };+ }+ function screenRadius(s) {+ return Math.max(3.5, s.r * Math.min(1.5, Math.max(0.55, graphSim.zoom)));+ }+ function graphHit(sx, sy) {+ var best = null, bestD = Infinity;+ graphSim.nodes.forEach(function(s) {+ if (!graphTypeVisible(s.type)) return;+ var p = toScreen(s);+ var r = screenRadius(s) + 5;+ var d = (p.x - sx) * (p.x - sx) + (p.y - sy) * (p.y - sy);+ if (d < r * r && d < bestD) { best = s; bestD = d; }+ });+ return best;+ }++ function graphShapePath(ctx, shape, x, y, r) {+ var i, a;+ ctx.beginPath();+ switch (shape) {+ case 'square': case 'squareRing':+ ctx.rect(x - r * 0.86, y - r * 0.86, r * 1.72, r * 1.72); break;+ case 'diamond': case 'diamondRing':+ ctx.moveTo(x, y - r * 1.15); ctx.lineTo(x + r * 1.15, y); ctx.lineTo(x, y + r * 1.15); ctx.lineTo(x - r * 1.15, y); ctx.closePath(); break;+ case 'triangle':+ ctx.moveTo(x, y - r * 1.15); ctx.lineTo(x + r * 1.1, y + r * 0.8); ctx.lineTo(x - r * 1.1, y + r * 0.8); ctx.closePath(); break;+ case 'triangleDown':+ ctx.moveTo(x, y + r * 1.15); ctx.lineTo(x + r * 1.1, y - r * 0.8); ctx.lineTo(x - r * 1.1, y - r * 0.8); ctx.closePath(); break;case 'hexagon':- ctx.beginPath();- for (var i = 0; i < 6; i++) {- var angle = (Math.PI / 3) * i - Math.PI / 2;- var hx = x + r * Math.cos(angle);- var hy = y + r * Math.sin(angle);- if (i === 0) ctx.moveTo(hx, hy); else ctx.lineTo(hx, hy);- }- ctx.closePath();- break;+ for (i = 0; i < 6; i++) { a = Math.PI / 3 * i; if (i === 0) ctx.moveTo(x + r * 1.05 * Math.cos(a), y + r * 1.05 * Math.sin(a)); else ctx.lineTo(x + r * 1.05 * Math.cos(a), y + r * 1.05 * Math.sin(a)); }+ ctx.closePath(); break;+ case 'pentagon':+ for (i = 0; i < 5; i++) { a = -Math.PI / 2 + (Math.PI * 2 / 5) * i; if (i === 0) ctx.moveTo(x + r * 1.1 * Math.cos(a), y + r * 1.1 * Math.sin(a)); else ctx.lineTo(x + r * 1.1 * Math.cos(a), y + r * 1.1 * Math.sin(a)); }+ ctx.closePath(); break;+ case 'star':+ for (i = 0; i < 10; i++) { a = -Math.PI / 2 + (Math.PI / 5) * i; var rr = i % 2 ? r * 0.55 : r * 1.25; if (i === 0) ctx.moveTo(x + rr * Math.cos(a), y + rr * Math.sin(a)); else ctx.lineTo(x + rr * Math.cos(a), y + rr * Math.sin(a)); }+ ctx.closePath(); break;+ case 'plus': case 'cross':+ var t = r * 0.42, l = r * 1.1;+ ctx.save(); ctx.translate(x, y); if (shape === 'cross') ctx.rotate(Math.PI / 4);+ ctx.moveTo(-t, -l); ctx.lineTo(t, -l); ctx.lineTo(t, -t); ctx.lineTo(l, -t); ctx.lineTo(l, t); ctx.lineTo(t, t); ctx.lineTo(t, l); ctx.lineTo(-t, l); ctx.lineTo(-t, t); ctx.lineTo(-l, t); ctx.lineTo(-l, -t); ctx.lineTo(-t, -t); ctx.closePath();+ ctx.restore(); break;default:- ctx.beginPath();ctx.arc(x, y, r, 0, Math.PI * 2);- break;}}-- function fitGraphToView() {- var canvas = graphSim.canvas;- if (!canvas || graphSim.nodes.length === 0) return;- var w = canvas.width / window.devicePixelRatio;- var h = canvas.height / window.devicePixelRatio;- var minX = Infinity, maxX = -Infinity, minY = Infinity, maxY = -Infinity;- graphSim.nodes.forEach(function(n) {- if (n.x < minX) minX = n.x;- if (n.x > maxX) maxX = n.x;- if (n.y < minY) minY = n.y;- if (n.y > maxY) maxY = n.y;- });- var pad = 150;- var spanX = (maxX - minX) + pad * 2;- var spanY = (maxY - minY) + pad * 2;- var z = Math.min(w / spanX, h / spanY);- graphSim.zoom = Math.max(0.35, Math.min(1.4, z));- graphSim.panX = w / 2 - ((minX + maxX) / 2) * graphSim.zoom;- graphSim.panY = h / 2 - ((minY + maxY) / 2) * graphSim.zoom;+ function graphShapeHollow(shape) {+ return shape === 'ring' || shape === 'squareRing' || shape === 'diamondRing';}-- function renderGraph() {+ function shapeSvg(type, size) {+ var s = size || 14;+ var c = s / 2;+ var r = s * 0.36;+ var shape = NODE_SHAPES[type] || 'circle';+ var color = nodeColor(type);+ var path = '';+ var pts = function(list) { return list.map(function(p) { return (c + p[0] * r).toFixed(2) + ',' + (c + p[1] * r).toFixed(2); }).join(' '); };+ var poly = function(n, start, scale) { var out = []; for (var i = 0; i < n; i++) { var a = start + (Math.PI * 2 / n) * i; out.push([Math.cos(a) * scale, Math.sin(a) * scale]); } return out; };+ switch (shape) {+ case 'square': case 'squareRing': path = '<rect x="' + (c - r * 0.86) + '" y="' + (c - r * 0.86) + '" width="' + (r * 1.72) + '" height="' + (r * 1.72) + '"'; break;+ case 'diamond': case 'diamondRing': path = '<polygon points="' + pts([[0, -1.15], [1.15, 0], [0, 1.15], [-1.15, 0]]) + '"'; break;+ case 'triangle': path = '<polygon points="' + pts([[0, -1.15], [1.1, 0.8], [-1.1, 0.8]]) + '"'; break;+ case 'triangleDown': path = '<polygon points="' + pts([[0, 1.15], [1.1, -0.8], [-1.1, -0.8]]) + '"'; break;+ case 'hexagon': path = '<polygon points="' + pts(poly(6, 0, 1.05)) + '"'; break;+ case 'pentagon': path = '<polygon points="' + pts(poly(5, -Math.PI / 2, 1.1)) + '"'; break;+ case 'star': var st = []; for (var i = 0; i < 10; i++) { var a = -Math.PI / 2 + (Math.PI / 5) * i; var rr = i % 2 ? 0.55 : 1.25; st.push([Math.cos(a) * rr, Math.sin(a) * rr]); } path = '<polygon points="' + pts(st) + '"'; break;+ case 'plus': path = '<polygon points="' + pts([[-0.42, -1.1], [0.42, -1.1], [0.42, -0.42], [1.1, -0.42], [1.1, 0.42], [0.42, 0.42], [0.42, 1.1], [-0.42, 1.1], [-0.42, 0.42], [-1.1, 0.42], [-1.1, -0.42], [-0.42, -0.42]]) + '"'; break;+ case 'cross': path = '<polygon transform="rotate(45 ' + c + ' ' + c + ')" points="' + pts([[-0.42, -1.1], [0.42, -1.1], [0.42, -0.42], [1.1, -0.42], [1.1, 0.42], [0.42, 0.42], [0.42, 1.1], [-0.42, 1.1], [-0.42, 0.42], [-1.1, 0.42], [-1.1, -0.42], [-0.42, -0.42]]) + '"'; break;+ default: path = '<circle cx="' + c + '" cy="' + c + '" r="' + r + '"';+ }+ var hollow = graphShapeHollow(shape);+ var fill = hollow ? 'none' : color;+ return '<svg class="g-shape" width="' + s + '" height="' + s + '" viewBox="0 0 ' + s + ' ' + s + '" aria-hidden="true">' + path + ' fill="' + fill + '" stroke="' + color + '" stroke-width="' + (hollow ? 2 : 1) + '"/></svg>';+ }+ function edgeSvg(type) {+ var dash = edgeDash(type);+ return '<svg class="g-edge" width="28" height="10" viewBox="0 0 28 10" aria-hidden="true"><line x1="1" y1="5" x2="22" y2="5" stroke="currentColor" stroke-width="1.6"' + (dash.length ? ' stroke-dasharray="' + dash.join(' ') + '"' : '') + '/><polygon points="21,1.5 27,5 21,8.5" fill="currentColor"/></svg>';+ }++ function drawGraph() {var ctx = graphSim.ctx;var canvas = graphSim.canvas;- if (!ctx || !canvas) return;- var w = canvas.width / window.devicePixelRatio;- var h = canvas.height / window.devicePixelRatio;-- ctx.clearRect(0, 0, w, h);-- // --- Canvas grid background ---- var gridSize = 24;- ctx.save();- ctx.strokeStyle = isDarkMode() ? 'rgba(255,255,255,0.04)' : 'rgba(0,0,0,0.04)';- ctx.lineWidth = 0.5;- for (var gx = 0; gx < w; gx += gridSize) {- ctx.beginPath(); ctx.moveTo(gx, 0); ctx.lineTo(gx, h); ctx.stroke();+ if (!ctx || !canvas || !graphSim.w) return;+ var g = state.graph;+ var dpr = graphSim.dpr;+ var dark = isDarkMode();+ var ink = dark ? '#eef0f3' : '#111111';+ var muted = dark ? '#94979d' : '#5c5f66';+ var bg = getComputedStyle(canvas.parentElement).backgroundColor || (dark ? '#16171a' : '#fbfaf7');+ var edgeBase = dark ? 'rgba(200,204,212,' : 'rgba(40,44,52,';+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0);+ ctx.clearRect(0, 0, graphSim.w, graphSim.h);++ var byId = graphSim.byId;+ var selected = g.selectedId;+ var focus = selected || graphSim.hoverId;+ var neighbors = {};+ if (focus) {+ graphSim.edges.forEach(function(e) {+ if (e.sourceNodeId === focus) neighbors[e.targetNodeId] = true;+ if (e.targetNodeId === focus) neighbors[e.sourceNodeId] = true;+ });}- for (var gy = 0; gy < h; gy += gridSize) {- ctx.beginPath(); ctx.moveTo(0, gy); ctx.lineTo(w, gy); ctx.stroke();+ var matches = {};+ var searching = g.search.trim().length > 0;+ if (searching) graphSearchMatches(500).forEach(function(n) { matches[n.id] = true; });+ function dimmed(id) {+ if (searching && !matches[id]) return true;+ if (focus && id !== focus && !neighbors[id]) return true;+ return false;}- ctx.restore();- ctx.save();- ctx.translate(graphSim.panX, graphSim.panY);- ctx.scale(graphSim.zoom, graphSim.zoom);+ var box = graphSim.isolatedBox;+ if (box) {+ var bx = box.x * graphSim.zoom + graphSim.panX, by = box.y * graphSim.zoom + graphSim.panY;+ var bw = box.w * graphSim.zoom, bh = box.h * graphSim.zoom;+ ctx.save();+ ctx.strokeStyle = dark ? 'rgba(255,255,255,0.14)' : 'rgba(0,0,0,0.14)';+ ctx.setLineDash([4, 4]);+ ctx.lineWidth = 1;+ ctx.strokeRect(Math.round(bx) + 0.5, Math.round(by) + 0.5, Math.round(bw), Math.round(bh));+ ctx.setLineDash([]);+ ctx.font = '600 10px Inter, system-ui, sans-serif';+ ctx.fillStyle = muted;+ ctx.textBaseline = 'bottom';+ ctx.fillText('NO RELATIONS YET · ' + box.count, Math.round(bx), Math.round(by) - 4);+ ctx.restore();+ }- var nodeMap = {};- graphSim.nodes.forEach(function(n) { nodeMap[n.id] = n; });-- var searchActive = graphSearchTerm.length > 0;- var drawnLabelRects = [];- function labelFits(x, y, w2, h2) {- for (var li = 0; li < drawnLabelRects.length; li++) {- var r = drawnLabelRects[li];- if (x < r.x + r.w && x + w2 > r.x && y < r.y + r.h && y + h2 > r.y) return false;+ var placed = [];+ function free(r) {+ if (r.x < 2 || r.y < 2 || r.x + r.w > graphSim.w - 2 || r.y + r.h > graphSim.h - 2) return false;+ for (var i = 0; i < placed.length; i++) {+ var p = placed[i];+ if (r.x < p.x + p.w && r.x + r.w > p.x && r.y < p.y + p.h && r.y + r.h > p.y) return false;}- drawnLabelRects.push({ x: x, y: y, w: w2, h: h2 });return true;}- var totalVisible = graphSim.nodes.filter(function(n) { return state.graph.filters[n.type]; }).length;- var isDense = totalVisible > 40;- var labelZoomThreshold = isDense ? 1.5 : 0.5;- var edgeLabelZoomThreshold = isDense ? 2.5 : 1.2;- var selectedId = state.graph.selectedNode ? state.graph.selectedNode.id : null;-- // --- Hover node detection for focus effect ---- var hoverNodeId = null;- if (!graphSim.dragNode && graphSim.canvas) {- var rect = graphSim.canvas.getBoundingClientRect();- var hx = (graphSim.mouseX - rect.left - graphSim.panX) / graphSim.zoom;- var hy = (graphSim.mouseY - rect.top - graphSim.panY) / graphSim.zoom;- for (var hi = graphSim.nodes.length - 1; hi >= 0; hi--) {- var hn = graphSim.nodes[hi];- if (!state.graph.filters[hn.type]) continue;- var hdx = hn.x - hx, hdy = hn.y - hy;- if (hdx * hdx + hdy * hdy < hn.r * hn.r + 25) { hoverNodeId = hn.id; break; }- }- }- var focusNodeId = selectedId || hoverNodeId;- // --- Draw edges ---- graphSim.edges.forEach(function(e) {- var s = nodeMap[e.sourceNodeId];- var t = nodeMap[e.targetNodeId];- if (!s || !t) return;- if (!state.graph.filters[s.type] || !state.graph.filters[t.type]) return;-- var edgeDimmed = searchActive && !(s.name.toLowerCase().includes(graphSearchTerm) || t.name.toLowerCase().includes(graphSearchTerm));- var isConnectedToFocus = focusNodeId && (e.sourceNodeId === focusNodeId || e.targetNodeId === focusNodeId);- var isFocusActive = focusNodeId !== null;- var weight = typeof e.weight === 'number' ? e.weight : 0.5;- var lineWidth = isConnectedToFocus ? 2 + weight * 2 : 1 + weight * 1.5;-- var dx = t.x - s.x;- var dy = t.y - s.y;+ var visibleEdges = graphSim.edges.filter(function(e) {+ var s = byId[e.sourceNodeId], t = byId[e.targetNodeId];+ return s && t && graphTypeVisible(s.type) && graphTypeVisible(t.type);+ });+ visibleEdges.forEach(function(e) {+ var s = byId[e.sourceNodeId], t = byId[e.targetNodeId];+ var a = toScreen(s), b = toScreen(t);+ var hot = focus && (e.sourceNodeId === focus || e.targetNodeId === focus);+ var dim = (focus && !hot) || (searching && !(matches[s.id] || matches[t.id]));+ var ra = screenRadius(s), rb = screenRadius(t);+ var dx = b.x - a.x, dy = b.y - a.y;var len = Math.sqrt(dx * dx + dy * dy) || 1;- var curveOffset = isDense ? 12 : 18;- var offsetX = -dy / len * curveOffset;- var offsetY = dx / len * curveOffset;- var cpx = (s.x + t.x) / 2 + offsetX;- var cpy = (s.y + t.y) / 2 + offsetY;-- // Colored edges based on source node type- var edgeColor = NODE_COLORS[s.type] || '#666666';- var edgeAlpha;- if (edgeDimmed) {- edgeAlpha = 0.06;- } else if (isFocusActive && isConnectedToFocus) {- edgeAlpha = 0.65;- } else if (isFocusActive && !isConnectedToFocus) {- edgeAlpha = 0.06;- } else {- edgeAlpha = isDense ? 0.15 : 0.25;- }-+ var ux = dx / len, uy = dy / len;+ var x1 = a.x + ux * (ra + 2), y1 = a.y + uy * (ra + 2);+ var x2 = b.x - ux * (rb + 3), y2 = b.y - uy * (rb + 3);+ if (len < ra + rb + 6) return;+ var alpha = dim ? 0.12 : hot ? 0.9 : 0.42;+ ctx.strokeStyle = edgeBase + alpha + ')';+ ctx.fillStyle = edgeBase + alpha + ')';+ ctx.lineWidth = hot ? 1.8 : 1.1 + Math.min(0.8, (e.weight || 0.5) * 0.6);+ ctx.setLineDash(edgeDash(e.type));ctx.beginPath();- ctx.moveTo(s.x, s.y);- ctx.quadraticCurveTo(cpx, cpy, t.x, t.y);- // Parse hex color to rgba- var r = parseInt(edgeColor.slice(1,3), 16);- var g = parseInt(edgeColor.slice(3,5), 16);- var b = parseInt(edgeColor.slice(5,7), 16);- ctx.strokeStyle = 'rgba(' + r + ',' + g + ',' + b + ',' + edgeAlpha + ')';- ctx.lineWidth = lineWidth;+ ctx.moveTo(x1, y1);+ ctx.lineTo(x2 - ux * 5, y2 - uy * 5);ctx.stroke();-- if (!isDense || isConnectedToFocus) {- var arrowAngle = Math.atan2(t.y - cpy, t.x - cpx);- var arrowLen = 5 + lineWidth;- ctx.beginPath();- ctx.moveTo(t.x - t.r * Math.cos(arrowAngle), t.y - t.r * Math.sin(arrowAngle));- ctx.lineTo(t.x - (t.r + arrowLen) * Math.cos(arrowAngle - 0.3), t.y - (t.r + arrowLen) * Math.sin(arrowAngle - 0.3));- ctx.lineTo(t.x - (t.r + arrowLen) * Math.cos(arrowAngle + 0.3), t.y - (t.r + arrowLen) * Math.sin(arrowAngle + 0.3));- ctx.closePath();- ctx.fillStyle = 'rgba(' + r + ',' + g + ',' + b + ',' + (edgeDimmed ? 0.06 : isConnectedToFocus ? 0.6 : 0.2) + ')';- ctx.fill();- }-- var showEdgeLabel = e.type && !edgeDimmed && (isConnectedToFocus ? graphSim.zoom > 0.6 : graphSim.zoom > edgeLabelZoomThreshold);- if (showEdgeLabel) {- var zoomInv = 1 / graphSim.zoom;- ctx.save();- ctx.fillStyle = isDarkMode() ? (isConnectedToFocus ? 'rgba(238,238,238,0.9)' : 'rgba(180,180,180,0.7)') : (isConnectedToFocus ? 'rgba(17,17,17,0.85)' : 'rgba(80,80,80,0.7)');- ctx.font = (isConnectedToFocus ? '600 ' : '500 ') + (11 * zoomInv).toFixed(1) + 'px Inter, sans-serif';- ctx.textAlign = 'center';- ctx.fillText(e.type, cpx, cpy - (4 * zoomInv));- ctx.restore();- }- });-- // --- Draw nodes ---- graphSim.nodes.forEach(function(n) {- if (!state.graph.filters[n.type]) return;- var color = NODE_COLORS[n.type] || '#666666';- var isSelected = selectedId === n.id;- var isHovered = hoverNodeId === n.id;- var matchesSearch = !searchActive || n.name.toLowerCase().includes(graphSearchTerm);- var isFocusFaded = graphSim.edges.length > 0 && focusNodeId && n.id !== focusNodeId && !graphSim.edges.some(function(ed) {- return (ed.sourceNodeId === focusNodeId && ed.targetNodeId === n.id) ||- (ed.targetNodeId === focusNodeId && ed.sourceNodeId === n.id);- });-- var nodeAlpha = !matchesSearch ? 0.12 : (isFocusFaded ? 0.2 : 1);-- ctx.save();- ctx.globalAlpha = nodeAlpha;-- // Glow effect- if (matchesSearch && !isFocusFaded && (isSelected || isHovered || !searchActive)) {- ctx.shadowColor = color;- ctx.shadowBlur = isSelected ? 20 : isHovered ? 16 : (isDense ? 4 : 8);- }-- // Gradient fill- drawNodeShape(ctx, n.x, n.y, n.r, n.type);- var grad = ctx.createRadialGradient(n.x - n.r * 0.3, n.y - n.r * 0.3, 0, n.x, n.y, n.r * 1.2);- var cr = parseInt(color.slice(1,3), 16);- var cg = parseInt(color.slice(3,5), 16);- var cb = parseInt(color.slice(5,7), 16);- grad.addColorStop(0, 'rgba(' + Math.min(255, cr + 60) + ',' + Math.min(255, cg + 60) + ',' + Math.min(255, cb + 60) + ',0.95)');- grad.addColorStop(1, color);- ctx.fillStyle = grad;+ ctx.setLineDash([]);+ ctx.beginPath();+ ctx.moveTo(x2, y2);+ ctx.lineTo(x2 - ux * 7 - uy * 3.5, y2 - uy * 7 + ux * 3.5);+ ctx.lineTo(x2 - ux * 7 + uy * 3.5, y2 - uy * 7 - ux * 3.5);+ ctx.closePath();ctx.fill();- ctx.restore();+ });- // Selected ring- if (isSelected) {- ctx.save();- drawNodeShape(ctx, n.x, n.y, n.r + 3, n.type);+ var order = graphSim.nodes.filter(function(s) { return graphTypeVisible(s.type); });+ order.sort(function(p, q) { return (dimmed(q.id) ? 0 : 1) - (dimmed(p.id) ? 0 : 1) || p.r - q.r; });+ order.reverse();+ order.forEach(function(s) {+ var p = toScreen(s);+ var r = screenRadius(s);+ if (p.x < -r - 4 || p.y < -r - 4 || p.x > graphSim.w + r + 4 || p.y > graphSim.h + r + 4) return;+ var shape = NODE_SHAPES[s.type] || 'circle';+ var color = nodeColor(s.type);+ ctx.globalAlpha = dimmed(s.id) ? 0.22 : 1;+ graphShapePath(ctx, shape, p.x, p.y, r);+ if (graphShapeHollow(shape)) {+ ctx.fillStyle = bg;+ ctx.fill();+ ctx.lineWidth = Math.max(2, r * 0.38);ctx.strokeStyle = color;- ctx.lineWidth = 3;- ctx.shadowColor = color;- ctx.shadowBlur = 12;ctx.stroke();- ctx.restore();- } else if (isHovered) {- drawNodeShape(ctx, n.x, n.y, n.r + 2, n.type);- ctx.strokeStyle = color;- ctx.lineWidth = 2;+ } else {+ ctx.fillStyle = color;+ ctx.fill();+ ctx.lineWidth = 1.5;+ ctx.strokeStyle = bg;ctx.stroke();- } else if (searchActive && matchesSearch) {- drawNodeShape(ctx, n.x, n.y, n.r, n.type);- ctx.strokeStyle = '#CC0000';- ctx.lineWidth = 2;+ }+ ctx.globalAlpha = 1;+ if (s.id === selected || s.id === graphSim.hoverId || (searching && matches[s.id])) {+ graphShapePath(ctx, shape, p.x, p.y, r + 4);+ ctx.lineWidth = s.id === selected ? 2.2 : 1.4;+ ctx.strokeStyle = s.id === selected ? ink : searching && matches[s.id] && s.id !== graphSim.hoverId ? (dark ? '#f2555a' : '#cc0000') : muted;ctx.stroke();}-- var showLabel = matchesSearch && !isFocusFaded && (- isSelected || isHovered ||- (searchActive && matchesSearch) ||- (totalVisible <= 30 && graphSim.zoom > 0.5) ||- (!isDense && graphSim.zoom > labelZoomThreshold) ||- (isDense && graphSim.zoom > labelZoomThreshold && n.r > 10)- );- if (showLabel) {- var zoomInv = 1 / graphSim.zoom;- ctx.save();- ctx.font = (isSelected || isHovered ? '600 ' : '500 ') + (13 * zoomInv).toFixed(1) + 'px Inter, sans-serif';- ctx.textAlign = 'center';-- var label = truncate(n.name, 18);- var textW = ctx.measureText(label).width;- var labelW = textW + (16 * zoomInv);- var labelH = 20 * zoomInv;- var labelY = n.y + n.r + (8 * zoomInv); // Top of the background pill- // Selected/hovered labels always win; others draw only into- // free space so zoomed-out views degrade to fewer labels- // instead of a pile of overlapping pills.- if (!isSelected && !isHovered && !labelFits(n.x - labelW / 2, labelY, labelW, labelH)) {- ctx.restore();- return;- }- ctx.fillStyle = isDarkMode() ? 'rgba(30,30,35,0.92)' : 'rgba(255,255,255,0.92)';+ if (g.fresh[s.id] && Date.now() - g.fresh[s.id] < 4000) {ctx.beginPath();- ctx.roundRect ? ctx.roundRect(n.x - labelW / 2, labelY, labelW, labelH, 4 * zoomInv) : ctx.rect(n.x - labelW / 2, labelY, labelW, labelH);- ctx.fill();-- ctx.strokeStyle = isDarkMode() ? 'rgba(255,255,255,0.08)' : 'rgba(0,0,0,0.08)';- ctx.lineWidth = 1 * zoomInv;+ ctx.arc(p.x, p.y, r + 7, 0, Math.PI * 2);+ ctx.lineWidth = 1.2;+ ctx.strokeStyle = dark ? 'rgba(92,192,143,0.9)' : 'rgba(45,106,79,0.9)';ctx.stroke();-- ctx.fillStyle = isDarkMode() ? (isSelected || isHovered ? '#eeeeee' : '#bbbbbb') : (isSelected || isHovered ? '#111111' : '#444444');- // Vertically center text in the pill box- ctx.fillText(label, n.x, labelY + (14 * zoomInv));- ctx.restore();}+ placed.push({ x: p.x - r, y: p.y - r, w: r * 2, h: r * 2, node: s.id });});- ctx.restore();-- if (graphSim.nodes.length === 0) {- ctx.fillStyle = '#999999';- ctx.font = '14px Lora, Georgia, serif';- ctx.textAlign = 'center';- ctx.fillText('No graph data yet.', w / 2, h / 2 - 16);- ctx.font = '12px Inter, sans-serif';- ctx.fillText('Set GRAPH_EXTRACTION_ENABLED=true to enable knowledge graph extraction.', w / 2, h / 2 + 8);- }+ var labelList = order.slice().sort(function(p, q) {+ function pri(s) {+ if (s.id === selected) return 5;+ if (s.id === graphSim.hoverId) return 4;+ if (searching && matches[s.id]) return 3;+ if (focus && neighbors[s.id]) return 2;+ return dimmed(s.id) ? 0 : 1;+ }+ return pri(q) - pri(p) || graphDegree(q.id) - graphDegree(p.id) || String(p.id).localeCompare(String(q.id));+ });+ var labeled = 0;+ ctx.textBaseline = 'middle';+ ctx.lineJoin = 'round';+ labelList.forEach(function(s) {+ if (focus && dimmed(s.id) && s.id !== selected) return;+ if (searching && !matches[s.id] && s.id !== selected) return;+ var node = g.nodeMap[s.id];+ if (!node) return;+ var strong = s.id === selected || s.id === graphSim.hoverId;+ var text = graphNodeLabel(node, strong ? 48 : 26);+ ctx.font = (strong ? '700 12px ' : '500 11px ') + 'Inter, system-ui, sans-serif';+ var tw = ctx.measureText(text).width;+ var p = toScreen(s);+ var r = screenRadius(s);+ var h = strong ? 15 : 14;+ var spots = [+ { x: p.x - tw / 2, y: p.y + r + 3 },+ { x: p.x + r + 5, y: p.y - h / 2 },+ { x: p.x - tw / 2, y: p.y - r - 3 - h },+ { x: p.x - r - 5 - tw, y: p.y - h / 2 }+ ];+ var own = placed.filter(function(pl) { return pl.node === s.id; });+ own.forEach(function(pl) { placed.splice(placed.indexOf(pl), 1); });+ var spot = null;+ for (var i = 0; i < spots.length; i++) {+ var rect = { x: spots[i].x - 2, y: spots[i].y, w: tw + 4, h: h };+ if (strong || free(rect)) { spot = rect; break; }+ }+ own.forEach(function(pl) { placed.push(pl); });+ if (!spot) return;+ placed.push(spot);+ labeled++;+ ctx.strokeStyle = bg;+ ctx.lineWidth = 3.5;+ ctx.strokeText(text, spot.x + 2, spot.y + h / 2);+ ctx.fillStyle = strong ? ink : (dark ? '#d6d8dc' : '#26282c');+ ctx.fillText(text, spot.x + 2, spot.y + h / 2);+ });++ ctx.font = '500 10px "JetBrains Mono", ui-monospace, monospace';+ visibleEdges.forEach(function(e) {+ var s = byId[e.sourceNodeId], t = byId[e.targetNodeId];+ var hot = focus && (e.sourceNodeId === focus || e.targetNodeId === focus);+ if (focus && !hot) return;+ if (searching && !(matches[s.id] || matches[t.id])) return;+ if (!hot && e.type === 'related_to' && graphSim.zoom < 1.3) return;+ var a = toScreen(s), b = toScreen(t);+ var len = Math.sqrt((b.x - a.x) * (b.x - a.x) + (b.y - a.y) * (b.y - a.y));+ var text = String(e.type || '').replace(/_/g, ' ');+ var tw = ctx.measureText(text).width;+ if (!hot && len < tw + screenRadius(s) + screenRadius(t) + 24) return;+ var rect = { x: (a.x + b.x) / 2 - tw / 2 - 3, y: (a.y + b.y) / 2 - 7, w: tw + 6, h: 13 };+ if (!free(rect)) return;+ placed.push(rect);+ ctx.fillStyle = bg;+ ctx.globalAlpha = 0.9;+ ctx.fillRect(rect.x, rect.y, rect.w, rect.h);+ ctx.globalAlpha = 1;+ ctx.fillStyle = hot ? ink : muted;+ ctx.fillText(text, rect.x + 3, rect.y + 6.5);+ });+ graphSim.labeled = labeled;}- async function loadMemories() {- var el = document.getElementById('view-memories');- if (!state.memories.loaded) el.innerHTML = '<div class="loading">Loading memories...</div>';- // cap at 2000 so the viewer remains responsive on large- // corpora. Older endpoints returned the full unbounded list which- // hit the iii invocation timeout and the UI fell through to 0.- var result = await apiGet('memories?latest=true&limit=2000');- var items = (result && result.memories) || [];- // Newest first — server returns KV-insertion order.- items.sort(function(a, b) {- var ac = (a && a.createdAt) || (a && a.updatedAt) || '';- var bc = (b && b.createdAt) || (b && b.updatedAt) || '';- return bc.localeCompare(ac);+ function graphLlmMode() {+ var flag = (store.flags || []).filter(function(f) { return f && f.key === 'GRAPH_EXTRACTION_ENABLED'; })[0];+ var llm = store.provider && store.provider !== 'noop';+ if (flag && flag.enabled && llm) return 'llm';+ if (!llm) return 'no-llm';+ return 'flag-off';+ }+ function graphLlmNote() {+ var mode = graphLlmMode();+ if (mode === 'llm') return 'LLM extraction is on: finished sessions add typed entities (functions, errors, decisions) and typed relations (uses, fixes, depends on).';+ if (mode === 'no-llm') return 'No LLM provider is set, so only structural relations exist: files and concepts that show up in the same observation, plus anything imported from a code graph. Typed entities and relations need an LLM.';+ return 'An LLM provider is set but GRAPH_EXTRACTION_ENABLED is off, so only structural relations exist. Turn it on for typed entities and relations.';+ }++ function renderGraphView() {+ var el = document.getElementById('view-graph');+ if (!el) return;+ if (!el.querySelector('.graph-page')) {+ el.innerHTML =+ '<div class="graph-page">' ++ '<div class="graph-toolbar" id="graph-toolbar">' ++ '<div class="graph-search-wrap"><input type="search" id="graph-search" class="graph-search" placeholder="Find a node (press /)" aria-label="Find a node by name" autocomplete="off" aria-controls="graph-search-results"><div id="graph-search-results" class="graph-search-results" role="listbox" aria-label="Matching nodes" hidden></div></div>' ++ '<select id="graph-type-filter" aria-label="Filter nodes by type"></select>' ++ '<span id="graph-summary" class="graph-summary"></span>' ++ '<button type="button" class="btn graph-build" data-action="rebuild-graph">Rebuild</button>' ++ '</div>' ++ '<div class="graph-body">' ++ '<div class="graph-stage" id="graph-stage">' ++ '<canvas id="graph-canvas" tabindex="0" role="img" aria-label="Knowledge graph. Use plus and minus to zoom, 0 to fit, arrow keys to pan. Pick nodes from the list beside the graph."></canvas>' ++ '<div class="graph-zoom" role="group" aria-label="Zoom">' ++ '<button type="button" data-action="zoom-graph" data-dir="1" aria-label="Zoom in" title="Zoom in (+)">+</button>' ++ '<button type="button" data-action="zoom-graph" data-dir="-1" aria-label="Zoom out" title="Zoom out (-)">−</button>' ++ '<button type="button" data-action="recenter-graph" aria-label="Fit the graph to the view" title="Fit (0)">fit</button>' ++ '</div>' ++ '<div class="graph-tooltip" id="graph-tooltip" role="tooltip"></div>' ++ '<div class="graph-stage-msg" id="graph-stage-msg" hidden></div>' ++ '</div>' ++ '<aside class="graph-side" aria-label="Graph details"><div id="graph-detail"></div><div id="graph-overview"></div></aside>' ++ '</div>' ++ '</div>';+ bindGraphChrome();+ mountGraphCanvas();+ }+ renderGraphToolbar();+ renderGraphStage();+ renderGraphDetail();+ renderGraphOverview();+ requestGraphDraw();+ }++ function renderGraphToolbar() {+ var g = state.graph;+ var sel = document.getElementById('graph-type-filter');+ if (sel) {+ var types = graphTypeCounts();+ var hiddenCount = types.filter(function(t) { return g.hidden[t.type]; }).length;+ var visible = types.filter(function(t) { return !g.hidden[t.type]; });+ var value = hiddenCount === 0 ? '' : (visible.length === 1 ? visible[0].type : '__custom');+ var html = '<option value="">All types (' + fmtNum(graphNodeList().length) + ')</option>';+ types.forEach(function(t) { html += '<option value="' + esc(t.type) + '">Only ' + esc(t.type) + ' (' + fmtNum(t.shown) + ')</option>'; });+ if (value === '__custom') html += '<option value="__custom">' + visible.length + ' of ' + types.length + ' types</option>';+ if (sel.__html !== html) { sel.innerHTML = html; sel.__html = html; }+ sel.value = value;+ sel.disabled = types.length === 0;+ }+ var sum = document.getElementById('graph-summary');+ if (sum) {+ var t = graphTotals();+ var shown = graphNodeList().length;+ var text = fmtNum(t.nodes) + ' nodes ' + help('graphNode') + ' · ' + fmtNum(t.edges) + ' relations ' + help('graphEdge');+ if (g.truncated && shown < t.nodes) text += ' · showing the ' + fmtNum(shown) + ' most connected';+ setViewHtml(sum, text);+ }+ var input = document.getElementById('graph-search');+ if (input && document.activeElement !== input && input.value !== g.search) input.value = g.search;+ renderGraphSearchResults();+ }++ function renderGraphSearchResults() {+ var g = state.graph;+ var box = document.getElementById('graph-search-results');+ if (!box) return;+ var q = g.search.trim();+ if (!q || !g.searchOpen) { box.hidden = true; box.innerHTML = ''; return; }+ var hits = graphSearchMatches(8);+ var html = '';+ hits.forEach(function(n, i) {+ html += '<button type="button" role="option" class="gs-hit' + (i === g.searchIndex ? ' active' : '') + '" aria-selected="' + (i === g.searchIndex ? 'true' : 'false') + '" data-action="graph-select" data-node-id="' + esc(n.id) + '">' + shapeSvg(n.type, 12) + '<span class="gs-name" title="' + esc(n.name) + '">' + esc(n.type === 'file' && String(n.name).indexOf('/') >= 0 ? (String(n.name).length > 48 ? '…' + String(n.name).slice(-47) : n.name) : graphNodeLabel(n, 60)) + '</span><span class="gs-meta">' + esc(n.type) + ' · ' + graphDegree(n.id) + '</span></button>';});- state.memories.items = items;- state.memories.total = (result && typeof result.total === 'number') ? result.total : items.length;- state.memories.loaded = true;- renderMemories();+ if (!hits.length) html += '<div class="gs-empty">No node in view matches “' + esc(q) + '”.</div>';+ if (g.truncated) html += '<button type="button" class="gs-hit gs-remote" data-action="graph-search-remote">Search all ' + fmtNum(graphTotals().nodes) + ' nodes on the server</button>';+ box.innerHTML = html;+ box.hidden = false;}- function renderMemories() {- var el = document.getElementById('view-memories');- var items = state.memories.items;- var search = state.memories.search.toLowerCase();- var typeFilter = state.memories.typeFilter;-- var filtered = items.filter(function(m) {- if (typeFilter && m.type !== typeFilter) return false;- const normalizedSearch = (search || '')- .normalize("NFKC")- .toLowerCase();-- const normalizedTitle = (m.title || '')- .normalize("NFKC")- .toLowerCase();-- const normalizedContent = (m.content || '')- .normalize("NFKC")- .toLowerCase();-- if (- search &&- !normalizedTitle.includes(normalizedSearch) &&- !normalizedContent.includes(normalizedSearch)- ) {- return false;+ function renderGraphStage() {+ var g = state.graph;+ var msg = document.getElementById('graph-stage-msg');+ var page = document.querySelector('#view-graph .graph-page');+ if (!msg || !page) return;+ var html = '';+ var empty = g.loaded && !g.queryError && !g.disabledInfo && graphNodeList().length === 0;+ if (!g.loaded) {+ html = '<div class="graph-loading">' + skeleton(4) + '<div class="empty-step-label">Loading the graph…</div></div>';+ } else if (g.disabledInfo) {+ html = emptyState({+ icon: '◌',+ title: 'The knowledge graph is off',+ what: 'Entities and relations agentmemory pulls out of what agents do.',+ why: esc(g.disabledInfo.enableHow || 'Graph extraction is disabled on this server.'),+ steps: [{ label: 'Turn it on and restart:', cmd: 'export GRAPH_EXTRACTION_ENABLED=true\nexport ANTHROPIC_API_KEY=sk-ant-...\nnpx @agentmemory/agentmemory' }],+ link: g.disabledInfo.docsHref ? { href: g.disabledInfo.docsHref, text: 'Knowledge graph docs' } : null+ });+ } else if (g.queryError) {+ html = emptyState({+ icon: '⚠',+ title: 'The graph could not be loaded',+ what: 'The graph page reads the top ' + GRAPH_LIMIT + ' most connected nodes in one request.',+ why: esc(g.queryError),+ steps: [{ label: 'Try the same request from a terminal:', cmd: curlPost('graph/query', { limit: GRAPH_LIMIT }) }]+ }) + '<div class="graph-msg-actions"><button type="button" class="btn" data-action="graph-retry">Retry</button></div>';+ } else if (empty) {+ html = emptyState({+ icon: '◌',+ title: 'No knowledge graph yet',+ what: 'A map of the files, functions, concepts, errors and decisions agents worked with, and how they relate. Each node links back to the observations and sessions it came from.',+ why: (store.counts && store.counts.sessions ? 'Nodes are added when a session ends: its observations are scanned for files and concepts. None of the ' + fmtNum(store.counts.sessions) + ' sessions has produced any yet. ' : 'No session has ended yet, and nothing was imported. ') + esc(graphLlmNote()),+ steps: [+ { label: 'Build it now from every stored observation (spends LLM tokens when extraction is on):', cmd: curlPost('graph/build', {}) },+ { label: 'Or import a structural code graph made by graphify (no LLM needed):', cmd: curlPost('graph/import-graphify', { cwd: '/path/to/repo' }) },+ { label: 'For typed entities and relations, turn on LLM extraction and restart:', cmd: 'export GRAPH_EXTRACTION_ENABLED=true\nexport ANTHROPIC_API_KEY=sk-ant-...' }+ ]+ }) + '<div class="graph-msg-actions"><button type="button" class="btn btn-primary" data-action="rebuild-graph">Build from observations</button></div>';+ }+ page.classList.toggle('is-empty', !!html && g.loaded);+ if (msg.__html !== html) { msg.innerHTML = html; msg.__html = html; }+ msg.hidden = !html;+ }++ function graphDetailRelations(id) {+ var g = state.graph;+ var rows = {};+ var d = g.detail && g.detail.id === id && g.detail.data ? g.detail.data : null;+ if (d && d.relations) d.relations.forEach(function(r) { rows[r.edgeId] = r; });+ graphEdgeList().forEach(function(e) {+ if (e.sourceNodeId !== id && e.targetNodeId !== id) return;+ var out = e.sourceNodeId === id;+ var n = g.nodeMap[out ? e.targetNodeId : e.sourceNodeId];+ rows[e.id] = { edgeId: e.id, type: e.type, direction: out ? 'out' : 'in', weight: e.weight, observationCount: (e.sourceObservationIds || []).length, neighbor: n ? { id: n.id, name: n.name, type: n.type } : (rows[e.id] && rows[e.id].neighbor) || null };+ });+ return Object.keys(rows).map(function(k) { return rows[k]; }).sort(function(a, b) {+ return String(a.type).localeCompare(String(b.type)) || (a.direction === b.direction ? 0 : a.direction === 'out' ? -1 : 1) || String(a.neighbor && a.neighbor.name).localeCompare(String(b.neighbor && b.neighbor.name));+ });+ }++ function graphCloseBtn() {+ return '<button type="button" class="icon-btn icon-close" data-action="graph-close" aria-label="Close node details">close</button>';+ }++ function renderGraphDetail() {+ var panel = document.getElementById('graph-detail');+ if (!panel) return;+ var g = state.graph;+ var page = document.querySelector('#view-graph .graph-page');+ if (page) page.classList.toggle('has-detail', !!g.selectedId);+ if (!g.selectedId) { setViewHtml(panel, ''); return; }+ var id = g.selectedId;+ var d = g.detail && g.detail.id === id ? g.detail : null;+ var node = g.nodeMap[id] || (d && d.data && d.data.node) || null;+ if (!node) {+ if (d && d.error) {+ setViewHtml(panel, '<div class="detail-panel mem-detail gd"><div class="mem-detail-head"><span>Node</span>' + graphCloseBtn() + '</div>' + emptyState({+ compact: true,+ icon: '🔍',+ title: 'Node not found',+ what: 'Graph links open this panel by node id.',+ why: 'No node has the id <code>' + esc(id) + '</code>. The graph was reset or rebuilt since the link was made.',+ steps: [{ label: 'Check from a terminal:', cmd: curlGet('graph/node?id=' + encodeURIComponent(id)) }]+ }) + '</div>');+ return;}+ setViewHtml(panel, '<div class="detail-panel mem-detail gd"><div class="mem-detail-head"><span>Loading node ' + esc(shortId(id)) + '…</span>' + graphCloseBtn() + '</div>' + skeleton(5) + '</div>');+ return;+ }+ var data = d && d.data ? d.data : null;+ var degree = data && typeof data.degree === 'number' ? data.degree : graphDegree(id);+ var html = '<div class="detail-panel mem-detail gd" data-detail-id="' + esc(id) + '">';+ html += '<div class="mem-detail-head">' + shapeSvg(node.type, 14) + '<span class="badge badge-muted gd-type" style="color:' + nodeColor(node.type) + ';border-color:' + nodeColor(node.type) + ';">' + esc(node.type) + '</span><span>' + fmtNum(degree) + ' relation' + (degree === 1 ? '' : 's') + ' ' + help('graphDegree') + '</span>' + graphCloseBtn() + '</div>';+ html += '<h3 class="gd-name" tabindex="-1">' + esc(node.name) + '</h3>';+ if (NODE_TYPE_TEXT[node.type]) html += '<div class="gd-typetext">' + esc(NODE_TYPE_TEXT[node.type]) + '</div>';+ html += '<div class="mem-actions">';+ html += '<button type="button" class="btn" data-action="graph-center" data-node-id="' + esc(id) + '">Center</button>';+ html += copyBtn(id, 'node id').replace('>copy<', '>copy id<');+ html += copyBtn(node.name, 'node name').replace('>copy<', '>copy name<');+ html += copyBtn('memory_graph_query { "startNodeId": ' + JSON.stringify(id) + ', "maxDepth": 1 }', 'MCP call').replace('>copy<', '>copy MCP call<');+ html += copyBtn(curlGet('graph/node?id=' + encodeURIComponent(id)), 'curl command').replace('>copy<', '>copy curl<');+ html += '</div>';+ if (d && d.stale) html += '<div class="mem-note">This node changed on the live stream. <button type="button" class="linkish" data-action="graph-refresh-detail" data-node-id="' + esc(id) + '">Reload sources</button></div>';++ var rels = graphDetailRelations(id);+ var relTotal = data && typeof data.relationsTotal === 'number' ? Math.max(data.relationsTotal, rels.length) : rels.length;+ html += '<div class="mem-section"><div class="mem-section-title">Relations ' + help('graphEdge') + '<span class="gd-count">' + fmtNum(rels.length) + (relTotal > rels.length ? ' of ' + fmtNum(relTotal) : '') + '</span></div>';+ if (data && data.relationsWarning) html += '<div class="mem-note">' + esc(data.relationsWarning) + '</div>';+ if (!rels.length) {+ html += '<div class="empty-step-label">' + (d && d.loading ? 'Loading relations…' : 'No relations yet. ' + esc(graphLlmMode() === 'llm' ? 'Relations appear as later sessions mention this entity together with others.' : 'Without LLM extraction, a relation appears only when this entity shows up in the same observation as another file or concept.')) + '</div>';+ } else {+ html += '<ul class="gd-rels">';+ rels.slice(0, 60).forEach(function(r) {+ var n = r.neighbor;+ html += '<li><span class="gd-dir" title="' + (r.direction === 'out' ? 'This node ' + esc(r.type) + ' the other' : 'The other node ' + esc(r.type) + ' this one') + '">' + (r.direction === 'out' ? '→' : '←') + '</span><span class="gd-etype" title="' + esc(EDGE_TYPE_TEXT[r.type] || r.type) + '">' + esc(String(r.type).replace(/_/g, ' ')) + '</span>';+ html += n ? '<button type="button" class="gd-neighbor" data-action="graph-select" data-node-id="' + esc(n.id) + '" title="Open ' + esc(n.name) + '">' + shapeSvg(n.type, 11) + '<span>' + esc(graphNodeLabel(n, 48)) + '</span></button>' : '<span class="gd-missing">node no longer stored</span>';+ html += '</li>';+ });+ html += '</ul>';+ if (rels.length > 60) html += '<div class="empty-step-label">+' + fmtNum(rels.length - 60) + ' more. ' + cmdBlock(curlGet('graph/node?id=' + encodeURIComponent(id))) + '</div>';+ }+ html += '</div>';- return true;- });+ html += '<div class="mem-section"><div class="mem-section-title">Where it came from ' + help('graphProvenance') + '</div>';+ if (!data) {+ html += d && d.error ? '<div class="mem-note err">Could not load the sources: ' + esc(d.error) + '</div>' : skeleton(3);+ } else {+ var p = data.provenance || {};+ var obs = p.observations || [];+ var any = false;+ html += '<dl class="mem-meta">';+ if (p.structural) {+ any = true;+ html += '<dt>Import</dt><dd>' + esc(p.structural.source === 'graphify' ? 'Structural code graph (graphify)' : p.structural.source) + (p.structural.sourceFile ? ' · <code>' + esc(p.structural.sourceFile) + '</code>' : '') + '</dd>';+ }+ if (p.projects && p.projects.length) {+ any = true;+ html += '<dt>Projects ' + help('project') + '</dt><dd class="tag-list" style="margin:0;">' + p.projects.map(function(pr) { return '<span class="mem-chip" title="' + esc(pr) + '">' + esc(pr) + '</span>'; }).join('') + '</dd>';+ }+ if (p.sessions && p.sessions.length) {+ any = true;+ html += '<dt>Sessions ' + help('session') + '</dt><dd>' + p.sessions.slice(0, 10).map(function(s) { return '<span class="id-chip">' + entityLink('session', s.id, (s.project ? s.project + ' · ' : '') + shortId(s.id, 16)) + copyBtn(s.id, 'session id') + '</span>'; }).join(' ') + (p.sessions.length > 10 ? ' +' + (p.sessions.length - 10) + ' more' : '') + '</dd>';+ }+ html += '</dl>';+ if (obs.length) {+ any = true;+ var totalObs = (p.observationIds || []).length;+ html += '<div class="gd-sub">Observations <span class="gd-count">' + fmtNum(obs.length) + (totalObs > obs.length ? ' of ' + fmtNum(totalObs) : '') + '</span></div><ul class="gd-obs">';+ obs.slice(0, 12).forEach(function(o) {+ html += '<li><a class="entity-link" href="#sessions/' + encodeURIComponent(o.sessionId) + '?obs=' + encodeURIComponent(o.id) + '" title="Open observation ' + esc(o.id) + ' in session ' + esc(o.sessionId) + '">' + esc(o.title || shortId(o.id)) + '</a><span class="gd-obs-meta">' + esc(o.type ? String(o.type).replace(/_/g, ' ') : '') + ' ' + relTime(o.timestamp) + '</span>' + copyBtn(o.id, 'observation id') + '</li>';+ });+ html += '</ul>';+ if (obs.length > 12) html += '<div class="empty-step-label">+' + fmtNum(obs.length - 12) + ' more in the sessions above.</div>';+ }+ if (p.memories && p.memories.length) {+ any = true;+ html += '<div class="gd-sub">Memories <span class="gd-count">' + fmtNum(p.memories.length) + '</span></div><ul class="gd-obs">';+ p.memories.forEach(function(m) {+ html += '<li>' + entityLink('memory', m.id, m.title || shortId(m.id)) + '<span class="gd-obs-meta">' + esc(m.type || '') + (m.via === 'name' ? ' · mentions it' : ' · same observations') + '</span></li>';+ });+ html += '</ul>';+ }+ if (!any) html += '<div class="empty-step-label">No sources recorded. Nodes added before provenance tracking, or through a direct API call, carry no observation ids.</div>';+ }+ html += '</div>';- var types = {};- items.forEach(function(m) { types[m.type] = true; });- var typeOptions = Object.keys(types).sort();+ html += '<div class="mem-section"><div class="mem-section-title">Details</div><dl class="mem-meta">';+ html += '<dt>Id</dt><dd>' + '<span class="id-chip"><span class="entity-link" title="' + esc(id) + '">' + esc(shortId(id, 22)) + '</span>' + copyBtn(id, 'node id') + '</span></dd>';+ if (node.createdAt) html += '<dt>First seen</dt><dd>' + relTime(node.createdAt) + '</dd>';+ if (node.updatedAt && node.updatedAt !== node.createdAt) html += '<dt>Updated</dt><dd>' + relTime(node.updatedAt) + '</dd>';+ if (node.aliases && node.aliases.length) html += '<dt>Also called</dt><dd>' + node.aliases.map(esc).join(', ') + '</dd>';+ Object.keys(node.properties || {}).slice(0, 8).forEach(function(k) {+ html += '<dt>' + esc(k) + '</dt><dd>' + esc(truncate(String(node.properties[k]), 120)) + '</dd>';+ });+ html += '</dl></div>';+ html += '<details style="margin-top:12px;"><summary style="cursor:pointer;font-size:11px;color:var(--ink-faint);font-family:var(--font-mono);">raw record</summary><pre class="gd-raw">' + esc(JSON.stringify(node, null, 2)) + '</pre></details>';+ html += '</div>';+ setViewHtml(panel, html);+ }- var html = '<div class="card" style="margin-bottom:12px;padding:12px;background:var(--bg-subtle);">';- html += '<div style="font-size:13px;color:var(--ink-muted);line-height:1.5;">';- html += '<strong>Memories</strong> are durable facts, architecture notes, conventions, and lessons saved via <code>memory_remember</code> MCP tool or the <code>/agentmemory/remember</code> endpoint. They survive across sessions and supersede each other as v1, v2, etc. ';- html += '<span style="color:var(--ink-faint);">Shown: ' + items.length + ' total.</span>';- html += '</div></div>';+ function renderGraphOverview() {+ var host = document.getElementById('graph-overview');+ if (!host) return;+ var g = state.graph;+ if (!g.loaded || g.disabledInfo || g.queryError || !graphNodeList().length) { setViewHtml(host, ''); return; }+ var t = graphTotals();+ var iso = graphIsolatedCount();+ var shown = graphNodeList().length;+ var html = '<div class="go">';+ html += '<div class="go-intro"><strong>Knowledge graph</strong> ' + help('graph') + ' The files, functions, concepts and decisions agents worked with, and how they relate. Click a node to see its relations and the observations it came from.</div>';+ html += '<div class="go-stats"><div><b>' + fmtNum(t.nodes) + '</b><span>nodes ' + help('graphNode') + '</span></div><div><b>' + fmtNum(t.edges) + '</b><span>relations ' + help('graphEdge') + '</span></div><div><b>' + fmtNum(iso) + '</b><span>unlinked ' + help('graphIsolated') + '</span></div></div>';+ if (shown >= 3 && (iso / shown > 0.4 || t.edges < shown / 2)) {+ html += '<div class="mem-note go-sparse"><b>Sparse graph.</b> ' + fmtNum(iso) + ' of ' + fmtNum(shown) + ' nodes have no relations yet. ' + esc(graphLlmNote()) + (graphLlmMode() !== 'llm' ? cmdBlock('export GRAPH_EXTRACTION_ENABLED=true\nexport ANTHROPIC_API_KEY=sk-ant-...') : '') + '</div>';+ }+ if (g.truncated && shown < t.nodes) html += '<div class="mem-note">Showing the ' + fmtNum(shown) + ' most connected of ' + fmtNum(t.nodes) + ' nodes. Search finds the rest on the server.</div>';+ if (g.warning) html += '<div class="mem-note">' + esc(g.warning) + '</div>';++ html += '<div class="mem-section"><div class="mem-section-title">Node types <span class="gd-count">click to hide or show</span></div><ul class="go-legend">';+ graphTypeCounts().forEach(function(c) {+ var on = !g.hidden[c.type];+ html += '<li><button type="button" class="go-type' + (on ? '' : ' off') + '" data-action="graph-toggle-type" data-type="' + esc(c.type) + '" aria-pressed="' + (on ? 'true' : 'false') + '" title="' + esc(NODE_TYPE_TEXT[c.type] || c.type) + '">' + shapeSvg(c.type, 14) + '<span class="go-name">' + esc(c.type) + '</span><span class="go-num">' + fmtNum(c.total) + '</span></button><div class="go-desc">' + esc(NODE_TYPE_TEXT[c.type] || '') + '</div></li>';+ });+ html += '</ul></div>';++ var edgeTypes = graphEdgeTypeCounts();+ html += '<div class="mem-section"><div class="mem-section-title">Relation types ' + help('graphEdge') + '</div>';+ if (!edgeTypes.length) html += '<div class="empty-step-label">No relations yet.</div>';+ else {+ html += '<ul class="go-legend go-edges">';+ edgeTypes.forEach(function(c) {+ html += '<li><span class="go-type static">' + edgeSvg(c.type) + '<span class="go-name">' + esc(String(c.type).replace(/_/g, ' ')) + '</span><span class="go-num">' + fmtNum(c.total) + '</span></span><div class="go-desc">' + esc(EDGE_TYPE_TEXT[c.type] || '') + '</div></li>';+ });+ html += '</ul>';+ }+ html += '</div>';- html += '<div class="toolbar">';- html += '<input type="text" id="mem-search" placeholder="Search memories..." value="' + esc(state.memories.search) + '">';- html += '<select id="mem-type-filter"><option value="">All types</option>';- typeOptions.forEach(function(t) {- html += '<option value="' + esc(t) + '"' + (typeFilter === t ? ' selected' : '') + '>' + esc(t) + '</option>';+ var top = graphNodeList().filter(graphNodeVisible).sort(function(a, b) { return graphDegree(b.id) - graphDegree(a.id) || String(graphNodeLabel(a)).localeCompare(String(graphNodeLabel(b))); }).slice(0, 12);+ html += '<div class="mem-section"><div class="mem-section-title">Most connected</div><ol class="go-top">';+ top.forEach(function(n) {+ html += '<li><button type="button" class="gd-neighbor" data-action="graph-select" data-node-id="' + esc(n.id) + '" aria-current="' + (n.id === g.selectedId ? 'true' : 'false') + '">' + shapeSvg(n.type, 11) + '<span>' + esc(graphNodeLabel(n, 40)) + '</span><span class="go-num">' + fmtNum(graphDegree(n.id)) + '</span></button></li>';});- html += '</select></div>';-- if (filtered.length === 0) {- html += '<div class="empty-state">' +- '<div class="empty-icon">📚</div>' +- '<div class="empty-title">No memories yet</div>' +- '<div class="empty-lead">Memories are the distilled facts agentmemory keeps across sessions — things like file paths, architectural decisions, and user preferences. Hooks capture them automatically during coding sessions; you can also save one directly.</div>' +- '<pre class="empty-cmd">memory_remember {\n title: "auth uses jose middleware",\n content: "src/middleware/auth.ts handles JWT validation",\n type: "architecture"\n}</pre>' +- '<div><a class="empty-link" href="https://github.com/rohitg00/agentmemory#memories" target="_blank" rel="noopener">Memory types →</a></div>' +- '</div>';+ html += '</ol></div>';+ html += '<div class="mem-section"><div class="mem-section-title">Add to the graph</div>';+ html += '<div class="empty-step-label">Import a structural code graph made by graphify:</div>' + cmdBlock(curlPost('graph/import-graphify', { cwd: '/path/to/repo' }));+ html += '<div class="empty-step-label" style="margin-top:8px;">Query it from an agent:</div>' + cmdBlock('memory_graph_query { "query": "checkout" }');+ html += '</div>';+ if (g.rebuildResult) html += '<div class="mem-note">' + esc(g.rebuildResult) + '</div>';+ html += '<div class="go-live">' + (g.patches ? 'Patched ' + fmtNum(g.patches) + ' time' + (g.patches === 1 ? '' : 's') + ' from the live stream, last ' + relTime(new Date(g.lastPatchAt).toISOString()) + '.' : 'Updates arrive on the live stream; nothing refreshes on a timer.') + ' ' + help('live') + '</div>';+ html += '</div>';+ setViewHtml(host, html);+ }++ function mountGraphCanvas() {+ var canvas = document.getElementById('graph-canvas');+ var stage = document.getElementById('graph-stage');+ if (!canvas || !stage) return;+ graphSim.canvas = canvas;+ graphSim.ctx = canvas.getContext('2d');+ function resize() {+ var r = stage.getBoundingClientRect();+ if (!r.width || !r.height) return;+ var dpr = window.devicePixelRatio || 1;+ var w = Math.round(r.width), h = Math.round(r.height);+ if (graphSim.w === w && graphSim.h === h && graphSim.dpr === dpr) return;+ graphSim.w = w;+ graphSim.h = h;+ graphSim.dpr = dpr;+ canvas.width = Math.round(w * dpr);+ canvas.height = Math.round(h * dpr);+ canvas.style.width = w + 'px';+ canvas.style.height = h + 'px';+ if (!graphSim.fitted) { layoutIsolated(); fitGraph(); }+ drawGraph();+ }+ if (graphSim.ro) graphSim.ro.disconnect();+ if (window.ResizeObserver) {+ graphSim.ro = new ResizeObserver(resize);+ graphSim.ro.observe(stage);} else {- html += '<table><tr><th>Title</th><th>Type</th><th>Strength</th><th>Version</th><th>Updated</th><th>Actions</th></tr>';- filtered.forEach(function(m) {- var badgeClass = TYPE_BADGES[m.type] || 'badge-muted';- var rawStrength = m.strength || 0;- var strength = Math.round(rawStrength <= 1 ? rawStrength * 100 : rawStrength * 10);- if (strength > 100) strength = 100;- var barColor = strength > 70 ? 'var(--green)' : strength > 40 ? 'var(--yellow)' : 'var(--red)';- var expanded = state.memories.selectedId === m.id;- html += '<tr class="memory-row' + (expanded ? ' selected' : '') + '" data-action="select-memory" data-memory-id="' + esc(m.id) + '" role="button" tabindex="0" aria-expanded="' + (expanded ? 'true' : 'false') + '" style="cursor:pointer;">';- var preview = (m.content || '').split('\n').slice(0, 2).join(' ').trim();- var previewHtml = esc(truncate(preview, 150));- if (search && search.length > 2) {- var re = new RegExp('(' + search.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + ')', 'gi');- previewHtml = previewHtml.replace(re, '<mark>$1</mark>');+ window.addEventListener('resize', resize);+ }+ resize();+ bindGraphPointer(canvas);+ }++ function bindGraphPointer(canvas) {+ var down = null;+ var tooltip = document.getElementById('graph-tooltip');+ function local(e) {+ var r = canvas.getBoundingClientRect();+ return { x: e.clientX - r.left, y: e.clientY - r.top };+ }+ function showTip(s, p) {+ if (!tooltip) return;+ if (!s) { tooltip.classList.remove('visible'); return; }+ var n = state.graph.nodeMap[s.id];+ if (!n) return;+ tooltip.innerHTML = '<div class="tt-name">' + esc(n.name) + '</div><div class="tt-meta">' + shapeSvg(n.type, 11) + esc(n.type) + ' · ' + fmtNum(graphDegree(n.id)) + ' relation' + (graphDegree(n.id) === 1 ? '' : 's') + '</div><div class="tt-hint">click for relations and sources</div>';+ var x = Math.min(p.x + 14, graphSim.w - 240);+ var y = p.y + 14 > graphSim.h - 70 ? p.y - 70 : p.y + 14;+ tooltip.style.left = Math.max(4, x) + 'px';+ tooltip.style.top = Math.max(4, y) + 'px';+ tooltip.classList.add('visible');+ }+ canvas.addEventListener('pointerdown', function(e) {+ var p = local(e);+ graphSim.pointers[e.pointerId] = p;+ var ids = Object.keys(graphSim.pointers);+ if (ids.length === 2) {+ var a = graphSim.pointers[ids[0]], b = graphSim.pointers[ids[1]];+ down = { pinch: Math.hypot(a.x - b.x, a.y - b.y), zoom: graphSim.zoom, moved: true };+ graphSim.drag = null;+ return;+ }+ var hit = graphHit(p.x, p.y);+ down = { x: p.x, y: p.y, panX: graphSim.panX, panY: graphSim.panY, node: hit, moved: false };+ try { canvas.setPointerCapture(e.pointerId); } catch (_) {}+ });+ canvas.addEventListener('pointermove', function(e) {+ var p = local(e);+ if (graphSim.pointers[e.pointerId]) graphSim.pointers[e.pointerId] = p;+ if (down && down.pinch) {+ var ids = Object.keys(graphSim.pointers);+ if (ids.length === 2) {+ var a = graphSim.pointers[ids[0]], b = graphSim.pointers[ids[1]];+ var dist = Math.hypot(a.x - b.x, a.y - b.y);+ zoomGraphAt((down.zoom * dist / down.pinch) / graphSim.zoom, (a.x + b.x) / 2, (a.y + b.y) / 2);}- html += '<td><span style="color:var(--ink);font-weight:600;">' + esc(truncate(m.title, 50)) + '</span>';- html += '<div style="font-size:12px;color:var(--ink-muted);margin-top:3px;line-height:1.4;max-height:34px;overflow:hidden;">' + previewHtml + '</div>';- if (m.concepts && m.concepts.length > 0) {- html += '<div style="margin-top:3px;display:flex;gap:4px;flex-wrap:wrap;">';- m.concepts.slice(0, 4).forEach(function(c) { html += '<span class="tag">' + esc(c) + '</span>'; });- html += '</div>';+ return;+ }+ if (down) {+ var dx = p.x - down.x, dy = p.y - down.y;+ if (!down.moved && dx * dx + dy * dy > 16) down.moved = true;+ if (!down.moved) return;+ if (down.node) {+ var s = down.node;+ graphSim.drag = s;+ s.x = (p.x - graphSim.panX) / graphSim.zoom;+ s.y = (p.y - graphSim.panY) / graphSim.zoom;+ if (s.isolated) s.pinned = 'user';+ reheatGraph(0.12);+ } else {+ graphSim.panX = down.panX + dx;+ graphSim.panY = down.panY + dy;+ requestGraphDraw();}- html += '</td>';- html += '<td><span class="badge ' + badgeClass + '">' + esc(m.type) + '</span></td>';- html += '<td><div class="strength-bar"><div class="fill" style="width:' + strength + '%;background:' + barColor + '"></div></div> <span style="font-size:10px;color:var(--ink-faint);font-family:var(--font-mono);">' + strength + '%</span></td>';- html += '<td style="color:var(--ink-muted);font-family:var(--font-mono);font-size:12px;">v' + (m.version || 1) + '</td>';- html += '<td style="font-size:11px;color:var(--ink-faint);font-family:var(--font-mono);">' + esc(formatTime(m.updatedAt)) + '</td>';- html += '<td><button class="btn btn-danger" style="font-size:9px;padding:2px 8px;" data-action="delete-memory" data-memory-id="' + esc(m.id) + '" data-memory-title="' + esc(m.title || '') + '">Delete</button></td>';- html += '</tr>';- if (expanded) {- html += '<tr class="memory-detail-row"><td colspan="6" style="background:var(--bg-alt);padding:14px 16px;">';- html += '<div style="font-size:13px;color:var(--ink);white-space:pre-wrap;line-height:1.5;margin-bottom:10px;">' + esc(m.content || '') + '</div>';- html += '<div style="display:flex;gap:16px;flex-wrap:wrap;font-size:11px;color:var(--ink-muted);font-family:var(--font-mono);margin-bottom:10px;">';- html += '<span>id: ' + esc(m.id) + '</span>';- if (m.origin && m.origin.channel) {- html += '<span>origin: ' + esc(m.origin.channel) + (m.origin.detail ? ' (' + esc(m.origin.detail) + ')' : '') + '</span>';+ showTip(null);+ return;+ }+ var hit = graphHit(p.x, p.y);+ var id = hit ? hit.id : null;+ canvas.style.cursor = hit ? 'pointer' : 'grab';+ if (id !== graphSim.hoverId) {+ graphSim.hoverId = id;+ requestGraphDraw();+ }+ showTip(hit, p);+ });+ function end(e) {+ delete graphSim.pointers[e.pointerId];+ if (!down) return;+ if (down.pinch) { if (!Object.keys(graphSim.pointers).length) down = null; return; }+ var d = down;+ down = null;+ graphSim.drag = null;+ if (d.moved) return;+ if (e.type === 'pointercancel') return;+ if (d.node) selectGraphNode(d.node.id, { focusDetail: e.pointerType !== 'mouse' });+ else if (state.graph.selectedId) selectGraphNode(null);+ }+ canvas.addEventListener('pointerup', end);+ canvas.addEventListener('pointercancel', end);+ canvas.addEventListener('pointerleave', function() {+ if (graphSim.hoverId) { graphSim.hoverId = null; requestGraphDraw(); }+ showTip(null);+ });+ canvas.addEventListener('wheel', function(e) {+ e.preventDefault();+ var p = local(e);+ zoomGraphAt(Math.exp(-e.deltaY * 0.0015), p.x, p.y);+ }, { passive: false });+ canvas.addEventListener('keydown', function(e) {+ var k = e.key;+ if (k === '+' || k === '=') zoomGraphAt(1.25);+ else if (k === '-' || k === '_') zoomGraphAt(0.8);+ else if (k === '0') fitGraph();+ else if (k === 'ArrowLeft') { graphSim.panX += 60; requestGraphDraw(); }+ else if (k === 'ArrowRight') { graphSim.panX -= 60; requestGraphDraw(); }+ else if (k === 'ArrowUp') { graphSim.panY += 60; requestGraphDraw(); }+ else if (k === 'ArrowDown') { graphSim.panY -= 60; requestGraphDraw(); }+ else if (k === 'Escape' && state.graph.selectedId) selectGraphNode(null);+ else return;+ e.preventDefault();+ e.stopPropagation();+ });+ }++ function bindGraphChrome() {+ var input = document.getElementById('graph-search');+ if (input) {+ bindImeSafeSearch(input, 120, function(v) {+ var g = state.graph;+ g.search = v;+ g.searchOpen = !!v.trim();+ g.searchIndex = 0;+ renderGraphSearchResults();+ requestGraphDraw();+ });+ input.addEventListener('focus', function() {+ if (state.graph.search.trim()) { state.graph.searchOpen = true; renderGraphSearchResults(); }+ });+ input.addEventListener('keydown', function(e) {+ var g = state.graph;+ var hits = graphSearchMatches(8);+ if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {+ if (!hits.length) return;+ g.searchOpen = true;+ g.searchIndex = (g.searchIndex + (e.key === 'ArrowDown' ? 1 : hits.length - 1)) % hits.length;+ renderGraphSearchResults();+ e.preventDefault();+ } else if (e.key === 'Enter') {+ g.search = input.value;+ var list = graphSearchMatches(8);+ var pick = list[Math.min(g.searchIndex, list.length - 1)];+ if (pick) {+ g.searchOpen = false;+ renderGraphSearchResults();+ selectGraphNode(pick.id, { center: true });+ } else if (g.truncated && input.value.trim()) {+ searchGraphRemote(input.value.trim());}- if (m.project) html += '<span>project: ' + esc(m.project) + '</span>';- if (m.createdAt) html += '<span>created: ' + esc(formatTime(m.createdAt)) + '</span>';- if (m.supersedes && m.supersedes.length > 0) html += '<span>supersedes: ' + esc(m.supersedes.join(', ')) + '</span>';- if (m.files && m.files.length > 0) html += '<span>files: ' + esc(m.files.join(', ')) + '</span>';- if (m.sessionIds && m.sessionIds.length > 0) html += '<span>sessions: ' + m.sessionIds.length + '</span>';- html += '</div>';- html += '<details><summary style="cursor:pointer;font-size:11px;color:var(--ink-faint);font-family:var(--font-mono);">raw record</summary>';- html += '<pre style="margin-top:8px;padding:10px;background:var(--bg);border:1px solid var(--border);font-size:11px;line-height:1.5;overflow-x:auto;">' + esc(JSON.stringify(m, null, 2)) + '</pre></details>';- html += '</td></tr>';+ e.preventDefault();+ } else if (e.key === 'Escape') {+ if (g.searchOpen) { g.searchOpen = false; renderGraphSearchResults(); }+ else if (input.value) { input.value = ''; g.search = ''; requestGraphDraw(); }+ e.preventDefault();+ e.stopPropagation();}});- html += '</table>';+ input.addEventListener('blur', function() {+ setTimeout(function() {+ var box = document.getElementById('graph-search-results');+ if (box && box.contains(document.activeElement)) return;+ state.graph.searchOpen = false;+ renderGraphSearchResults();+ }, 150);+ });}+ var sel = document.getElementById('graph-type-filter');+ if (sel) {+ sel.addEventListener('change', function() {+ var g = state.graph;+ var v = sel.value;+ if (v === '__custom') return;+ g.hidden = {};+ if (v) graphTypeCounts().forEach(function(t) { if (t.type !== v) g.hidden[t.type] = true; });+ afterGraphFilter();+ });+ }+ }- var __focus = captureSearchFocus(['mem-search']);- setViewHtml(el, html);+ function afterGraphFilter() {+ var g = state.graph;+ if (g.selectedId && g.nodeMap[g.selectedId] && g.hidden[g.nodeMap[g.selectedId].type]) selectGraphNode(null);+ graphSim.fitted = false;+ fitGraph();+ renderGraphToolbar();+ renderGraphOverview();+ }- var searchInput = document.getElementById('mem-search');- if (searchInput) {- bindImeSafeSearch(searchInput, 200, function(v){ state.memories.search = v; renderMemories(); });+ async function searchGraphRemote(q) {+ var g = state.graph;+ var box = document.getElementById('graph-search-results');+ if (box) { box.hidden = false; box.innerHTML = '<div class="gs-empty">Searching all nodes…</div>'; }+ var res = await apiPost('graph/query', { query: q, limit: 50 });+ if (!res) {+ if (box) box.innerHTML = '<div class="gs-empty">The server search failed.</div>';+ return;}- var typeSelect = document.getElementById('mem-type-filter');- if (typeSelect) {- typeSelect.addEventListener('change', function() {- state.memories.typeFilter = this.value;- renderMemories();- });+ mergeGraphRows(res.nodes || [], res.edges || []);+ syncGraphSim(false);+ g.search = q;+ g.searchOpen = true;+ g.searchIndex = 0;+ renderGraphView();+ var first = graphSearchMatches(1)[0];+ if (first) selectGraphNode(first.id, { center: true });+ }++ function handleGraphAction(action, target) {+ var g = state.graph;+ var id = target.getAttribute('data-node-id');+ if (action === 'graph-select' && id) {+ g.searchOpen = false;+ renderGraphSearchResults();+ selectGraphNode(id, { center: true, focusDetail: true });+ return true;+ }+ if (action === 'graph-close') {+ selectGraphNode(null);+ var canvas = document.getElementById('graph-canvas');+ if (canvas) canvas.focus({ preventScroll: true });+ return true;}- restoreSearchFocus(__focus);+ if (action === 'graph-center' && id) { centerGraphOn(id); return true; }+ if (action === 'graph-refresh-detail' && id) { fetchGraphDetail(id); return true; }+ if (action === 'graph-toggle-type') {+ var type = target.getAttribute('data-type');+ if (!type) return true;+ if (g.hidden[type]) delete g.hidden[type];+ else g.hidden[type] = true;+ afterGraphFilter();+ var again = document.querySelector('#graph-overview [data-action="graph-toggle-type"][data-type="' + cssEscape(type) + '"]');+ if (again) again.focus({ preventScroll: true });+ return true;+ }+ if (action === 'graph-retry') { g.loaded = false; loadGraph(); return true; }+ if (action === 'graph-search-remote') {+ var input = document.getElementById('graph-search');+ if (input && input.value.trim()) searchGraphRemote(input.value.trim());+ return true;+ }+ return false;}- function deleteMemory(id, title) {- var modal = document.getElementById('modal');- var overlay = document.getElementById('modal-overlay');- modal.innerHTML = '<h3>Delete Memory</h3><p>Are you sure you want to delete "' + esc(title) + '"? This action cannot be undone.</p><div class="modal-actions"><button class="btn" data-action="close-modal">Cancel</button><button class="btn btn-danger" data-action="confirm-delete-memory" data-memory-id="' + esc(id) + '">Delete</button></div>';- overlay.classList.add('open');- }+ window.zoomGraph = function(dir) {+ zoomGraphAt(dir > 0 ? 1.25 : 0.8);+ };+ window.recenterGraph = function() {+ fitGraph();+ };- async function confirmDeleteMemory(id) {- closeModal();- await apiDelete('governance/memories', { memoryIds: [id], reason: 'Deleted via viewer' });- loadMemories();+ var graphRebuilding = false;+ async function rebuildGraph() {+ if (graphRebuilding) return;+ var ok = window.confirm(+ 'Rebuild the knowledge graph from every stored observation?\n\n' ++ 'This replays the whole corpus and can take several minutes on a large store. ' ++ 'With LLM extraction on it also spends provider tokens.'+ );+ if (!ok) return;+ graphRebuilding = true;+ var g = state.graph;+ g.rebuildResult = 'Rebuilding from stored observations…';+ renderGraphOverview();+ try {+ var result = await apiPost('graph/build', {});+ g.rebuildResult = result && result.success+ ? 'Rebuilt from ' + (result.sessions || 0) + ' sessions: ' + (result.nodes || 0) + ' nodes and ' + (result.edges || 0) + ' relations extracted. New ones arrive on the live stream.'+ : 'The rebuild failed. Check the server log.';+ } finally {+ graphRebuilding = false;+ renderGraphView();+ }}- function closeModal() {- document.getElementById('modal-overlay').classList.remove('open');- }-- async function loadTimeline() {- var el = document.getElementById('view-timeline');- if (!state.timeline.loaded) el.innerHTML = '<div class="loading">Loading timeline...</div>';- var sessResult = await apiGet('sessions');- var sessions = (sessResult && sessResult.sessions) || [];- state.timeline.loaded = true;-- if (sessions.length > 0 && !state.timeline.sessionId) {- // Default to the session with the most observations — the newest- // one is often a sparse just-started session, which made the tab- // look empty on first open.- var sorted = sessions.slice().sort(function(a, b) {- return (b.observationCount || 0) - (a.observationCount || 0) ||- (b.startedAt || '').localeCompare(a.startedAt || '');- });- var firstSelectable = sorted.find(function(s) { return sessionId(s); });- state.timeline.sessionId = firstSelectable ? sessionId(firstSelectable) : '';+ function memoryRows() {+ var m = state.memories;+ var rows;+ if (m.searchIds) {+ rows = m.searchIds.map(function(id) { return store.entities.memory[id]; }).filter(Boolean);+ } else {+ rows = sortByTimeDesc(entityList('memory').filter(function(x) { return x && x.isLatest !== false; }), ['updatedAt', 'createdAt']);}+ return rows.filter(memoryMatchesFilters);+ }++ var MEMORY_TYPES = ['architecture', 'bug', 'fact', 'pattern', 'preference', 'workflow'];- renderTimelineToolbar(sessions);- if (state.timeline.sessionId) await loadObservations();+ function memoryFiltersActive() {+ var m = state.memories;+ return !!(m.typeFilter || m.projectFilter || m.agentFilter);}- function renderTimelineToolbar(sessions) {- var el = document.getElementById('view-timeline');- var html = '<div class="toolbar">';- html += '<select id="tl-session"><option value="">Select session</option>';- sessions.sort(function(a, b) { return (b.startedAt || '').localeCompare(a.startedAt || ''); }).forEach(function(s) {- var id = sessionId(s);- var disabled = id ? '' : ' disabled';- html += '<option value="' + esc(id) + '"' + (id && state.timeline.sessionId === id ? ' selected' : '') + disabled + '>' + esc(sessionLabel(s)) + '</option>';- });- html += '</select>';- html += '<select id="tl-importance"><option value="0">All importance</option>';- for (var i = 1; i <= 9; i++) {- html += '<option value="' + i + '"' + (state.timeline.minImportance === i ? ' selected' : '') + '>≥ ' + i + '</option>';- }- html += '</select></div>';- html += '<div id="tl-content"></div>';- el.innerHTML = html;+ function memoryMatchesFilters(mem) {+ var m = state.memories;+ if (!mem || mem.isLatest === false) return false;+ if (m.typeFilter && mem.type !== m.typeFilter) return false;+ if (m.projectFilter && mem.project !== m.projectFilter) return false;+ if (m.agentFilter && mem.agentId !== m.agentFilter) return false;+ return true;+ }- document.getElementById('tl-session').addEventListener('change', function() {- state.timeline.sessionId = this.value;- state.timeline.page = 0;- loadObservations();- });- document.getElementById('tl-importance').addEventListener('change', function() {- state.timeline.minImportance = parseInt(this.value);- renderObservations();- });+ function memoryQueryPath(extra) {+ var m = state.memories;+ var path = 'memories?latest=true&limit=100';+ if (m.projectFilter) path += '&project=' + encodeURIComponent(m.projectFilter);+ if (m.agentFilter) path += '&agentId=' + encodeURIComponent(m.agentFilter);+ if (m.typeFilter) path += '&type=' + encodeURIComponent(m.typeFilter);+ return path + (extra || '');}- async function loadObservations() {- var content = document.getElementById('tl-content');- if (!content) return;- if (!state.timeline.sessionId) {- content.innerHTML = '<div class="empty-state"><div class="empty-icon">🕑</div><p>Select a session to view observations</p></div>';- return;- }- content.innerHTML = '<div class="loading">Loading observations...</div>';- var result = await apiGet('observations?sessionId=' + encodeURIComponent(state.timeline.sessionId));- state.timeline.observations = (result && result.observations) || [];- renderObservations();+ function mergeMemoryRows(rows) {+ (rows || []).forEach(function(r) {+ if (r && r.id) store.entities.memory[r.id] = Object.assign({}, store.entities.memory[r.id] || {}, r);+ });}- var tlTypeFilter = '';+ function strengthScore(m) {+ var raw = Number(m.strength) || 0;+ var score = raw <= 1 ? raw * 10 : raw;+ return Math.max(0, Math.min(10, Math.round(score * 10) / 10));+ }- function renderObservations() {- var content = document.getElementById('tl-content');- if (!content) return;- var obs = state.timeline.observations;- var minImp = state.timeline.minImportance;- var filtered = minImp > 0 ? obs.filter(function(o) { return (o.importance || 0) >= minImp; }) : obs;+ function memoryParentId(m) {+ return (m && (m.parentId || (m.supersedes && m.supersedes[0]))) || '';+ }- var TOOL_TYPE_MAP = { Read: 'file_read', Write: 'file_write', Edit: 'file_edit', Bash: 'command_run', Grep: 'search', Glob: 'search', WebFetch: 'web_fetch', WebSearch: 'web_fetch', AskUserQuestion: 'conversation', Task: 'subagent' };+ function memoryHeadline(mem) {+ var content = String(mem.content || '').replace(/\s+/g, ' ').trim();+ var title = String(mem.title || '').replace(/\s+/g, ' ').trim().replace(/(\.\.\.|…)$/, '').replace(/[;:,]+$/, '');+ if (title && content.indexOf(title) !== 0) {+ return { head: title, excerpt: content === title ? '' : content };+ }+ var end = -1;+ var re = /[.!?;](\s|$)/g;+ var hit;+ while ((hit = re.exec(content))) {+ if (hit.index >= 24) { end = hit.index + 1; break; }+ }+ if (end > 0 && end <= 150) {+ return { head: content.slice(0, end).replace(/[;:,]+$/, ''), excerpt: content.slice(end).trim() };+ }+ if (content.length <= 150) return { head: content, excerpt: '' };+ var cut = content.lastIndexOf(' ', 120);+ if (cut < 60) cut = 120;+ return { head: content.slice(0, cut) + '…', excerpt: '…' + content.slice(cut).trim() };+ }- var typeCounts = {};- filtered.forEach(function(o) {- var t = o.type || TOOL_TYPE_MAP[o.toolName] || (o.hookType ? o.hookType.replace(/_/g, ' ') : 'other');- typeCounts[t] = (typeCounts[t] || 0) + 1;+ function memoryFacetList(dim) {+ var f = state.memories.facets;+ var key = dim === 'project' ? 'projects' : dim === 'agent' ? 'agents' : 'types';+ if (f && f[key]) return f[key];+ var counts = {};+ entityList('memory').forEach(function(x) {+ if (!x || x.isLatest === false) return;+ var v = dim === 'project' ? x.project : dim === 'agent' ? x.agentId : x.type;+ if (v) counts[v] = (counts[v] || 0) + 1;});- var typeList = Object.keys(typeCounts).sort(function(a, b) { return typeCounts[b] - typeCounts[a]; });-- if (tlTypeFilter) {- filtered = filtered.filter(function(o) {- var t = o.type || TOOL_TYPE_MAP[o.toolName] || (o.hookType ? o.hookType.replace(/_/g, ' ') : 'other');- return t === tlTypeFilter;+ return Object.keys(counts).sort(function(a, b) { return counts[b] - counts[a] || a.localeCompare(b); }).map(function(v) { return { value: v, count: counts[v] }; });+ }++ function adjustMemoryFacets(prev, next) {+ var f = state.memories.facets;+ if (!f) return;+ function bump(row, delta) {+ if (!row || row.isLatest === false) return;+ [['projects', row.project], ['agents', row.agentId], ['types', row.type]].forEach(function(pair) {+ if (!pair[1] || !f[pair[0]]) return;+ var list = f[pair[0]];+ var item = list.filter(function(x) { return x.value === pair[1]; })[0];+ if (!item) { if (delta < 0) return; item = { value: pair[1], count: 0 }; list.push(item); }+ item.count = Math.max(0, item.count + delta);});}+ bump(prev, -1);+ bump(next, 1);+ }- var pageSize = state.timeline.pageSize;- var page = state.timeline.page;- var start = page * pageSize;- var paged = filtered.slice(start, start + pageSize);- var totalPages = Math.ceil(filtered.length / pageSize);-- var html = '<div class="type-chips">';- html += '<span class="type-chip' + (!tlTypeFilter ? ' active' : '') + '" data-action="timeline-filter" data-type-filter="">All (' + obs.length + ')</span>';- typeList.forEach(function(t) {- var color = OBS_TYPE_COLORS[t] || '#666666';- html += '<span class="type-chip' + (tlTypeFilter === t ? ' active' : '') + '" data-action="timeline-filter" data-type-filter="' + esc(t) + '" style="' + (tlTypeFilter === t ? 'background:' + color + ';border-color:' + color + ';' : 'border-color:' + color + ';color:' + color + ';') + '">' + esc(t.replace(/_/g, ' ')) + ' (' + typeCounts[t] + ')</span>';- });- html += '</div>';+ function noteMemoryChange(prev, next, id) {+ var m = state.memories;+ adjustMemoryFacets(prev, next);+ if (m.query && typeof m.query.total === 'number') {+ m.query.total += (memoryMatchesFilters(next) ? 1 : 0) - (memoryMatchesFilters(prev) ? 1 : 0);+ }+ if (!next && m.checked[id]) delete m.checked[id];+ if (next && next.isLatest === false && m.checked[id]) delete m.checked[id];+ if (next && m.pendingId && next.id === m.pendingId) m.pendingId = null;+ }- if (paged.length === 0) {- html += '<div class="empty-state"><div class="empty-icon">🕑</div><p>No observations' + (obs.length > 0 ? ' match the filter (' + obs.length + ' total)' : ' for this session') + '</p></div>';- content.innerHTML = html;+ var memorySearchSeq = 0;+ async function runMemorySearch(q) {+ var query = String(q || '').trim();+ state.memories.search = q;+ var seq = ++memorySearchSeq;+ if (!query) {+ state.memories.searchIds = null;+ state.memories.searchMode = '';+ state.memories.searching = false;+ applyMemoryFilters();return;}+ state.memories.searching = true;+ renderMemories();+ var res = await apiGet(memoryQueryPath('&q=' + encodeURIComponent(query)));+ if (seq !== memorySearchSeq) return;+ state.memories.searching = false;+ if (!res) {+ state.memories.searchIds = [];+ state.memories.searchMode = 'failed';+ } else {+ var rows = res.memories || [];+ mergeMemoryRows(rows);+ state.memories.searchIds = rows.map(function(r) { return r.id; });+ state.memories.searchMode = (res.search && res.search.mode) || 'keyword';+ }+ renderMemories();+ }- html += '<div style="font-size:11px;color:var(--ink-faint);margin-bottom:16px;font-family:var(--font-mono);text-transform:uppercase;letter-spacing:0.06em;">' + filtered.length + ' observations shown</div>';+ var memoryFilterSeq = 0;+ async function applyMemoryFilters() {+ var m = state.memories;+ m.checked = {};+ if (String(m.search || '').trim()) {+ runMemorySearch(m.search);+ return;+ }+ var seq = ++memoryFilterSeq;+ if (!memoryFiltersActive()) {+ m.query = null;+ renderMemories();+ return;+ }+ m.query = { loading: true, total: null, nextCursor: null };+ renderMemories();+ var res = await apiGet(memoryQueryPath());+ if (seq !== memoryFilterSeq) return;+ if (res) {+ mergeMemoryRows(res.memories);+ m.query = { loading: false, total: typeof res.total === 'number' ? res.total : null, nextCursor: res.nextCursor || null };+ } else {+ m.query = { loading: false, failed: true, total: null, nextCursor: null };+ }+ renderMemories();+ }- html += '<div class="timeline-container">';+ function setMemoryFilter(dim, value) {+ var m = state.memories;+ if (dim === 'project') m.projectFilter = value;+ else if (dim === 'agent') m.agentFilter = value;+ else if (dim === 'type') m.typeFilter = value;+ applyMemoryFilters();+ }++ function clearMemoryFilters() {+ var m = state.memories;+ m.projectFilter = '';+ m.agentFilter = '';+ m.typeFilter = '';+ m.search = '';+ m.searchIds = null;+ m.searchMode = '';+ m.searching = false;+ memorySearchSeq++;+ var input = document.getElementById('mem-search');+ if (input) input.value = '';+ applyMemoryFilters();+ }++ async function loadMoreMemories() {+ var m = state.memories;+ var cursor = m.query ? m.query.nextCursor : m.nextCursor;+ if (!cursor || m.loadingMore) return;+ m.loadingMore = true;+ renderMemories();+ var res = await apiGet(memoryQueryPath('&cursor=' + encodeURIComponent(cursor)));+ m.loadingMore = false;+ if (res) {+ mergeMemoryRows(res.memories);+ if (m.query) m.query.nextCursor = res.nextCursor || null;+ else m.nextCursor = res.nextCursor || null;+ }+ renderMemories();+ }- var lastDateGroup = '';- paged.forEach(function(o, idx) {- var isCompressed = !!o.narrative || !!o.type;- var isRaw = !isCompressed;- var type = o.type || TOOL_TYPE_MAP[o.toolName] || 'other';- var impVal = typeof o.importance === 'number' ? o.importance : 5;- var impClass = impVal >= 7 ? 'high' : impVal >= 4 ? 'med' : 'low';- var title = o.title || o.toolName || (o.hookType ? o.hookType.replace(/_/g, ' ') : 'Observation');- var typeColor = OBS_TYPE_COLORS[type] || '#666666';- var icon = OBS_TYPE_ICONS[type] || '📄';+ async function fetchMemoryVersion(id) {+ var m = state.memories;+ if (!id || m.fetches[id]) return;+ m.fetches[id] = 'loading';+ var res = await apiGet('memories/' + encodeURIComponent(id));+ if (res && res.memory) {+ mergeMemoryRows([res.memory]);+ m.fetches[id] = 'done';+ } else {+ m.fetches[id] = 'missing';+ }+ if (state.activeTab === 'memories') renderMemories();+ }- var dateGroup = '';- try {- var d = new Date(o.timestamp);- dateGroup = d.toLocaleDateString() + ' ' + d.getHours() + ':00';- } catch(e) { dateGroup = ''; }+ function renderMemories() {+ var el = document.getElementById('view-memories');+ var m = state.memories;+ if (!el.querySelector('#memory-list')) {+ el.innerHTML = '<div class="inline-note"><strong>Memories</strong> ' + help('memory') + ' are durable facts, architecture notes, conventions and preferences agents keep across sessions. Saving a near-duplicate, or editing one here, creates a new version ' + help('version') + ' and keeps the old one as history. Click a row for provenance, versions, edits and copy actions. Longer-lived facts and procedures are distilled from sessions by <a class="empty-link" href="#health/consolidation">consolidation →</a></div>' ++ '<div id="memory-toolbar"></div><div class="memories-layout"><div id="memory-list"></div><div id="memory-detail"></div></div>';+ el.__renderedHtml = null;+ }+ var focus = captureSearchFocus(['mem-search']);+ setViewHtml(document.getElementById('memory-toolbar'), memoryToolbarHtml());+ bindMemoryToolbar();+ restoreSearchFocus(focus);+ var layout = el.querySelector('.memories-layout');+ if (!store.loaded.memory) {+ layout.classList.remove('has-detail');+ setViewHtml(document.getElementById('memory-list'), skeleton(10));+ setViewHtml(document.getElementById('memory-detail'), '');+ return;+ }+ setViewHtml(document.getElementById('memory-list'), memoryListHtml());+ renderMemoryDetailPanel();+ layout.classList.toggle('has-detail', !!document.getElementById('memory-detail').firstElementChild);+ }- if (dateGroup && dateGroup !== lastDateGroup) {- html += '<div class="timeline-date-marker"><span>' + esc(dateGroup) + '</span></div>';- lastDateGroup = dateGroup;+ function memoryFilterSelect(dim, allLabel, current) {+ var list = memoryFacetList(dim).slice();+ if (dim === 'type') {+ MEMORY_TYPES.forEach(function(t) {+ if (!list.some(function(x) { return x.value === t; })) list.push({ value: t, count: 0 });+ });+ }+ if (current && !list.some(function(x) { return x.value === current; })) list.unshift({ value: current, count: 0 });+ var none = list.length === 0;+ var html = '<select id="mem-' + dim + '-filter" data-dim="' + dim + '" aria-label="Filter by ' + dim + '"' + (none ? ' disabled title="No memory has a' + (dim === 'agent' ? 'n agent id' : ' ' + dim) + ' yet"' : '') + '>';+ html += '<option value="">' + esc(none ? 'No ' + dim + 's' : allLabel) + '</option>';+ list.forEach(function(x) {+ var label = dim === 'project' ? String(x.value).split('/').pop() : x.value;+ html += '<option value="' + esc(x.value) + '"' + (current === x.value ? ' selected' : '') + '>' + esc(label) + ' (' + fmtNum(x.count) + ')</option>';+ });+ return html + '</select>';+ }++ function memoryToolbarHtml() {+ var m = state.memories;+ var html = '<div class="toolbar mem-filters">';+ html += '<input type="search" id="mem-search" placeholder="Search memories by meaning or keyword (press /)" value="' + esc(m.search) + '" aria-label="Search memories">';+ html += memoryFilterSelect('project', 'All projects', m.projectFilter);+ html += memoryFilterSelect('agent', 'All agents', m.agentFilter);+ html += memoryFilterSelect('type', 'All types', m.typeFilter);+ return html + '</div>';+ }++ function memoryFilterDescription() {+ var m = state.memories;+ var parts = [];+ if (String(m.search || '').trim()) parts.push('the search “' + esc(m.search) + '”');+ if (m.projectFilter) parts.push('project <b>' + esc(m.projectFilter) + '</b>');+ if (m.agentFilter) parts.push('agent <b>' + esc(m.agentFilter) + '</b>');+ if (m.typeFilter) parts.push('type <b>' + esc(m.typeFilter) + '</b>');+ return parts.join(', ');+ }++ function memoryRowHtml(mem) {+ var m = state.memories;+ var hl = memoryHeadline(mem);+ var selected = m.selectedId === mem.id;+ var checked = !!m.checked[mem.id];+ var score = strengthScore(mem);+ var barColor = score >= 7 ? 'var(--green)' : score >= 4 ? 'var(--yellow)' : 'var(--red)';+ var version = mem.version || 1;+ var html = '<tr class="memory-row' + (selected ? ' selected' : '') + (checked ? ' checked' : '') + '" data-action="select-memory" data-memory-id="' + esc(mem.id) + '" role="button" tabindex="0" aria-expanded="' + (selected ? 'true' : 'false') + '" style="cursor:pointer;">';+ html += '<td class="mem-check"><input type="checkbox" data-action="mem-check" data-memory-id="' + esc(mem.id) + '" aria-label="Select this memory"' + (checked ? ' checked' : '') + '></td>';+ html += '<td style="max-width:0;width:100%;"><div class="mem-head clamp-2">' + esc(hl.head) + '</div>';+ if (hl.excerpt) html += '<div class="mem-excerpt">' + esc(hl.excerpt) + '</div>';+ html += '<div class="mem-chips">';+ if (mem.project) html += '<button type="button" class="mem-chip' + (m.projectFilter === mem.project ? ' on' : '') + '" data-action="mem-filter" data-dim="project" data-value="' + esc(mem.project) + '" title="Show only project ' + esc(mem.project) + '">' + esc(String(mem.project).split('/').pop()) + '</button>';+ if (mem.agentId) html += '<button type="button" class="mem-chip' + (m.agentFilter === mem.agentId ? ' on' : '') + '" data-action="mem-filter" data-dim="agent" data-value="' + esc(mem.agentId) + '" title="Show only memories written by agent ' + esc(mem.agentId) + '">@' + esc(mem.agentId) + '</button>';+ if (version > 1) html += '<span class="ver-badge" title="Version ' + version + ': ' + (version - 1) + ' earlier version' + (version === 2 ? '' : 's') + ' kept as history">v' + version + '</span>';+ (mem.concepts || []).slice(0, 3).forEach(function(cn) { html += '<span class="tag">' + esc(cn) + '</span>'; });+ html += '<span class="mob-only">' + score + '/10 · ' + esc(timeAgo(mem.updatedAt || mem.createdAt)) + '</span>';+ html += '</div></td>';+ html += '<td><span class="badge ' + (TYPE_BADGES[mem.type] || 'badge-muted') + '">' + esc(mem.type) + '</span></td>';+ html += '<td class="col-opt" style="white-space:nowrap;" title="Strength ' + score + ' of 10"><div class="strength-bar"><div class="fill" style="width:' + (score * 10) + '%;background:' + barColor + '"></div></div> <span class="strength-num">' + score + '/10</span></td>';+ html += '<td class="col-opt">' + relTime(mem.updatedAt || mem.createdAt) + '</td>';+ return html + '</tr>';+ }++ function memoryListHtml() {+ var m = state.memories;+ var c = store.counts || {};+ var rows = memoryRows();+ var filtered = memoryFiltersActive();+ var searching = !!m.searchIds || m.searching;+ var html = '';+ if (searching || filtered) {+ var summary;+ if (searching) {+ summary = m.searching ? 'Searching…' : fmtNum(rows.length) + ' result' + (rows.length === 1 ? '' : 's') + ' · ' + (m.searchMode === 'hybrid' ? 'meaning + keyword search' : m.searchMode === 'failed' ? 'search failed, try again' : 'keyword search (no embeddings configured)');+ } else if (m.query && m.query.loading) {+ summary = 'Filtering on the server…';+ } else if (m.query && m.query.failed) {+ summary = 'The filter request failed. Change a filter to retry.';+ } else {+ var total = m.query && typeof m.query.total === 'number' ? m.query.total : rows.length;+ summary = fmtNum(total) + ' matching memor' + (total === 1 ? 'y' : 'ies');}+ html += '<div class="mem-filter-note"><span>' + summary + ' for ' + memoryFilterDescription() + '</span><button type="button" class="btn" data-action="mem-clear-filters">Clear all</button></div>';+ }+ var checkedIds = Object.keys(m.checked);+ if (checkedIds.length > 0) {+ html += '<div class="bulk-bar" role="region" aria-label="Bulk actions"><span class="bulk-count">' + fmtNum(checkedIds.length) + ' selected</span>' ++ '<button type="button" class="btn" data-action="mem-export">Export JSON</button>' ++ '<button type="button" class="btn btn-danger" data-action="mem-bulk-forget">Forget ' + fmtNum(checkedIds.length) + '…</button>' ++ '<button type="button" class="btn" data-action="mem-uncheck-all">Clear selection</button></div>';+ }++ if (rows.length === 0) {+ if ((m.query && m.query.loading) || m.searching) return html + skeleton(6);+ if (searching || filtered) {+ var q = String(m.search || '').trim();+ html += emptyState({+ icon: '🔍',+ title: 'No memories match',+ what: 'This list shows the latest version of every memory that matches the search box and the project, agent and type filters. Filters and search run on the server over all memories, not only the loaded page.',+ why: 'No latest memory matches ' + memoryFilterDescription() + '.',+ steps: [+ { label: 'Run the same query from a terminal:', cmd: curlGet(memoryQueryPath(q ? '&q=' + encodeURIComponent(q) : '').replace('limit=100', 'limit=20')) },+ { label: 'Or save a memory that matches:', cmd: curlPost('remember', { content: q || 'Describe the fact to keep', type: m.typeFilter || 'fact', project: m.projectFilter || undefined, agentId: m.agentFilter || undefined }) }+ ]+ });+ html += '<div style="margin-top:10px;"><button type="button" class="btn" data-action="mem-clear-filters">Clear search and filters</button></div>';+ return html;+ }+ return html + emptyState({+ icon: '📚',+ title: 'No memories yet',+ what: 'Memories are distilled facts agentmemory keeps across sessions: file locations, architecture decisions, conventions, user preferences. Agents recall them at the start of every session.',+ why: 'No agent has saved one yet. Hooks save them during coding sessions once an agent runs with agentmemory.',+ steps: [+ { label: 'From an agent, call the MCP function:', cmd: 'memory_save { "content": "src/middleware/auth.ts validates JWTs with jose", "type": "architecture" }' },+ { label: 'Or from a terminal:', cmd: curlPost('remember', { content: 'src/middleware/auth.ts validates JWTs with jose', type: 'architecture' }) }+ ],+ link: { href: 'https://github.com/rohitg00/agentmemory#memories', text: 'Memory types' }+ });+ }- var side = idx % 2 === 0 ? 'tl-left' : 'tl-right';-- html += '<div class="timeline-item ' + side + '">';- html += '<div class="timeline-dot" style="background:' + typeColor + ';"></div>';- html += '<div class="timeline-connector"></div>';+ var allChecked = rows.every(function(r) { return !!m.checked[r.id]; });+ html += '<div class="table-wrap"><table class="mem-table"><tr><th class="mem-check"><input type="checkbox" data-action="mem-check-all" aria-label="Select all shown memories"' + (allChecked ? ' checked' : '') + '></th><th>Memory</th><th>Type</th><th class="col-opt">Strength ' + help('strength') + '</th><th class="col-opt">Updated</th></tr>';+ rows.forEach(function(mem) { html += memoryRowHtml(mem); });+ html += '</table></div>';- html += '<div class="obs-card imp-' + impClass + '" style="border-left-color:' + typeColor + ';text-align:left;">';- html += '<div class="obs-head">';- html += '<div class="obs-title-row">';- html += '<span class="obs-type-icon">' + icon + '</span>';- html += '<span class="obs-title" title="' + esc(title) + '">' + esc(title) + '</span>';- if (isRaw) html += '<span class="badge badge-muted" style="font-size:8px;margin-left:4px;">raw</span>';+ if (!searching) {+ var shownTotal = m.query ? m.query.total : c.latestMemories;+ var cursor = m.query ? m.query.nextCursor : m.nextCursor;+ html += '<div class="load-more">Showing ' + fmtNum(rows.length) + (typeof shownTotal === 'number' ? ' of ' + fmtNum(Math.max(shownTotal, rows.length)) : '') + (filtered ? ' matching' : ' latest') + ' memories';+ if (cursor) html += '<button class="btn" data-action="memories-load-more"' + (m.loadingMore ? ' disabled' : '') + '>' + (m.loadingMore ? 'Loading…' : 'Load 100 more') + '</button>';html += '</div>';- html += '<div class="obs-meta">';- if (isCompressed) html += '<span class="obs-importance imp-' + impVal + '" title="Importance: ' + impVal + '/10">' + impVal + '</span>';- html += '<span class="obs-time">' + esc(shortTime(o.timestamp)) + '</span>';- html += '</div></div>';-- if (o.subtitle) html += '<div class="obs-subtitle">' + esc(humanizeSubtitle(o.subtitle)) + '</div>';+ }+ if (!filtered && !searching && rows.length < 12) html += usageCard('memory');+ return html;+ }- html += '<div style="margin-top:4px;">';- html += '<span class="badge" style="border-color:' + typeColor + ';color:' + typeColor + ';margin-right:4px;">' + esc(type.replace(/_/g, ' ')) + '</span>';- if (o.hookType) html += '<span class="badge badge-muted" style="margin-right:4px;">' + esc(o.hookType) + '</span>';- html += '</div>';+ function memoryCloseBtn() {+ return '<button type="button" class="icon-btn icon-close" data-action="mem-close" aria-label="Close memory details">close</button>';+ }- if (isRaw && o.toolInput) {- var inputStr = typeof o.toolInput === 'string' ? o.toolInput : JSON.stringify(o.toolInput);- html += '<div style="margin-top:6px;"><span style="font-size:10px;color:var(--ink-muted);font-weight:600;font-family:var(--font-ui);text-transform:uppercase;letter-spacing:0.08em;">Input:</span>';- html += '<pre style="font-size:11px;color:var(--ink-muted);background:var(--bg-alt);padding:8px 10px;border:1px solid var(--border-light);margin-top:3px;overflow-x:auto;max-height:80px;font-family:var(--font-mono);">' + esc(truncate(inputStr, 300)) + '</pre></div>';- }- if (isRaw && o.toolOutput) {- var outputStr = typeof o.toolOutput === 'string' ? o.toolOutput : JSON.stringify(o.toolOutput);- html += '<div style="margin-top:4px;"><span style="font-size:10px;color:var(--ink-muted);font-weight:600;font-family:var(--font-ui);text-transform:uppercase;letter-spacing:0.08em;">Output:</span>';- html += '<div class="obs-narrative" style="margin-top:3px;">' + esc(truncate(outputStr, 300)) + '</div></div>';+ function renderMemoryDetailPanel() {+ var panel = document.getElementById('memory-detail');+ if (!panel) return;+ var m = state.memories;+ var id = m.selectedId;+ if (!id) { setViewHtml(panel, ''); return; }+ var e = m.editing;+ if (e && e.id === id && panel.querySelector('#mem-edit-text') && panel.__editRev === e.rev) return;+ var mem = store.entities.memory[id];+ if (!mem) {+ if (m.pendingId === id) {+ setViewHtml(panel, '<div class="detail-panel mem-detail"><div class="mem-detail-head"><span>Saving the new version</span>' + memoryCloseBtn() + '</div><div class="mem-note">Saved. Waiting for the new version to arrive on the live stream…</div>' + skeleton(4) + '</div>');+ return;}- if (o.narrative) html += '<div class="obs-narrative" style="margin-top:8px;">' + esc(o.narrative) + '</div>';- if (o.facts && o.facts.length > 0) {- html += '<ul class="obs-facts">';- o.facts.forEach(function(f) { html += '<li>' + esc(f) + '</li>'; });- html += '</ul>';+ if (!m.fetches[id]) fetchMemoryVersion(id);+ if (m.fetches[id] === 'missing') {+ setViewHtml(panel, '<div class="detail-panel mem-detail"><div class="mem-detail-head"><span>Memory</span>' + memoryCloseBtn() + '</div>' + emptyState({+ compact: true,+ icon: '🔍',+ title: 'Memory not found',+ what: 'Memory links anywhere in the viewer open this panel by id.',+ why: 'No memory has the id <code>' + esc(id) + '</code>. It was forgotten, or the link comes from another install.',+ steps: [{ label: 'Check from a terminal:', cmd: curlGet('memories/' + encodeURIComponent(id)) }]+ }) + '</div>');+ return;}-- var hasTags = (o.concepts && o.concepts.length) || (o.files && o.files.length);- if (hasTags) {- html += '<div class="tag-list">';- (o.concepts || []).forEach(function(c) { html += '<span class="tag">' + esc(c) + '</span>'; });- (o.files || []).forEach(function(f) {- var short = f.split('/').pop();- html += '<span class="tag file-tag" title="' + esc(f) + '">' + esc(short) + '</span>';- });- html += '</div>';+ setViewHtml(panel, '<div class="detail-panel mem-detail"><div class="mem-detail-head"><span>Loading memory ' + esc(shortId(id)) + '…</span>' + memoryCloseBtn() + '</div>' + skeleton(5) + '</div>');+ return;+ }+ setViewHtml(panel, renderMemoryDetail(mem));+ if (e && e.id === id) {+ panel.__editRev = e.rev;+ var ta = document.getElementById('mem-edit-text');+ var typeSel = document.getElementById('mem-edit-type');+ if (ta) ta.addEventListener('input', function() { e.content = ta.value; });+ if (typeSel) typeSel.addEventListener('change', function() { e.type = typeSel.value; });+ }+ }++ function memoryChain(mem) {+ var seen = {};+ seen[mem.id] = true;+ var older = [];+ var missing = '';+ var cur = mem;+ for (var i = 0; i < 50; i++) {+ var pid = memoryParentId(cur);+ if (!pid || seen[pid]) break;+ seen[pid] = true;+ var parent = store.entities.memory[pid];+ if (!parent) { missing = pid; break; }+ older.push(parent);+ cur = parent;+ }+ var all = entityList('memory');+ var newer = [];+ cur = mem;+ for (var j = 0; j < 50; j++) {+ var child = null;+ for (var k = 0; k < all.length; k++) {+ if (all[k] && !seen[all[k].id] && memoryParentId(all[k]) === cur.id) { child = all[k]; break; }}- if (isRaw && o.toolInput) {- var files = [];- var ti = o.toolInput;- if (typeof ti === 'object' && ti !== null) {- if (ti.file_path) files.push(ti.file_path);- if (ti.path) files.push(ti.path);- }- if (files.length > 0) {- html += '<div class="tag-list">';- files.forEach(function(f) {- var short = String(f).split('/').pop();- html += '<span class="tag file-tag" title="' + esc(f) + '">' + esc(short) + '</span>';- });- html += '</div>';- }+ if (!child) break;+ seen[child.id] = true;+ newer.unshift(child);+ cur = child;+ }+ return { versions: newer.concat([mem], older), older: older, missing: missing };+ }++ function diffWordsHtml(before, after) {+ var a = String(before || '').split(/(\s+)/).filter(Boolean);+ var b = String(after || '').split(/(\s+)/).filter(Boolean);+ var n = a.length;+ var w = b.length;+ if (n * w > 4000000) return null;+ var dp = [];+ for (var i = 0; i <= n; i++) dp.push(new Uint32Array(w + 1));+ for (i = n - 1; i >= 0; i--) {+ for (var j = w - 1; j >= 0; j--) {+ dp[i][j] = a[i] === b[j] ? dp[i + 1][j + 1] + 1 : Math.max(dp[i + 1][j], dp[i][j + 1]);}- html += '</div>';- html += '</div>';+ }+ var ops = [];+ function push(op, tok) {+ var last = ops[ops.length - 1];+ if (last && last.op === op) last.text += tok;+ else ops.push({ op: op, text: tok });+ }+ i = 0;+ j = 0;+ while (i < n && j < w) {+ if (a[i] === b[j]) { push('=', a[i]); i++; j++; }+ else if (dp[i + 1][j] >= dp[i][j + 1]) { push('-', a[i]); i++; }+ else { push('+', b[j]); j++; }+ }+ while (i < n) push('-', a[i++]);+ while (j < w) push('+', b[j++]);+ var added = 0;+ var removed = 0;+ var html = ops.map(function(o) {+ var words = o.text.trim() ? o.text.trim().split(/\s+/).length : 0;+ if (o.op === '+') { added += words; return '<ins>' + esc(o.text) + '</ins>'; }+ if (o.op === '-') { removed += words; return '<del>' + esc(o.text) + '</del>'; }+ return esc(o.text);+ }).join('');+ return { html: html, added: added, removed: removed };+ }++ function memoryDiffHtml(prev, next) {+ var diff = diffWordsHtml(prev.content, next.content);+ var html = '';+ if (prev.type !== next.type) html += '<div class="mem-diff-sum">Type changed: <b>' + esc(prev.type) + '</b> → <b>' + esc(next.type) + '</b></div>';+ if (!diff) return html + '<div class="mem-diff">' + esc(next.content || '') + '</div><div class="mem-diff-sum">Too long to compare word by word; showing the new text.</div>';+ if (!diff.added && !diff.removed) return html + '<div class="mem-diff-sum">The text did not change.</div>';+ return html + '<div class="mem-diff">' + diff.html + '</div><div class="mem-diff-sum">+' + fmtNum(diff.added) + ' word' + (diff.added === 1 ? '' : 's') + ' added, −' + fmtNum(diff.removed) + ' removed</div>';+ }++ function memoryVersionsHtml(mem, chain) {+ var m = state.memories;+ var versions = chain.versions;+ if (chain.missing && !m.fetches[chain.missing]) fetchMemoryVersion(chain.missing);+ var html = '<div class="mem-section"><div class="mem-section-title">Versions ' + help('version') + '</div>';+ if (versions.length === 1 && !chain.missing) {+ return html + '<div class="empty-step-label">Only one version so far. Editing it here, or saving a near-duplicate with memory_save, creates v' + ((mem.version || 1) + 1) + ' and keeps this text as history.</div></div>';+ }+ var diffable = versions.filter(function(v, idx) { return idx < versions.length - 1 && memoryParentId(v) === versions[idx + 1].id; });+ var diffId = m.diffId && diffable.some(function(v) { return v.id === m.diffId; }) ? m.diffId : (diffable.some(function(v) { return v.id === mem.id; }) ? mem.id : (diffable[0] && diffable[0].id));+ html += '<ul class="ver-list">';+ versions.forEach(function(v) {+ var canDiff = diffable.indexOf(v) >= 0;+ html += '<li class="ver-item' + (v.id === mem.id ? ' current' : '') + '"><span class="ver-badge">v' + (v.version || 1) + '</span>';+ html += '<a href="#memories/' + encodeURIComponent(v.id) + '" title="Open version ' + (v.version || 1) + ' (' + esc(v.id) + ')"><span class="ver-text">' + esc(memoryHeadline(v).head) + '</span></a>';+ html += '<span class="ver-tools">' + relTime(v.createdAt) + (v.isLatest !== false ? ' <span class="badge badge-green">latest</span>' : '');+ if (canDiff) html += ' <button type="button" class="linkish" data-action="mem-diff" data-memory-id="' + esc(v.id) + '" aria-pressed="' + (v.id === diffId ? 'true' : 'false') + '" title="Compare with the version before it">changes</button>';+ html += '</span></li>';});+ if (chain.missing) {+ html += '<li class="ver-item"><span class="ver-badge">…</span><span class="ver-text">' + (m.fetches[chain.missing] === 'missing' ? 'An older version (' + esc(shortId(chain.missing)) + ') was forgotten.' : 'Loading older versions…') + '</span><span></span></li>';+ }+ html += '</ul>';+ if (diffId) {+ var idx = -1;+ versions.forEach(function(v, i) { if (v.id === diffId) idx = i; });+ var next = versions[idx];+ var prev = versions[idx + 1];+ html += '<div class="mem-section-title" style="margin-top:10px;">Changes from v' + (prev.version || 1) + ' to v' + (next.version || 1) + ' ' + help('diff') + '</div>' + memoryDiffHtml(prev, next);+ }+ return html + '</div>';+ }++ var obsLocations = {};+ var obsLocating = {};+ function locateObservations(ids) {+ var missing = ids.filter(function(id) { return !(id in obsLocations) && !obsLocating[id]; }).slice(0, 200);+ if (!missing.length) return;+ missing.forEach(function(id) { obsLocating[id] = true; });+ apiGet('observations/locate?ids=' + encodeURIComponent(missing.join(','))).then(function(res) {+ missing.forEach(function(id) {+ obsLocations[id] = (res && res.sessions && res.sessions[id]) || '';+ delete obsLocating[id];+ });+ if (state.activeTab === 'memories') renderMemories();+ else if (['audit', 'lessons', 'actions'].indexOf(state.activeTab) >= 0) renderTab(state.activeTab);+ });+ }+ function idKind(id) {+ var s = String(id || '');+ if (/^mem_/.test(s)) return 'memory';+ if (/^(lsn|lesson)_/.test(s)) return 'lesson';+ if (/^act_/.test(s)) return 'action';+ if (/^(crys|crystal)_/.test(s)) return 'crystal';+ if (/^obs_/.test(s)) return 'observation';+ if (/^gn_/.test(s)) return 'node';+ if (store.entities.session[s] || /^(ses|sess|session)[_-]/.test(s)) return 'session';+ return '';+ }++ var ID_KIND_LABELS = { memory: 'memory', lesson: 'lesson', action: 'action', crystal: 'crystal', observation: 'observation', node: 'graph node', session: 'session' };++ function anyIdLink(id, label) {+ var s = String(id || '');+ var kind = idKind(s);+ var text = esc(label || shortId(s));+ if (kind === 'observation') {+ var sid = obsLocations[s];+ if (sid) return '<a class="entity-link" href="#sessions/' + encodeURIComponent(sid) + '?obs=' + encodeURIComponent(s) + '" title="Open observation ' + esc(s) + ' in session ' + esc(sid) + '">' + text + '</a>';+ return '<span class="entity-link" title="' + esc(s) + (sid === '' ? ' (no longer stored)' : ' (looking up its session)') + '" style="border-bottom-style:dashed;color:var(--ink-muted);">' + text + '</span>';+ }+ if (kind) return entityLink(kind, s, label);+ return '<span class="entity-link" title="' + esc(s) + '" style="border-bottom:none;color:var(--ink-muted);">' + text + '</span>';+ }++ function anyIdChip(id, label) {+ return '<span class="id-chip">' + anyIdLink(id, label) + copyBtn(id, (ID_KIND_LABELS[idKind(id)] || 'record') + ' id') + '</span>';+ }++ function memoryProvenanceHtml(mem) {+ var sessions = mem.sessionIds || [];+ var obs = mem.sourceObservationIds || [];+ var html = '<div class="mem-section"><div class="mem-section-title">Provenance ' + help('provenance') + '</div>';+ if (!sessions.length && !obs.length) {+ return html + '<div class="empty-step-label">No sources recorded. This memory was saved directly' + (mem.origin && mem.origin.channel ? ' (origin ' + esc(mem.origin.channel) + ')' : '') + ' with memory_save or POST /remember, not distilled from observations. Pass <code>sourceObservationIds</code> when saving to link it to what the agent saw.</div></div>';+ }+ html += '<dl class="mem-meta">';+ if (sessions.length) {+ html += '<dt>Sessions</dt><dd>' + sessions.slice(0, 8).map(function(id) { return '<span class="id-chip">' + entityLink('session', id) + copyBtn(id, 'session id') + '</span>'; }).join(' ') + (sessions.length > 8 ? ' +' + (sessions.length - 8) + ' more' : '') + '</dd>';+ }+ if (obs.length) {+ var home = sessions.length === 1 ? sessions[0] : '';+ if (!home) locateObservations(obs.slice(0, 12));+ html += '<dt>Observations</dt><dd>' + obs.slice(0, 12).map(function(id) {+ var label = esc(shortId(id));+ var sid = home || obsLocations[id] || '';+ var link = sid ? '<a class="entity-link" href="#sessions/' + encodeURIComponent(sid) + '?obs=' + encodeURIComponent(id) + '" title="Open observation ' + esc(id) + ' in session ' + esc(sid) + '">' + label + '</a>' : '<span class="entity-link" title="' + esc(id) + (obsLocations[id] === '' ? ' (no longer stored)' : '') + '">' + label + '</span>';+ return '<span class="id-chip">' + link + copyBtn(id, 'observation id') + '</span>';+ }).join(' ') + (obs.length > 12 ? ' +' + (obs.length - 12) + ' more' : '') + '</dd>';+ }+ return html + '</dl></div>';+ }++ function memoryEditHtml(mem) {+ var e = state.memories.editing;+ var version = mem.version || 1;+ var html = '<div class="mem-edit">';+ html += '<textarea id="mem-edit-text" aria-label="Memory text">' + esc(e.content) + '</textarea>';+ html += '<div class="mem-edit-row"><label for="mem-edit-type">Type</label><select id="mem-edit-type">';+ MEMORY_TYPES.forEach(function(t) { html += '<option value="' + t + '"' + (e.type === t ? ' selected' : '') + '>' + t + '</option>'; });+ html += '</select><span>Saving creates v' + (version + 1) + '. v' + version + ' stays in history and leaves search.</span></div>';+ html += '<div class="mem-edit-row"><button type="button" class="btn btn-primary" data-action="mem-save-edit"' + (state.memories.saving ? ' disabled' : '') + '>' + (state.memories.saving ? 'Saving…' : 'Review and save') + '</button><button type="button" class="btn" data-action="mem-cancel-edit">Cancel</button></div>';+ return html + '</div>';+ }++ function renderMemoryDetail(mem) {+ var m = state.memories;+ var chain = memoryChain(mem);+ var latest = chain.versions[0];+ var isLatest = mem.isLatest !== false;+ var version = mem.version || 1;+ var editing = m.editing && m.editing.id === mem.id;+ var score = strengthScore(mem);+ var html = '<div class="detail-panel mem-detail" data-detail-id="' + esc(mem.id) + '">';+ html += '<div class="mem-detail-head"><span class="badge ' + (TYPE_BADGES[mem.type] || 'badge-muted') + '">' + esc(mem.type || 'memory') + '</span><span class="ver-badge">v' + version + '</span>';+ html += isLatest ? '<span>latest version</span>' : '<span style="color:var(--yellow);font-weight:600;">older version</span>';+ html += '<span>· saved ' + relTime(mem.createdAt) + '</span>' + memoryCloseBtn() + '</div>';+ if (!isLatest) {+ html += '<div class="mem-note">Version ' + version + ' is kept as history and is not searched.' + (latest && latest.id !== mem.id ? ' The current text is ' + entityLink('memory', latest.id, 'v' + (latest.version || 1)) + '.' : '') + '</div>';+ }+ if (m.error) html += '<div class="mem-note err" role="alert">' + esc(m.error) + '</div>';+ html += editing ? memoryEditHtml(mem) : '<div class="mem-detail-content">' + esc(mem.content || '') + '</div>';++ html += '<div class="mem-actions">';+ if (isLatest && !editing) html += '<button type="button" class="btn" data-action="mem-edit" data-memory-id="' + esc(mem.id) + '">Edit</button>';+ html += copyBtn(mem.id, 'memory id').replace('>copy<', '>copy id<');+ html += copyBtn('memory_recall { "query": ' + JSON.stringify(memoryHeadline(mem).head.slice(0, 80)) + ' }', 'MCP recall call').replace('>copy<', '>copy MCP call<');+ html += copyBtn(curlGet('memories/' + encodeURIComponent(mem.id)), 'curl command').replace('>copy<', '>copy curl<');+ html += copyBtn(mem.content || '', 'memory text').replace('>copy<', '>copy text<');+ html += '<button type="button" class="btn btn-danger" data-action="mem-forget" data-memory-id="' + esc(mem.id) + '">Forget…</button>';html += '</div>';- if (totalPages > 1) {- html += '<div class="pagination">';- if (page > 0) html += '<button class="btn" data-action="timeline-page" data-page="' + (page - 1) + '">Prev</button>';- html += '<span style="color:var(--ink-faint);font-size:12px;padding:6px;font-family:var(--font-mono);">Page ' + (page + 1) + ' of ' + totalPages + ' (' + filtered.length + ' total)</span>';- if (page < totalPages - 1) html += '<button class="btn" data-action="timeline-page" data-page="' + (page + 1) + '">Next</button>';- html += '</div>';+ html += '<div class="mem-section"><div class="mem-section-title">Details</div><dl class="mem-meta">';+ html += '<dt>Id</dt><dd>' + idChip('memory', mem.id) + '</dd>';+ html += '<dt>Project ' + help('project') + '</dt><dd>' + (mem.project ? '<button type="button" class="mem-chip" data-action="mem-filter" data-dim="project" data-value="' + esc(mem.project) + '" title="Show only this project">' + esc(mem.project) + '</button>' : '<span style="color:var(--ink-faint);">none (shared across projects)</span>') + '</dd>';+ html += '<dt>Agent ' + help('agent') + '</dt><dd>' + (mem.agentId ? '<button type="button" class="mem-chip" data-action="mem-filter" data-dim="agent" data-value="' + esc(mem.agentId) + '" title="Show only this agent">@' + esc(mem.agentId) + '</button>' : '<span style="color:var(--ink-faint);">none (visible to every agent)</span>') + '</dd>';+ html += '<dt>Strength ' + help('strength') + '</dt><dd>' + score + ' of 10</dd>';+ html += '<dt>Created</dt><dd>' + relTime(mem.createdAt) + '</dd>';+ if (mem.updatedAt && mem.updatedAt !== mem.createdAt) html += '<dt>Updated</dt><dd>' + relTime(mem.updatedAt) + '</dd>';+ if (mem.origin && mem.origin.channel) html += '<dt>Origin ' + help('origin') + '</dt><dd>' + esc(mem.origin.channel) + (mem.origin.detail ? ' (' + esc(mem.origin.detail) + ')' : '') + '</dd>';+ if (mem.forgetAfter) html += '<dt>Expires</dt><dd>' + relTime(mem.forgetAfter) + ' <span style="color:var(--ink-faint);">(' + esc(formatTime(mem.forgetAfter)) + ')</span></dd>';+ if (mem.files && mem.files.length) html += '<dt>Files</dt><dd class="tag-list" style="margin:0;">' + mem.files.slice(0, 12).map(function(f) { return '<span class="tag file-tag" title="' + esc(f) + '">' + esc(String(f).split('/').pop()) + '</span>'; }).join('') + '</dd>';+ if (mem.concepts && mem.concepts.length) html += '<dt>Concepts</dt><dd class="tag-list" style="margin:0;">' + mem.concepts.slice(0, 12).map(function(cn) { return '<span class="tag">' + esc(cn) + '</span>'; }).join('') + '</dd>';+ html += '</dl></div>';++ html += memoryVersionsHtml(mem, chain);+ html += memoryProvenanceHtml(mem);+ html += '<details style="margin-top:12px;"><summary style="cursor:pointer;font-size:11px;color:var(--ink-faint);font-family:var(--font-mono);">raw record</summary>';+ html += '<pre style="margin-top:8px;padding:10px;background:var(--bg);border:1px solid var(--border);font-size:11px;line-height:1.5;overflow-x:auto;white-space:pre-wrap;overflow-wrap:anywhere;">' + esc(JSON.stringify(mem, null, 2)) + '</pre></details>';+ return html + '</div>';+ }++ function bindMemoryToolbar() {+ var searchInput = document.getElementById('mem-search');+ if (searchInput && !searchInput.__bound) {+ searchInput.__bound = true;+ bindImeSafeSearch(searchInput, 300, function(v) { runMemorySearch(v); });+ }+ ['project', 'agent', 'type'].forEach(function(dim) {+ var sel = document.getElementById('mem-' + dim + '-filter');+ if (sel && !sel.__bound) {+ sel.__bound = true;+ sel.addEventListener('change', function() { setMemoryFilter(dim, this.value); });+ }+ });+ }++ var modalReturnFocus = null;+ function openModal(html, focusSelector) {+ var modal = document.getElementById('modal');+ var overlay = document.getElementById('modal-overlay');+ if (!overlay.classList.contains('open')) modalReturnFocus = document.activeElement;+ modal.innerHTML = html;+ var title = modal.querySelector('h3');+ if (title) {+ title.id = 'modal-title';+ modal.setAttribute('aria-labelledby', 'modal-title');+ } else {+ modal.removeAttribute('aria-labelledby');+ }+ overlay.classList.add('open');+ var focusEl = modal.querySelector(focusSelector || '[data-action="close-modal"]');+ if (focusEl) focusEl.focus();+ }++ function modalFocusables() {+ var modal = document.getElementById('modal');+ return Array.prototype.slice.call(modal.querySelectorAll('a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), summary, [tabindex]:not([tabindex="-1"])')).filter(function(el) { return el.offsetParent !== null; });+ }++ document.addEventListener('keydown', function(e) {+ if (e.key !== 'Tab' || !document.getElementById('modal-overlay').classList.contains('open')) return;+ var items = modalFocusables();+ if (!items.length) { e.preventDefault(); return; }+ var first = items[0];+ var last = items[items.length - 1];+ var inside = document.getElementById('modal').contains(document.activeElement);+ if (e.shiftKey && (document.activeElement === first || !inside)) { e.preventDefault(); last.focus(); }+ else if (!e.shiftKey && (document.activeElement === last || !inside)) { e.preventDefault(); first.focus(); }+ });++ function startMemoryEdit(id) {+ var mem = store.entities.memory[id];+ if (!mem) return;+ var m = state.memories;+ m.error = '';+ m.editing = { id: id, content: mem.content || '', type: mem.type || 'fact', rev: (m.editing ? m.editing.rev : 0) + 1 };+ renderMemories();+ var ta = document.getElementById('mem-edit-text');+ if (ta) ta.focus();+ }++ function reviewMemoryEdit() {+ var m = state.memories;+ var e = m.editing;+ var mem = e && store.entities.memory[e.id];+ if (!mem) return;+ var ta = document.getElementById('mem-edit-text');+ var typeSel = document.getElementById('mem-edit-type');+ if (ta) e.content = ta.value;+ if (typeSel) e.type = typeSel.value;+ if (!e.content.trim()) {+ m.error = 'The memory text cannot be empty. Use Forget to delete a memory.';+ e.rev++;+ renderMemories();+ return;+ }+ if (e.content === mem.content && e.type === mem.type) {+ m.error = 'Nothing changed yet. Edit the text or the type, or press Cancel.';+ e.rev++;+ renderMemories();+ return;}+ var version = mem.version || 1;+ openModal('<h3>Save as version ' + (version + 1) + '?</h3>' ++ '<p>agentmemory keeps v' + version + ' as history and removes it from search. Agents recall v' + (version + 1) + ' from now on. This is the same call as <code>POST /agentmemory/evolve</code>.</p>' ++ memoryDiffHtml(mem, { content: e.content, type: e.type }) ++ '<div class="modal-actions" style="margin-top:14px;"><button class="btn" data-action="close-modal">Cancel</button><button class="btn btn-primary" data-action="mem-confirm-edit">Save v' + (version + 1) + '</button></div>', '[data-action="mem-confirm-edit"]');+ }- content.innerHTML = html;+ async function saveMemoryEdit() {+ closeModal();+ var m = state.memories;+ var e = m.editing;+ if (!e || m.saving) return;+ var mem = store.entities.memory[e.id];+ var body = { memoryId: e.id, newContent: e.content };+ if (mem && e.type !== mem.type) body.newType = e.type;+ m.saving = true;+ m.error = '';+ e.rev++;+ renderMemories();+ var res = await api('evolve', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body), readErrorBody: true });+ m.saving = false;+ if (res && res.success && res.memory && res.memory.id) {+ m.editing = null;+ m.selectedId = res.memory.id;+ m.diffId = res.memory.id;+ m.pendingId = store.entities.memory[res.memory.id] ? null : res.memory.id;+ setRouteEntity('memories', res.memory.id);+ } else {+ m.error = res && res.code === 'not_latest'+ ? 'Someone saved a newer version while you were editing. Your text is still here; open the latest version to edit that one.'+ : 'Saving failed' + (res && res.error ? ': ' + res.error : '. Check that agentmemory is running.');+ if (m.editing) m.editing.rev++;+ }+ renderMemories();}- function setTlTypeFilter(type) {- tlTypeFilter = type;- state.timeline.page = 0;- renderObservations();+ function openForgetModal(id) {+ var mem = store.entities.memory[id];+ if (!mem) return;+ var chain = memoryChain(mem);+ var older = chain.older;+ openModal('<h3>Forget this memory permanently?</h3>' ++ '<p>“' + esc(truncate(memoryHeadline(mem).head, 120)) + '” (v' + (mem.version || 1) + ', <code>' + esc(shortId(mem.id, 22)) + '</code>) is deleted from storage and from both search indexes. Agents stop recalling it. This cannot be undone; the delete is recorded in the audit log.</p>' ++ (older.length ? '<label class="modal-check"><input type="checkbox" id="mem-forget-history" checked> Also delete its ' + older.length + ' older version' + (older.length === 1 ? '' : 's') + '. Otherwise they stay as hidden history.</label>' : '') ++ '<p style="font-size:11px;">From an agent: <code>memory_governance_delete { "memoryIds": "' + esc(mem.id) + '" }</code></p>' ++ '<div class="modal-actions"><button class="btn" data-action="close-modal">Cancel</button><button class="btn btn-danger" data-action="mem-confirm-forget" data-memory-id="' + esc(mem.id) + '">Forget permanently</button></div>');+ }++ function openBulkForgetModal() {+ var ids = Object.keys(state.memories.checked);+ if (!ids.length) return;+ var items = ids.slice(0, 6).map(function(id) {+ var mem = store.entities.memory[id];+ return '<li>' + esc(mem ? truncate(memoryHeadline(mem).head, 90) : id) + '</li>';+ }).join('');+ openModal('<h3>Forget ' + fmtNum(ids.length) + ' memor' + (ids.length === 1 ? 'y' : 'ies') + ' permanently?</h3>' ++ '<p>These are deleted from storage and from both search indexes, and agents stop recalling them. This cannot be undone; each delete is recorded in the audit log. Older versions of these memories stay as hidden history.</p>' ++ '<ul class="modal-list">' + items + (ids.length > 6 ? '<li>and ' + fmtNum(ids.length - 6) + ' more</li>' : '') + '</ul>' ++ '<div class="modal-actions"><button class="btn" data-action="close-modal">Cancel</button><button class="btn btn-danger" data-action="mem-confirm-bulk-forget">Forget ' + fmtNum(ids.length) + '</button></div>');+ }++ async function forgetMemories(ids, reason) {+ if (!ids.length) return;+ var res = await apiDelete('governance/memories', { memoryIds: ids, reason: reason });+ var m = state.memories;+ if (res && res.success !== false) {+ ids.forEach(function(id) { delete m.checked[id]; });+ if (m.selectedId && ids.indexOf(m.selectedId) >= 0) {+ m.selectedId = null;+ m.editing = null;+ setRouteEntity('memories', '');+ }+ m.error = '';+ } else {+ m.error = 'Forget failed. Check that agentmemory is running and try again.';+ }+ renderMemories();}- function tlPage(p) {- state.timeline.page = p;- renderObservations();+ function exportCheckedMemories() {+ var rows = Object.keys(state.memories.checked).map(function(id) { return store.entities.memory[id]; }).filter(Boolean);+ if (!rows.length) return;+ var payload = JSON.stringify({ exportedAt: new Date().toISOString(), source: apiBase(), count: rows.length, memories: rows }, null, 2);+ var url = URL.createObjectURL(new Blob([payload], { type: 'application/json' }));+ var a = document.createElement('a');+ a.href = url;+ a.download = 'agentmemory-memories-' + new Date().toISOString().slice(0, 10) + '.json';+ document.body.appendChild(a);+ a.click();+ setTimeout(function() { URL.revokeObjectURL(url); a.remove(); }, 0);+ }++ function handleMemoryAction(action, target) {+ var m = state.memories;+ var id = target.getAttribute('data-memory-id') || '';+ if (action === 'mem-check') {+ if (target.checked) m.checked[id] = true;+ else delete m.checked[id];+ renderMemories();+ } else if (action === 'mem-check-all') {+ var rows = memoryRows();+ if (target.checked) rows.forEach(function(r) { m.checked[r.id] = true; });+ else rows.forEach(function(r) { delete m.checked[r.id]; });+ renderMemories();+ } else if (action === 'mem-uncheck-all') {+ m.checked = {};+ renderMemories();+ } else if (action === 'mem-export') {+ exportCheckedMemories();+ } else if (action === 'mem-bulk-forget') {+ openBulkForgetModal();+ } else if (action === 'mem-confirm-bulk-forget') {+ closeModal();+ forgetMemories(Object.keys(m.checked), 'Forgotten in the viewer (bulk)');+ } else if (action === 'mem-filter') {+ var dim = target.getAttribute('data-dim');+ var value = target.getAttribute('data-value') || '';+ var current = dim === 'project' ? m.projectFilter : dim === 'agent' ? m.agentFilter : m.typeFilter;+ setMemoryFilter(dim, current === value ? '' : value);+ } else if (action === 'mem-clear-filters') {+ clearMemoryFilters();+ } else if (action === 'mem-close') {+ m.selectedId = null;+ m.editing = null;+ m.error = '';+ setRouteEntity('memories', '');+ renderMemories();+ } else if (action === 'mem-diff') {+ m.diffId = id;+ renderMemories();+ } else if (action === 'mem-edit') {+ startMemoryEdit(id);+ } else if (action === 'mem-cancel-edit') {+ m.editing = null;+ m.error = '';+ renderMemories();+ } else if (action === 'mem-save-edit') {+ reviewMemoryEdit();+ } else if (action === 'mem-confirm-edit') {+ saveMemoryEdit();+ } else if (action === 'mem-forget') {+ openForgetModal(id);+ } else if (action === 'mem-confirm-forget') {+ var mem = store.entities.memory[id];+ var withHistory = document.getElementById('mem-forget-history');+ var ids = [id];+ if (mem && withHistory && withHistory.checked) ids = ids.concat(memoryChain(mem).older.map(function(v) { return v.id; }));+ closeModal();+ forgetMemories(ids, 'Forgotten in the viewer');+ }}- async function loadActivity() {- var el = document.getElementById('view-activity');- if (!state.activity.loaded) el.innerHTML = '<div class="loading">Loading activity...</div>';- var results = await Promise.all([- apiGet('sessions'),- apiGet('audit?limit=200')- ]);- var sessions = (results[0] && results[0].sessions) || [];- var auditEntries = (results[1] && results[1].entries) || [];+ function closeModal() {+ var overlay = document.getElementById('modal-overlay');+ var wasOpen = overlay.classList.contains('open');+ overlay.classList.remove('open');+ document.getElementById('modal').classList.remove('overlay-panel');+ var back = modalReturnFocus;+ modalReturnFocus = null;+ if (wasOpen && back && document.contains(back) && typeof back.focus === 'function') back.focus();+ }- var allObs = [];- var sorted = sessions.slice().sort(function(a, b) { return (b.startedAt || '').localeCompare(a.startedAt || ''); });- var recentSessions = sorted.slice(0, 5);+ var ACTIVITY_SESSIONS = 10;- var obsResults = await Promise.all(recentSessions.filter(function(s) { return sessionId(s); }).map(function(s) {- return apiGet('observations?sessionId=' + encodeURIComponent(sessionId(s)));+ async function loadActivity() {+ var sessions = sortByTimeDesc(entityList('session'), ['startedAt']).filter(function(x) { return sessionId(x); }).slice(0, ACTIVITY_SESSIONS);+ var results = await Promise.all(sessions.map(function(x) {+ return apiGet('observations?sessionId=' + encodeURIComponent(sessionId(x)) + '&limit=100');}));- obsResults.forEach(function(r) {- if (r && r.observations) allObs = allObs.concat(r.observations);+ var seen = {};+ var allObs = [];+ results.forEach(function(r) {+ ((r && r.observations) || []).forEach(function(o) {+ if (o && o.id && !seen[o.id]) { seen[o.id] = true; allObs.push(o); }+ });});-- state.activity.sessions = sessions;state.activity.observations = allObs;- state.activity.audit = auditEntries;+ state.activity.sessionCount = sessions.length;state.activity.loaded = true;- renderActivity();+ if (state.activeTab === 'activity') renderActivity();}- function renderActivity() {- var el = document.getElementById('view-activity');- var obs = state.activity.observations;- var sessions = state.activity.sessions;+ var FILE_BASENAMES = { Makefile: 1, Dockerfile: 1, Containerfile: 1, Procfile: 1, Gemfile: 1, Rakefile: 1, Jenkinsfile: 1, Vagrantfile: 1, Justfile: 1, LICENSE: 1, README: 1 };- var TOOL_TYPE_MAP = { Read: 'file_read', Write: 'file_write', Edit: 'file_edit', Bash: 'command_run', Grep: 'search', Glob: 'search', WebFetch: 'web_fetch', WebSearch: 'web_fetch', AskUserQuestion: 'conversation', Task: 'subagent' };+ function looksLikeFile(f, cwd) {+ var s = String(f || '').trim();+ if (!s || /[*?{}[\]]/.test(s)) return false;+ var bare = s.replace(/[\/\\]+$/, '');+ if (cwd && bare === String(cwd).replace(/[\/\\]+$/, '')) return false;+ var base = bare.split(/[\/\\]/).pop() || '';+ return !!FILE_BASENAMES[base] || /\.[A-Za-z0-9_-]{1,12}$/.test(base);+ }- var html = '';+ function obsFiles(o) {+ var out = {};+ var cwd = (store.entities.session[o.sessionId] || {}).cwd;+ (o.files || []).forEach(function(f) { if (looksLikeFile(f, cwd)) out[f] = true; });+ var ti = o.toolInput;+ if (ti && typeof ti === 'object') {+ [ti.file_path, ti.notebook_path].forEach(function(f) { if (typeof f === 'string' && looksLikeFile(f, cwd)) out[f] = true; });+ }+ return Object.keys(out);+ }- html += '<div class="card"><div class="card-title">Activity Heatmap (Past Year)</div>';- var dayCounts = {};- obs.forEach(function(o) {- try {- var d = new Date(o.timestamp);- var key = d.toISOString().slice(0, 10);- dayCounts[key] = (dayCounts[key] || 0) + 1;- } catch(e) {}- });+ function dayKey(ts) {+ var d = new Date(ts);+ if (!isFinite(d.getTime())) return '';+ return d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') + '-' + String(d.getDate()).padStart(2, '0');+ }++ function activityDays(sessions) {+ var days = {};sessions.forEach(function(s) {- try {- var d = new Date(s.startedAt);- var key = d.toISOString().slice(0, 10);- dayCounts[key] = (dayCounts[key] || 0) + 1;- } catch(e) {}+ var k = dayKey(s.startedAt);+ if (!k) return;+ var d = days[k] || (days[k] = { sessions: [], obs: 0 });+ d.sessions.push(s);+ d.obs += s.observationCount || 0;});+ return days;+ }- var maxCount = 0;- Object.keys(dayCounts).forEach(function(k) { if (dayCounts[k] > maxCount) maxCount = dayCounts[k]; });-+ function heatmapHtml(sessions) {+ var act = state.activity;+ var days = activityDays(sessions);+ var keys = Object.keys(days).sort();var today = new Date();- var dayLabels = ['Mon', '', 'Wed', '', 'Fri', '', ''];- html += '<div class="heatmap-labels">';- dayLabels.forEach(function(l) { html += '<span style="width:10px;text-align:center;">' + l + '</span>'; });+ today.setHours(0, 0, 0, 0);+ var earliest = keys.length ? new Date(keys[0] + 'T00:00:00') : today;+ var spanWeeks = Math.ceil((today - earliest) / (7 * 86400000)) + 1;+ var weeks = Math.min(53, Math.max(16, spanWeeks));+ var start = new Date(today);+ start.setDate(start.getDate() - today.getDay() - (weeks - 1) * 7);+ var max = 0;+ keys.forEach(function(k) { if (days[k].obs > max) max = days[k].obs; });+ var totalObs = 0;+ var busiest = '';+ keys.forEach(function(k) { totalObs += days[k].obs; if (!busiest || days[k].obs > days[busiest].obs) busiest = k; });+ var html = '<div class="hm-stats">';+ html += '<div><b>' + fmtNum(keys.length) + '</b>active day' + (keys.length === 1 ? '' : 's') + '</div>';+ html += '<div><b>' + fmtNum(sessions.length) + '</b>sessions ' + help('session') + '</div>';+ html += '<div><b>' + fmtNum(totalObs) + '</b>observations ' + help('observation') + '</div>';+ html += '<div><b>' + (busiest ? esc(new Date(busiest + 'T00:00:00').toLocaleDateString(undefined, { month: 'short', day: 'numeric' })) : '-') + '</b>busiest day' + (busiest ? ' · ' + fmtNum(days[busiest].obs) + ' obs' : '') + '</div>';html += '</div>';- html += '<div class="heatmap-wrap"><div class="heatmap-grid">';- for (var w = 51; w >= 0; w--) {+ var labels = [];+ var cells = '';+ for (var w = 0; w < weeks; w++) {+ var weekStart = new Date(start);+ weekStart.setDate(start.getDate() + w * 7);+ labels[w] = w === 0 ? weekStart.toLocaleDateString(undefined, { month: 'short' }) : '';+ for (var i = 0; i < 7; i++) {+ var probe = new Date(weekStart);+ probe.setDate(weekStart.getDate() + i);+ if (probe.getDate() === 1) labels[w] = probe.toLocaleDateString(undefined, { month: 'short' });+ }for (var d = 0; d < 7; d++) {- var cellDate = new Date(today);- cellDate.setDate(cellDate.getDate() - (w * 7 + (6 - d)));- var key = cellDate.toISOString().slice(0, 10);- var count = dayCounts[key] || 0;- var level = count === 0 ? '' : count <= (maxCount * 0.25) ? 'level-1' : count <= (maxCount * 0.5) ? 'level-2' : count <= (maxCount * 0.75) ? 'level-3' : 'level-4';- var title = key + ': ' + count + ' event' + (count !== 1 ? 's' : '');- html += '<div class="heatmap-cell ' + level + '" title="' + esc(title) + '"></div>';+ var day = new Date(weekStart);+ day.setDate(weekStart.getDate() + d);+ var k = dayKey(day);+ if (day > today) { cells += '<span class="hm-cell future" aria-hidden="true"></span>'; continue; }+ var info = days[k];+ var niceDate = day.toLocaleDateString(undefined, { weekday: 'short', month: 'short', day: 'numeric' });+ if (!info) { cells += '<span class="hm-cell" title="' + esc(niceDate) + ': nothing recorded"></span>'; continue; }+ var ratio = max ? info.obs / max : 0;+ var level = ratio > 0.75 ? 4 : ratio > 0.5 ? 3 : ratio > 0.25 ? 2 : 1;+ var text = niceDate + ': ' + info.sessions.length + ' session' + (info.sessions.length === 1 ? '' : 's') + ', ' + info.obs + ' observation' + (info.obs === 1 ? '' : 's');+ cells += '<button type="button" class="hm-cell level-' + level + (act.day === k ? ' on' : '') + '" data-action="activity-day" data-day="' + k + '" title="' + esc(text) + '" aria-label="' + esc(text) + '" aria-pressed="' + (act.day === k ? 'true' : 'false') + '"></button>';}}- html += '</div></div>';- html += '<div style="display:flex;align-items:center;gap:4px;margin-top:8px;font-size:10px;color:var(--ink-faint);font-family:var(--font-mono);justify-content:flex-end;">Less ';- html += '<div class="heatmap-cell" style="display:inline-block;"></div>';- html += '<div class="heatmap-cell level-1" style="display:inline-block;"></div>';- html += '<div class="heatmap-cell level-2" style="display:inline-block;"></div>';- html += '<div class="heatmap-cell level-3" style="display:inline-block;"></div>';- html += '<div class="heatmap-cell level-4" style="display:inline-block;"></div>';- html += ' More</div>';- html += '</div>';+ if (labels[1] || labels[2]) labels[0] = '';+ html += '<div class="hm"><span></span><div class="hm-months" aria-hidden="true">' + labels.map(function(l) { return '<span>' + esc(l) + '</span>'; }).join('') + '</div>';+ html += '<div class="hm-days" aria-hidden="true"><span></span><span>Mon</span><span></span><span>Wed</span><span></span><span>Fri</span><span></span></div>';+ html += '<div class="hm-grid" role="group" aria-label="Sessions and observations per day">' + cells + '</div></div>';+ var c = store.counts || {};+ var total = typeof c.sessions === 'number' ? c.sessions : sessions.length;+ var cursor = state.sessions.nextCursor;+ html += '<div class="hm-foot"><span>Counts the ' + fmtNum(sessions.length) + (total > sessions.length ? ' newest of ' + fmtNum(total) : '') + ' sessions loaded in this viewer, on the day each started. Pick a shaded day to list its sessions.</span>';+ if (cursor) html += '<button class="btn" data-action="sessions-load-more"' + (state.sessions.loadingMore ? ' disabled' : '') + '>' + (state.sessions.loadingMore ? 'Loading…' : 'Load older sessions') + '</button>';+ html += '<span class="hm-legend" aria-hidden="true">less <span class="hm-cell"></span><span class="hm-cell level-1"></span><span class="hm-cell level-2"></span><span class="hm-cell level-3"></span><span class="hm-cell level-4"></span> more</span></div>';+ if (act.day && days[act.day]) {+ var list = sortByTimeDesc(days[act.day].sessions, ['startedAt']);+ html += '<div class="day-panel"><div class="mem-section-title">' + esc(new Date(act.day + 'T00:00:00').toLocaleDateString(undefined, { weekday: 'long', month: 'long', day: 'numeric' })) + ' · ' + list.length + ' session' + (list.length === 1 ? '' : 's') + ' <button type="button" class="linkish" data-action="activity-day" data-day="' + act.day + '" style="margin-left:auto;font-size:11px;">close</button></div><ul class="ses-links">';+ list.slice(0, 20).forEach(function(s) {+ html += '<li><span class="badge ' + (s.status === 'active' ? 'badge-green' : 'badge-blue') + '">' + esc(s.status || 'unknown') + '</span>' + entityLink('session', sessionId(s), sessionDisplayName(s)) + '<span class="rel-time">' + esc(absTime(s.startedAt)) + ' · ' + fmtNum(s.observationCount || 0) + ' obs</span><span class="src-text">' + esc(s.firstPrompt || '') + '</span></li>';+ });+ html += '</ul></div>';+ }+ return html;+ }++ function activityFeedHtml(obs) {+ var act = state.activity;+ var list = obs.filter(function(o) {+ if (act.typeFilter && obsType(o) !== act.typeFilter) return false;+ if (act.fileFilter && obsFiles(o).indexOf(act.fileFilter) < 0) return false;+ return true;+ }).sort(function(a, b) { return String(b.timestamp || '').localeCompare(String(a.timestamp || '')); });+ var html = '';+ if (act.typeFilter || act.fileFilter) {+ html += '<div class="act-filter"><span>' + fmtNum(list.length) + ' observation' + (list.length === 1 ? '' : 's') + (act.typeFilter ? ' of type <b>' + esc(act.typeFilter.replace(/_/g, ' ')) + '</b>' : '') + (act.fileFilter ? ' touching <b>' + esc(act.fileFilter.split('/').pop()) + '</b>' : '') + '</span><button type="button" class="btn" data-action="activity-clear">Show all</button></div>';+ }+ if (!list.length) {+ return html + emptyState({+ compact: true,+ icon: '🕑',+ title: act.typeFilter || act.fileFilter ? 'No observations match' : 'Nothing captured yet',+ what: 'The newest observations from the ' + ACTIVITY_SESSIONS + ' newest sessions, grouped by session. New ones appear at the top the moment an agent records them.',+ why: act.typeFilter || act.fileFilter ? 'None of the loaded observations match the picked type or file.' : 'The newest sessions have no captured tool use yet.',+ steps: act.typeFilter || act.fileFilter ? [{ label: 'Press Show all above.' }] : [{ label: 'Record one by hand to watch it arrive:', cmd: curlPost('observe', { hookType: 'post_tool_use', sessionId: 'demo-1', project: 'my-project', cwd: '/path/to/project', timestamp: new Date().toISOString(), data: { tool_name: 'Read', tool_input: { file_path: 'README.md' } } }) }]+ });+ }+ html += '<ol class="obs-timeline">';+ var last = null;+ list.slice(0, 40).forEach(function(o) {+ var s = store.entities.session[o.sessionId] || { id: o.sessionId };+ if (o.sessionId !== last) {+ last = o.sessionId;+ html += '<li class="feed-session" aria-hidden="false">' + entityLink('session', o.sessionId, sessionDisplayName(s)) + (s.agentId ? '<span>@' + esc(s.agentId) + '</span>' : '') + (s.firstPrompt ? '<span class="src-text" title="' + esc(s.firstPrompt) + '">' + esc(truncate(s.firstPrompt, 90)) + '</span>' : '') + '</li>';+ }+ html += obsItemHtml(o, s.cwd, o.sessionId);+ });+ html += '</ol>';+ if (list.length > 40) html += '<div class="load-more">Showing the newest 40 of ' + fmtNum(list.length) + '. Open a session for its full timeline.</div>';+ return html;+ }++ function renderActivity() {+ var el = document.getElementById('view-activity');+ var act = state.activity;+ if (!store.loaded.session || !act.loaded) {+ setViewHtml(el, skeleton(10));+ return;+ }+ var sessions = entityList('session').filter(function(s) { return sessionId(s); });+ if (!sessions.length) {+ setViewHtml(el, emptyState({+ icon: '📈',+ title: 'No activity yet',+ what: 'This page shows when agents worked, what kinds of things they did and which files they touched, with a live feed of the newest observations.',+ why: 'No session has been recorded on this install yet.',+ steps: [+ { label: 'Connect your agent with hooks so its work is captured (swap in codex, cursor, gemini-cli or another supported agent):', cmd: connectCmd() },+ { label: 'Or record a session by hand:', cmd: curlPost('session/start', { sessionId: 'demo-1', project: 'my-project', cwd: '/path/to/project' }) }+ ],+ link: { href: 'https://github.com/rohitg00/agentmemory#quick-start', text: 'Supported agents' }+ }));+ return;+ }+ var obs = act.observations || [];+ var html = '<div class="inline-note"><strong>Activity</strong> shows when agents worked and what they did. Pick a day, a kind of work or a file to narrow the feed; every entry links to its session and observation. The feed updates live.</div>';+ html += '<div class="card"><div class="card-title">When agents worked ' + help('heatmap') + '</div>' + heatmapHtml(sessions) + '</div>';var typeCounts = {};+ var fileCounts = {};obs.forEach(function(o) {- var t = o.type || TOOL_TYPE_MAP[o.toolName] || (o.hookType ? o.hookType.replace(/_/g, ' ') : 'other');+ var t = obsType(o);typeCounts[t] = (typeCounts[t] || 0) + 1;+ obsFiles(o).forEach(function(f) { fileCounts[f] = (fileCounts[f] || 0) + 1; });});var typeList = Object.keys(typeCounts).sort(function(a, b) { return typeCounts[b] - typeCounts[a]; });- var totalObs = obs.length || 1;-- html += '<div class="two-col" style="margin-top:16px;">';+ var topFiles = Object.keys(fileCounts).sort(function(a, b) { return fileCounts[b] - fileCounts[a] || a.localeCompare(b); }).slice(0, 8);+ var busiest = sortByTimeDesc(sessions, ['startedAt']).slice(0, 60).sort(function(a, b) { return (b.observationCount || 0) - (a.observationCount || 0); }).slice(0, 5);- html += '<div class="card"><div class="card-title">Type Breakdown</div>';- if (typeList.length === 0) {- html += '<div style="font-size:13px;color:var(--ink-faint);font-style:italic;">No observations yet</div>';+ html += '<div class="dash-cols">';+ html += '<div class="card"><div class="card-title">What agents did <span class="section-sub" style="text-transform:none;letter-spacing:0;font-family:var(--font-ui);font-weight:400;font-size:11px;color:var(--ink-faint);">' + fmtNum(obs.length) + ' observations from the ' + fmtNum(act.sessionCount || 0) + ' newest sessions</span></div>';+ if (!typeList.length) {+ html += '<p class="empty-step-label">The newest sessions have no captured tool use yet. Kinds of work appear here as agents read, edit, run and search.</p>';+ } else {+ html += '<div class="mem-section-title" style="margin-top:0;">Kind of work ' + help('observation') + '</div><div class="bar-chart">';+ var maxT = typeCounts[typeList[0]] || 1;+ typeList.slice(0, 8).forEach(function(t) {+ var on = act.typeFilter === t;+ html += '<button type="button" class="bar-row linkrow' + (on ? ' on' : '') + '" data-action="activity-type" data-type="' + esc(t) + '" aria-pressed="' + (on ? 'true' : 'false') + '" title="Show only ' + esc(t.replace(/_/g, ' ')) + ' observations"><span class="bar-label">' + esc(t.replace(/_/g, ' ')) + '</span><span class="bar-track"><span class="bar-fill" style="display:block;width:' + Math.round((typeCounts[t] / maxT) * 100) + '%;background:' + (OBS_TYPE_COLORS[t] || '#666666') + ';"></span></span><span class="bar-value">' + typeCounts[t] + '</span></button>';+ });+ html += '</div>';+ }+ html += '<div class="mem-section-title" style="margin-top:14px;">Most touched files</div>';+ if (!topFiles.length) {+ html += '<p class="empty-step-label">No file reads or edits in the newest sessions yet.</p>';} else {html += '<div class="bar-chart">';- typeList.slice(0, 12).forEach(function(t) {- var pct = Math.round((typeCounts[t] / totalObs) * 100);- var color = OBS_TYPE_COLORS[t] || '#666666';- html += '<div class="bar-row"><span class="bar-label">' + esc(t.replace(/_/g, ' ')) + '</span><div class="bar-track"><div class="bar-fill" style="width:' + pct + '%;background:' + color + ';"></div></div><span class="bar-value">' + typeCounts[t] + '</span></div>';+ var maxF = fileCounts[topFiles[0]] || 1;+ topFiles.forEach(function(f) {+ var on = act.fileFilter === f;+ html += '<button type="button" class="bar-row linkrow' + (on ? ' on' : '') + '" data-action="activity-file" data-file="' + esc(f) + '" aria-pressed="' + (on ? 'true' : 'false') + '" title="' + esc(f) + ': show only observations touching it"><span class="bar-label">' + esc(f.split('/').pop()) + '</span><span class="bar-track"><span class="bar-fill" style="display:block;width:' + Math.round((fileCounts[f] / maxF) * 100) + '%;background:var(--green);"></span></span><span class="bar-value">' + fileCounts[f] + '</span></button>';});html += '</div>';}- html += '</div>';+ html += '<div class="mem-section-title" style="margin-top:14px;">Busiest recent sessions</div><ul class="ses-links">';+ busiest.forEach(function(s) {+ html += '<li><span class="strength-num" style="min-width:48px;">' + fmtNum(s.observationCount || 0) + ' obs</span>' + entityLink('session', sessionId(s), sessionDisplayName(s)) + '<span class="src-text" title="' + esc(s.firstPrompt || '') + '">' + esc(s.firstPrompt || '') + '</span></li>';+ });+ html += '</ul></div>';++ html += '<div class="card"><div class="card-title">Latest observations ' + help('observation') + ' <span class="ses-live-note" style="font-family:var(--font-ui);font-size:11px;color:var(--ink-faint);">updates live</span></div><div class="card-scroll" style="max-height:640px;padding-left:14px;">';+ html += activityFeedHtml(obs);+ html += '</div></div></div>';+ setViewHtml(el, html);+ }++ function handleActivityAction(action, target) {+ var act = state.activity;+ if (action === 'activity-type') { var t = target.getAttribute('data-type') || ''; act.typeFilter = act.typeFilter === t ? '' : t; }+ else if (action === 'activity-file') { var f = target.getAttribute('data-file') || ''; act.fileFilter = act.fileFilter === f ? '' : f; }+ else if (action === 'activity-day') { var d = target.getAttribute('data-day') || ''; act.day = act.day === d ? '' : d; }+ else if (action === 'activity-clear') { act.typeFilter = ''; act.fileFilter = ''; }+ renderActivity();+ }++ var TOOL_TYPE_MAP = { Read: 'file_read', Write: 'file_write', Edit: 'file_edit', MultiEdit: 'file_edit', NotebookEdit: 'file_edit', Bash: 'command_run', Grep: 'search', Glob: 'search', WebFetch: 'web_fetch', WebSearch: 'web_fetch', AskUserQuestion: 'conversation', Task: 'subagent' };+ var SESSION_OBS_PAGE = 50;++ function obsType(o) {+ if (o.type) return o.type;+ if (o.toolName && TOOL_TYPE_MAP[o.toolName]) return TOOL_TYPE_MAP[o.toolName];+ if (o.hookType === 'prompt_submit') return 'conversation';+ if (o.hookType === 'post_tool_failure') return 'error';+ return 'other';+ }++ function formatDuration(ms) {+ if (!(ms >= 0)) return '';+ var sec = Math.round(ms / 1000);+ if (sec < 60) return sec + 's';+ var min = Math.round(sec / 60);+ if (min < 60) return min + 'm';+ var h = Math.floor(min / 60);+ if (h < 48) return h + 'h ' + (min % 60) + 'm';+ return Math.round(h / 24) + 'd';+ }++ function sessionDuration(s) {+ var start = new Date(s.startedAt).getTime();+ if (!isFinite(start)) return { label: '-', title: 'No start time recorded' };+ if (s.status === 'active' || !s.endedAt) {+ var last = new Date(s.updatedAt || s.startedAt).getTime();+ var span = isFinite(last) && last - start >= 1000 ? formatDuration(last - start) : '';+ return { label: 'running', running: true, span: span, title: span ? 'Still running. The last observation arrived ' + span + ' after the start.' : 'Still running.' };+ }+ var end = new Date(s.endedAt).getTime();+ return { label: formatDuration(end - start) || '-', title: 'From ' + formatTime(s.startedAt) + ' to ' + formatTime(s.endedAt) };+ }++ function absTime(ts) {+ if (!ts) return '';+ try { return new Date(ts).toLocaleString(undefined, { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' }); } catch (_) { return ''; }+ }++ function sessionFiltersActive() {+ var f = state.sessions.filters;+ return !!(String(f.q || '').trim() || f.project || f.agent || f.status);+ }++ function sessionMatches(s) {+ var f = state.sessions.filters;+ if (f.project && s.project !== f.project) return false;+ if (f.agent && s.agentId !== f.agent) return false;+ if (f.status && s.status !== f.status) return false;+ var q = String(f.q || '').trim().toLowerCase();+ if (q) {+ var hay = [sessionId(s), s.project, s.cwd, s.firstPrompt, s.agentId].map(function(v) { return String(v || '').toLowerCase(); }).join('\n');+ if (hay.indexOf(q) < 0) return false;+ }+ return true;+ }++ function sessionRows() {+ return sortByTimeDesc(entityList('session').filter(function(s) { return sessionId(s) && sessionMatches(s); }), ['startedAt']);+ }++ function sessionQueryPath(extra) {+ var f = state.sessions.filters;+ var p = 'sessions?limit=50';+ if (f.project) p += '&project=' + encodeURIComponent(f.project);+ if (f.agent) p += '&agentId=' + encodeURIComponent(f.agent);+ if (f.status) p += '&status=' + encodeURIComponent(f.status);+ if (String(f.q || '').trim()) p += '&q=' + encodeURIComponent(String(f.q).trim());+ return p + (extra || '');+ }++ function mergeSessionRows(rows) {+ (rows || []).forEach(function(row) {+ var id = sessionKey(row);+ if (id) store.entities.session[id] = Object.assign({}, store.entities.session[id] || {}, row);+ });+ }- html += '<div class="card"><div class="card-title">Activity Feed</div>';- var sortedObs = obs.slice().sort(function(a, b) { return (b.timestamp || '').localeCompare(a.timestamp || ''); });- if (sortedObs.length === 0) {- html += '<div style="font-size:13px;color:var(--ink-faint);font-style:italic;">No recent activity</div>';+ async function applySessionFilters() {+ var s = state.sessions;+ if (!sessionFiltersActive()) {+ s.query = null;+ renderSessions();+ return;+ }+ var path = sessionQueryPath();+ s.query = { path: path, loading: true, failed: false, nextCursor: null };+ renderSessions();+ var res = await apiGet(path);+ if (!s.query || s.query.path !== path) return;+ s.query.loading = false;+ if (!res) {+ s.query.failed = true;} else {- sortedObs.slice(0, 20).forEach(function(o) {- var type = o.type || TOOL_TYPE_MAP[o.toolName] || 'other';- var typeColor = OBS_TYPE_COLORS[type] || '#666666';- var icon = OBS_TYPE_ICONS[type] || '📄';- var title = o.title || o.toolName || (o.hookType ? o.hookType.replace(/_/g, ' ') : 'Observation');-- html += '<div class="activity-feed-item">';- html += '<div class="activity-feed-icon" style="color:' + typeColor + ';border-color:' + typeColor + ';">' + icon + '</div>';- html += '<div class="activity-feed-body">';- html += '<div class="activity-feed-title">' + esc(truncate(title, 60)) + '</div>';- if (o.narrative) html += '<div style="font-size:12px;color:var(--ink-muted);margin-top:2px;">' + esc(truncate(o.narrative, 100)) + '</div>';- html += '<div class="activity-feed-meta">' + esc(type.replace(/_/g, ' '));- if (o.files && o.files.length) html += ' · <span class="tag file-tag" style="font-size:9px;padding:0 4px;">' + esc(o.files[0].split('/').pop()) + '</span>';- html += ' · ' + esc(shortTime(o.timestamp)) + '</div>';- html += '</div></div>';- });+ mergeSessionRows(res.sessions);+ s.query.nextCursor = res.nextCursor || null;}- html += '</div>';+ renderSessions();+ }- html += '</div>';+ var applySessionFiltersSoon = debounce(applySessionFilters, 300);- setViewHtml(el, html);+ function setSessionFilter(dim, value) {+ state.sessions.filters[dim] = value || '';+ if (state.sessions.selectedId && window.matchMedia('(max-width: 1100px)').matches) {+ state.sessions.selectedId = null;+ setRouteEntity('sessions', '');+ }+ if (state.sessions.autoSelected) {+ state.sessions.selectedId = null;+ state.sessions.autoSelected = false;+ }+ if (dim === 'q') applySessionFiltersSoon();+ else applySessionFilters();}- async function loadSessions() {- var el = document.getElementById('view-sessions');- if (!state.sessions.loaded) el.innerHTML = '<div class="loading">Loading sessions...</div>';- var seqAtStart = liveSessionSeq;- var result = await apiGet('sessions');- if (result && Array.isArray(result.sessions)) {- state.sessions.items = replaySessionEvents(result.sessions, seqAtStart);- } else if (!state.sessions.loaded) {- state.sessions.items = [];- }- state.sessions.detailStale = true;- state.sessions.loaded = true;+ function clearSessionFilters() {+ state.sessions.filters = { q: '', project: '', agent: '', status: '' };+ state.sessions.query = null;renderSessions();}- function renderSessions() {- var el = document.getElementById('view-sessions');- var items = state.sessions.items.slice().sort(function(a, b) {- return (b.startedAt || '').localeCompare(a.startedAt || '');+ async function loadMoreSessions() {+ var s = state.sessions;+ var q = s.query;+ var cursor = q ? q.nextCursor : s.nextCursor;+ if (!cursor || s.loadingMore) return;+ s.loadingMore = true;+ renderTab(state.activeTab);+ var res = await apiGet(q ? q.path + '&cursor=' + encodeURIComponent(cursor) : 'sessions?limit=100&cursor=' + encodeURIComponent(cursor));+ s.loadingMore = false;+ if (res) {+ mergeSessionRows(res.sessions);+ if (q && s.query === q) q.nextCursor = res.nextCursor || null;+ else if (!q) s.nextCursor = res.nextCursor || null;+ }+ markDirty(['sessions', 'activity', 'profile', 'replay']);+ renderTab(state.activeTab);+ }++ function adjustSessionFacets(prev, next) {+ var f = state.sessions.facets;+ if (!f) return;+ function bump(list, value, delta) {+ if (!value) return;+ var row = list.find(function(x) { return x.value === value; });+ if (row) row.count = Math.max(0, row.count + delta);+ else if (delta > 0) list.push({ value: value, count: delta });+ }+ [['projects', 'project'], ['agents', 'agentId'], ['statuses', 'status']].forEach(function(pair) {+ var list = f[pair[0]] || (f[pair[0]] = []);+ var a = prev ? prev[pair[1]] : '';+ var b = next ? next[pair[1]] : '';+ if (a === b) return;+ bump(list, a, -1);+ bump(list, b, 1);});+ }- var html = '<div class="sessions-layout"><div class="session-list">';- if (items.length === 0) {- html += '<div class="empty-state"><div class="empty-icon">🗒</div><p>No sessions</p></div>';- } else {- items.forEach(function(s) {- var statusBadge = s.status === 'active' ? 'badge-green' : s.status === 'completed' ? 'badge-blue' : 'badge-muted';- var id = sessionId(s);- var selected = id && state.sessions.selectedId === id;- html += '<div class="session-item' + (selected ? ' selected' : '') + '"' + (id ? ' data-action="select-session" data-session-id="' + esc(id) + '" role="button" tabindex="0" aria-expanded="' + (selected ? 'true' : 'false') + '"' : '') + '>';- html += '<div class="session-top"><span class="session-project">' + esc(sessionDisplayName(s)) + '</span>';- html += '<span class="badge ' + statusBadge + '">' + esc(s.status) + '</span></div>';- var preview = s.firstPrompt || summaryText(s.summary) || '';- if (preview) {- html += '<div class="session-preview" style="font-size:13px;color:var(--ink);margin:4px 0;line-height:1.4;">' + esc(truncate(preview, 140)) + '</div>';- }- html += '<div class="session-meta">' + esc(shortSessionId(s, 12) || 'missing id') + ' · ' + esc(formatTime(s.startedAt));- html += ' · ' + (s.observationCount || 0) + ' obs';- if (s.model) html += ' · ' + esc(s.model);- html += '</div></div>';+ function sessionFilterSelect(dim, facetKey, allLabel, current, labelFn) {+ var list = ((state.sessions.facets || {})[facetKey] || []).filter(function(x) { return x.count > 0 || x.value === current; }).slice();+ if (dim === 'status') {+ ['active', 'completed'].forEach(function(v) { if (!list.some(function(x) { return x.value === v; })) list.push({ value: v, count: 0 }); });+ }+ if (current && !list.some(function(x) { return x.value === current; })) list.unshift({ value: current, count: 0 });+ var none = list.length === 0;+ var html = '<select id="ses-' + dim + '-filter" data-dim="' + dim + '" aria-label="Filter sessions by ' + dim + '"' + (none ? ' disabled title="No session has a' + (dim === 'agent' ? 'n agent id' : ' ' + dim) + ' yet"' : '') + '>';+ html += '<option value="">' + esc(none ? 'No ' + dim + 's' : allLabel) + '</option>';+ list.forEach(function(x) {+ html += '<option value="' + esc(x.value) + '"' + (current === x.value ? ' selected' : '') + '>' + esc(labelFn ? labelFn(x.value) : x.value) + ' (' + fmtNum(x.count) + ')</option>';+ });+ return html + '</select>';+ }++ function sessionToolbarHtml() {+ var f = state.sessions.filters;+ var html = '<div class="toolbar mem-filters">';+ html += '<input type="search" id="ses-search" placeholder="Search prompt, project, id or agent (press /)" value="' + esc(f.q) + '" aria-label="Search sessions">';+ html += sessionFilterSelect('project', 'projects', 'All projects', f.project, function(v) { return String(v).split('/').pop(); });+ html += sessionFilterSelect('agent', 'agents', 'All agents', f.agent);+ html += sessionFilterSelect('status', 'statuses', 'Any status', f.status);+ return html + '</div>';+ }++ function bindSessionToolbar() {+ var input = document.getElementById('ses-search');+ if (input && !input.__bound) {+ input.__bound = true;+ bindImeSafeSearch(input, 1, function(v) { setSessionFilter('q', v); });+ }+ ['project', 'agent', 'status'].forEach(function(dim) {+ var sel = document.getElementById('ses-' + dim + '-filter');+ if (sel && !sel.__bound) {+ sel.__bound = true;+ sel.addEventListener('change', function() { setSessionFilter(dim, this.value); });+ }+ });+ }++ function sessionFilterDescription() {+ var f = state.sessions.filters;+ var parts = [];+ if (String(f.q || '').trim()) parts.push('the search “' + esc(f.q) + '”');+ if (f.project) parts.push('project <b>' + esc(f.project) + '</b>');+ if (f.agent) parts.push('agent <b>' + esc(f.agent) + '</b>');+ if (f.status) parts.push('status <b>' + esc(f.status) + '</b>');+ return parts.join(', ');+ }++ function sessionRowHtml(s) {+ var id = sessionId(s);+ var f = state.sessions.filters;+ var selected = state.sessions.selectedId === id;+ var dur = sessionDuration(s);+ var html = '<div class="session-item' + (selected ? ' selected' : '') + '" data-action="select-session" data-session-id="' + esc(id) + '" role="button" tabindex="0" aria-current="' + (selected ? 'true' : 'false') + '">';+ html += '<div class="session-top"><span class="session-project">' + esc(sessionDisplayName(s)) + '</span>';+ html += '<span class="badge ' + (s.status === 'active' ? 'badge-green' : s.status === 'completed' ? 'badge-blue' : 'badge-muted') + '">' + esc(s.status || 'unknown') + '</span></div>';+ var preview = s.firstPrompt || summaryText(s.summary) || '';+ html += preview ? '<div class="session-preview clamp-2">' + esc(preview) + '</div>' : '<div class="session-preview none">No prompt recorded</div>';+ html += '<div class="mem-chips">';+ if (s.agentId) html += '<button type="button" class="mem-chip' + (f.agent === s.agentId ? ' on' : '') + '" data-action="ses-filter" data-dim="agent" data-value="' + esc(s.agentId) + '" title="Show only sessions of agent ' + esc(s.agentId) + '">@' + esc(s.agentId) + '</button>';+ html += '<span>' + fmtNum(s.observationCount || 0) + ' obs</span><span>·</span>';+ html += '<span title="' + esc(formatTime(s.startedAt)) + '">' + esc(timeAgo(s.startedAt) || '-') + ' (' + esc(absTime(s.startedAt)) + ')</span><span>·</span>';+ html += dur.running ? '<span class="running-dot" title="' + esc(dur.title) + '">running</span>' : '<span title="' + esc(dur.title) + '">' + esc(dur.label) + '</span>';+ html += '<span class="ses-id-mini" title="' + esc(id) + '">' + esc(shortId(id, 18)) + '</span>';+ return html + '</div></div>';+ }++ function sessionListHtml(rows) {+ var s = state.sessions;+ var c = store.counts || {};+ var filtered = sessionFiltersActive();+ var html = '';+ if (filtered) {+ var q = s.query;+ var summary = q && q.loading ? 'Filtering on the server…' : q && q.failed ? 'The filter request failed. Change a filter to retry.' : fmtNum(rows.length) + (q && q.nextCursor ? '+' : '') + ' matching session' + (rows.length === 1 ? '' : 's');+ html += '<div class="mem-filter-note"><span>' + summary + ' for ' + sessionFilterDescription() + '</span><button type="button" class="btn" data-action="ses-clear-filters">Clear all</button></div>';+ }+ if (rows.length === 0) {+ if (filtered && s.query && s.query.loading) return html + skeleton(6);+ if (filtered) {+ html += emptyState({+ icon: '🔍',+ title: 'No sessions match',+ what: 'This list shows sessions that match the search box and the project, agent and status filters. The filters run on the server over every session, not only the loaded page.',+ why: 'No session matches ' + sessionFilterDescription() + '.',+ steps: [{ label: 'Run the same query from a terminal:', cmd: curlGet(sessionQueryPath().replace('limit=50', 'limit=20')) }]+ });+ return html + '<div style="margin-top:10px;"><button type="button" class="btn" data-action="ses-clear-filters">Clear search and filters</button></div>';+ }+ return html + emptyState({+ icon: '🗒',+ title: 'No sessions yet',+ what: 'A session is one run of an agent in a project, from start to end. Every observation (file read, edit, command, error) belongs to one, and memories and lessons distilled from the work link back to it.',+ why: 'No agent with agentmemory hooks has started a session on this install yet.',+ steps: [+ { label: 'Connect an agent with hooks so each run is recorded (Claude Code shown):', cmd: connectCmd() },+ { label: 'Or start one by hand and record an observation:', cmd: curlPost('session/start', { sessionId: 'demo-1', project: 'my-project', cwd: '/path/to/project' }) + '\n\n' + curlPost('observe', { hookType: 'post_tool_use', sessionId: 'demo-1', project: 'my-project', cwd: '/path/to/project', timestamp: new Date().toISOString(), data: { tool_name: 'Read', tool_input: { file_path: 'README.md' } } }) }+ ],+ link: { href: 'https://github.com/rohitg00/agentmemory#quick-start', text: 'Connect an agent' }});}- html += '</div>';- html += '<div id="session-detail"></div></div>';- setViewHtml(el, html);+ rows.forEach(function(row) { html += sessionRowHtml(row); });+ var cursor = s.query ? s.query.nextCursor : s.nextCursor;+ var total = filtered ? null : c.sessions;+ html += '<div class="load-more">Showing ' + fmtNum(rows.length) + (typeof total === 'number' ? ' of ' + fmtNum(Math.max(total, rows.length)) : '') + (filtered ? ' matching' : '') + ' sessions, newest first';+ if (cursor) html += '<button class="btn" data-action="sessions-load-more"' + (s.loadingMore ? ' disabled' : '') + '>' + (s.loadingMore ? 'Loading…' : 'Load more') + '</button>';+ return html + '</div>';+ }- if (!state.sessions.selectedId) return;- var cached = state.sessions.detailCache;- if (cached && cached.id === state.sessions.selectedId && !state.sessions.detailStale) {- var panel = document.getElementById('session-detail');- if (panel && panel.innerHTML !== cached.html) panel.innerHTML = cached.html;+ function renderSessions() {+ var el = document.getElementById('view-sessions');+ var s = state.sessions;+ if (!el.querySelector('#session-list')) {+ el.innerHTML = '<div class="inline-note"><strong>Sessions</strong> ' + help('session') + ' are single runs of an agent in a project. Pick one to see its observations ' + help('observation') + ' in order, the files it touched, and the memories and lessons it produced. New sessions and observations appear here live.</div>' ++ '<div id="session-toolbar"></div><div class="sessions-layout" id="sessions-layout"><div id="session-list" class="session-list"></div><div id="session-detail"></div></div>';+ el.__renderedHtml = null;+ }+ var focus = captureSearchFocus(['ses-search']);+ setViewHtml(document.getElementById('session-toolbar'), sessionToolbarHtml());+ bindSessionToolbar();+ restoreSearchFocus(focus);+ var layout = document.getElementById('sessions-layout');+ if (!store.loaded.session) {+ layout.classList.add('has-detail');+ setViewHtml(document.getElementById('session-list'), skeleton(8));+ setViewHtml(document.getElementById('session-detail'), '<div class="detail-panel ses-detail">' + skeleton(10) + '</div>');return;}- renderSessionDetail();+ var rows = sessionRows();+ if (s.autoSelected && s.selectedId && !rows.some(function(r) { return sessionId(r) === s.selectedId; })) {+ s.selectedId = null;+ s.autoSelected = false;+ }+ if (!s.selectedId && !s.closed && rows.length > 0 && window.matchMedia('(min-width: 1101px)').matches) {+ s.selectedId = sessionId(rows[0]);+ s.autoSelected = true;+ }+ setViewHtml(document.getElementById('session-list'), sessionListHtml(rows));+ renderSessionDetailPanel();+ layout.classList.toggle('has-detail', !!document.getElementById('session-detail').firstElementChild);}- function selectSession(id) {- state.sessions.selectedId = state.sessions.selectedId === id ? null : id;+ function selectSession(id, opts) {+ opts = opts || {};+ var s = state.sessions;+ if (s.selectedId === id && !s.autoSelected && !opts.force) {+ if (!opts.keep) {+ s.selectedId = null;+ s.closed = true;+ }+ } else {+ s.selectedId = id;+ s.closed = false;+ }+ s.autoSelected = false;+ setRouteEntity('sessions', s.selectedId);renderSessions();- // On the stacked layout (narrow screens) the detail renders below- // the list; bring it into view. The wide two-pane layout keeps the- // panel sticky beside the list, so no scroll is needed there.- if (- state.sessions.selectedId &&- window.matchMedia('(max-width: 1100px)').matches- ) {+ if (s.selectedId && window.matchMedia('(max-width: 1100px)').matches) {var panel = document.getElementById('session-detail');- if (panel && panel.scrollIntoView) {- panel.scrollIntoView({ behavior: 'smooth', block: 'start' });- }+ if (panel && panel.scrollIntoView) panel.scrollIntoView({ behavior: 'smooth', block: 'start' });}}- var sessionDetailRequest = 0;- async function renderSessionDetail() {+ function closeSessionDetail() {+ state.sessions.selectedId = null;+ state.sessions.autoSelected = false;+ state.sessions.closed = true;+ setRouteEntity('sessions', '');+ renderSessions();+ }++ function newSessionDetail(id) {+ return { id: id, obs: [], total: 0, nextCursor: null, loading: true, loadingMore: false, failed: false, type: '', minImp: 0, types: {}, rev: 0, focusObs: '', produced: { memories: [], loading: true, failed: false, total: 0 } };+ }++ function detailObsPath(d, cursor) {+ var p = 'observations?sessionId=' + encodeURIComponent(d.id) + '&limit=' + SESSION_OBS_PAGE;+ if (d.type) p += '&type=' + encodeURIComponent(d.type);+ if (d.minImp) p += '&minImportance=' + d.minImp;+ if (cursor) p += '&cursor=' + encodeURIComponent(cursor);+ return p;+ }++ function noteObsTypes(d, list) {+ list.forEach(function(o) { d.types[obsType(o)] = true; });+ }++ async function loadSessionObservations(d, more) {+ var path = detailObsPath(d, more ? d.nextCursor : '');+ var key = d.type + '|' + d.minImp;+ if (more) d.loadingMore = true;+ else { d.loading = true; d.obs = []; d.nextCursor = null; }+ d.rev++;+ renderSessionObs();+ var res = await apiGet(path);+ if (state.sessions.detail !== d || d.type + '|' + d.minImp !== key) return;+ d.loading = false;+ d.loadingMore = false;+ if (!res) {+ d.failed = true;+ } else {+ d.failed = false;+ var seen = {};+ d.obs.forEach(function(o) { seen[o.id] = true; });+ (res.observations || []).forEach(function(o) { if (!seen[o.id]) d.obs.push(o); });+ noteObsTypes(d, d.obs);+ d.total = typeof res.total === 'number' ? res.total : d.obs.length;+ d.nextCursor = res.nextCursor || null;+ }+ d.rev++;+ renderSessionHead();+ renderSessionObs();+ revealFocusObs(d);+ }++ async function loadSessionProduced(d) {+ var res = await apiGet('memories?latest=true&sessionId=' + encodeURIComponent(d.id) + '&limit=50');+ if (state.sessions.detail !== d) return;+ d.produced.loading = false;+ if (!res) d.produced.failed = true;+ else {+ d.produced.memories = res.memories || [];+ d.produced.total = typeof res.total === 'number' ? res.total : d.produced.memories.length;+ }+ renderSessionProduced();+ }++ var sessionLookups = {};+ async function lookupSession(id) {+ if (sessionLookups[id]) return;+ sessionLookups[id] = 'loading';+ var res = await apiGet('sessions?limit=20&q=' + encodeURIComponent(id));+ var hit = res && (res.sessions || []).find(function(r) { return sessionKey(r) === id; });+ if (hit) mergeSessionRows([hit]);+ sessionLookups[id] = hit ? 'found' : 'missing';+ if (state.activeTab === 'sessions') renderSessions();+ }++ function ensureSessionDetail(id) {+ var s = state.sessions;+ if (s.detail && s.detail.id === id) return s.detail;+ var d = newSessionDetail(id);+ if (s.pendingObs && s.pendingObs.sid === id) {+ d.focusObs = s.pendingObs.obs;+ s.pendingObs = null;+ }+ s.detail = d;+ Promise.all([ensureLoaded('lesson'), ensureLoaded('crystal')]).then(function() { if (state.sessions.detail === d) renderSessionProduced(); });+ loadSessionObservations(d, false);+ loadSessionProduced(d);+ return d;+ }++ function renderSessionDetailPanel() {var panel = document.getElementById('session-detail');if (!panel) return;- var s = state.sessions.items.find(function(x) { return sessionId(x) === state.sessions.selectedId; });+ var s = state.sessions;+ var id = s.selectedId;+ if (!id) { setViewHtml(panel, ''); panel.__sid = ''; return; }+ var row = store.entities.session[id];+ if (!row) {+ if (!sessionLookups[id]) lookupSession(id);+ panel.__sid = '';+ if (sessionLookups[id] === 'missing') {+ setViewHtml(panel, '<div class="detail-panel ses-detail"><div class="mem-detail-head"><span>Session</span>' + sessionCloseBtn() + '</div>' + emptyState({+ compact: true,+ icon: '🔍',+ title: 'Session not found',+ what: 'Session links anywhere in the viewer open this panel by id.',+ why: 'No session has the id <code>' + esc(id) + '</code>. It was deleted, or the link comes from another install.',+ steps: [{ label: 'Check from a terminal:', cmd: curlGet('sessions?limit=20&q=' + encodeURIComponent(id)) }]+ }) + '</div>');+ } else {+ setViewHtml(panel, '<div class="detail-panel ses-detail"><div class="mem-detail-head"><span>Loading session ' + esc(shortId(id, 22)) + '…</span>' + sessionCloseBtn() + '</div>' + skeleton(8) + '</div>');+ }+ return;+ }+ ensureSessionDetail(id);+ if (panel.__sid !== id || !panel.querySelector('#ses-head')) {+ panel.innerHTML = '<div class="detail-panel ses-detail" data-detail-id="' + esc(id) + '"><div id="ses-head"></div><div id="ses-produced"></div><div id="ses-obs"></div></div>';+ panel.__renderedHtml = null;+ panel.__sid = id;+ }+ renderSessionHead();+ renderSessionProduced();+ renderSessionObs();+ }++ function sessionCloseBtn() {+ return '<button type="button" class="icon-btn icon-close" data-action="ses-close" aria-label="Close session details">close</button>';+ }++ function sessionToolStats(d) {+ var tools = {};+ var files = {};+ d.obs.forEach(function(o) {+ var t = obsType(o);+ var tool = o.toolName || (o.origin && o.origin.channel === 'tool' ? o.origin.detail : '') || (t !== 'conversation' && t !== 'other' ? o.title : '');+ if (tool) tools[tool] = (tools[tool] || 0) + 1;+ (o.files || []).forEach(function(f) { files[f] = (files[f] || 0) + 1; });+ var ti = o.toolInput;+ if (ti && typeof ti === 'object' && (ti.file_path || ti.path)) files[ti.file_path || ti.path] = (files[ti.file_path || ti.path] || 0) + 1;+ });+ return { tools: tools, files: files };+ }++ function relPath(f, cwd) {+ var p = String(f || '');+ if (cwd && p.indexOf(cwd + '/') === 0) return p.slice(cwd.length + 1);+ return p;+ }++ function sessionSummaryHtml(sum) {+ if (!sum) return '';+ if (typeof sum === 'string') return '<div class="mem-section"><div class="mem-section-title">Summary</div><div class="ses-summary">' + esc(sum) + '</div></div>';+ var html = '<div class="mem-section"><div class="mem-section-title">Summary</div>';+ if (sum.title) html += '<div class="ses-summary"><b>' + esc(sum.title) + '</b></div>';+ if (sum.narrative) html += '<div class="ses-summary">' + esc(sum.narrative) + '</div>';+ if (Array.isArray(sum.keyDecisions) && sum.keyDecisions.length) html += '<ul class="obs-facts">' + sum.keyDecisions.map(function(k) { return '<li>' + esc(k) + '</li>'; }).join('') + '</ul>';+ return html + '</div>';+ }++ function sessionHeadHtml(s, d) {var id = sessionId(s);- if (!s || !id) { panel.innerHTML = ''; return; }+ var dur = sessionDuration(s);+ var stats = sessionToolStats(d);+ var toolKeys = Object.keys(stats.tools).sort(function(a, b) { return stats.tools[b] - stats.tools[a]; });+ var fileKeys = Object.keys(stats.files).sort(function(a, b) { return stats.files[b] - stats.files[a]; });+ var partial = d.nextCursor || d.type || d.minImp;+ var html = '<div class="mem-detail-head"><span class="badge ' + (s.status === 'active' ? 'badge-green' : 'badge-blue') + '">' + esc(s.status || 'unknown') + '</span>' + help('sessionStatus');+ html += '<span>' + esc(sessionDisplayName(s)) + '</span>';+ if (s.agentId) html += '<span>· @' + esc(s.agentId) + '</span>';+ html += '<span>· started ' + relTime(s.startedAt) + '</span>' + sessionCloseBtn() + '</div>';+ var prompt = s.firstPrompt || summaryText(s.summary) || '';+ html += prompt ? '<div class="mem-detail-content ses-prompt">' + esc(truncate(prompt, 600)) + '</div>' : '<div class="mem-detail-content ses-prompt none">No first prompt was recorded for this session.</div>';++ html += '<div class="mem-actions">';+ html += copyBtn(id, 'session id').replace('>copy<', '>copy id<');+ html += copyBtn(curlGet('observations?sessionId=' + encodeURIComponent(id) + '&limit=50'), 'curl command').replace('>copy<', '>copy curl<');+ html += copyBtn('memory_timeline { "anchor": ' + JSON.stringify(s.startedAt || '') + ', "project": ' + JSON.stringify(s.project || '') + ', "after": 20 }', 'MCP call').replace('>copy<', '>copy MCP call<');+ html += '<a class="btn" href="#replay" data-replay-session="' + esc(id) + '">Replay</a>';+ html += '<span class="ses-danger-actions">';+ if (s.status === 'active') html += '<button type="button" class="btn btn-danger" data-action="ses-end" data-session-id="' + esc(id) + '">End session…</button>';+ html += '<button type="button" class="btn" data-action="ses-summarize" data-session-id="' + esc(id) + '"' + (state.sessions.summarizing === id ? ' disabled' : '') + '>' + (state.sessions.summarizing === id ? 'Summarizing…' : 'Summarize…') + '</button>';+ html += '</span></div>';+ if (state.sessions.notice && state.sessions.notice.id === id) html += '<div class="mem-note' + (state.sessions.notice.err ? ' err' : '') + '" role="status">' + state.sessions.notice.html + '</div>';++ html += '<div class="ses-stats">';+ html += '<div><span>' + fmtNum(s.observationCount || d.total || 0) + '</span><small>Observations ' + help('observation') + '</small></div>';+ html += '<div><span>' + fmtNum(toolKeys.length) + '</span><small>Tools used' + (partial ? '*' : '') + '</small></div>';+ html += '<div><span>' + fmtNum(fileKeys.length) + '</span><small>Files touched' + (partial ? '*' : '') + '</small></div>';+ html += '<div title="' + esc(dur.title) + '"><span>' + esc(dur.running ? (dur.span ? dur.span + '+' : 'running') : dur.label) + '</span><small>' + (dur.running ? 'Running so far' : 'Duration') + '</small></div>';+ html += '</div>';+ if (partial) html += '<div class="ses-foot">* counted over the ' + fmtNum(d.obs.length) + ' observation' + (d.obs.length === 1 ? '' : 's') + ' loaded below' + (d.type || d.minImp ? ' with the current filter' : '') + '. Load more to widen it.</div>';++ html += '<div class="mem-section"><div class="mem-section-title">Details</div><dl class="mem-meta">';+ html += '<dt>Id</dt><dd>' + idChip('session', id) + '</dd>';+ html += '<dt>Project ' + help('project') + '</dt><dd>' + (s.project ? '<button type="button" class="mem-chip" data-action="ses-filter" data-dim="project" data-value="' + esc(s.project) + '" title="Show only this project">' + esc(s.project) + '</button>' : '<span style="color:var(--ink-faint);">none</span>') + '</dd>';+ html += '<dt>Agent ' + help('agent') + '</dt><dd>' + (s.agentId ? '<button type="button" class="mem-chip" data-action="ses-filter" data-dim="agent" data-value="' + esc(s.agentId) + '" title="Show only this agent">@' + esc(s.agentId) + '</button>' : '<span style="color:var(--ink-faint);">not recorded</span>') + '</dd>';+ html += '<dt>Started</dt><dd>' + relTime(s.startedAt) + ' <span style="color:var(--ink-faint);">(' + esc(formatTime(s.startedAt)) + ')</span></dd>';+ if (s.endedAt && s.status !== 'active') html += '<dt>Ended</dt><dd>' + relTime(s.endedAt) + ' <span style="color:var(--ink-faint);">(' + esc(formatTime(s.endedAt)) + ')</span></dd>';+ else html += '<dt>Last activity</dt><dd>' + relTime(s.updatedAt || s.startedAt) + ' <span style="color:var(--ink-faint);">(still running; updates live)</span></dd>';+ if (s.cwd) html += '<dt>Directory</dt><dd><code>' + esc(s.cwd) + '</code></dd>';+ if (s.model) html += '<dt>Model</dt><dd>' + esc(s.model) + '</dd>';+ if (asTags(s.tags).length) html += '<dt>Tags</dt><dd>' + asTags(s.tags).map(function(t) { return '<span class="tag">' + esc(t) + '</span>'; }).join(' ') + '</dd>';+ if (toolKeys.length) html += '<dt>Tools</dt><dd class="tag-list" style="margin:0;">' + toolKeys.slice(0, 16).map(function(t) { return '<span class="tag">' + esc(t) + ' ×' + stats.tools[t] + '</span>'; }).join('') + '</dd>';+ if (fileKeys.length) {+ html += '<dt>Files</dt><dd class="tag-list" style="margin:0;">' + fileKeys.slice(0, 24).map(function(f) { return '<span class="tag file-tag" title="' + esc(f) + ' (' + stats.files[f] + '×)">' + esc(relPath(f, s.cwd)) + '</span>'; }).join('') + (fileKeys.length > 24 ? '<span class="ses-foot">+' + (fileKeys.length - 24) + ' more</span>' : '') + '</dd>';+ }+ html += '</dl></div>';+ html += sessionSummaryHtml(s.summary);+ return html;+ }++ function renderSessionHead() {+ var host = document.getElementById('ses-head');+ var d = state.sessions.detail;+ if (!host || !d) return;+ var s = store.entities.session[d.id];+ if (!s) return;+ setViewHtml(host, sessionHeadHtml(s, d));+ }++ function sessionLessons(id) {+ var memIds = {};+ var d = state.sessions.detail;+ if (d && d.id === id) d.produced.memories.forEach(function(m) { memIds[m.id] = true; });+ entityList('memory').forEach(function(m) { if ((m.sessionIds || []).indexOf(id) >= 0) memIds[m.id] = true; });+ var crystalIds = {};+ entityList('crystal').forEach(function(c) { if (c.sessionId === id) crystalIds[c.id] = true; });+ return sortByTimeDesc(entityList('lesson').filter(function(l) {+ if (l.deleted) return false;+ return (l.sourceIds || []).some(function(src) { return src === id || crystalIds[src] || memIds[src]; });+ }), ['updatedAt', 'createdAt']);+ }++ function sessionProducedHtml(d) {+ var s = store.entities.session[d.id] || {};+ var p = d.produced;+ var lessons = sessionLessons(d.id);+ var html = '<div class="mem-section"><div class="mem-section-title">Produced from this session ' + help('provenance') + '</div>';+ if (p.loading) return html + skeleton(2) + '</div>';+ if (!p.memories.length && !lessons.length) {+ var newest = d.obs[0];+ html += '<div class="empty-step-label">Nothing links back here yet. A memory links to this session when it is distilled from its observations by consolidation (needs an LLM) or saved with <code>sourceObservationIds</code>; a lesson links here when it is crystallized from this session.' + (p.failed ? ' The lookup failed; reopen the session to retry.' : '') + '</div>';+ if (newest) html += cmdBlock(curlPost('remember', { content: 'What the agent learned in this session', type: 'fact', project: s.project || undefined, sourceObservationIds: [newest.id] }));+ return html + '</div>';+ }+ html += '<dl class="mem-meta">';+ if (p.memories.length) {+ html += '<dt>Memories ' + help('memory') + '</dt><dd><ul class="ses-links">' + p.memories.slice(0, 12).map(function(m) {+ return '<li><span class="badge ' + (TYPE_BADGES[m.type] || 'badge-muted') + '">' + esc(m.type || 'memory') + '</span> ' + entityLink('memory', m.id, truncate(memoryHeadline(m).head, 110)) + '</li>';+ }).join('') + '</ul>' + (p.total > 12 ? '<div class="ses-foot">+' + fmtNum(p.total - 12) + ' more. ' + copyBtn(curlGet('memories?latest=true&sessionId=' + encodeURIComponent(d.id)), 'curl command').replace('>copy<', '>copy curl for all<') + '</div>' : '') + '</dd>';+ }+ if (lessons.length) {+ html += '<dt>Lessons ' + help('lesson') + '</dt><dd><ul class="ses-links">' + lessons.slice(0, 8).map(function(l) {+ return '<li>' + entityLink('lesson', l.id, truncate(l.content || l.id, 110)) + '</li>';+ }).join('') + '</ul></dd>';+ }+ return html + '</dl></div>';+ }++ function renderSessionProduced() {+ var host = document.getElementById('ses-produced');+ var d = state.sessions.detail;+ if (!host || !d) return;+ setViewHtml(host, sessionProducedHtml(d));+ }++ function splitNarrative(n) {+ var text = String(n || '');+ if (text.charAt(0) !== '{') return { input: null, output: text };+ var at = text.indexOf('} | ');+ while (at >= 0) {+ try {+ var parsed = JSON.parse(text.slice(0, at + 1));+ if (parsed && typeof parsed === 'object') return { input: parsed, output: text.slice(at + 4) };+ } catch (_) {}+ at = text.indexOf('} | ', at + 1);+ }+ try {+ var whole = JSON.parse(text);+ if (whole && typeof whole === 'object') return { input: whole, output: '' };+ } catch (_) {}+ return { input: null, output: text };+ }++ function obsCodeHtml(text, label) {+ var str = String(text);+ var lines = str.split('\n').length;+ return '<div class="obs-block"><div class="obs-block-label">' + esc(label) + (lines > 12 ? ' <span>' + fmtNum(lines) + ' lines, scroll</span>' : '') + '</div><pre class="obs-code">' + esc(truncate(str, 20000)) + '</pre></div>';+ }++ function obsFieldsHtml(input, cwd, skip) {+ if (input === null || input === undefined || input === '') return '';+ if (typeof input !== 'object') return obsCodeHtml(input, 'Input');+ var keys = Object.keys(input);+ if (!keys.length) return '';+ var inline = [];+ var blocks = [];+ keys.forEach(function(k) {+ var v = input[k];+ var label = k.replace(/_/g, ' ');+ if (v !== null && typeof v === 'object') { blocks.push(obsCodeHtml(JSON.stringify(v, null, 2), label)); return; }+ var sv = String(v);+ if (sv.length > 140 || sv.indexOf('\n') >= 0) { blocks.push(obsCodeHtml(sv, label)); return; }+ if (skip && sv === skip) return;+ var shown = /path$|^file/.test(k) ? relPath(sv, cwd) : sv;+ inline.push('<dt>' + esc(label) + '</dt><dd><code title="' + esc(sv) + '">' + esc(shown) + '</code></dd>');+ });+ return (inline.length ? '<dl class="obs-fields">' + inline.join('') + '</dl>' : '') + blocks.join('');+ }++ function obsBodyHtml(o, cwd, sub) {+ var type = obsType(o);+ var html = '';+ if (o.toolInput !== undefined || o.toolOutput !== undefined || o.userPrompt) {+ if (o.userPrompt) html += '<div class="obs-prompt">' + esc(o.userPrompt) + '</div>';+ var ti = o.toolInput;+ if (typeof ti === 'string') { try { var pj = JSON.parse(ti); if (pj && typeof pj === 'object') ti = pj; } catch (_) {} }+ html += obsFieldsHtml(ti, cwd, sub);+ var out = o.toolOutput !== undefined ? o.toolOutput : o.error;+ if (out !== undefined && out !== null && out !== '') html += obsCodeHtml(typeof out === 'string' ? out : JSON.stringify(out, null, 2), type === 'error' ? 'Error' : 'Output');+ return html;+ }+ if (o.narrative) {+ if (type === 'conversation') return '<div class="obs-prompt">' + esc(o.narrative) + '</div>';+ var parts = splitNarrative(o.narrative);+ if (parts.input) {+ html += obsFieldsHtml(parts.input, cwd, sub);+ if (parts.output) html += obsCodeHtml(parts.output, type === 'error' ? 'Error' : 'Output');+ } else {+ html += '<div class="obs-narrative">' + esc(humanizeNarrative(o.narrative)) + '</div>';+ }+ }+ if (o.facts && o.facts.length) html += '<ul class="obs-facts">' + o.facts.map(function(f) { return '<li>' + esc(f) + '</li>'; }).join('') + '</ul>';+ return html;+ }++ function obsItemHtml(o, cwd, sid) {+ var type = obsType(o);+ var color = OBS_TYPE_COLORS[type] || '#666666';+ var title = o.title || o.toolName || (o.hookType ? o.hookType.replace(/_/g, ' ') : 'Observation');+ if (type === 'conversation' && (title === 'prompt_submit' || o.hookType === 'prompt_submit')) title = 'User prompt';+ var sub = o.subtitle ? humanizeSubtitle(o.subtitle) : '';+ if (!sub && o.toolInput && typeof o.toolInput === 'object') sub = o.toolInput.file_path || o.toolInput.path || o.toolInput.command || o.toolInput.pattern || '';+ if (sub && sub.charAt(0) === '{') sub = '';+ if (!sub && o.narrative && obsType(o) !== 'conversation') {+ var pin = splitNarrative(o.narrative).input;+ if (pin) sub = pin.file_path || pin.path || pin.command || pin.pattern || pin.url || pin.query || '';+ }+ sub = typeof sub === 'string' ? sub : '';+ var imp = typeof o.importance === 'number' ? o.importance : null;+ var focus = state.sessions.detail && state.sessions.detail.focusObs === o.id;+ var html = '<li class="obs-item' + (focus ? ' focus' : '') + '" id="obs-' + esc(o.id) + '" data-obs-id="' + esc(o.id) + '" style="--obs-color:' + color + ';">';+ html += '<div class="obs-item-head">';+ html += '<span class="obs-type-chip">' + esc(type.replace(/_/g, ' ')) + '</span>';+ html += '<span class="obs-item-title">' + esc(title) + '</span>';+ if (sub) html += '<span class="obs-item-sub" title="' + esc(sub) + '">' + esc(relPath(sub, cwd)) + '</span>';+ html += '<span class="obs-item-meta">';+ if (imp !== null) html += '<span class="obs-importance imp-' + imp + '" title="Importance ' + imp + ' of 10. ' + (imp >= 7 ? 'High' : imp >= 4 ? 'Medium' : 'Low') + '.">' + imp + '</span>';+ else html += '<span class="obs-importance raw" title="Just captured. Importance is set when the observation is compressed.">·</span>';+ html += copyBtn(o.id, 'observation id').replace('>copy<', '>copy id<');+ html += '<a class="obs-time" href="#sessions/' + encodeURIComponent(sid) + '?obs=' + encodeURIComponent(o.id) + '" title="' + esc(formatTime(o.timestamp)) + '. Link to this observation.">' + esc(shortTime(o.timestamp)) + '</a>';+ html += '</span></div>';+ html += '<div class="obs-item-body">' + obsBodyHtml(o, cwd, sub);+ var files = (o.files || []).filter(function(f) { return relPath(f, cwd) !== relPath(sub, cwd); });+ if (files.length || (o.concepts && o.concepts.length)) {+ html += '<div class="tag-list">' + (o.concepts || []).map(function(c) { return '<span class="tag">' + esc(c) + '</span>'; }).join('') + files.map(function(f) { return '<span class="tag file-tag" title="' + esc(f) + '">' + esc(relPath(f, cwd)) + '</span>'; }).join('') + '</div>';+ }+ return html + '</div></li>';+ }++ function sessionObsControlsHtml(d) {+ var html = '<div class="type-chips">';+ html += '<span class="type-chip' + (!d.type ? ' active' : '') + '" role="button" tabindex="0" data-action="ses-obs-type" data-type-filter="">All' + (!d.type && !d.minImp ? ' (' + fmtNum(d.total) + ')' : '') + '</span>';+ Object.keys(d.types).sort().forEach(function(t) {+ var color = OBS_TYPE_COLORS[t] || '#666666';+ var on = d.type === t;+ html += '<span class="type-chip' + (on ? ' active' : '') + '" role="button" tabindex="0" data-action="ses-obs-type" data-type-filter="' + esc(t) + '" style="' + (on ? 'background:' + color + ';border-color:' + color + ';' : 'border-color:' + color + ';color:' + color + ';') + '">' + esc(t.replace(/_/g, ' ')) + (on ? ' (' + fmtNum(d.total) + ')' : '') + '</span>';+ });+ html += '<select id="ses-obs-imp" aria-label="Minimum importance"><option value="0">Any importance</option>';+ [4, 7].forEach(function(i) { html += '<option value="' + i + '"' + (d.minImp === i ? ' selected' : '') + '>importance ' + i + '+</option>'; });+ return html + '</select></div>';+ }++ function sessionObsHtml(d) {+ var s = store.entities.session[d.id] || {};+ var html = '<div class="mem-section"><div class="mem-section-title">Observations ' + help('observation') + ' <span class="ses-live-note">newest first · importance ' + help('importance') + ' · updates live</span></div>';+ html += sessionObsControlsHtml(d);+ if (d.loading) return html + skeleton(6) + '</div>';+ if (!d.obs.length) {+ if (d.type || d.minImp) {+ html += emptyState({+ compact: true,+ icon: '🕑',+ title: 'No observations match',+ what: 'The type chips and the importance picker narrow this list on the server.',+ why: 'No observation in this session is ' + (d.type ? 'of type <b>' + esc(d.type.replace(/_/g, ' ')) + '</b>' : '') + (d.type && d.minImp ? ' with ' : '') + (d.minImp ? 'importance ' + d.minImp + ' or higher' : '') + '.',+ steps: [{ label: 'Pick All, or choose Any importance.' }]+ });+ } else {+ html += emptyState({+ compact: true,+ icon: '🕑',+ title: d.failed ? 'Observations could not be loaded' : 'No observations yet',+ what: 'Observations are the individual things the agent did: prompts, file reads and edits, commands, searches, errors.',+ why: d.failed ? 'The request failed. Check that agentmemory is running, then reopen the session.' : s.status === 'active' ? 'The session is running but no tool use was captured yet. New ones appear here the moment they arrive.' : 'This session ended before any tool use was captured.',+ steps: [{ label: 'Record one by hand to watch it arrive live:', cmd: curlPost('observe', { hookType: 'post_tool_use', sessionId: d.id, project: s.project || 'my-project', cwd: s.cwd || '/path/to/project', timestamp: new Date().toISOString(), data: { tool_name: 'Read', tool_input: { file_path: 'README.md' } } }) }]+ });+ }+ return html + '</div>';+ }+ html += '<ol class="obs-timeline" id="ses-obs-list">';+ d.obs.forEach(function(o) { html += obsItemHtml(o, s.cwd, d.id); });+ html += '</ol>';+ html += '<div class="load-more" id="ses-obs-more">' + sessionObsMoreHtml(d) + '</div>';+ return html + '</div>';+ }++ function sessionObsMoreHtml(d) {+ var html = 'Showing ' + fmtNum(d.obs.length) + ' of ' + fmtNum(Math.max(d.total, d.obs.length)) + (d.type || d.minImp ? ' matching' : '') + ' observations';+ if (d.nextCursor) html += '<button class="btn" data-action="ses-obs-more"' + (d.loadingMore ? ' disabled' : '') + '>' + (d.loadingMore ? 'Loading…' : 'Load ' + SESSION_OBS_PAGE + ' more') + '</button>';+ return html;+ }++ function renderSessionObs() {+ var host = document.getElementById('ses-obs');+ var d = state.sessions.detail;+ if (!host || !d) return;+ if (host.__rev === d.rev && host.__detail === d) return;+ host.__rev = d.rev;+ host.__detail = d;+ host.innerHTML = sessionObsHtml(d);+ host.__renderedHtml = null;+ var sel = document.getElementById('ses-obs-imp');+ if (sel) sel.addEventListener('change', function() { setSessionObsFilter(d.type, parseInt(this.value, 10) || 0); });+ }++ function setSessionObsFilter(type, minImp) {+ var d = state.sessions.detail;+ if (!d) return;+ d.type = type;+ d.minImp = minImp;+ loadSessionObservations(d, false);+ renderSessionHead();+ }++ function obsMatchesDetail(d, o) {+ if (d.type && obsType(o) !== d.type) return false;+ if (d.minImp && !(typeof o.importance === 'number' && o.importance >= d.minImp)) return false;+ return true;+ }++ function liveSessionObservation(o) {+ var d = state.sessions.detail;+ if (!d || d.id !== o.sessionId || d.loading) return;+ var s = store.entities.session[d.id] || {};+ var idx = d.obs.findIndex(function(x) { return x.id === o.id; });+ var list = document.getElementById('ses-obs-list');+ var inView = state.activeTab === 'sessions' && list && document.getElementById('ses-obs').__detail === d;+ if (idx >= 0) {+ d.obs[idx] = o.narrative || o.type ? o : Object.assign({}, d.obs[idx], o);+ d.types[obsType(d.obs[idx])] = true;+ var node = inView ? document.getElementById('obs-' + o.id) : null;+ if (node) node.outerHTML = obsItemHtml(d.obs[idx], s.cwd, d.id);+ else d.rev++;+ } else {+ if (!obsMatchesDetail(d, o)) return;+ var newType = !d.types[obsType(o)];+ d.types[obsType(o)] = true;+ d.obs.unshift(o);+ d.total++;+ if (inView && !newType) {+ list.insertAdjacentHTML('afterbegin', obsItemHtml(o, s.cwd, d.id).replace('class="obs-item', 'class="obs-item fresh'));+ var more = document.getElementById('ses-obs-more');+ if (more) more.innerHTML = sessionObsMoreHtml(d);+ } else {+ d.rev++;+ }+ }+ if (state.activeTab === 'sessions') {+ renderSessionObs();+ renderSessionHead();+ }+ }++ function noteSessionProduced(change) {+ var d = state.sessions.detail;+ if (!d || d.produced.loading) return;+ var list = d.produced.memories;+ var idx = list.findIndex(function(m) { return m.id === change.id; });+ var row = change.row;+ var links = !!row && row.isLatest !== false && ((row.sessionIds || []).indexOf(d.id) >= 0 || (row.sourceObservationIds || []).some(function(oid) { return d.obs.some(function(o) { return o.id === oid; }); }));+ if (idx >= 0 && !links) {+ list.splice(idx, 1);+ d.produced.total = Math.max(0, d.produced.total - 1);+ } else if (idx >= 0) {+ list[idx] = row;+ } else if (links) {+ list.unshift(row);+ d.produced.total++;+ } else {+ return;+ }+ if (state.activeTab === 'sessions') renderSessionProduced();+ }++ function revealFocusObs(d) {+ if (!d.focusObs || d.loading) return;+ var hit = d.obs.some(function(o) { return o.id === d.focusObs; });+ if (!hit) {+ if (d.nextCursor && !d.loadingMore && (d.focusPages || 0) < 40) {+ d.focusPages = (d.focusPages || 0) + 1;+ loadSessionObservations(d, true);+ } else if (!d.nextCursor) {+ state.sessions.notice = { id: d.id, err: true, html: 'Observation <code>' + esc(d.focusObs) + '</code> is not in this session' + (d.type || d.minImp ? ' with the current filter' : '') + '.' };+ d.focusObs = '';+ renderSessionHead();+ }+ return;+ }+ if (state.activeTab !== 'sessions') return;+ var el = document.getElementById('obs-' + d.focusObs);+ if (el && el.scrollIntoView) el.scrollIntoView({ block: 'center' });+ }++ function focusSessionObservation(sid, obsId) {+ var s = state.sessions;+ if (s.detail && s.detail.id === sid) {+ s.detail.focusObs = obsId;+ s.detail.focusPages = 0;+ s.detail.rev++;+ renderSessionObs();+ revealFocusObs(s.detail);+ } else {+ s.pendingObs = { sid: sid, obs: obsId };+ }+ }++ function openEndSessionModal(id) {+ var s = store.entities.session[id];+ if (!s) return;+ var llm = store.provider !== 'noop';+ openModal('<h3>End this session?</h3>' ++ '<p>Marks <b>' + esc(sessionDisplayName(s)) + '</b> (<code>' + esc(shortId(id, 22)) + '</code>) as completed and records the end time now. It does not stop the agent: if it keeps working, its observations are still recorded under this session id.</p>' ++ '<p>Ending runs the same wrap-up as the agent’s own stop hook: ' + (llm ? 'an LLM summary of the session, knowledge-graph extraction and, when consolidation is on, crystals and lessons.' : 'with no LLM provider configured, the summary and graph extraction are skipped, so ending only changes the status.') + '</p>' ++ '<p style="font-size:11px;">Same call from a terminal: <code>' + esc(curlPost('session/end', { sessionId: id }).replace(/\s*\\\n\s*/g, ' ')) + '</code></p>' ++ '<div class="modal-actions"><button class="btn" data-action="close-modal">Cancel</button><button class="btn btn-danger" data-action="ses-confirm-end" data-session-id="' + esc(id) + '">End session</button></div>');+ }++ function openSummarizeModal(id) {+ var s = store.entities.session[id];+ if (!s) return;+ var llm = store.provider !== 'noop';+ var body = '<h3>Summarize this session?</h3>' ++ '<p>An LLM reads the observations of <b>' + esc(sessionDisplayName(s)) + '</b> (' + fmtNum(s.observationCount || 0) + ') and writes a short summary: a title, what happened and the key decisions. The summary is shown here and in the session list, and later feeds consolidation into facts and procedures. Running it again replaces the old summary.</p>';+ if (!llm) {+ body += '<div class="mem-note err">No LLM provider is configured, so Summarize would do nothing. Set a key and restart agentmemory:</div>' + cmdBlock('export ANTHROPIC_API_KEY=sk-ant-...\nnpx @agentmemory/agentmemory');+ body += '<div class="modal-actions" style="margin-top:14px;"><button class="btn" data-action="close-modal">Close</button></div>';+ } else {+ body += '<p style="font-size:11px;">Same call from a terminal: <code>' + esc(curlPost('summarize', { sessionId: id }).replace(/\s*\\\n\s*/g, ' ')) + '</code></p>';+ body += '<div class="modal-actions"><button class="btn" data-action="close-modal">Cancel</button><button class="btn btn-primary" data-action="ses-confirm-summarize" data-session-id="' + esc(id) + '">Summarize</button></div>';+ }+ openModal(body, llm ? '[data-action="ses-confirm-summarize"]' : '[data-action="close-modal"]');+ }++ async function endSession(id) {+ closeModal();+ var res = await apiPost('session/end', { sessionId: id });+ state.sessions.notice = res && res.success !== false+ ? { id: id, html: 'Session ended. The wrap-up (summary, graph, consolidation) runs in the background and its results appear here live.' }+ : { id: id, err: true, html: 'Ending the session failed. Check that agentmemory is running and try again.' };+ renderSessionHead();+ }++ var SUMMARIZE_ERRORS = {+ no_provider: 'No LLM provider is configured, so nothing was summarized. Set ANTHROPIC_API_KEY (or another provider key) and restart agentmemory.',+ no_observations: 'This session has no observations to summarize yet.',+ session_not_found: 'agentmemory does not know this session any more.'+ };++ async function summarizeSession(id) {+ closeModal();+ state.sessions.summarizing = id;+ state.sessions.notice = null;+ renderSessionHead();+ var res = await apiPost('summarize', { sessionId: id });+ state.sessions.summarizing = '';+ if (res && res.success !== false) {+ state.sessions.notice = { id: id, html: 'Summary saved. It is shown under Details below.' };+ if (res.summary && store.entities.session[id]) store.entities.session[id].summary = res.summary;+ } else {+ var code = res && res.error;+ state.sessions.notice = { id: id, err: true, html: esc(SUMMARIZE_ERRORS[code] || ('Summarize failed' + (code ? ': ' + code : '. Check that agentmemory is running.'))) };+ }+ renderSessionHead();+ }++ function handleSessionAction(action, target) {+ var id = target.getAttribute('data-session-id') || '';+ if (action === 'ses-close') { closeSessionDetail(); return; }+ if (action === 'ses-filter') {+ var dim = target.getAttribute('data-dim');+ var value = target.getAttribute('data-value') || '';+ if (dim) setSessionFilter(dim, state.sessions.filters[dim] === value ? '' : value);+ return;+ }+ if (action === 'ses-clear-filters') { clearSessionFilters(); return; }+ if (action === 'ses-obs-type') {+ var d = state.sessions.detail;+ if (d) setSessionObsFilter(target.getAttribute('data-type-filter') || '', d.minImp);+ return;+ }+ if (action === 'ses-obs-more') {+ if (state.sessions.detail) loadSessionObservations(state.sessions.detail, true);+ return;+ }+ if (action === 'ses-end') { openEndSessionModal(id); return; }+ if (action === 'ses-confirm-end') { endSession(id); return; }+ if (action === 'ses-summarize') { openSummarizeModal(id); return; }+ if (action === 'ses-confirm-summarize') { summarizeSession(id); return; }+ }++ function isFresh(id) {+ var at = state.freshRows[id];+ return !!at && Date.now() - at < 3000;+ }++ function confColor(pct) {+ return pct >= 70 ? 'var(--green)' : pct >= 40 ? 'var(--yellow)' : 'var(--red)';+ }++ function listDetailShell(el, kind, note) {+ if (!el.querySelector('#' + kind + '-list')) {+ el.innerHTML = '<div id="' + kind + '-note"></div><div id="' + kind + '-toolbar"></div><div class="list-detail" id="' + kind + '-layout"><div id="' + kind + '-list"></div><div class="ld-detail" id="' + kind + '-detail"></div></div>';+ el.__renderedHtml = null;+ }+ setViewHtml(document.getElementById(kind + '-note'), note || '');+ }- state.sessions.detailStale = false;- var request = ++sessionDetailRequest;- var cached = state.sessions.detailCache;- if (!cached || cached.id !== id) {- panel.innerHTML = '<div class="detail-panel"><h3>Loading session details…</h3></div>';+ function sourceItemHtml(id) {+ var kind = idKind(id);+ var text = '';+ if (kind === 'session') {+ var s = store.entities.session[id];+ text = s ? sessionDisplayName(s) + (s.firstPrompt ? ': ' + s.firstPrompt : '') : '';+ } else if (kind === 'memory') {+ var m = store.entities.memory[id];+ text = m ? memoryHeadline(m).head : '';+ } else if (kind === 'crystal') {+ var c = store.entities.crystal[id];+ text = c ? c.narrative || '' : '';+ } else if (kind === 'action') {+ var a = store.entities.action[id];+ text = a ? a.title || '' : '';}+ return '<li><span class="kind-tag">' + esc(ID_KIND_LABELS[kind] || 'record') + '</span>' + anyIdChip(id) + (text ? '<span class="src-text" title="' + esc(text) + '">' + esc(text) + '</span>' : '') + '</li>';+ }- var obsRes = await apiGet('observations?sessionId=' + encodeURIComponent(id));- if (request !== sessionDetailRequest || state.sessions.selectedId !== id) return;- var obs = (obsRes && obsRes.observations) || [];+ function lessonRows() {+ var l = state.lessons;+ var search = String(l.search || '').trim().toLowerCase();+ return sortByTimeDesc(entityList('lesson').filter(function(x) {+ if (!x || x.deleted === true) return false;+ if (l.projectFilter && (x.project || '') !== l.projectFilter) return false;+ if (search && (String(x.content || '') + ' ' + String(x.context || '') + ' ' + asTags(x.tags).join(' ')).toLowerCase().indexOf(search) < 0) return false;+ return true;+ }), ['updatedAt', 'createdAt']);+ }- var typeCounts = {};- var toolCounts = {};- var fileSet = new Set();- var firstPromptFromObs = '';- obs.forEach(function(o) {- var t = o.type || o.hookType || 'other';- typeCounts[t] = (typeCounts[t] || 0) + 1;- var tool = o.title || o.toolName;- if (tool && t !== 'conversation') toolCounts[tool] = (toolCounts[tool] || 0) + 1;- (o.files || []).forEach(function(f) { fileSet.add(f); });- if (!firstPromptFromObs && (o.userPrompt || (o.type === 'conversation' && o.narrative))) {- firstPromptFromObs = o.userPrompt || o.narrative || '';- }+ function lessonToolbarHtml(total) {+ var l = state.lessons;+ var projects = {};+ entityList('lesson').forEach(function(x) { if (x && !x.deleted) projects[x.project || ''] = (projects[x.project || ''] || 0) + 1; });+ var html = '<div class="toolbar mem-filters">';+ html += '<input id="lessons-search" type="search" placeholder="Filter lessons by text, reason or tag (press /)" value="' + esc(l.search) + '" aria-label="Filter lessons">';+ html += '<select id="lessons-project" aria-label="Filter lessons by project"><option value="">All projects</option>';+ Object.keys(projects).sort().forEach(function(p) {+ html += '<option value="' + esc(p) + '"' + (l.projectFilter === p && p ? ' selected' : '') + (p ? '' : ' disabled') + '>' + esc(p || 'no project') + ' (' + projects[p] + ')</option>';});-- var durationMs = s.endedAt ? new Date(s.endedAt).getTime() - new Date(s.startedAt).getTime() : 0;- var durationLabel = durationMs > 0 ? (durationMs < 60000 ? (durationMs / 1000).toFixed(1) + 's' : (durationMs / 60000).toFixed(1) + 'm') : '-';-- var preview = s.firstPrompt || summaryText(s.summary) || firstPromptFromObs || '';-- var html = '<div class="detail-panel">';- html += '<div style="display:flex;justify-content:space-between;align-items:flex-start;margin-bottom:12px;">';- html += '<h3 style="margin:0;">Session · ' + esc(s.project || 'Unknown') + '</h3>';- html += '<span class="badge ' + (s.status === 'active' ? 'badge-green' : 'badge-blue') + '">' + esc(s.status) + '</span>';+ html += '</select><span class="tb-count">' + fmtNum(total) + ' lesson' + (total === 1 ? '' : 's') + '</span>';+ return html + '</div>';+ }++ function lessonRowHtml(x) {+ var pct = Math.round((x.confidence || 0) * 100);+ var selected = state.lessons.selectedId === x.id;+ var html = '<tr class="lesson-row' + (selected ? ' row-select' : '') + (isFresh(x.id) ? ' fresh' : '') + '" data-action="select-lesson" data-lesson-id="' + esc(x.id) + '" role="button" tabindex="0" aria-expanded="' + (selected ? 'true' : 'false') + '" style="cursor:pointer;">';+ html += '<td style="max-width:0;width:100%;"><div class="mem-head clamp-2">' + esc(x.content) + '</div>' + (x.context ? '<div class="mem-excerpt">' + esc(x.context) + '</div>' : '');+ html += '<div class="mem-chips">' + (x.project ? '<span class="mem-chip" style="cursor:default;">' + esc(x.project) + '</span>' : '') + '<span class="badge badge-' + (x.source === 'crystal' ? 'purple' : x.source === 'consolidation' ? 'yellow' : 'blue') + '">' + esc(x.source || 'manual') + '</span>' + ((x.sourceIds || []).length ? '<span>' + x.sourceIds.length + ' source' + (x.sourceIds.length === 1 ? '' : 's') + '</span>' : '') + '<span class="mob-only">' + pct + '% · ' + (x.reinforcements || 0) + ' uses</span></div></td>';+ html += '<td class="col-opt" style="white-space:nowrap;" title="Confidence ' + pct + '%"><div class="strength-bar"><div class="fill" style="width:' + pct + '%;background:' + confColor(pct) + '"></div></div> <span class="strength-num">' + pct + '%</span></td>';+ html += '<td class="col-opt" style="text-align:center;font-family:var(--font-mono);font-size:12px;">' + (x.reinforcements || 0) + '</td>';+ html += '<td class="col-opt">' + relTime(x.updatedAt || x.createdAt) + '</td>';+ return html + '</tr>';+ }++ function lessonDetailHtml(x) {+ var pct = Math.round((x.confidence || 0) * 100);+ var html = '<div class="detail-panel mem-detail" data-detail-id="' + esc(x.id) + '">';+ html += '<div class="mem-detail-head"><span class="badge badge-' + (x.source === 'crystal' ? 'purple' : x.source === 'consolidation' ? 'yellow' : 'blue') + '">' + esc(x.source || 'manual') + '</span><span>lesson</span><span>· learned ' + relTime(x.createdAt) + '</span><button type="button" class="icon-btn icon-close" data-action="lesson-close" aria-label="Close lesson details">close</button></div>';+ html += '<div class="mem-detail-content">' + esc(x.content) + '</div>';+ if (state.lessons.notice && state.lessons.notice.id === x.id) html += '<div class="mem-note' + (state.lessons.notice.err ? ' err' : '') + '" role="status">' + state.lessons.notice.html + '</div>';+ html += '<div class="mem-actions">';+ html += '<button type="button" class="btn" data-action="lesson-strengthen" data-lesson-id="' + esc(x.id) + '"' + (state.lessons.busy === x.id ? ' disabled' : '') + ' title="Record one more use: confidence rises and the decay clock restarts">' + (state.lessons.busy === x.id ? 'Saving…' : 'Strengthen') + '</button>';+ html += copyBtn(x.id, 'lesson id').replace('>copy<', '>copy id<');+ html += copyBtn('memory_lesson_recall { "query": ' + JSON.stringify(String(x.content || '').slice(0, 60)) + ' }', 'MCP recall call').replace('>copy<', '>copy MCP call<');+ html += copyBtn(curlPost('lessons/search', { query: String(x.content || '').slice(0, 60) }), 'curl command').replace('>copy<', '>copy curl<');+ html += '<button type="button" class="btn btn-danger" data-action="lesson-delete" data-lesson-id="' + esc(x.id) + '">Delete…</button>';html += '</div>';-- if (preview) {- html += '<div style="padding:10px 12px;margin-bottom:12px;background:var(--bg-alt);border-left:3px solid var(--accent);font-size:13px;line-height:1.5;color:var(--ink);">' + esc(truncate(preview, 600)) + '</div>';+ html += '<div class="mem-section"><div class="mem-section-title">Details</div><dl class="mem-meta">';+ if (x.context) html += '<dt>Why learned</dt><dd>' + esc(x.context) + '</dd>';+ html += '<dt>Confidence ' + help('confidence') + '</dt><dd><span class="conf-line"><span class="hbar' + (pct < 40 ? ' bad' : pct < 70 ? ' warn' : '') + '"><span style="width:' + pct + '%"></span></span><b>' + pct + '%</b></span></dd>';+ html += '<dt>Uses ' + help('reinforcements') + '</dt><dd>' + fmtNum(x.reinforcements || 0) + (x.lastReinforcedAt ? ', last ' + relTime(x.lastReinforcedAt) : ', never confirmed again yet') + '</dd>';+ var baseline = x.lastDecayedAt || x.lastReinforcedAt || x.createdAt;+ var weeks = baseline ? (Date.now() - new Date(baseline).getTime()) / (7 * 86400000) : 0;+ var rate = typeof x.decayRate === 'number' ? x.decayRate : 0.05;+ var daysLeft = Math.max(1, Math.ceil((1 - weeks) * 7));+ var points = Math.round(rate * 100);+ html += '<dt>Decay ' + help('decay') + '</dt><dd>' + (weeks < 1+ ? 'Starts in ' + daysLeft + ' day' + (daysLeft === 1 ? '' : 's') + ' if it stays unused, then −' + points + ' points a week.'+ : 'Unused for ' + Math.floor(weeks) + ' week' + (Math.floor(weeks) === 1 ? '' : 's') + '; loses ' + points + ' points a week until an agent uses it again.') + '</dd>';+ html += '<dt>Project ' + help('project') + '</dt><dd>' + (x.project ? esc(x.project) : '<span style="color:var(--ink-faint);">all projects</span>') + '</dd>';+ if (asTags(x.tags).length) html += '<dt>Tags</dt><dd class="tag-list" style="margin:0;">' + asTags(x.tags).map(function(t) { return '<span class="tag">' + esc(t) + '</span>'; }).join('') + '</dd>';+ html += '<dt>Id</dt><dd>' + idChip('lesson', x.id) + '</dd>';+ html += '<dt>Updated</dt><dd>' + relTime(x.updatedAt || x.createdAt) + '</dd>';+ html += '</dl></div>';+ var src = x.sourceIds || [];+ html += '<div class="mem-section"><div class="mem-section-title">Sources ' + help('lessonSources') + '</div>';+ if (!src.length) {+ html += '<div class="empty-step-label">No sources recorded. This lesson was saved by hand without <code>sourceIds</code>. Link it to the session or memory it came from by saving it again with them; the lesson is strengthened and the sources are added:</div>' + cmdBlock(curlPost('lessons', { content: x.content, sourceIds: ['ses_...', 'mem_...'] }));+ } else {+ var obs = src.filter(function(id) { return idKind(id) === 'observation'; });+ if (obs.length) locateObservations(obs);+ html += '<ul class="src-list">' + src.slice(0, 30).map(sourceItemHtml).join('') + '</ul>' + (src.length > 30 ? '<div class="ses-foot">+' + (src.length - 30) + ' more</div>' : '');}-- html += '<div style="display:grid;grid-template-columns:repeat(4, 1fr);gap:10px;margin-bottom:14px;">';- html += '<div class="card" style="padding:10px;"><div style="font-size:10px;letter-spacing:0.08em;color:var(--ink-muted);">OBSERVATIONS</div><div style="font-size:20px;font-weight:600;">' + obs.length + '</div></div>';- html += '<div class="card" style="padding:10px;"><div style="font-size:10px;letter-spacing:0.08em;color:var(--ink-muted);">TOOLS USED</div><div style="font-size:20px;font-weight:600;">' + Object.keys(toolCounts).length + '</div></div>';- html += '<div class="card" style="padding:10px;"><div style="font-size:10px;letter-spacing:0.08em;color:var(--ink-muted);">FILES TOUCHED</div><div style="font-size:20px;font-weight:600;">' + fileSet.size + '</div></div>';- html += '<div class="card" style="padding:10px;"><div style="font-size:10px;letter-spacing:0.08em;color:var(--ink-muted);">DURATION</div><div style="font-size:20px;font-weight:600;">' + esc(durationLabel) + '</div></div>';html += '</div>';+ html += '<details style="margin-top:12px;"><summary style="cursor:pointer;font-size:11px;color:var(--ink-faint);font-family:var(--font-mono);">raw record</summary><pre class="gd-raw">' + esc(JSON.stringify(x, null, 2)) + '</pre></details>';+ return html + '</div>';+ }- var topTools = Object.keys(toolCounts).sort(function(a, b) { return toolCounts[b] - toolCounts[a]; }).slice(0, 10);- if (topTools.length > 0) {- var maxC = toolCounts[topTools[0]] || 1;- html += '<div class="card" style="margin-bottom:12px;"><div class="card-title">Tool Invocations</div>';- html += '<div class="bar-chart" style="margin-top:8px;">';- topTools.forEach(function(t) {- var pct = Math.round((toolCounts[t] / maxC) * 100);- html += '<div class="bar-row"><span class="bar-label" style="font-family:var(--font-mono);">' + esc(t) + '</span><div class="bar-track"><div class="bar-fill" style="width:' + pct + '%;background:var(--accent);"></div></div><span class="bar-value">' + toolCounts[t] + '</span></div>';- });- html += '</div></div>';+ function renderLessons() {+ var el = document.getElementById('view-lessons');+ var l = state.lessons;+ if (!store.loaded.lesson) {+ listDetailShell(el, 'lessons', '');+ setViewHtml(document.getElementById('lessons-list'), skeleton(8));+ return;}-- var typeKeys = Object.keys(typeCounts).sort(function(a, b) { return typeCounts[b] - typeCounts[a]; });- if (typeKeys.length > 0) {- html += '<div class="card" style="margin-bottom:12px;"><div class="card-title">Activity Breakdown</div>';- html += '<div style="display:flex;gap:6px;flex-wrap:wrap;margin-top:8px;">';- typeKeys.forEach(function(t) {- html += '<span class="badge badge-muted" style="font-family:var(--font-mono);">' + esc(t.replace(/_/g, ' ')) + ' · ' + typeCounts[t] + '</span>';+ var all = entityList('lesson').filter(function(x) { return x && x.deleted !== true; });+ var rows = lessonRows();+ listDetailShell(el, 'lessons', all.length ? '<div class="inline-note"><strong>Lessons</strong> ' + help('lesson') + ' are short rules learned from past work. Confidence ' + help('confidence') + ' rises each time an agent uses a lesson and decays when it goes unused; uses ' + help('reinforcements') + ' counts those confirmations. Pick a row for its sources and actions.</div>' : '');+ var focus = captureSearchFocus(['lessons-search']);+ setViewHtml(document.getElementById('lessons-toolbar'), all.length ? lessonToolbarHtml(rows.length) : '');+ var input = document.getElementById('lessons-search');+ if (input && !input.__bound) {+ input.__bound = true;+ bindImeSafeSearch(input, 200, function(v) { state.lessons.search = v; renderLessons(); });+ }+ var proj = document.getElementById('lessons-project');+ if (proj && !proj.__bound) {+ proj.__bound = true;+ proj.addEventListener('change', function() { state.lessons.projectFilter = this.value; renderLessons(); });+ }+ restoreSearchFocus(focus);+ var html = '';+ if (!all.length) {+ html = emptyState({+ icon: '💡',+ title: 'No lessons yet',+ what: 'Lessons are short rules learned from past work, such as a mistake you corrected once that an agent should not repeat. Agents recall the matching ones before they start a task.',+ why: 'No agent has saved a lesson, and no crystal or transcript import has produced one on this install yet.',+ steps: [+ { label: 'From an agent, call the MCP function:', cmd: 'memory_lesson_save { "content": "Run tsc before committing", "context": "CI failed twice on type errors" }' },+ { label: 'Or from a terminal, linked to the session it came from:', cmd: curlPost('lessons', { content: 'Run tsc before committing', context: 'CI failed twice on type errors', sourceIds: ['ses_...'] }) },+ { label: 'Crystallizing finished actions and importing transcripts on the Replay page also produce lessons.' }+ ],+ link: { href: 'https://github.com/rohitg00/agentmemory#lessons', text: 'Lesson decay and scoring' }});- html += '</div></div>';- }-- if (fileSet.size > 0) {- var filesArr = Array.from(fileSet).slice(0, 30);- html += '<div class="card" style="margin-bottom:12px;"><div class="card-title">Files</div>';- html += '<div style="font-size:12px;font-family:var(--font-mono);line-height:1.6;margin-top:8px;">';- filesArr.forEach(function(f) { html += '<div>• ' + esc(f) + '</div>'; });- if (fileSet.size > 30) html += '<div style="color:var(--ink-faint);">+' + (fileSet.size - 30) + ' more</div>';- html += '</div></div>';- }-- html += '<div class="card" style="margin-bottom:12px;"><div class="card-title">Metadata</div>';- html += '<div style="font-size:12px;font-family:var(--font-mono);margin-top:8px;line-height:1.7;">';- var detailId = sessionId(s);- html += '<div><span style="color:var(--ink-muted);">id:</span> ' + esc(detailId || 'missing id') + '</div>';- html += '<div><span style="color:var(--ink-muted);">cwd:</span> ' + esc(s.cwd || '-') + '</div>';- html += '<div><span style="color:var(--ink-muted);">started:</span> ' + esc(formatTime(s.startedAt)) + '</div>';- if (s.endedAt) html += '<div><span style="color:var(--ink-muted);">ended:</span> ' + esc(formatTime(s.endedAt)) + '</div>';- if (s.model) html += '<div><span style="color:var(--ink-muted);">model:</span> ' + esc(s.model) + '</div>';- if (asTags(s.tags).length) html += '<div><span style="color:var(--ink-muted);">tags:</span> ' + asTags(s.tags).map(esc).join(', ') + '</div>';- html += '</div></div>';-- html += '<div style="display:flex;gap:8px;">';- if (detailId && s.status === 'active') {- html += '<button class="btn btn-danger" data-action="end-session" data-session-id="' + esc(detailId) + '">End Session</button>';- }- if (detailId) {- html += '<button class="btn btn-primary" data-action="summarize-session" data-session-id="' + esc(detailId) + '">Summarize</button>';+ } else if (!rows.length) {+ html = emptyState({+ icon: '🔍',+ title: 'No lessons match',+ what: 'The filter matches lesson text, the reason it was learned and its tags, within the chosen project.',+ why: 'None of the ' + fmtNum(all.length) + ' lessons match' + (l.search ? ' “' + esc(l.search) + '”' : '') + (l.projectFilter ? ' in project <b>' + esc(l.projectFilter) + '</b>' : '') + '.',+ steps: [{ label: 'Search by meaning on the server instead:', cmd: curlPost('lessons/search', { query: l.search || 'deploy', project: l.projectFilter || undefined }) }]+ }) + '<div style="margin-top:10px;"><button type="button" class="btn" data-action="lesson-clear-filters">Clear filters</button></div>';} else {- html += '<button class="btn btn-primary" disabled>Summarize unavailable</button>';+ html = '<div class="table-wrap"><table class="mem-table"><thead><tr><th>Lesson</th><th class="col-opt">Confidence ' + help('confidence') + '</th><th class="col-opt">Uses ' + help('reinforcements') + '</th><th class="col-opt">Updated</th></tr></thead><tbody>';+ rows.forEach(function(x) { html += lessonRowHtml(x); });+ html += '</tbody></table></div>';+ if (all.length < 8) html += usageCard('lesson');+ }+ setViewHtml(document.getElementById('lessons-list'), html);+ var sel = l.selectedId ? store.entities.lesson[l.selectedId] : null;+ var detail = document.getElementById('lessons-detail');+ if (l.selectedId && !sel) {+ setViewHtml(detail, '<div class="detail-panel mem-detail" id="lesson-detail"><div class="mem-detail-head"><span>Lesson</span><button type="button" class="icon-btn icon-close" data-action="lesson-close" aria-label="Close lesson details">close</button></div>' + emptyState({+ compact: true,+ icon: '🔍',+ title: 'Lesson not found',+ what: 'Lesson links anywhere in the viewer open this panel by id.',+ why: 'No current lesson has the id <code>' + esc(l.selectedId) + '</code>. It was deleted or decayed away, or the link comes from another install.',+ steps: [{ label: 'List lessons from a terminal:', cmd: curlGet('lessons') }]+ }) + '</div>');+ } else {+ setViewHtml(detail, sel ? lessonDetailHtml(sel).replace('<div class="detail-panel mem-detail"', '<div id="lesson-detail" class="detail-panel mem-detail"') : '');}- html += '</div></div>';- state.sessions.detailCache = { id: id, html: html };- panel = document.getElementById('session-detail');- if (panel) panel.innerHTML = html;+ document.getElementById('lessons-layout').classList.toggle('has-detail', !!detail.firstElementChild);}- async function endSession(id) {- await apiPost('session/end', { sessionId: id });- loadSessions();+ async function strengthenLesson(id) {+ var l = state.lessons;+ l.busy = id;+ renderLessons();+ var res = await apiPost('lessons/strengthen', { lessonId: id });+ l.busy = '';+ l.notice = res && res.success !== false+ ? { id: id, html: 'Recorded one more use. Confidence and uses update here from the live stream.' }+ : { id: id, err: true, html: 'Strengthen failed' + (res && res.error ? ': ' + esc(res.error) : '. Check that agentmemory is running.') };+ renderLessons();}- async function summarizeSession(id, btn) {- if (!btn) return;- btn.textContent = 'Summarizing...';- btn.disabled = true;- await apiPost('summarize', { sessionId: id });- btn.textContent = 'Done';- setTimeout(function() { btn.textContent = 'Summarize'; btn.disabled = false; }, 2000);+ function openLessonDeleteModal(id) {+ var x = store.entities.lesson[id];+ if (!x) return;+ openModal('<h3>Delete this lesson?</h3>' ++ '<p>“' + esc(truncate(x.content, 140)) + '” stops being recalled by agents. It is soft-deleted and recorded in the audit log; saving the same text again later creates it fresh.</p>' ++ '<p style="font-size:11px;">Same call from a terminal: <code>' + esc(curlPost('lessons/delete', { lessonId: id }).replace(/\s*\\\n\s*/g, ' ')) + '</code></p>' ++ '<div class="modal-actions"><button class="btn" data-action="close-modal">Cancel</button><button class="btn btn-danger" data-action="lesson-confirm-delete" data-lesson-id="' + esc(id) + '">Delete lesson</button></div>');}- async function loadLessons() {- var el = document.getElementById('view-lessons');- if (!state.lessons.loaded) el.innerHTML = '<div class="loading">Loading lessons...</div>';- var result = await apiGet('lessons');- state.lessons.items = (result && result.lessons) || [];- state.lessons.loaded = true;+ async function deleteLesson(id) {+ closeModal();+ var res = await apiPost('lessons/delete', { lessonId: id });+ if (res && res.success !== false) {+ state.lessons.selectedId = null;+ setRouteEntity('lessons', '');+ } else {+ state.lessons.notice = { id: id, err: true, html: 'Delete failed' + (res && res.error ? ': ' + esc(res.error) : '. Check that agentmemory is running.') };+ }renderLessons();}- function renderLessons() {- var el = document.getElementById('view-lessons');- var items = state.lessons.items;- var search = state.lessons.search.toLowerCase();-- if (search) {- items = items.filter(function(l) {- return (l.content + ' ' + l.context + ' ' + asTags(l.tags).join(' ')).toLowerCase().indexOf(search) >= 0;- });+ function actionRows() {+ var a = state.actions;+ var search = String(a.search || '').trim().toLowerCase();+ return entityList('action').filter(function(x) {+ if (!x) return false;+ if (a.statusFilter && x.status !== a.statusFilter) return false;+ if (search && (String(x.title || '') + ' ' + String(x.description || '') + ' ' + asTags(x.tags).join(' ')).toLowerCase().indexOf(search) < 0) return false;+ return true;+ }).sort(function(p, q) { return (q.priority || 0) - (p.priority || 0) || String(q.updatedAt || '').localeCompare(String(p.updatedAt || '')); });+ }++ var ACTION_STATUS_BADGES = { done: 'badge-green', active: 'badge-blue', blocked: 'badge-red', cancelled: 'badge-muted', pending: 'badge-yellow' };++ function actionRowHtml(x, ready) {+ var selected = state.actions.selectedId === x.id;+ var html = '<tr class="lesson-row' + (selected ? ' row-select' : '') + (isFresh(x.id) ? ' fresh' : '') + '" data-action="select-action" data-action-id="' + esc(x.id) + '" role="button" tabindex="0" aria-expanded="' + (selected ? 'true' : 'false') + '" style="cursor:pointer;">';+ html += '<td style="max-width:0;width:100%;"><div class="mem-head clamp-2">' + esc(x.title) + '</div>' + (x.description ? '<div class="mem-excerpt">' + esc(x.description) + '</div>' : '');+ html += '<div class="mem-chips">' + (x.project ? '<span class="mem-chip" style="cursor:default;">' + esc(x.project) + '</span>' : '') + asTags(x.tags).slice(0, 3).map(function(t) { return '<span class="tag">' + esc(t) + '</span>'; }).join('') + '<span class="mob-only">priority ' + (x.priority || '-') + '</span></div></td>';+ html += '<td><span class="badge ' + (ACTION_STATUS_BADGES[x.status] || 'badge-muted') + '">' + esc(x.status) + '</span>' + (ready ? ' <span class="ready-badge" title="' + esc(GLOSSARY.frontierReady.text) + '">ready</span>' : '') + '</td>';+ html += '<td class="col-opt" style="text-align:center;font-family:var(--font-mono);font-size:12px;">' + (x.priority || '-') + '</td>';+ html += '<td class="col-opt">' + relTime(x.updatedAt || x.createdAt) + '</td>';+ return html + '</tr>';+ }++ function actionDetailHtml(x, ready) {+ var html = '<div id="action-detail" class="detail-panel mem-detail" data-detail-id="' + esc(x.id) + '">';+ html += '<div class="mem-detail-head"><span class="badge ' + (ACTION_STATUS_BADGES[x.status] || 'badge-muted') + '">' + esc(x.status) + '</span>' + (ready ? '<span class="ready-badge">ready</span>' + help('frontierReady') : '') + '<span>· priority ' + (x.priority || '-') + '</span><span>· created ' + relTime(x.createdAt) + '</span><button type="button" class="icon-btn icon-close" data-action="action-close" aria-label="Close action details">close</button></div>';+ html += '<div class="mem-detail-content ses-prompt">' + esc(x.title) + '</div>';+ if (x.description) html += '<div class="ses-summary">' + esc(x.description) + '</div>';+ if (state.actions.notice && state.actions.notice.id === x.id) html += '<div class="mem-note' + (state.actions.notice.err ? ' err' : '') + '" role="status">' + state.actions.notice.html + '</div>';+ html += '<div class="mem-actions">';+ ['active', 'done', 'blocked'].forEach(function(st) {+ if (x.status === st) return;+ html += '<button type="button" class="btn' + (st === 'done' ? ' btn-primary' : '') + '" data-action="action-set-status" data-status="' + st + '" data-action-id="' + esc(x.id) + '"' + (state.actions.busy === x.id ? ' disabled' : '') + '>' + (st === 'done' ? 'Mark done' : st === 'active' ? 'Start' : 'Mark blocked') + '</button>';+ });+ html += copyBtn(x.id, 'action id').replace('>copy<', '>copy id<');+ html += copyBtn('memory_action_update { "actionId": "' + x.id + '", "status": "done" }', 'MCP call').replace('>copy<', '>copy MCP call<');+ html += copyBtn(curlGet('actions/get?actionId=' + encodeURIComponent(x.id)), 'curl command').replace('>copy<', '>copy curl<');+ html += '</div>';+ html += '<div class="mem-section"><div class="mem-section-title">Details</div><dl class="mem-meta">';+ html += '<dt>Id</dt><dd>' + idChip('action', x.id) + '</dd>';+ html += '<dt>Project ' + help('project') + '</dt><dd>' + (x.project ? esc(x.project) : '<span style="color:var(--ink-faint);">none</span>') + '</dd>';+ if (x.createdBy) html += '<dt>Created by</dt><dd>' + esc(x.createdBy === 'unknown' ? 'not recorded' : x.createdBy) + '</dd>';+ if (x.assignedTo) html += '<dt>Assigned to</dt><dd>' + esc(x.assignedTo) + '</dd>';+ if (asTags(x.tags).length) html += '<dt>Tags</dt><dd class="tag-list" style="margin:0;">' + asTags(x.tags).map(function(t) { return '<span class="tag">' + esc(t) + '</span>'; }).join('') + '</dd>';+ if (x.parentId) html += '<dt>Parent</dt><dd>' + anyIdChip(x.parentId) + '</dd>';+ if (x.crystallizedInto) html += '<dt>Crystal ' + help('crystal') + '</dt><dd>' + anyIdChip(x.crystallizedInto) + '</dd>';+ if (x.result) html += '<dt>Result</dt><dd>' + esc(x.result) + '</dd>';+ html += '<dt>Updated</dt><dd>' + relTime(x.updatedAt || x.createdAt) + '</dd>';+ html += '</dl></div>';+ var src = (x.sourceMemoryIds || []).concat(x.sourceObservationIds || []);+ html += '<div class="mem-section"><div class="mem-section-title">Sources ' + help('provenance') + '</div>';+ if (!src.length) {+ html += '<div class="empty-step-label">No sources recorded. Pass <code>sourceMemoryIds</code> or <code>sourceObservationIds</code> when creating an action to link it to what the agent saw.</div>';+ } else {+ var obs = src.filter(function(id) { return idKind(id) === 'observation'; });+ if (obs.length) locateObservations(obs);+ html += '<ul class="src-list">' + src.slice(0, 30).map(sourceItemHtml).join('') + '</ul>';}-- var html = '<div class="card" style="margin-bottom:12px;padding:12px;background:var(--bg-subtle);">';- html += '<div style="font-size:13px;color:var(--ink-muted);line-height:1.5;">';- html += '<strong>Lessons</strong> are portable heuristics — short imperative rules (always/never/prefer/avoid) extracted from past work. Auto-surface from JSONL imports (low confidence, tag <code>auto-import</code>), get reinforced when the agent applies them, and decay if unused. Higher confidence = more battle-tested.';- html += '</div></div>';-- html += '<div style="display:flex;gap:8px;margin-bottom:12px;">';- html += '<input id="lessons-search" class="search-input" type="text" placeholder="Search lessons..." value="' + esc(state.lessons.search) + '" style="flex:1" />';- html += '<span style="font-size:12px;color:var(--ink-faint);align-self:center;">' + items.length + ' lessons</span>';html += '</div>';+ html += '<details style="margin-top:12px;"><summary style="cursor:pointer;font-size:11px;color:var(--ink-faint);font-family:var(--font-mono);">raw record</summary><pre class="gd-raw">' + esc(JSON.stringify(x, null, 2)) + '</pre></details>';+ return html + '</div>';+ }- if (items.length === 0) {- html += '<div class="empty-state">' +- '<div class="empty-icon">💡</div>' +- '<div class="empty-title">No lessons yet</div>' +- '<div class="empty-lead">Lessons are short imperative rules (always/never/prefer/avoid) learned from past work — things you corrected once that the agent should never repeat. Confidence grows when they hold and decays when unused.</div>' +- '<pre class="empty-cmd"># Save a lesson explicitly\nmemory_lesson_save { rule, reason, confidence }\n\n# Or: Replay tab → Import JSONL auto-extracts lessons\n# from your past Claude Code sessions</pre>' +- '<div><a class="empty-link" href="https://github.com/rohitg00/agentmemory#lessons" target="_blank" rel="noopener">Lesson decay & scoring →</a></div>' +- '</div>';- } else {- html += '<table><thead><tr><th>Lesson</th><th title="How battle-tested the rule is. Grows each time it is reinforced, decays weekly when unused.">Confidence</th><th title="Times the agent re-confirmed this rule.">Uses</th><th>Source</th><th>Project</th><th>Updated</th></tr></thead><tbody>';- items.forEach(function(l) {- var confPct = Math.round(l.confidence * 100);- var confColor = confPct >= 70 ? 'var(--green)' : confPct >= 40 ? 'var(--yellow)' : 'var(--red)';- var expanded = state.lessons.selectedId === l.id;- html += '<tr class="lesson-row' + (expanded ? ' selected' : '') + '" data-action="select-lesson" data-lesson-id="' + esc(l.id) + '" role="button" tabindex="0" aria-expanded="' + (expanded ? 'true' : 'false') + '" style="cursor:pointer;">';- html += '<td style="max-width:400px;">' + esc(truncate(l.content, 120)) + (l.context ? '<div style="font-size:11px;color:var(--ink-faint);margin-top:2px;">' + esc(truncate(l.context, 80)) + '</div>' : '') + '</td>';- html += '<td><div class="gauge" style="min-width:80px;"><div class="gauge-bar"><div class="gauge-fill" style="width:' + confPct + '%;background:' + confColor + '"></div></div><span class="gauge-value" style="font-size:11px;">' + confPct + '%</span></div></td>';- html += '<td style="text-align:center;">' + (l.reinforcements || 0) + '</td>';- html += '<td><span class="badge badge-' + (l.source === 'crystal' ? 'purple' : l.source === 'consolidation' ? 'yellow' : 'blue') + '">' + esc(l.source) + '</span></td>';- html += '<td style="font-size:12px;color:var(--ink-muted);">' + esc(l.project || '-') + '</td>';- html += '<td style="font-size:12px;color:var(--ink-muted);">' + shortTime(l.updatedAt) + '</td>';- html += '</tr>';- if (expanded) {- html += '<tr class="lesson-detail-row"><td colspan="6" style="background:var(--bg-alt);padding:14px 16px;">';- html += '<div style="font-size:13px;color:var(--ink);white-space:pre-wrap;line-height:1.5;margin-bottom:8px;">' + esc(l.content) + '</div>';- if (l.context) html += '<div style="font-size:12px;color:var(--ink-muted);margin-bottom:8px;"><span style="font-family:var(--font-ui);font-size:10px;text-transform:uppercase;letter-spacing:0.1em;">Why learned</span><br>' + esc(l.context) + '</div>';- html += '<div style="display:flex;gap:16px;flex-wrap:wrap;font-size:11px;color:var(--ink-muted);font-family:var(--font-mono);margin-bottom:8px;">';- html += '<span>id: ' + esc(l.id) + '</span>';- if (asTags(l.tags).length) html += '<span>tags: ' + esc(asTags(l.tags).join(', ')) + '</span>';- if (l.createdAt) html += '<span>learned: ' + esc(formatTime(l.createdAt)) + '</span>';- if (l.lastReinforcedAt) html += '<span>last confirmed: ' + esc(formatTime(l.lastReinforcedAt)) + '</span>';- if (l.sourceIds && l.sourceIds.length) html += '<span>from ' + l.sourceIds.length + ' session(s)</span>';- html += '</div>';- html += '<details><summary style="cursor:pointer;font-size:11px;color:var(--ink-faint);font-family:var(--font-mono);">raw record</summary>';- html += '<pre style="margin-top:8px;padding:10px;background:var(--bg);border:1px solid var(--border);font-size:11px;line-height:1.5;overflow-x:auto;">' + esc(JSON.stringify(l, null, 2)) + '</pre></details>';- html += '</td></tr>';- }+ function renderActions() {+ var el = document.getElementById('view-actions');+ var a = state.actions;+ if (!store.loaded.action) {+ listDetailShell(el, 'actions', '');+ setViewHtml(document.getElementById('actions-list'), skeleton(8));+ return;+ }+ var all = entityList('action');+ var rows = actionRows();+ var frontierIds = {};+ (a.frontier || []).forEach(function(f) {+ var fid = f && (f.id || (f.action && f.action.id));+ if (fid) frontierIds[fid] = true;+ });+ listDetailShell(el, 'actions', all.length ? '<div class="inline-note"><strong>Actions</strong> ' + help('action') + ' are follow-ups agents track between sessions. Status moves pending, active, done or blocked; <span class="ready-badge">ready</span> ' + help('frontierReady') + ' marks what is unblocked. Pick a row to change its status or see where it came from.</div>' : '');+ var focus = captureSearchFocus(['actions-search']);+ var tb = '';+ if (all.length) {+ tb = '<div class="toolbar mem-filters"><input id="actions-search" type="search" placeholder="Filter actions by title, description or tag (press /)" value="' + esc(a.search) + '" aria-label="Filter actions">';+ tb += '<select id="actions-status-filter" aria-label="Filter actions by status"><option value="">All statuses</option>';+ ['pending', 'active', 'done', 'blocked', 'cancelled'].forEach(function(s) {+ var n = all.filter(function(x) { return x.status === s; }).length;+ tb += '<option value="' + s + '"' + (a.statusFilter === s ? ' selected' : '') + '>' + s + ' (' + n + ')</option>';+ });+ tb += '</select><span class="tb-count">' + fmtNum(rows.length) + ' action' + (rows.length === 1 ? '' : 's') + ' · ' + fmtNum(Object.keys(frontierIds).length) + ' ready</span></div>';+ }+ setViewHtml(document.getElementById('actions-toolbar'), tb);+ var input = document.getElementById('actions-search');+ if (input && !input.__bound) {+ input.__bound = true;+ bindImeSafeSearch(input, 200, function(v) { state.actions.search = v; renderActions(); });+ }+ var sf = document.getElementById('actions-status-filter');+ if (sf && !sf.__bound) {+ sf.__bound = true;+ sf.addEventListener('change', function() { state.actions.statusFilter = this.value; renderActions(); });+ }+ restoreSearchFocus(focus);+ var html;+ if (!all.length) {+ html = emptyState({+ icon: '☑',+ title: 'No actions tracked yet',+ what: 'Actions are follow-ups an agent surfaced during a session: decisions to revisit, files to inspect, tasks blocked on input. They stay here so nothing slips between sessions, and the ready ones are handed to the next session first.',+ why: 'No agent has created an action on this install yet.',+ steps: [+ { label: 'From an agent, call the MCP function:', cmd: 'memory_action_create { "title": "Ship v1", "priority": 8 }' },+ { label: 'Or from a terminal:', cmd: curlPost('actions', { title: 'Ship v1', priority: 8 }) }+ ],+ link: { href: 'https://github.com/rohitg00/agentmemory#actions', text: 'Action lifecycle' }});- html += '</tbody></table>';+ } else if (!rows.length) {+ html = emptyState({+ icon: '🔍',+ title: 'No actions match',+ what: 'The filter matches action titles, descriptions and tags, and the status picker narrows by status.',+ why: 'None of the ' + fmtNum(all.length) + ' tracked actions match the current filter.',+ steps: [{ label: 'List them from a terminal:', cmd: curlGet('actions' + (a.statusFilter ? '?status=' + a.statusFilter : '')) }]+ }) + '<div style="margin-top:10px;"><button type="button" class="btn" data-action="action-clear-filters">Clear filters</button></div>';+ } else {+ html = '<div class="table-wrap"><table class="mem-table"><thead><tr><th>Action</th><th>Status</th><th class="col-opt">Priority</th><th class="col-opt">Updated</th></tr></thead><tbody>';+ rows.forEach(function(x) { html += actionRowHtml(x, !!frontierIds[x.id]); });+ html += '</tbody></table></div>';+ if (all.length < 8) html += usageCard('action');+ }+ setViewHtml(document.getElementById('actions-list'), html);+ var detail = document.getElementById('actions-detail');+ var sel = a.selectedId ? store.entities.action[a.selectedId] : null;+ if (a.selectedId && !sel) {+ setViewHtml(detail, '<div id="action-detail" class="detail-panel mem-detail"><div class="mem-detail-head"><span>Action</span><button type="button" class="icon-btn icon-close" data-action="action-close" aria-label="Close action details">close</button></div>' + emptyState({+ compact: true,+ icon: '🔍',+ title: 'Action not found',+ what: 'Action links anywhere in the viewer open this panel by id.',+ why: 'No action has the id <code>' + esc(a.selectedId) + '</code>. It was removed, or the link comes from another install.',+ steps: [{ label: 'Check from a terminal:', cmd: curlGet('actions/get?actionId=' + encodeURIComponent(a.selectedId)) }]+ }) + '</div>');+ } else {+ setViewHtml(detail, sel ? actionDetailHtml(sel, !!frontierIds[sel.id]) : '');}-- var __focus = captureSearchFocus(['lessons-search']);- el.innerHTML = html;- var __ls = document.getElementById('lessons-search');- if (__ls) bindImeSafeSearch(__ls, 200, function(v){ state.lessons.search = v; renderLessons(); });- restoreSearchFocus(__focus);+ document.getElementById('actions-layout').classList.toggle('has-detail', !!detail.firstElementChild);}- async function loadActions() {- var el = document.getElementById('view-actions');- if (!state.actions.loaded) el.innerHTML = '<div class="loading">Loading actions...</div>';- var results = await Promise.all([apiGet('actions'), apiGet('frontier')]);- state.actions.items = (results[0] && results[0].actions) || [];- state.actions.frontier = (results[1] && (results[1].frontier || results[1].actions)) || [];- state.actions.loaded = true;+ async function setActionStatus(id, status) {+ var a = state.actions;+ a.busy = id;+ renderActions();+ var res = await apiPost('actions/update', { actionId: id, status: status });+ a.busy = '';+ a.notice = res && res.success !== false+ ? { id: id, html: 'Status set to <b>' + esc(status) + '</b>. Ready markers update from the live stream.' }+ : { id: id, err: true, html: 'Update failed' + (res && res.error ? ': ' + esc(res.error) : '. Check that agentmemory is running.') };renderActions();}- function renderActions() {- var el = document.getElementById('view-actions');- var items = state.actions.items;- var introCard = '<div class="card" style="margin-bottom:12px;padding:12px;background:var(--bg-subtle);">' +- '<div style="font-size:13px;color:var(--ink-muted);line-height:1.5;">' +- '<strong>Actions</strong> are follow-ups the agent surfaced during sessions — decisions to revisit, files to inspect, tasks blocked on input. Status flows pending → active → done/blocked; the <em>frontier</em> marks what is unblocked and ready to pick up next.' +- '</div></div>';- var search = state.actions.search.toLowerCase();- var statusFilter = state.actions.statusFilter;- var frontierIds = new Set((state.actions.frontier || []).map(function(a) { return a.id; }));-- if (search) {- items = items.filter(function(a) {- return (a.title + ' ' + (a.description || '') + ' ' + asTags(a.tags).join(' ')).toLowerCase().indexOf(search) >= 0;+ function renderCrystals() {+ var el = document.getElementById('view-crystals');+ if (!store.loaded.crystal) {+ setViewHtml(el, skeleton(8));+ return;+ }+ var all = sortByTimeDesc(entityList('crystal'), ['createdAt', 'updatedAt']);+ var search = String(state.crystals.search || '').trim().toLowerCase();+ var lessonMap = store.entities.lesson || {};+ var items = !search ? all : all.filter(function(c) {+ var lessonText = (c.lessons || []).map(function(lid) { return lessonMap[lid] ? lessonMap[lid].content : lid; }).join(' ');+ return [c.narrative || '', (c.keyOutcomes || []).join(' '), lessonText, (c.filesAffected || []).join(' '), c.project || ''].join(' ').toLowerCase().indexOf(search) >= 0;+ });+ var html = '';+ if (!all.length) {+ var llm = store.provider !== 'noop';+ html = emptyState({+ icon: '💎',+ title: 'No crystals yet',+ what: 'A crystal ' + help('crystal') + ' condenses a finished chain of actions into one narrative with outcomes, files and lessons, so later sessions reuse it without replaying raw observations.',+ why: llm ? 'No action has been marked done and crystallized yet. Crystals are built from done actions.' : 'Crystallizing needs an LLM provider, and none is configured. Transcript imports on the Replay page still create crystals without one.',+ steps: llm ? [+ { label: 'Crystallize every finished action now:', cmd: curlPost('crystals/auto', {}) },+ { label: 'Or from an agent, for specific actions:', cmd: 'memory_crystallize { "actionIds": ["act_..."] }' }+ ] : [+ { label: 'Set an LLM key and restart agentmemory:', cmd: 'export ANTHROPIC_API_KEY=sk-ant-...\nnpx @agentmemory/agentmemory' },+ { label: 'Then crystallize finished actions:', cmd: curlPost('crystals/auto', {}) }+ ],+ link: { href: 'https://github.com/rohitg00/agentmemory#crystals', text: 'How crystals are built' }});+ setViewHtml(el, html);+ return;}- if (statusFilter) {- items = items.filter(function(a) { return a.status === statusFilter; });+ html += '<div class="inline-note"><strong>Crystals</strong> ' + help('crystal') + ' are compact summaries of finished work. They outlive pruned observations, so the next session gets the outcome, the files and the lessons in one read.</div>';+ html += '<div class="toolbar"><input id="crystals-search" class="search-input" type="search" placeholder="Filter crystals by text, file, project or lesson (press /)" value="' + esc(state.crystals.search) + '" style="flex:1" aria-label="Filter crystals" /><span class="tb-count">' + fmtNum(items.length) + ' crystal' + (items.length === 1 ? '' : 's') + '</span></div>';+ if (!items.length) {+ html += emptyState({+ icon: '🔍',+ title: 'No crystals match',+ what: 'The filter matches crystal narratives, outcomes, files, project and lesson text.',+ why: 'None of the ' + fmtNum(all.length) + ' crystals contain “' + esc(state.crystals.search) + '”.',+ steps: [{ label: 'List every crystal from a terminal:', cmd: curlGet('crystals') }]+ });}-- var html = introCard;- html += '<div style="display:flex;gap:8px;margin-bottom:12px;flex-wrap:wrap;">';- html += '<input id="actions-search" class="search-input" type="text" placeholder="Search actions..." value="' + esc(state.actions.search) + '" style="flex:1;min-width:200px" />';- html += '<select id="actions-status-filter" style="padding:4px 8px;font-size:12px;border:1px solid var(--border);border-radius:4px;background:var(--bg);color:var(--ink);">';- html += '<option value="">All statuses</option>';- ['pending','active','done','blocked','cancelled'].forEach(function(s) {- html += '<option value="' + s + '"' + (statusFilter === s ? ' selected' : '') + '>' + s + '</option>';+ items.forEach(function(c) {+ var selected = state.crystals.selectedId === c.id;+ html += '<article class="card crystal-card' + (selected ? ' selected' : '') + (isFresh(c.id) ? ' fresh' : '') + '" data-crystal-id="' + esc(c.id) + '" style="border-left:3px solid var(--accent);">';+ html += '<div class="mem-detail-head">' + (c.project ? '<span class="mem-chip" style="cursor:default;">' + esc(c.project) + '</span>' : '') + (c.sessionId ? '<span>session ' + entityLink('session', c.sessionId, sessionDisplayName(store.entities.session[c.sessionId] || { id: c.sessionId })) + '</span>' : '') + '<span>· ' + relTime(c.createdAt) + '</span><span style="margin-left:auto;">' + idChip('crystal', c.id) + '</span></div>';+ html += '<div class="mem-detail-content" style="font-weight:600;">' + esc(truncate(c.narrative || 'Untitled crystal', 600)) + '</div>';+ if ((c.keyOutcomes || []).length) html += '<div class="mem-section"><div class="mem-section-title">Tools used</div><div class="tag-list" style="margin:0;">' + c.keyOutcomes.map(function(o) { return '<span class="tag">' + esc(o) + '</span>'; }).join('') + '</div></div>';+ if ((c.filesAffected || []).length) html += '<div class="mem-section"><div class="mem-section-title">Files touched</div><div class="tag-list" style="margin:0;">' + c.filesAffected.slice(0, 16).map(function(f) { return '<span class="tag file-tag" title="' + esc(f) + '">' + esc(f) + '</span>'; }).join('') + (c.filesAffected.length > 16 ? '<span class="ses-foot">+' + (c.filesAffected.length - 16) + ' more</span>' : '') + '</div></div>';+ if ((c.lessons || []).length) {+ html += '<div class="mem-section"><div class="mem-section-title">Lessons surfaced ' + help('lesson') + '</div><ul class="ses-links">' + c.lessons.slice(0, 8).map(function(lid) {+ var l = lessonMap[lid];+ return '<li>' + (l ? entityLink('lesson', lid, truncate(l.content, 120)) : anyIdLink(lid)) + '</li>';+ }).join('') + '</ul>' + (c.lessons.length > 8 ? '<div class="ses-foot">+' + (c.lessons.length - 8) + ' more</div>' : '') + '</div>';+ }+ if ((c.sourceActionIds || []).length) html += '<div class="mem-section"><div class="mem-section-title">Built from actions ' + help('action') + '</div><ul class="src-list">' + c.sourceActionIds.slice(0, 12).map(sourceItemHtml).join('') + '</ul></div>';+ html += '<div class="mem-actions">' + copyBtn(c.narrative || '', 'crystal text').replace('>copy<', '>copy text<') + copyBtn(curlGet('crystals'), 'curl command').replace('>copy<', '>copy curl<') + '</div>';+ html += '</article>';});- html += '</select>';- html += '<span style="font-size:12px;color:var(--ink-faint);align-self:center;">' + items.length + ' actions</span>';- html += '</div>';-- if (items.length === 0) {- html += '<div class="empty-state">' +- '<div class="empty-icon">☑</div>' +- '<div class="empty-title">No actions tracked yet</div>' +- '<div class="empty-lead">Actions are follow-ups the agent surfaced during a session: <em>decisions to revisit</em>, <em>files to inspect</em>, <em>tasks blocked on input</em>. They show up here with status pending → active → done/blocked so nothing slips through between sessions.</div>' +- '<div class="empty-lead" style="margin-top:0;">Three ways to create them:</div>' +- '<pre class="empty-cmd"># 1. MCP tool (from any agent)\nmemory_action_create { title, description, priority }\n\n# 2. Curl\ncurl -X POST http://localhost:3111/agentmemory/actions \\\n -H \'Content-Type: application/json\' \\\n -d \'{"title":"ship v1","priority":"high"}\'\n\n# 3. Hooks auto-extract from long session bodies</pre>' +- '<div><a class="empty-link" href="https://github.com/rohitg00/agentmemory#actions" target="_blank" rel="noopener">Action lifecycle docs →</a></div>' +- '</div>';- } else {- html += '<table><thead><tr><th>Title</th><th>Status</th><th>Priority</th><th>Tags</th><th>Frontier</th><th>Updated</th></tr></thead><tbody>';- items = items.slice().sort(function(a, b) { return (b.priority || 0) - (a.priority || 0); });- items.forEach(function(a) {- var statusClass = a.status === 'done' ? 'badge-green' : a.status === 'active' ? 'badge-blue' : a.status === 'blocked' ? 'badge-red' : a.status === 'cancelled' ? 'badge-red' : 'badge-yellow';- var isFrontier = frontierIds.has(a.id);- html += '<tr' + (isFrontier ? ' style="background:rgba(45,106,79,0.08);"' : '') + '>';- html += '<td style="max-width:350px;"><strong>' + esc(a.title) + '</strong>';- if (a.description) html += '<div style="font-size:11px;color:var(--ink-faint);margin-top:2px;">' + esc(truncate(a.description, 80)) + '</div>';- html += '</td>';- html += '<td><span class="badge ' + statusClass + '">' + esc(a.status) + '</span></td>';- html += '<td style="text-align:center;font-weight:600;">' + (a.priority || '-') + '</td>';- html += '<td style="font-size:11px;color:var(--ink-muted);">' + asTags(a.tags).map(esc).join(', ') + '</td>';- html += '<td style="text-align:center;">' + (isFrontier ? '⚡' : '') + '</td>';- html += '<td style="font-size:12px;color:var(--ink-muted);">' + shortTime(a.updatedAt) + '</td>';- html += '</tr>';- });- html += '</tbody></table>';+ var focus = captureSearchFocus(['crystals-search']);+ setViewHtml(el, html);+ var cs = document.getElementById('crystals-search');+ if (cs && !cs.__bound) {+ cs.__bound = true;+ bindImeSafeSearch(cs, 200, function(v) { state.crystals.search = v; renderCrystals(); });+ }+ restoreSearchFocus(focus);+ }++ function handlePageAction(action, target) {+ if (action === 'lesson-close') { state.lessons.selectedId = null; setRouteEntity('lessons', ''); renderLessons(); return true; }+ if (action === 'lesson-strengthen') { strengthenLesson(target.getAttribute('data-lesson-id')); return true; }+ if (action === 'lesson-delete') { openLessonDeleteModal(target.getAttribute('data-lesson-id')); return true; }+ if (action === 'lesson-confirm-delete') { deleteLesson(target.getAttribute('data-lesson-id')); return true; }+ if (action === 'lesson-clear-filters') { state.lessons.search = ''; state.lessons.projectFilter = ''; var li = document.getElementById('lessons-search'); if (li) li.value = ''; renderLessons(); return true; }+ if (action === 'select-action') {+ var aid = target.getAttribute('data-action-id');+ state.actions.selectedId = state.actions.selectedId === aid ? null : aid;+ setRouteEntity('actions', state.actions.selectedId);+ renderActions();+ if (state.actions.selectedId && window.matchMedia('(max-width: 1100px)').matches) {+ var ad = document.getElementById('action-detail');+ if (ad && ad.scrollIntoView) ad.scrollIntoView({ behavior: 'smooth', block: 'start' });+ }+ return true;}+ if (action === 'action-close') { state.actions.selectedId = null; setRouteEntity('actions', ''); renderActions(); return true; }+ if (action === 'action-set-status') { setActionStatus(target.getAttribute('data-action-id'), target.getAttribute('data-status')); return true; }+ if (action === 'action-clear-filters') { state.actions.search = ''; state.actions.statusFilter = ''; var ai = document.getElementById('actions-search'); if (ai) ai.value = ''; renderActions(); return true; }+ if (action === 'activity-type' || action === 'activity-file' || action === 'activity-day' || action === 'activity-clear') { handleActivityAction(action, target); return true; }+ if (action.indexOf('profile-') === 0) { handleProfileAction(action, target); return true; }+ if (action === 'replay-jump') { jumpReplay(parseInt(target.getAttribute('data-replay-idx') || '0', 10)); return true; }+ return false;+ }++ var AUDIT_PAGE = 100;+ var AUDIT_VERBS = {+ observe: 'Processed observations', compress: 'Compressed observations', remember: 'Saved a memory',+ forget: 'Forgot', evolve: 'Saved a new memory version', consolidate: 'Ran consolidation',+ share: 'Shared', delete: 'Deleted', import: 'Imported', export: 'Exported',+ action_create: 'Created an action', action_update: 'Updated an action',+ lease_acquire: 'Took a lease', lease_release: 'Released a lease', lease_renew: 'Renewed a lease',+ routine_run: 'Ran a routine', signal_send: 'Sent a signal', checkpoint_resolve: 'Resolved a checkpoint',+ mesh_sync: 'Synced with a peer', relation_create: 'Linked records', relation_update: 'Updated a link',+ sentinel_create: 'Created a sentinel', sentinel_trigger: 'A sentinel fired',+ sketch_create: 'Started a sketch', sketch_promote: 'Promoted a sketch', sketch_discard: 'Discarded a sketch',+ retention_score: 'Scored retention', crystallize: 'Crystallized finished work',+ diagnose: 'Ran diagnostics', heal: 'Repaired stored data', index_persist: 'Saved the search index',+ facet_tag: 'Tagged records', lesson_save: 'Saved a lesson', lesson_recall: 'Recalled lessons',+ lesson_strengthen: 'Strengthened a lesson', lesson_delete: 'Deleted a lesson',+ obsidian_export: 'Exported to Obsidian', reflect: 'Reflected on memories', insight_search: 'Searched insights',+ skill_extract: 'Extracted a skill', core_add: 'Added core memory', core_remove: 'Removed core memory',+ auto_page: 'Paged memory out', vision_embed: 'Embedded an image',+ slot_append: 'Appended to a slot', slot_replace: 'Replaced a slot', slot_create: 'Created a slot',+ slot_delete: 'Deleted a slot', slot_reflect: 'Reflected into a slot'+ };- var __focus = captureSearchFocus(['actions-search']);- el.innerHTML = html;- var __as = document.getElementById('actions-search');- if (__as) bindImeSafeSearch(__as, 200, function(v){ state.actions.search = v; renderActions(); });- var __af = document.getElementById('actions-status-filter');- if (__af) __af.addEventListener('change', function(){ state.actions.statusFilter = this.value; renderActions(); });- restoreSearchFocus(__focus);+ function auditVerb(op) {+ return AUDIT_VERBS[op] || String(op || 'change').replace(/_/g, ' ');}- async function loadCrystals() {- var el = document.getElementById('view-crystals');- if (!state.crystals.loaded) el.innerHTML = '<div class="loading">Loading crystals...</div>';- var results = await Promise.all([apiGet('crystals'), apiGet('lessons')]);- state.crystals.items = (results[0] && results[0].crystals) || [];- var lessonMap = {};- var lessons = (results[1] && results[1].lessons) || [];- lessons.forEach(function(l) { if (l && l.id) lessonMap[l.id] = l; });- state.crystals.lessonMap = lessonMap;- state.crystals.loaded = true;- renderCrystals();+ function auditTargetSummary(ids) {+ var counts = {};+ (ids || []).forEach(function(id) {+ var k = ID_KIND_LABELS[idKind(id)] || 'record';+ counts[k] = (counts[k] || 0) + 1;+ });+ return Object.keys(counts).map(function(k) {+ var n = counts[k];+ var plural = k === 'memory' ? 'memories' : k + 's';+ return n + ' ' + (n === 1 ? k : plural);+ }).join(', ');+ }++ function auditDetailScalars(details) {+ var out = [];+ Object.keys(details || {}).forEach(function(k) {+ var v = details[k];+ if (v === null || v === undefined || v === '' || typeof v === 'object') return;+ out.push({ key: k, value: String(v) });+ });+ return out;+ }++ function recordName(id) {+ var kind = idKind(id);+ var row;+ if (kind === 'memory' && (row = store.entities.memory[id])) return memoryHeadline(row).head;+ if (kind === 'lesson' && (row = store.entities.lesson[id])) return row.content || '';+ if (kind === 'action' && (row = store.entities.action[id])) return row.title || '';+ if (kind === 'crystal' && (row = store.entities.crystal[id])) return row.narrative || '';+ if (kind === 'session' && (row = store.entities.session[id])) return sessionDisplayName(row) + (row.firstPrompt ? ': ' + row.firstPrompt : '');+ return '';+ }++ function auditSummaryHtml(a) {+ var html = esc(auditVerb(a.operation));+ var ids = a.targetIds || [];+ var name = ids.length === 1 ? recordName(ids[0]) : '';+ if (name) html += ': ' + esc('“' + truncate(name, 90) + '”');+ else if (ids.length > 1) html += ': ' + esc(auditTargetSummary(ids));+ var d = a.details || {};+ var note = d.reason || d.source || d.tier || d.message || '';+ if (typeof note === 'string' && note) html += ' <span style="color:var(--ink-muted);">(' + esc(truncate(note, 80)) + ')</span>';+ return html;}- function renderCrystals() {- var el = document.getElementById('view-crystals');- var items = state.crystals.items;- var search = state.crystals.search.toLowerCase();- var lessonMap = state.crystals.lessonMap || {};-- if (search) {- items = items.filter(function(c) {- var lessonText = (c.lessons || [])- .map(function(lid) {- var l = lessonMap[lid];- return l && typeof l.content === 'string' ? l.content : lid;- })- .join(' ');- var filesText = (c.filesAffected || []).join(' ');- var haystack = [- c.narrative || '',- (c.keyOutcomes || []).join(' '),- lessonText,- filesText,- c.project || '',- ].join(' ').toLowerCase();- return haystack.indexOf(search) >= 0;- });- }+ function auditFilterActive() {+ var a = state.audit;+ return !!(a.opFilter || a.from || a.to || String(a.q || '').trim());+ }- var html = '<div class="card" style="margin-bottom:12px;padding:12px;background:var(--bg-subtle);">';- html += '<div style="font-size:13px;color:var(--ink-muted);line-height:1.5;">';- html += '<strong>Crystals</strong> are frozen snapshots of completed work. Each crystal captures one session\'s narrative, the tools invoked (key outcomes), files touched, and lessons surfaced — a replayable summary you keep after raw observations are pruned. Auto-created on JSONL import or via <code>memory_crystallize</code>.';- html += '</div></div>';+ function auditRange() {+ var a = state.audit;+ var from = a.from ? new Date(a.from + 'T00:00:00').getTime() : null;+ var to = a.to ? new Date(a.to + 'T23:59:59.999').getTime() : null;+ return { from: from !== null && isFinite(from) ? from : null, to: to !== null && isFinite(to) ? to : null };+ }- html += '<div style="display:flex;gap:8px;margin-bottom:12px;">';- html += '<input id="crystals-search" class="search-input" type="text" placeholder="Search crystals..." value="' + esc(state.crystals.search) + '" style="flex:1" />';- html += '<span style="font-size:12px;color:var(--ink-faint);align-self:center;">' + items.length + ' crystals</span>';- html += '</div>';+ function auditMatches(e) {+ var a = state.audit;+ if (!e) return false;+ if (a.opFilter && e.operation !== a.opFilter) return false;+ var r = auditRange();+ var t = new Date(e.timestamp).getTime();+ if (r.from !== null && !(t >= r.from)) return false;+ if (r.to !== null && !(t <= r.to)) return false;+ var q = String(a.q || '').trim().toLowerCase();+ if (q && ![e.functionId].concat(e.targetIds || []).some(function(v) { return String(v || '').toLowerCase().indexOf(q) >= 0; })) return false;+ return true;+ }- if (items.length === 0) {- html += '<div class="empty-state">' +- '<div class="empty-icon">💎</div>' +- '<div class="empty-title">No crystals yet</div>' +- '<div class="empty-lead">Crystals are frozen snapshots of completed work — one session’s narrative, key outcomes, files touched, and lessons surfaced, kept after raw observations are pruned so the next session gets fast context.</div>' +- '<pre class="empty-cmd"># Auto: import a JSONL transcript\n# Replay tab → Import JSONL\n\n# Manual: crystallize a specific session\nmemory_crystallize { sessionId }</pre>' +- '<div><a class="empty-link" href="https://github.com/rohitg00/agentmemory#crystals" target="_blank" rel="noopener">Crystal pipeline →</a></div>' +- '</div>';- } else {- items.forEach(function(c) {- html += '<div class="card" style="margin-bottom:12px;border-left:3px solid var(--accent);">';- html += '<div style="display:flex;justify-content:space-between;align-items:flex-start;gap:12px;margin-bottom:8px;">';- html += '<div style="flex:1;font-size:14px;font-weight:600;color:var(--ink);line-height:1.4;">' + esc(truncate(c.narrative || 'Untitled crystal', 300)) + '</div>';- html += '<div style="font-size:10px;color:var(--ink-faint);font-family:var(--font-mono);white-space:nowrap;">' + esc(formatTime(c.createdAt)) + '</div>';- html += '</div>';-- var pillRow = [];- if (c.project) pillRow.push('<span class="badge badge-muted">' + esc(c.project) + '</span>');- if (c.sessionId) pillRow.push('<span class="badge badge-blue" style="font-family:var(--font-mono);">' + esc(c.sessionId.slice(0, 14)) + '</span>');- if (c.keyOutcomes && c.keyOutcomes.length) pillRow.push('<span style="font-size:11px;color:var(--ink-muted);">' + c.keyOutcomes.length + ' tools</span>');- if (c.filesAffected && c.filesAffected.length) pillRow.push('<span style="font-size:11px;color:var(--ink-muted);">' + c.filesAffected.length + ' files</span>');- if (c.lessons && c.lessons.length) pillRow.push('<span style="font-size:11px;color:var(--ink-muted);">' + c.lessons.length + ' lessons</span>');- if (pillRow.length) html += '<div style="display:flex;gap:6px;flex-wrap:wrap;margin-bottom:10px;">' + pillRow.join('') + '</div>';-- if (c.keyOutcomes && c.keyOutcomes.length > 0) {- html += '<div style="margin:10px 0;"><div style="font-size:10px;letter-spacing:0.08em;color:var(--ink-muted);margin-bottom:4px;">TOOLS USED</div>';- html += '<div style="display:flex;gap:4px;flex-wrap:wrap;">';- c.keyOutcomes.forEach(function(o) {- html += '<span class="badge" style="background:var(--bg-alt);color:var(--ink);font-family:var(--font-mono);">' + esc(o) + '</span>';- });- html += '</div></div>';- }+ function auditFilterKey() {+ var a = state.audit;+ return [a.opFilter, a.from, a.to, String(a.q || '').trim()].join('|');+ }- if (c.filesAffected && c.filesAffected.length > 0) {- html += '<div style="margin:10px 0;"><div style="font-size:10px;letter-spacing:0.08em;color:var(--ink-muted);margin-bottom:4px;">FILES TOUCHED</div>';- html += '<div style="font-size:12px;font-family:var(--font-mono);color:var(--ink);line-height:1.6;">';- c.filesAffected.slice(0, 10).forEach(function(f) {- html += '<div>• ' + esc(f) + '</div>';- });- if (c.filesAffected.length > 10) html += '<div style="color:var(--ink-faint);">+' + (c.filesAffected.length - 10) + ' more</div>';- html += '</div></div>';- }+ function auditQueryPath(extra) {+ var a = state.audit;+ var r = auditRange();+ var p = 'audit?limit=' + AUDIT_PAGE;+ if (a.opFilter) p += '&operation=' + encodeURIComponent(a.opFilter);+ if (r.from !== null) p += '&dateFrom=' + encodeURIComponent(new Date(r.from).toISOString());+ if (r.to !== null) p += '&dateTo=' + encodeURIComponent(new Date(r.to).toISOString());+ if (String(a.q || '').trim()) p += '&q=' + encodeURIComponent(String(a.q).trim());+ return p + (extra || '');+ }- if (c.lessons && c.lessons.length > 0) {- html += '<div style="margin:10px 0;"><div style="font-size:10px;letter-spacing:0.08em;color:var(--ink-muted);margin-bottom:4px;">LESSONS SURFACED</div>';- c.lessons.slice(0, 8).forEach(function(lid) {- var content = lessonMap[lid] ? lessonMap[lid].content : lid;- html += '<div style="font-size:12px;padding:4px 8px;margin:2px 0;background:var(--bg-alt);border-radius:3px;color:var(--ink);line-height:1.4;">💡 ' + esc(content) + '</div>';- });- if (c.lessons.length > 8) html += '<div style="font-size:11px;color:var(--ink-faint);margin-top:4px;">+' + (c.lessons.length - 8) + ' more lessons</div>';- html += '</div>';- }+ function mergeAuditRows(rows) {+ var added = 0;+ (rows || []).forEach(function(r) {+ if (!r || !r.id) return;+ if (!store.entities.audit[r.id]) added++;+ store.entities.audit[r.id] = r;+ });+ return added;+ }- html += '</div>';- });- }+ function auditRows() {+ var rows = entityList('audit');+ if (auditFilterActive()) rows = rows.filter(auditMatches);+ return sortByTimeDesc(rows, ['timestamp']);+ }- var __focus = captureSearchFocus(['crystals-search']);- el.innerHTML = html;- var __cs = document.getElementById('crystals-search');- if (__cs) bindImeSafeSearch(__cs, 200, function(v){ state.crystals.search = v; renderCrystals(); });- restoreSearchFocus(__focus);+ var auditQuerySeq = 0;+ async function applyAuditFilters() {+ var a = state.audit;+ var key = auditFilterKey();+ a.selectedIdx = null;+ if (!auditFilterActive()) { a.query = null; renderAudit(); return; }+ var seq = ++auditQuerySeq;+ a.query = { key: key, loading: true, failed: false };+ renderAudit();+ var res = await apiGet(auditQueryPath());+ if (seq !== auditQuerySeq) return;+ a.query.loading = false;+ if (!res) a.query.failed = true;+ else {+ mergeAuditRows(res.entries);+ if ((res.entries || []).length < AUDIT_PAGE) a.exhausted[key] = true;+ }+ renderAudit();}+ var applyAuditFiltersSoon = debounce(applyAuditFilters, 300);- async function loadAudit() {- var el = document.getElementById('view-audit');- if (!state.audit.loaded) el.innerHTML = '<div class="loading">Loading audit log...</div>';- var result = await apiGet('audit?limit=100');- state.audit.entries = (result && result.entries) || [];- state.audit.loaded = true;+ async function loadMoreAudit() {+ var a = state.audit;+ var key = auditFilterKey();+ var rows = auditRows();+ if (a.loadingMore || a.exhausted[key] || !rows.length) return;+ a.loadingMore = true;+ renderAudit();+ var oldest = rows[rows.length - 1].timestamp;+ var path = auditFilterActive() ? auditQueryPath() : 'audit?limit=' + AUDIT_PAGE;+ path = path.replace(/&dateTo=[^&]*/, '') + '&dateTo=' + encodeURIComponent(oldest);+ var res = await apiGet(path);+ a.loadingMore = false;+ if (res) {+ var added = mergeAuditRows(res.entries);+ if ((res.entries || []).length < AUDIT_PAGE || added === 0) a.exhausted[key] = true;+ }renderAudit();}- function renderAudit() {- var el = document.getElementById('view-audit');- var entries = state.audit.entries;- var opFilter = state.audit.opFilter;+ function clearAuditFilters() {+ var a = state.audit;+ a.opFilter = '';+ a.from = '';+ a.to = '';+ a.q = '';+ a.query = null;+ auditQuerySeq++;+ renderAudit();+ }+ function auditToolbarHtml() {+ var a = state.audit;var ops = {};- entries.forEach(function(e) { ops[e.operation] = true; });- var opList = Object.keys(ops).sort();-- var filtered = opFilter ? entries.filter(function(e) { return e.operation === opFilter; }) : entries;+ Object.keys(AUDIT_VERBS).forEach(function(op) { ops[op] = 0; });+ entityList('audit').forEach(function(e) { if (e.operation) ops[e.operation] = (ops[e.operation] || 0) + 1; });+ var seen = Object.keys(ops).filter(function(op) { return ops[op] > 0 || op === a.opFilter; }).sort();+ var rest = Object.keys(ops).filter(function(op) { return seen.indexOf(op) < 0; }).sort();+ var html = '<div class="toolbar mem-filters">';+ html += '<input type="search" id="audit-q" placeholder="Filter by target id or function, e.g. mem_ or lesson-save (press /)" value="' + esc(a.q) + '" aria-label="Filter audit entries by target id or function">';+ html += '<select id="audit-op-filter" aria-label="Filter by operation"><option value="">All operations</option>';+ if (seen.length) html += '<optgroup label="In the loaded entries">' + seen.map(function(op) { return '<option value="' + esc(op) + '"' + (a.opFilter === op ? ' selected' : '') + '>' + esc(op) + ' (' + fmtNum(ops[op]) + ')</option>'; }).join('') + '</optgroup>';+ html += '<optgroup label="Other operations">' + rest.map(function(op) { return '<option value="' + esc(op) + '"' + (a.opFilter === op ? ' selected' : '') + '>' + esc(op) + '</option>'; }).join('') + '</optgroup></select>';+ html += '<label class="tb-label">From <input type="date" id="audit-from" value="' + esc(a.from) + '" aria-label="From date"></label>';+ html += '<label class="tb-label">To <input type="date" id="audit-to" value="' + esc(a.to) + '" aria-label="To date"></label>';+ return html + '</div>';+ }++ function bindAuditToolbar() {+ var q = document.getElementById('audit-q');+ if (q && !q.__bound) {+ q.__bound = true;+ bindImeSafeSearch(q, 300, function(v) { state.audit.q = v; applyAuditFilters(); });+ }+ [['audit-op-filter', 'opFilter'], ['audit-from', 'from'], ['audit-to', 'to']].forEach(function(pair) {+ var el = document.getElementById(pair[0]);+ if (el && !el.__bound) {+ el.__bound = true;+ el.addEventListener('change', function() { state.audit[pair[1]] = this.value; applyAuditFiltersSoon(); });+ }+ });+ }- var html = '<div class="toolbar">';- html += '<select id="audit-op-filter"><option value="">All operations</option>';- opList.forEach(function(op) {- html += '<option value="' + esc(op) + '"' + (opFilter === op ? ' selected' : '') + '>' + esc(op) + '</option>';+ function auditFilterDescription() {+ var a = state.audit;+ var parts = [];+ if (a.opFilter) parts.push('operation <b>' + esc(a.opFilter) + '</b>');+ if (a.from) parts.push('from <b>' + esc(a.from) + '</b>');+ if (a.to) parts.push('to <b>' + esc(a.to) + '</b>');+ if (String(a.q || '').trim()) parts.push('target or function containing “' + esc(a.q) + '”');+ return parts.join(', ');+ }++ function auditDetailHtml(a) {+ var d = a.details || {};+ var html = '<div class="audit-more" id="audit-detail-' + esc(a.id) + '"><dl class="mem-meta">';+ html += '<dt>When</dt><dd>' + esc(formatTime(a.timestamp)) + '</dd>';+ html += '<dt>Function</dt><dd><code>' + esc(a.functionId || '') + '</code></dd>';+ if (a.userId) html += '<dt>User</dt><dd>' + esc(a.userId) + '</dd>';+ if (typeof a.qualityScore === 'number') html += '<dt>Quality</dt><dd>' + esc(String(a.qualityScore)) + '</dd>';+ html += '<dt>Entry</dt><dd>' + '<span class="id-chip"><code>' + esc(shortId(a.id, 22)) + '</code>' + copyBtn(a.id, 'audit entry id') + '</span></dd>';+ if ((a.targetIds || []).length) {+ html += '<dt>Targets ' + help('auditTargets') + '</dt><dd style="display:flex;gap:6px;flex-wrap:wrap;">' + a.targetIds.slice(0, 40).map(function(id) { return anyIdChip(id); }).join('') + (a.targetIds.length > 40 ? '<span class="ses-foot">+' + (a.targetIds.length - 40) + ' more</span>' : '') + '</dd>';+ }+ Object.keys(d).forEach(function(k) {+ var v = d[k];+ if (v === null || v === undefined || v === '') return;+ var label = k.replace(/([a-z])([A-Z])/g, '$1 $2').replace(/_/g, ' ');+ if (Array.isArray(v) && v.length && v.every(function(x) { return typeof x === 'string' && idKind(x); })) {+ html += '<dt>' + esc(label) + '</dt><dd style="display:flex;gap:6px;flex-wrap:wrap;">' + v.slice(0, 20).map(function(id) { return anyIdChip(id); }).join('') + '</dd>';+ } else if (typeof v === 'object') {+ html += '<dt>' + esc(label) + '</dt><dd><pre class="obs-code" style="max-height:160px;">' + esc(truncate(JSON.stringify(v, null, 2), 4000)) + '</pre></dd>';+ } else {+ html += '<dt>' + esc(label) + '</dt><dd>' + (typeof v === 'string' && idKind(v) ? anyIdChip(v) : esc(String(v))) + '</dd>';+ }});- html += '</select></div>';+ html += '</dl><div class="mem-actions" style="margin-top:8px;">' + copyBtn(curlGet('audit?q=' + encodeURIComponent((a.targetIds || [])[0] || a.functionId || '') + '&limit=20'), 'curl command').replace('>copy<', '>copy curl<') + copyBtn(JSON.stringify(a, null, 2), 'raw entry').replace('>copy<', '>copy JSON<') + '</div></div>';+ return html;+ }- html += '<div class="card">';- if (filtered.length === 0) {- html += '<div class="empty-state"><div class="empty-icon">📜</div><p>No audit entries yet</p><p style="font-size:12px;color:var(--ink-faint);font-style:italic;">Audit entries are created by governance operations (delete, evolve, consolidate).</p></div>';- } else {- filtered.forEach(function(a, idx) {- var badgeClass = OP_BADGES[a.operation] || 'badge-muted';- html += '<div class="audit-entry">';- html += '<div class="audit-head">';- html += '<span class="badge ' + badgeClass + '">' + esc(a.operation) + '</span>';- html += '<span style="font-size:12px;color:var(--ink-muted);font-family:var(--font-mono);">' + esc(a.functionId || '') + '</span>';- html += '<span style="font-size:10px;color:var(--ink-faint);margin-left:auto;font-family:var(--font-mono);">' + esc(formatTime(a.timestamp)) + '</span>';- html += '<button class="btn" style="font-size:9px;padding:1px 6px;margin-left:8px;" data-action="toggle-audit" data-audit-index="' + idx + '">▼</button>';- html += '</div>';- if (a.targetIds && a.targetIds.length) {- html += '<div style="font-size:10px;color:var(--ink-faint);font-family:var(--font-mono);">' + a.targetIds.length + ' target(s): ' + esc(a.targetIds.slice(0, 3).join(', ')) + (a.targetIds.length > 3 ? '...' : '') + '</div>';- }- html += '<div class="audit-detail" id="audit-detail-' + idx + '"><pre>' + esc(JSON.stringify(a.details || {}, null, 2)) + '</pre></div>';- html += '</div>';- });+ function auditRowHtml(a) {+ var open = state.audit.selectedIdx === a.id;+ var fresh = state.audit.fresh[a.id] && Date.now() - state.audit.fresh[a.id] < 3000;+ var html = '<div class="audit-row' + (open ? ' open' : '') + (fresh ? ' fresh' : '') + '" data-audit-row="' + esc(a.id) + '">';+ html += '<span class="badge audit-op ' + (OP_BADGES[a.operation] || 'badge-muted') + '" title="' + esc(a.operation) + '">' + esc(String(a.operation || '').replace(/_/g, ' ')) + '</span>';+ html += '<div class="audit-sum">' + auditSummaryHtml(a) + '<span class="audit-fn">' + esc(a.functionId || '') + '</span></div>';+ html += '<span class="audit-when">' + relTime(a.timestamp) + '<button type="button" class="icon-btn" data-action="toggle-audit" data-audit-id="' + esc(a.id) + '" aria-expanded="' + (open ? 'true' : 'false') + '" aria-controls="audit-detail-' + esc(a.id) + '">' + (open ? 'hide' : 'details') + '</button></span>';+ var ids = a.targetIds || [];+ if (ids.length) {+ html += '<div class="audit-targets"><span class="kind-tag">' + (ids.length === 1 ? 'target' : ids.length + ' targets') + '</span>' + ids.slice(0, 5).map(function(id) { return anyIdLink(id); }).join(' ') + (ids.length > 5 ? '<span>+' + (ids.length - 5) + ' more</span>' : '') + '</div>';}- html += '</div>';+ if (open) html += auditDetailHtml(a);+ return html + '</div>';+ }- el.innerHTML = html;+ function auditListHtml() {+ var a = state.audit;+ var filtered = auditFilterActive();+ var rows = auditRows();+ var key = auditFilterKey();+ var html = '';+ if (filtered) {+ var summary = a.query && a.query.loading ? 'Filtering on the server…' : a.query && a.query.failed ? 'The filter request failed. Change a filter to retry.' : fmtNum(rows.length) + (a.exhausted[key] ? '' : '+') + ' matching entr' + (rows.length === 1 ? 'y' : 'ies');+ html += '<div class="mem-filter-note"><span>' + summary + ' for ' + auditFilterDescription() + '</span><button type="button" class="btn" data-action="audit-clear-filters">Clear all</button></div>';+ }+ if (!rows.length) {+ if (filtered && a.query && a.query.loading) return html + skeleton(6);+ if (filtered) {+ html += emptyState({+ icon: '🔍',+ title: 'No audit entries match',+ what: 'The audit log records every change agentmemory made to stored data. The filters run on the server over the whole log, not only the loaded page.',+ why: 'No entry matches ' + auditFilterDescription() + '.',+ steps: [{ label: 'Run the same query from a terminal:', cmd: curlGet(auditQueryPath().replace('limit=' + AUDIT_PAGE, 'limit=20')) }]+ });+ return html + '<div style="margin-top:10px;"><button type="button" class="btn" data-action="audit-clear-filters">Clear filters</button></div>';+ }+ return html + emptyState({+ icon: '📜',+ title: 'No audit entries yet',+ what: 'Every save, delete, import, export, consolidation run and lesson change is recorded here with the function that made it and the records it touched. New entries appear the moment they are written.',+ why: 'agentmemory has not changed any stored data on this install yet. Reads and searches are not audited.',+ steps: [+ { label: 'Save a lesson; its entry appears here immediately:', cmd: curlPost('lessons', { content: 'Run tsc before committing', context: 'audit demo' }) },+ { label: 'Read the log from a terminal:', cmd: curlGet('audit?limit=20') }+ ]+ });+ }+ var locate = [];+ rows.slice(0, 400).forEach(function(r) { (r.targetIds || []).slice(0, r.id === a.selectedIdx ? 40 : 5).forEach(function(id) { if (idKind(id) === 'observation') locate.push(id); }); });+ if (locate.length) locateObservations(locate);+ html += '<div class="audit-list" role="list">' + rows.slice(0, 400).map(auditRowHtml).join('') + '</div>';+ html += '<div class="load-more">Showing ' + fmtNum(Math.min(rows.length, 400)) + (filtered ? ' matching' : ' newest') + ' entries';+ if (!a.exhausted[key] && rows.length < 400) html += '<button class="btn" data-action="audit-load-more"' + (a.loadingMore ? ' disabled' : '') + '>' + (a.loadingMore ? 'Loading…' : 'Load ' + AUDIT_PAGE + ' older') + '</button>';+ else if (rows.length >= 400) html += '<span>Narrow the dates to see older entries.</span>';+ return html + '</div>';+ }- document.getElementById('audit-op-filter').addEventListener('change', function() {- state.audit.opFilter = this.value;- renderAudit();- });+ function renderAudit() {+ var el = document.getElementById('view-audit');+ if (!el.querySelector('#audit-list')) {+ el.innerHTML = '<div class="inline-note"><strong>Audit log</strong> ' + help('audit') + ' lists every change agentmemory made to stored data, newest first, as it happens. Target ids ' + help('auditTargets') + ' open the record they changed; details shows everything the entry recorded.</div>' ++ '<div id="audit-toolbar"></div><div id="audit-list"></div>';+ el.__renderedHtml = null;+ }+ var focus = captureSearchFocus(['audit-q']);+ var bare = store.loaded.audit && !entityList('audit').length && !auditFilterActive();+ var note = el.querySelector('.inline-note');+ if (note) note.hidden = bare;+ setViewHtml(document.getElementById('audit-toolbar'), bare ? '' : auditToolbarHtml());+ bindAuditToolbar();+ restoreSearchFocus(focus);+ if (!store.loaded.audit) {+ setViewHtml(document.getElementById('audit-list'), skeleton(10));+ return;+ }+ setViewHtml(document.getElementById('audit-list'), auditListHtml());}- function toggleAuditDetail(idx) {- var el = document.getElementById('audit-detail-' + idx);- if (el) el.classList.toggle('open');+ function toggleAuditDetail(id) {+ state.audit.selectedIdx = state.audit.selectedIdx === id ? null : id;+ setRouteEntity('audit', state.audit.selectedIdx);+ renderAudit();}var HEALTH_LEVEL_BADGES = { ok: 'badge-green', info: 'badge-blue', warn: 'badge-yellow', error: 'badge-red' };+ var statusReportRequest = null;+ function ensureStatusReport() {+ if (statusReportRequest) return statusReportRequest;+ state.health.checking = true;+ markDirty(['health']);+ renderTab('health');+ statusReportRequest = loadHealth().finally(function() {+ statusReportRequest = null;+ state.health.checking = false;+ markDirty(['health']);+ if (state.activeTab === 'health') renderTab('health');+ });+ return statusReportRequest;+ }+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;+ store.report = report;state.health.error = null;} else {- state.health.error = 'The status check did not answer. The server may be restarting.';- }- renderHealth();+ state.health.error = 'The check did not answer. The server may be restarting.';+ }+ }++ var BM25_EXPLAINER = 'The keyword index holds observations, memories and lessons, so its total is larger than the observation count.';+ var LLM_KEY_FIX = 'Add one LLM provider key (for example ANTHROPIC_API_KEY or OPENAI_API_KEY) to ~/.agentmemory/.env and restart.';++ function hrow(label, valueHtml, helpKey, note) {+ return '<div class="detail-row"><div class="dl">' + esc(label) + (helpKey ? ' ' + help(helpKey) : '') + '</div><div class="dv">' + valueHtml + (note ? '<div class="hnote">' + note + '</div>' : '') + '</div></div>';+ }++ function durationText(ms) {+ var mins = Math.round(ms / 60000);+ if (mins < 1) return Math.round(ms / 1000) + ' seconds';+ if (mins < 120) return mins + ' minute' + (mins === 1 ? '' : 's');+ return Math.round(mins / 60) + ' hours';+ }++ function flagHowText(f) {+ if (!f.enabled) return f.enableHow || ('Set ' + f.key + '=true and restart.');+ if (f.inactiveReason) return LLM_KEY_FIX;+ return 'Set ' + f.key + '=false and restart to turn it off.';+ }++ function healthStaleHtml(r) {+ var last = store.lastHealthAt ? new Date(store.lastHealthAt).toLocaleTimeString() : '';+ if (conn.state === 'reconnecting' || conn.state === 'offline') {+ return '<div class="hstale offline" id="health-live-state"><strong>Offline: live updates are paused.</strong> The viewer lost its connection to agentmemory' + (conn.lostAt ? ' at ' + esc(new Date(conn.lostAt).toLocaleTimeString()) : '') + '. Everything on this page is the last report' + (last ? ' from ' + esc(last) : '') + ' and may be out of date. It refreshes by itself when the connection returns.' ++ '<div style="margin-top:6px;">Check that the server is running:</div>' + cmdBlock('npx @agentmemory/agentmemory status') ++ '<button class="btn" data-action="reconnect-now" style="margin-top:6px;">Reconnect now</button></div>';+ }+ if (store.lastHealthAt && Date.now() - store.lastHealthAt > HEALTH_STALE_MS) {+ var secs = Math.round((Date.now() - store.lastHealthAt) / 1000);+ return '<div class="hstale" id="health-live-state"><strong>Stale: no health report for ' + secs + 's.</strong> Reports normally arrive every 30 seconds. The stream is connected, so the worker is busy or the iii engine is paused. The numbers below are from ' + esc(last) + '.' ++ '<div style="margin-top:6px;">Fix: wait a minute; if it stays stale, check the server log and restart agentmemory.</div></div>';+ }+ return '';+ }++ function problemHtml(p) {+ return '<div class="problem"><div><span class="badge ' + (HEALTH_LEVEL_BADGES[p.level] || 'badge-muted') + '">' + esc(p.level) + '</span></div><div>' ++ '<div class="pm">' + esc(p.message) + '</div>' ++ (p.fix ? '<div class="pf">' + esc(p.fix) + '</div>' : '') + '</div></div>';+ }++ function healthVerdictHtml(r) {+ var level = r ? r.status : 'unknown';+ var text = r ? (r.headline || (r.status === 'ok' ? 'Every check passed.' : 'Some checks need attention.')) : 'Waiting for the first health report from the server.';+ var html = '<div class="card" style="margin-top:0;">';+ var badgeText = level === 'unknown' ? 'waiting' : level;+ var paused = conn.state === 'reconnecting' || conn.state === 'offline';+ var quiet = !paused && store.lastHealthAt && Date.now() - store.lastHealthAt > HEALTH_STALE_MS;+ if (r && (paused || quiet)) {+ badgeText = paused ? 'offline' : 'stale';+ level = 'unknown';+ text = 'Last known state: ' + text;+ }+ html += '<div class="verdict"><span class="verdict-badge ' + esc(level) + '">' + esc(badgeText) + '</span><div style="min-width:0;flex:1;">' ++ '<div class="verdict-text">' + esc(text) + '</div>' ++ '<div class="verdict-meta">' + (r ? 'Report ' + relTime(r.checkedAt) + ' · ' : '') + 'updates every 30 s over the live stream, no refresh needed ' + help('live') + '</div></div></div>';+ html += healthStaleHtml(r);+ if (state.health.error) html += '<div class="mem-note err" style="margin-top:10px;">' + esc(state.health.error) + '</div>';+ if (r && r.problems.length) {+ html += '<div style="margin-top:12px;">' + r.problems.map(problemHtml).join('') + '</div>';+ } else if (r) {+ html += '<p class="hnote" style="margin-top:10px;font-size:12px;">No problems found: the engine is connected, the search index matches the stored observations and no function is failing.</p>';+ }+ html += '<div style="display:flex;gap:10px;align-items:center;flex-wrap:wrap;margin-top:12px;font-size:11px;color:var(--ink-faint);font-family:var(--font-ui);">' ++ '<button class="btn" data-action="refresh-health"' + (state.health.checking ? ' disabled' : '') + '>' + (state.health.checking ? 'Checking…' : 'Re-check now') + '</button>' ++ '<span>Machine checks (keys, engine binary, pid files):</span>' + cmdBlock((customPort() ? 'AGENTMEMORY_URL=' + agentUrl() + ' ' : '') + 'npx @agentmemory/agentmemory doctor') ++ '<a class="empty-link" href="' + esc(REST) + '/agentmemory/status" target="_blank" rel="noopener">same report as a plain page →</a>' + copyBtn('curl -s ' + apiBase() + '/status', 'curl command') + '</div>';+ return html + '</div>';+ }++ function engineCardHtml(r, snap) {+ var ports = (r && r.service && r.service.ports) || {};+ var kv = snap.kvConnectivity;+ var streamText = conn.state === 'live' ? 'live' : conn.state;+ return '<div class="card"><div class="card-title">Engine and connection ' + help('engineConnection') + '</div>' ++ hrow('Engine connection', esc(snap.connectionState || 'unknown'), 'engineConnection', 'The worker\'s link to the iii engine, which stores the data and runs the functions.') ++ (kv ? hrow('State store', esc(kv.status + (kv.latencyMs !== undefined ? ' · ' + kv.latencyMs + ' ms' : '') + (kv.error ? ' · ' + kv.error : ''))) : '') ++ hrow('Viewer stream', esc(streamText), 'live', 'This page\'s own connection. Offline means the numbers here stop changing.') ++ hrow('Uptime', esc(formatUptime(snap.uptimeSeconds)), 'uptime') ++ hrow('Version', esc('v' + (store.version || (r && r.service.version) || '?') + (r ? ' · engine ' + r.service.engineVersion : ''))) ++ hrow('Ports', esc('REST ' + (ports.rest || '?') + ' · streams ' + (ports.streams || '?') + ' · viewer ' + (ports.viewer || 'off'))) ++ '</div>';}- 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 legText(leg) {+ if (!leg) return 'not saved yet';+ if (leg.lastError) return 'failing: ' + leg.lastError;+ var saved = leg.lastSavedAt ? 'saved ' + timeAgo(leg.lastSavedAt) : 'not saved since start';+ return leg.dirtySince ? saved + ', unsaved changes since ' + timeAgo(leg.dirtySince) : saved;+ }++ function indexCardHtml(r, idx, c) {+ var ri = (r && r.index) || {};+ var b = ri.breakdown;+ var p = idx.persistence || (r && r.indexPersistence) || null;+ var hasVectors = store.embeddingProvider && store.embeddingProvider !== 'none';+ var html = '<div class="card"><div class="card-title">Search index ' + help('bm25') + '</div>';+ html += hrow('Keyword index', esc(fmtNum(idx.bm25Documents) + ' documents'), 'bm25',+ (b ? esc(fmtNum(b.observations) + ' observations + ' + fmtNum(b.memories) + ' memories + ' + fmtNum(b.lessons) + ' lessons. ') : '') + esc(BM25_EXPLAINER));+ html += hrow('Vector index', hasVectors ? esc(fmtNum(idx.vectorDocuments) + ' vectors') : 'off', 'vector',+ hasVectors ? 'Meaning-based search. Each vector is one embedded record.' : 'No embedding provider, so search is keyword only. Set an embedding provider key (for example OPENAI_API_KEY) and restart.');+ html += hrow('Waiting for embeddings', esc(fmtNum(idx.pendingVectorBackfill || 0)), 'pendingBackfill', idx.pendingVectorBackfill ? 'Embedded in the background, capped per start by AGENTMEMORY_VECTOR_BACKFILL_MAX.' : '');+ html += hrow('Missing from index', ri.missingObservations === null || ri.missingObservations === undefined ? 'not checked yet' : esc(fmtNum(ri.missingObservations)), 'missingFromIndex');+ html += hrow('Keyword rebuild', ri.bm25Incomplete ? '<span style="color:var(--accent);">incomplete</span>' : 'complete', null, 'Rebuilt from stored data at every start, so it is never saved to disk.');+ if (p) {+ html += hrow('Vector save', esc(legText(p.vector)), null, 'Saved at most every ' + esc(durationText(p.saveIntervalMs || 600000)) + ' (AGENTMEMORY_INDEX_SAVE_INTERVAL_MS). ' + esc(fmtNum(p.buckets) + ' bucket' + (p.buckets === 1 ? '' : 's') + ', ' + fmtNum(p.pendingChanges) + ' unsaved change' + (p.pendingChanges === 1 ? '' : 's') + (p.saving ? ', saving now' : '') + '.'));+ }+ html += hrow('Graph', esc(fmtNum(c.graphNodes) + ' nodes · ' + fmtNum(c.graphEdges) + ' edges'), 'graph', store.graph && store.graph.updatedAt ? 'Snapshot rebuilt ' + esc(timeAgo(store.graph.updatedAt)) + '.' : '');+ return html + '</div>';+ }++ function llmCardHtml(r) {+ var cb = store.circuitBreaker;+ var noLlm = store.provider === 'noop' || (r && r.provider.llm === 'noop');+ var off = (r && r.provider.offWithoutLlm) || [];+ var html = '<div class="card"><div class="card-title">LLM and embeddings ' + help('circuitBreaker') + '</div>';+ html += hrow('LLM provider', noLlm ? '<span class="badge badge-muted">none</span>' : '<span class="badge badge-green">configured</span>', null,+ noLlm ? 'Capture, keyword and vector search, saved memories, lessons and the structural graph all work without one.' : 'Used for summaries, consolidation, typed graph extraction and optional compression.');+ if (noLlm && off.length) {+ html += hrow('Off without an LLM', esc(off.join(', ')), null, esc(LLM_KEY_FIX) + cmdBlock("echo 'ANTHROPIC_API_KEY=sk-ant-...' >> ~/.agentmemory/.env"));+ }+ var emb = (r && r.provider.embeddings) || store.embeddingProvider || 'none';+ html += hrow('Embeddings', esc(emb === 'none' ? 'none (keyword search only)' : emb), 'vector', emb === 'none' ? 'Meaning-based search is off.' : 'The number in brackets is the vector size (dimensions) the provider returns.');+ html += hrow('Circuit breaker', esc(cb ? cb.state + ' (' + (cb.failures || 0) + ' failures)' : 'not in use'), 'circuitBreaker');+ return html + '</div>';+ }++ function flagsCardHtml(r) {+ var byKey = {};+ (store.flags || []).forEach(function(f) { byKey[f.key] = f; });+ var flags = (r && r.flags) || store.flags || [];+ var html = '<div class="card"><div class="card-title">Feature flags ' + help('flags') + '</div>';+ if (!flags.length) return html + '<p class="hnote">No flag data yet. It arrives with the first report.</p></div>';+ flags.forEach(function(f) {+ var meta = byKey[f.key] || {};+ var badge = !f.enabled ? '<span class="badge badge-muted">off</span>' : f.inactiveReason ? '<span class="badge badge-yellow">on, inactive</span>' : '<span class="badge badge-green">on</span>';+ html += '<div class="flag-row"><div class="flag-head"><strong>' + esc(f.label) + '</strong>' + badge + '<code>' + esc(f.key) + '</code></div>' ++ (meta.description ? '<div class="hnote">' + esc(meta.description) + '</div>' : '') ++ (f.inactiveReason ? '<div class="flag-how" style="color:var(--yellow);">Inactive: ' + esc(f.inactiveReason) + '.</div>' : '') ++ '<div class="flag-how">' + esc(flagHowText(f)) + '</div></div>';+ });+ return html + '</div>';+ }++ function processCardHtml(snap) {+ var m = snap.memory;+ var html = '<div class="card"><div class="card-title">Process ' + help('heap') + '</div>';+ if (!m) return html + '<p class="hnote">No process numbers yet. They arrive with the first health report.</p></div>';+ var limit = m.heapLimit || m.heapTotal || 1;+ var pct = Math.round((m.heapUsed / limit) * 100);+ var bigRss = (m.rss || 0) >= 512 * 1048576;+ var cls = pct > 95 && bigRss ? 'bad' : pct > 80 && bigRss ? 'warn' : '';+ html += hrow('Heap', esc(mb(m.heapUsed) + ' of ' + mb(limit) + ' MB (' + pct + '%)') + '<div class="hbar ' + cls + '"><span style="width:' + Math.min(100, pct) + '%"></span></div>', 'heap',+ 'JavaScript memory in use against the most it may grow to. It only matters above 80% while RSS is also over 512 MB.');+ html += hrow('RSS', esc(mb(m.rss) + ' MB'), 'rss', 'Everything the process holds from the operating system, including code and buffers.');+ var lag = snap.eventLoopLagMs;+ html += hrow('Event loop delay', lag !== undefined ? esc(Number(lag).toFixed(1) + ' ms') : '-', 'eventLoop', 'How far behind the worker is. Under 100 ms is fine; above that requests answer slowly.');+ if (snap.cpu) html += hrow('CPU', esc(Math.round(snap.cpu.percent || 0) + '%'), null, 'Share of one core used since the last report. Short bursts during imports are normal.');+ (snap.notes || []).forEach(function(n) { html += '<div class="hnote" style="margin-top:6px;">' + esc(humanizeHealthFlag(n)) + '</div>'; });+ return html + '</div>';+ }++ function recordsCardHtml(c) {+ return '<div class="card"><div class="card-title">Stored records</div>' ++ hrow('Sessions', esc(fmtNum(c.sessions) + ' (' + fmtNum(c.activeSessions) + ' running)'), 'session') ++ hrow('Observations', esc(fmtNum(c.observations)), 'observation') ++ hrow('Memories', esc(fmtNum(c.latestMemories) + ' latest · ' + fmtNum(c.memories) + ' including older versions'), 'memory') ++ hrow('Lessons / crystals', esc(fmtNum(c.lessons) + ' / ' + fmtNum(c.crystals)), 'lesson') ++ hrow('Semantic facts / procedures', esc(fmtNum(c.semantic) + ' / ' + fmtNum(c.procedural)), 'consolidation', '<a class="empty-link" href="#health/consolidation">Why these can be empty →</a>') ++ '</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 functionsCardHtml(r) {+ var fns = ((r && r.functions) || store.functionMetrics || []).slice().sort(function(a, b) { return (b.totalCalls || 0) - (a.totalCalls || 0); });+ var html = '<div class="card" style="margin-top:16px;"><div class="card-title">Functions ' + help('functionCalls') + '</div>';+ if (!fns.length) {+ return html + emptyState({ compact: true, title: 'No function has run since the worker started',+ what: 'Call counts, failures and latency for every agentmemory function (observe, search, remember, summarize).',+ why: 'Nothing has called the worker yet in this process. Rows appear here live as agents observe, search and save.',+ steps: [{ label: 'Make a first call from a terminal:', cmd: curlPost('smart-search', { query: 'test' }) }] }) + '</div>';+ }+ html += '<div class="table-wrap"><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 ' + help('failureRate') + '</th><th style="text-align:right">Avg latency ' + help('latency') + '</th></tr>';+ fns.forEach(function(f) {+ var total = f.totalCalls || 0;+ var rate = total > 0 ? (f.failureCount || 0) / total : 0;+ var off = !!f.offWithoutLlm;+ var bad = !off && total >= 5 && rate >= 0.2;+ html += '<tr><td class="metric-fn">' + esc(f.functionId) + (off ? ' <span class="badge badge-muted">off, no LLM</span>' : '') + '</td>' ++ '<td class="metric-num">' + fmtNum(total) + '</td>' ++ '<td class="metric-num" style="color:' + ((f.failureCount || 0) > 0 && !off ? 'var(--red)' : 'var(--ink-faint)') + '">' + (off ? '-' : fmtNum(f.failureCount || 0)) + '</td>' ++ '<td class="metric-num" style="color:' + (bad ? 'var(--red)' : 'var(--ink-muted)') + '">' + (off ? 'off' : Math.round(rate * 100) + '%') + '</td>' ++ '<td class="metric-num">' + Math.round(f.avgLatencyMs || 0) + ' ms</td></tr>';+ });+ return html + '</table></div></div>';}- 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>';+ function consolidationResultText(name, res) {+ if (!res) return '';+ if (res.error) return 'failed: ' + res.error;+ if (res.skipped) return 'skipped: ' + (res.reason || 'not enough input');+ if (name === 'semantic') return fmtNum(res.newFacts || 0) + ' new facts from ' + fmtNum(res.totalSummaries || 0) + ' summaries';+ if (name === 'procedural') return fmtNum(res.newProcedures || 0) + ' new procedures from ' + fmtNum(res.patternsAnalyzed || 0) + ' patterns';+ if (name === 'decay') return 'checked ' + fmtNum(res.semantic || 0) + ' facts and ' + fmtNum(res.procedural || 0) + ' procedures';+ if (name === 'reflect') return res.success === false ? 'no insights' : fmtNum(res.newInsights || 0) + ' new insights';+ if (name === 'obsidianExport') return res.success ? 'exported' : 'export failed';+ return '';+ }++ function consolidationWhyEmpty(cs, c) {+ if (!cs.llmConfigured) return { text: 'No LLM provider is configured on this instance, so no session summaries are written and consolidation never runs. Semantic facts and procedures stay at zero.', cmd: "echo 'ANTHROPIC_API_KEY=sk-ant-...' >> ~/.agentmemory/.env" };+ if (!cs.enabled) return { text: 'CONSOLIDATION_ENABLED is set to false, so consolidation is switched off even though an LLM key exists. Remove that line from ~/.agentmemory/.env (or set it to true) and restart. Find it with:', cmd: 'grep -n CONSOLIDATION_ENABLED ~/.agentmemory/.env' };+ var t = cs.thresholds || {};+ if ((c.semantic || 0) === 0 && cs.summaries < (t.semanticMinSummaries || 5)) return { text: 'Not enough finished sessions yet: semantic facts need ' + (t.semanticMinSummaries || 5) + ' session summaries and there are ' + cs.summaries + '. End sessions normally (the Stop hook does it) so each one gets a summary.', cmd: curlPost('session/end', { sessionId: 'ses_...' }) };+ if ((c.procedural || 0) === 0 && cs.recurringPatterns < (t.proceduralMinPatterns || 2)) return { text: 'Procedures need ' + (t.proceduralMinPatterns || 2) + ' pattern memories that each appear in ' + (t.proceduralMinSessionsPerPattern || 2) + '+ sessions; there are ' + cs.recurringPatterns + '. They build up as the same workflow repeats across sessions.', cmd: '' };+ return null;+ }++ function consolidationPanelHtml(cs, c) {+ var html = '<div class="card" id="health-consolidation" style="margin-top:16px;"><div class="card-title">How consolidation works ' + help('consolidation');+ if (cs) {+ var on = cs.enabled && cs.llmConfigured;+ html += ' <span class="badge ' + (on ? 'badge-green' : 'badge-muted') + '">' + (on ? 'on' : 'off') + '</span>';}- 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') ++ html += '<p style="font-size:13px;color:var(--ink-secondary);line-height:1.6;">Consolidation is a background job that turns many raw observations into fewer records that last longer. Observations are never deleted by it and stay searchable. Each step asks the LLM to summarize, so it needs an LLM provider.</p>';+ if (!cs) return html + skeleton(4) + '</div>';+ var sch = cs.schedule || {};+ var t = cs.thresholds || {};+ html += '<div class="cflow">' ++ '<div class="cstep"><div class="cstep-n">1 · captured</div><div class="cstep-t">Observations</div><div class="cstep-d">Hooks record every tool call, edit and command.</div><div class="cstep-c">' + fmtNum(c.observations) + '</div></div>' ++ '<div class="cstep"><div class="cstep-n">2 · session end</div><div class="cstep-t">Summaries</div><div class="cstep-d">The LLM writes one summary when a session ends.</div><div class="cstep-c">' + fmtNum(cs.summaries) + '</div></div>' ++ '<div class="cstep"><div class="cstep-n">3 · merge</div><div class="cstep-t">Semantic facts ' + help('semantic') + '</div><div class="cstep-d">Merged from the newest 20 summaries once at least ' + (t.semanticMinSummaries || 5) + ' exist.</div><div class="cstep-c">' + fmtNum(c.semantic) + '</div></div>' ++ '<div class="cstep"><div class="cstep-n">4 · repeat</div><div class="cstep-t">Procedures ' + help('procedural') + '</div><div class="cstep-d">From pattern memories seen in ' + (t.proceduralMinSessionsPerPattern || 2) + '+ sessions, once ' + (t.proceduralMinPatterns || 2) + ' exist.</div><div class="cstep-c">' + fmtNum(c.procedural) + '</div></div>' ++ '<div class="cstep"><div class="cstep-n">5 · forget</div><div class="cstep-t">Decay ' + help('decay') + '</div><div class="cstep-d">Facts and procedures unused for ' + (sch.decayDays || 30) + ' days lose 10% strength per period (never below 0.1).</div></div>' +'</div>';- html += '<div class="card"><div class="card-title">Search index & 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>';+ var why = consolidationWhyEmpty(cs, c);+ if (why) {+ html += '<div class="hstale" style="margin-top:12px;"><strong>Why semantic facts or procedures are empty here:</strong> ' + esc(why.text) + (why.cmd ? cmdBlock(why.cmd) : '') + '</div>';+ }+ html += '<div class="ccols"><div><h4>Schedule and thresholds</h4>' ++ '<div class="ckv"><span>After a session ends</span><span>runs at most once every ' + esc(durationText(sch.cooldownMs || 300000)) + ' (AGENTMEMORY_CONSOLIDATION_COOLDOWN_MS)</span></div>' ++ '<div class="ckv"><span>On a timer</span><span>every ' + esc(durationText(sch.intervalMs || 7200000)) + ' (CONSOLIDATION_INTERVAL_MS), if it was on when the server started</span></div>' ++ '<div class="ckv"><span>Semantic facts</span><span>need ' + (t.semanticMinSummaries || 5) + ' summaries (have ' + fmtNum(cs.summaries) + ')</span></div>' ++ '<div class="ckv"><span>Procedures</span><span>need ' + (t.proceduralMinPatterns || 2) + ' recurring patterns (have ' + fmtNum(cs.recurringPatterns) + ')</span></div>' ++ '<div class="ckv"><span>Decay period</span><span>' + (sch.decayDays || 30) + ' days (CONSOLIDATION_DECAY_DAYS)</span></div>' ++ '<div class="ckv"><span>Lessons ' + help('lesson') + '</span><span>saved by agents (memory_lesson_save), stronger with each reuse; unused ones lose confidence weekly</span></div>' ++ '<div class="ckv"><span>Crystals ' + help('crystal') + '</span><span>finished actions grouped into one digest after each consolidation at session end</span></div>' ++ '</div><div><h4>Last run</h4>';+ var lr = cs.lastRun || (store.consolidation && store.consolidation.lastRun);+ if (!lr) {+ html += '<p class="hnote" style="font-size:12px;">Never ran on this instance. ' + (cs.enabled && cs.llmConfigured ? 'It runs after the next session ends, or now with the button below.' : 'It is off; see the reason above.') + '</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 += '<div class="ckv"><span>When</span><span>' + relTime(lr.at) + ' · tier ' + esc(lr.tier || 'all') + '</span></div>';+ Object.keys(lr.results || {}).forEach(function(k) {+ var txt = consolidationResultText(k, lr.results[k]);+ if (txt) html += '<div class="ckv"><span>' + esc(k === 'obsidianExport' ? 'Obsidian export' : k) + '</span><span>' + esc(txt) + '</span></div>';});- 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;+ if (cs.enabled && cs.llmConfigured) {+ html += '<div style="display:flex;gap:8px;align-items:center;flex-wrap:wrap;margin-top:10px;"><button class="btn" data-action="run-consolidation"' + (state.health.consolidating ? ' disabled' : '') + '>' + (state.health.consolidating ? 'Running…' : 'Run consolidation now') + '</button>' + copyBtn(curlPost('consolidate-pipeline', { tier: 'all' }), 'curl command') + '</div>';+ }+ html += '</div></div>';+ html += '<h4 style="font-family:var(--font-ui);font-size:10px;font-weight:700;letter-spacing:0.1em;text-transform:uppercase;color:var(--ink-muted);margin:16px 0 0;">Each layer now</h4>';+ (cs.tiers || []).forEach(function(tier) {+ var count = tier.id === 'semantic' ? c.semantic : tier.id === 'procedural' ? c.procedural : tier.count;+ html += '<div class="layer-row"><div class="layer-head"><span class="layer-name">' + esc(tier.label) + '</span>' ++ '<span class="layer-count">' + esc(fmtNum(count === undefined ? tier.count : count)) + '</span>' ++ '<span class="badge ' + (LAYER_STATE_BADGES[tier.state] || 'badge-muted') + '">' + esc(LAYER_STATE_LABELS[tier.state] || tier.state) + '</span></div>' ++ '<div class="layer-from">' + esc(tier.from) + '</div><div class="layer-detail">' + esc(tier.detail) + '</div></div>';+ });+ return html + '</div>';}- async function loadProfile() {- var el = document.getElementById('view-profile');- el.innerHTML = '<div class="loading">Loading profile...</div>';- var sessResult = await apiGet('sessions');- var sessions = (sessResult && sessResult.sessions) || [];-- var projects = {};- sessions.forEach(function(s) { if (s.project) projects[s.project] = true; });- state.profile.projects = Object.keys(projects).sort();- state.profile.loaded = true;-- if (state.profile.projects.length > 0 && !state.profile.selectedProject) {- state.profile.selectedProject = state.profile.projects[0];+ async function runConsolidation() {+ if (state.health.consolidating) return;+ state.health.consolidating = true;+ markDirty(['health']);+ renderTab('health');+ try {+ var res = await apiPost('consolidate-pipeline', { tier: 'all' });+ state.health.error = res && res.success === false && res.reason ? res.reason : null;+ } finally {+ state.health.consolidating = false;+ markDirty(['health']);+ if (state.activeTab === 'health') renderTab('health');}+ }- renderProfileToolbar();- if (state.profile.selectedProject) await loadProfileData();+ function renderHealth() {+ var el = document.getElementById('view-health');+ if (!store.snapshot) {+ setViewHtml(el, skeleton(10));+ return;+ }+ var r = store.report;+ var snap = store.health || {};+ var idx = store.indexes || {};+ var c = store.counts || {};+ var html = '<div class="inline-note"><strong>Health</strong> ' + help('health') + ' is the live version of the <a class="empty-link" href="' + esc(REST) + '/agentmemory/status" target="_blank" rel="noopener">/agentmemory/status</a> page: the same checks and verdict, pushed over the stream every 30 seconds. Every problem says what to do. Scroll down for how consolidation works.</div>';+ html += healthVerdictHtml(r);+ html += '<div class="hgrid">' + engineCardHtml(r, snap) + indexCardHtml(r, idx, c) + llmCardHtml(r) + flagsCardHtml(r) + processCardHtml(snap) + recordsCardHtml(c) + '</div>';+ html += consolidationPanelHtml(store.consolidationStatus, c);+ html += functionsCardHtml(r);+ setViewHtml(el, html);+ var reveal = state.health.reveal && document.getElementById('health-' + state.health.reveal);+ if (reveal) {+ state.health.reveal = '';+ reveal.scrollIntoView({ block: 'start' });+ }+ }++ function profileProjects() {+ var map = {};+ entityList('session').forEach(function(x) {+ if (!x.project) return;+ var p = map[x.project] || (map[x.project] = { project: x.project, count: 0, lastAt: '', cwd: '' });+ p.count++;+ var at = String(x.updatedAt || x.startedAt || '');+ if (at > p.lastAt) { p.lastAt = at; if (x.cwd) p.cwd = x.cwd; }+ if (!p.cwd && x.cwd) p.cwd = x.cwd;+ });+ return Object.keys(map).map(function(k) { return map[k]; }).sort(function(a, b) { return b.lastAt.localeCompare(a.lastAt) || b.count - a.count; });}- function renderProfileToolbar() {+ function renderProfilePage() {var el = document.getElementById('view-profile');- var html = '<div class="toolbar">';- html += '<select id="profile-project">';- if (state.profile.projects.length === 0) {- html += '<option value="">No projects</option>';- } else {- state.profile.projects.forEach(function(p) {- html += '<option value="' + esc(p) + '"' + (state.profile.selectedProject === p ? ' selected' : '') + '>' + esc(p) + '</option>';- });+ var pr = state.profile;+ if (!store.loaded.session) {+ setViewHtml(el, skeleton(10));+ return;}- html += '</select></div>';- html += '<div id="profile-content"></div>';- el.innerHTML = html;-- document.getElementById('profile-project').addEventListener('change', function() {- state.profile.selectedProject = this.value;- loadProfileData();+ var projects = profileProjects();+ if (projects.length === 0) {+ setViewHtml(el, emptyState({+ icon: '📋',+ title: 'No projects yet',+ what: 'A project profile ' + help('profile') + ' sums up what agentmemory learned about one codebase: the concepts and files that come up most, the conventions it noticed, recurring errors and recent highlights. Agents get it as context at session start.',+ why: 'Profiles are built from sessions, and no session with a project has been recorded yet.',+ steps: [+ { label: 'Connect your agent with hooks and run it inside a project (swap in codex, cursor, gemini-cli or another supported agent):', cmd: connectCmd() },+ { label: 'Or start a session by hand:', cmd: curlPost('session/start', { sessionId: 'demo-1', project: 'my-project', cwd: '/path/to/project' }) }+ ]+ }));+ return;+ }+ var names = projects.map(function(p) { return p.project; });+ if (!pr.selectedProject || names.indexOf(pr.selectedProject) < 0 || (!pr.userPicked && pr.selectedProject !== names[0])) {+ pr.selectedProject = names[0];+ ensureProfileData();+ }+ var html = '<div class="inline-note">A project profile ' + help('profile') + ' is what agentmemory learned about one codebase from its sessions and memories. Agents get it as context at session start. It opens on the project an agent worked in most recently.</div>';+ html += '<div class="toolbar"><select id="profile-project" aria-label="Project">';+ projects.forEach(function(p) {+ html += '<option value="' + esc(p.project) + '"' + (pr.selectedProject === p.project ? ' selected' : '') + '>' + esc(p.project) + ' · ' + p.count + ' session' + (p.count === 1 ? '' : 's') + ' · active ' + esc(timeAgo(p.lastAt) || '-') + '</option>';});+ html += '</select>';+ html += '<button type="button" class="btn" data-action="profile-rebuild"' + (pr.loadingProject ? ' disabled' : '') + ' title="Rebuild the profile from the latest sessions and memories now instead of using the cached copy">' + (pr.loadingProject ? 'Building…' : 'Rebuild') + '</button>';+ html += copyBtn('memory_profile { "project": ' + JSON.stringify(pr.selectedProject) + ' }', 'MCP call').replace('>copy<', '>copy MCP call<');+ html += copyBtn(curlGet('profile?project=' + encodeURIComponent(pr.selectedProject)), 'curl command').replace('>copy<', '>copy curl<');+ html += '</div><div id="profile-content"></div>';+ setViewHtml(el, html);+ var sel = document.getElementById('profile-project');+ if (sel && !sel.__bound) {+ sel.__bound = true;+ sel.addEventListener('change', function() {+ state.profile.selectedProject = this.value;+ state.profile.userPicked = true;+ ensureProfileData();+ renderProfilePage();+ });+ }+ renderProfile();}- async function loadProfileData() {- var content = document.getElementById('profile-content');- if (!content || !state.profile.selectedProject) return;- content.innerHTML = '<div class="loading">Loading profile data...</div>';- var result = await apiGet('profile?project=' + encodeURIComponent(state.profile.selectedProject));- state.profile.data = (result && result.profile) ? result.profile : result;+ async function ensureProfileData(refresh) {+ var pr = state.profile;+ var project = pr.selectedProject;+ if (!project || pr.loadingProject === project || (!refresh && pr.dataProject === project)) return;+ pr.loadingProject = project;+ if (!refresh) pr.data = null;renderProfile();+ var result = await apiGet('profile?project=' + encodeURIComponent(project) + (refresh ? '&refresh=true' : ''));+ pr.loadingProject = '';+ if (pr.selectedProject !== project) return;+ pr.dataProject = project;+ pr.data = result && result.profile !== undefined ? result.profile : result;+ pr.cached = !!(result && result.cached);+ pr.notice = refresh ? (result ? { html: 'Rebuilt just now from the latest sessions and memories.' } : { err: true, html: 'Rebuild failed. Check that agentmemory is running.' }) : null;+ if (state.activeTab === 'profile') renderProfilePage();+ }++ function profileBarsHtml(items, labelFn, titleFn, color, action, attr) {+ var max = Math.max.apply(null, items.map(function(x) { return x.frequency; })) || 1;+ return '<div class="bar-chart">' + items.map(function(x) {+ var label = labelFn(x);+ var inner = '<span class="bar-label">' + esc(label) + '</span><span class="bar-track"><span class="bar-fill" style="display:block;width:' + Math.round((x.frequency / max) * 100) + '%;background:' + color + ';"></span></span><span class="bar-value">' + x.frequency + '</span>';+ if (!action) return '<div class="bar-row" title="' + esc(titleFn(x)) + '">' + inner + '</div>';+ return '<button type="button" class="bar-row linkrow" data-action="' + action + '" ' + attr + '="' + esc(label) + '" title="' + esc(titleFn(x)) + '">' + inner + '</button>';+ }).join('') + '</div>';}function renderProfile() {var content = document.getElementById('profile-content');if (!content) return;- var p = state.profile.data;-+ var pr = state.profile;+ var p = pr.data;+ var project = pr.selectedProject;+ var info = profileProjects().filter(function(x) { return x.project === project; })[0] || {};if (!p) {- content.innerHTML = '<div class="empty-state"><div class="empty-icon">📋</div><p>No profile data for this project</p></div>';+ if (pr.loadingProject || pr.dataProject !== project) { setViewHtml(content, skeleton(8)); return; }+ setViewHtml(content, emptyState({+ icon: '📋',+ title: 'No profile for this project yet',+ what: 'The profile lists top concepts, files, conventions, recurring errors and recent highlights for ' + esc(project) + '.',+ why: 'agentmemory found no sessions for this project on the server, so there is nothing to build it from.',+ steps: [{ label: 'Build it from a terminal to see the raw answer:', cmd: curlGet('profile?project=' + encodeURIComponent(project) + '&refresh=true') }]+ }));return;}-- var html = '<div class="two-col">';-- html += '<div class="card"><div class="card-title">Top Concepts</div>';- var concepts = p.topConcepts || [];- if (concepts.length === 0) {- html += '<div style="font-size:13px;color:var(--ink-faint);line-height:1.5;">No concepts yet. Concepts are tagged when observations are compressed by an LLM (<code>AGENTMEMORY_AUTO_COMPRESS=true</code> + provider key) or attached to saved memories.</div>';+ var html = '';+ if (pr.notice) html += '<div class="inline-status' + (pr.notice.err ? ' err' : ' ok') + '" role="status">' + pr.notice.html + '</div>';+ html += '<div class="prof-cols">';+ html += '<div class="card"><div class="card-title">Top concepts</div>';+ var concepts = (p.topConcepts || []).slice(0, 10);+ if (!concepts.length) {+ html += '<p class="empty-step-label">No concepts yet. Concepts come from the tags on saved memories and from observations compressed by an LLM (<code>AGENTMEMORY_AUTO_COMPRESS=true</code> with a provider key). Save a memory with concepts to start:</p>' + cmdBlock(curlPost('remember', { content: 'Checkout totals apply coupons first', type: 'bug', project: project, concepts: ['pricing', 'checkout'] }));} else {- var maxC = Math.max.apply(null, concepts.map(function(c) { return c.frequency; })) || 1;- html += '<div class="bar-chart">';- concepts.slice(0, 10).forEach(function(c) {- var pct = Math.round((c.frequency / maxC) * 100);- html += '<div class="bar-row"><span class="bar-label">' + esc(c.concept) + '</span><div class="bar-track"><div class="bar-fill" style="width:' + pct + '%;background:var(--yellow);"></div></div><span class="bar-value">' + c.frequency + '</span></div>';- });- html += '</div>';+ html += profileBarsHtml(concepts, function(c) { return c.concept; }, function(c) { return 'Search memories for ' + c.concept; }, 'var(--yellow)', 'profile-concept', 'data-concept');+ html += '<div class="hnote">Counted over memories and the last 20 sessions. Pick one to search memories for it.</div>';}html += '</div>';-- html += '<div class="card"><div class="card-title">Top Files</div>';- var files = p.topFiles || [];- if (files.length === 0) {- html += '<div style="font-size:13px;color:var(--ink-faint);font-style:italic;">No files yet</div>';+ html += '<div class="card"><div class="card-title">Top files</div>';+ var files = (p.topFiles || []).slice(0, 10);+ if (!files.length) {+ html += '<p class="empty-step-label">No file activity recorded for this project yet. Files appear once agents read or edit them during a captured session; search directories and patterns are not counted.</p>';} else {- var maxF = Math.max.apply(null, files.map(function(f) { return f.frequency; })) || 1;- html += '<div class="bar-chart">';- files.slice(0, 10).forEach(function(f) {- var pct = Math.round((f.frequency / maxF) * 100);- html += '<div class="bar-row"><span class="bar-label">' + esc(f.file.split('/').pop()) + '</span><div class="bar-track"><div class="bar-fill" style="width:' + pct + '%;background:var(--green);"></div></div><span class="bar-value">' + f.frequency + '</span></div>';- });- html += '</div>';+ html += profileBarsHtml(files, function(f) { return relPath(f.file, info.cwd); }, function(f) { return f.file + ' (' + f.frequency + ' observations)'; }, 'var(--green)', '', '');+ html += '<div class="hnote">Files read, edited or written in the last 20 sessions, relative to ' + esc(info.cwd || 'the project') + '.</div>';}- html += '</div>';-- html += '</div>';+ html += '</div></div>';- html += '<div class="card" style="margin-top:16px;"><div class="card-title">Conventions</div>';+ html += '<div class="prof-cols" style="margin-top:16px;">';+ html += '<div class="card"><div class="card-title">Conventions ' + help('conventions') + '</div>';var conventions = p.conventions || [];- if (conventions.length === 0) {- html += '<div style="font-size:13px;color:var(--ink-faint);font-style:italic;">No conventions detected yet</div>';+ if (!conventions.length) {+ html += '<p class="empty-step-label"><b>None detected yet.</b> ' + (files.length || concepts.length ? 'None of the patterns show up often enough in this project yet.' : 'This project has no file activity or concepts yet, so there is nothing to infer from.') + ' agentmemory infers conventions from the files and concepts above: TypeScript when .ts files outnumber .js, a src/ layout when most files sit under src/, tests when test or spec files appear, and any concept seen 3 or more times.</p>';+ html += '<div class="empty-step-label" style="margin-top:8px;">Record a convention you already know as a preference memory; agents recall it with the rest:</div>' + cmdBlock(curlPost('remember', { content: 'Use named CSS grid areas in checkout', type: 'preference', project: project }));} else {- html += '<ul style="padding-left:16px;">';- conventions.forEach(function(c) { html += '<li style="font-size:13px;color:var(--ink-muted);margin-bottom:4px;">' + esc(c) + '</li>'; });- html += '</ul>';+ html += '<ul class="ses-links">' + conventions.map(function(c) { return '<li><span class="badge badge-muted">rule</span>' + esc(c) + '</li>'; }).join('') + '</ul>';+ html += '<div class="hnote" style="margin-top:8px;">Inferred from the files and concepts above, not written by an agent. Preferences you save as memories sit on the Memories page.</div>';}html += '</div>';+ html += '<div class="card"><div class="card-title">At a glance</div><dl class="mem-meta">';+ html += '<dt>Sessions ' + help('session') + '</dt><dd><button type="button" class="linkish" data-action="profile-sessions">' + fmtNum(p.sessionCount || 0) + ' sessions</button>' + (info.lastAt ? ', last active ' + relTime(info.lastAt) : '') + '</dd>';+ html += '<dt>Observations ' + help('observation') + '</dt><dd>' + fmtNum(p.totalObservations || 0) + ' in the last ' + Math.min(20, p.sessionCount || 0) + ' sessions</dd>';+ var memFacet = ((state.memories.facets || {}).projects || []).filter(function(x) { return x.value === project; })[0];+ if (memFacet) html += '<dt>Memories ' + help('memory') + '</dt><dd><button type="button" class="linkish" data-action="profile-memories">' + fmtNum(memFacet.count) + ' memories</button></dd>';+ var lessonCount = entityList('lesson').filter(function(l) { return !l.deleted && l.project === project; }).length;+ if (store.loaded.lesson) html += '<dt>Lessons ' + help('lesson') + '</dt><dd>' + fmtNum(lessonCount) + '</dd>';+ if (info.cwd) html += '<dt>Directory</dt><dd><code>' + esc(info.cwd) + '</code></dd>';+ html += '<dt>Profile built</dt><dd>' + relTime(p.updatedAt) + (pr.cached ? ' <span class="hnote" style="display:inline;">cached for up to an hour; Rebuild refreshes it</span>' : '') + '</dd>';+ html += '</dl>';+ if (p.summary) html += '<p class="ses-summary" style="margin-top:10px;">' + esc(summaryText(p.summary)) + '</p>';+ html += '</div></div>';- if (p.summary) {- html += '<div class="card" style="margin-top:16px;"><div class="card-title">Project Summary</div>';- html += '<p style="font-size:13px;color:var(--ink-muted);line-height:1.7;">' + esc(summaryText(p.summary)) + '</p></div>';+ var errors = p.commonErrors || [];+ var recent = p.recentActivity || [];+ html += '<div class="prof-cols" style="margin-top:16px;">';+ html += '<div class="card"><div class="card-title">Recurring errors</div>';+ html += errors.length ? '<ul class="ses-links">' + errors.map(function(e) { return '<li><span class="badge badge-red">error</span>' + esc(e) + '</li>'; }).join('') + '</ul>' : '<p class="empty-step-label">No errors recorded in the last 20 sessions. Failed tool calls land here once the same kind of error shows up.</p>';+ html += '</div>';+ html += '<div class="card"><div class="card-title">Recent highlights ' + help('importance') + '</div>';+ html += recent.length ? '<ul class="ses-links">' + recent.map(function(r) {+ var m = /^\[(\d{4}-\d{2}-\d{2})\]\s*(.*)$/.exec(r);+ return '<li>' + (m ? '<span class="rel-time">' + esc(m[1]) + '</span>' + esc(m[2]) : esc(r)) + '</li>';+ }).join('') + '</ul>' : '<p class="empty-step-label">The most important observation of each recent session shows here once one is rated 7 or higher. Ratings come from LLM compression; without it every observation gets the default 5.</p>';+ html += '</div></div>';+ setViewHtml(content, html);+ }++ function handleProfileAction(action, target) {+ var project = state.profile.selectedProject;+ if (action === 'profile-rebuild') { ensureProfileData(true); renderProfilePage(); return; }+ if (action === 'profile-concept') {+ var concept = target.getAttribute('data-concept') || '';+ state.memories.search = concept;+ state.memories.projectFilter = project;+ switchTab('memories');+ var input = document.getElementById('mem-search');+ if (input) input.value = concept;+ runMemorySearch(concept);+ return;+ }+ if (action === 'profile-memories') {+ state.memories.projectFilter = project;+ switchTab('memories');+ applyMemoryFilters();+ return;+ }+ if (action === 'profile-sessions') {+ state.sessions.filters.project = project;+ switchTab('sessions');+ applySessionFilters();}-- var stats = '<div class="card" style="margin-top:16px;"><div class="card-title">Project Stats</div>';- stats += '<div class="detail-row"><div class="dl">Sessions</div><div class="dv" style="font-family:var(--font-mono);">' + (p.sessionCount || 0) + '</div></div>';- stats += '<div class="detail-row"><div class="dl">Total Obs</div><div class="dv" style="font-family:var(--font-mono);">' + (p.totalObservations || 0) + '</div></div>';- stats += '<div class="detail-row"><div class="dl">Updated</div><div class="dv" style="font-family:var(--font-mono);font-size:12px;">' + esc(formatTime(p.updatedAt)) + '</div></div>';- stats += '</div>';-- content.innerHTML = html + stats;}var wsReconnectTimer = null;var wsRetries = 0;- var WS_MAX_RETRIES = 4;var directFailed = true;var directFailures = 0;var wsHasConnected = false;+ var wsOpenedAt = null;var DIRECT_FAILURE_THRESHOLD = 2;- var pollTimer = null;- var POLL_INTERVAL_MS = 10000;+ var OFFLINE_AFTER_RETRIES = 3;+ var HEALTH_STALE_MS = 90000;+ var conn = { state: 'connecting', nextRetryAt: 0, lostAt: 0 };++ function reconnectDelay(attempt) {+ var n = Math.max(1, attempt || 1);+ return Math.min(30000, 1000 * Math.pow(2, n - 1));+ }function setWsStatus(text, cls) {var el = document.getElementById('ws-status');@@ -4027,126 +7584,185 @@el.className = 'ws-status ' + cls;}- var WS_REPROBE_EVERY_TICKS = 6;-- function startPolling() {- if (pollTimer) return;- setWsStatus('polling · ' + (POLL_INTERVAL_MS / 1000) + 's', 'disconnected');- var tick = 0;- pollTimer = setInterval(function() {- tick++;- if (state.activeTab === 'dashboard') {- loadDashboard();- } else if (state.activeTab === 'memories') {- loadMemories();- } else if (state.activeTab === 'sessions') {- loadSessions();- } else if (state.activeTab === 'activity') {- loadActivity();- }- if (tick % WS_REPROBE_EVERY_TICKS === 0) {- var ws = state.ws;- if (!ws || ws.readyState !== WebSocket.OPEN) {- wsRetries = 0;- directFailures = 0;- directFailed = true;- connectWs();- }+ function setConnection(next) {+ conn.state = next;+ if (next === 'live') conn.lostAt = 0;+ else if (!conn.lostAt && wsHasConnected) conn.lostAt = Date.now();+ document.body.classList.toggle('is-stale', next !== 'live' && next !== 'connecting');+ renderConnection();+ if (store.snapshot) {+ markDirty(['health']);+ if (state.activeTab === 'health') renderTab('health');+ }+ }++ function renderConnection() {+ var secs = conn.nextRetryAt ? Math.max(0, Math.ceil((conn.nextRetryAt - Date.now()) / 1000)) : 0;+ var healthStale = conn.state === 'live' && store.lastHealthAt && Date.now() - store.lastHealthAt > HEALTH_STALE_MS;+ if (conn.state === 'live') setWsStatus(healthStale ? 'live · health quiet' : 'live', healthStale ? 'stale-health' : 'connected');+ else if (conn.state === 'connecting') setWsStatus('connecting', 'connecting');+ else if (conn.state === 'reconnecting') setWsStatus('reconnecting' + (secs ? ' · ' + secs + 's' : ''), 'reconnecting');+ else setWsStatus('offline' + (secs ? ' · retry ' + secs + 's' : ''), 'offline');+ var chip = document.getElementById('ws-status');+ if (chip) chip.title = healthStale+ ? 'Connected, but no health update arrived for ' + Math.round((Date.now() - store.lastHealthAt) / 1000) + 's. The worker may be busy.'+ : GLOSSARY.live.text;+ var banner = document.getElementById('offline-banner');+ if (!banner) return;+ var showBanner = conn.state === 'reconnecting' || conn.state === 'offline';+ if (!showBanner) { banner.hidden = true; banner.innerHTML = ''; return; }+ var asOf = store.snapshotAt ? new Date(conn.lostAt || store.snapshotAt).toLocaleTimeString() : '';+ banner.hidden = false;+ banner.className = 'offline-banner' + (conn.state === 'offline' ? ' offline' : '');+ banner.innerHTML = '<strong>' + (conn.state === 'offline' ? 'agentmemory is unreachable.' : 'Live updates paused.') + '</strong>' ++ '<span>' + (asOf ? 'Showing data as of ' + esc(asOf) + '.' : 'No data loaded yet.') + ' ' + (secs ? 'Next reconnect attempt in ' + secs + 's.' : 'Reconnecting now.') + '</span>' ++ (conn.state === 'offline' ? '<span style="color:var(--ink-muted);">Check that the server is running:</span>' + cmdBlock('npx @agentmemory/agentmemory status') : '') ++ '<button class="btn" data-action="reconnect-now">Reconnect now</button>';+ }++ var healthStaleTimer = null;+ function scheduleHealthStaleCheck() {+ if (healthStaleTimer) clearTimeout(healthStaleTimer);+ healthStaleTimer = setTimeout(function() {+ healthStaleTimer = null;+ renderConnection();+ markDirty(['health', 'dashboard']);+ if (state.activeTab === 'health' || state.activeTab === 'dashboard') renderTab(state.activeTab);+ }, HEALTH_STALE_MS + 1000);+ }++ var countdownTimer = null;+ function scheduleCountdown() {+ if (countdownTimer) return;+ countdownTimer = setTimeout(function() {+ countdownTimer = null;+ if (conn.state === 'reconnecting' || conn.state === 'offline') {+ renderConnection();+ scheduleCountdown();}- }, POLL_INTERVAL_MS);+ }, 1000);+ }++ function scheduleReconnect() {+ wsRetries++;+ var delay = reconnectDelay(wsRetries);+ conn.nextRetryAt = Date.now() + delay;+ setConnection(wsRetries >= OFFLINE_AFTER_RETRIES ? 'offline' : 'reconnecting');+ scheduleCountdown();+ if (wsReconnectTimer) clearTimeout(wsReconnectTimer);+ wsReconnectTimer = setTimeout(connectWs, delay);}- function stopPolling() {- if (!pollTimer) return;- clearInterval(pollTimer);- pollTimer = null;+ function reconnectNow() {+ if (wsReconnectTimer) clearTimeout(wsReconnectTimer);+ wsReconnectTimer = null;+ directFailures = 0;+ directFailed = true;+ conn.nextRetryAt = 0;+ var ws = state.ws;+ if (ws && (ws.readyState === WebSocket.OPEN || ws.readyState === WebSocket.CONNECTING)) return;+ connectWs();}var WS_CONNECT_TIMEOUT_MS = 5000;function connectWs() {- if (wsRetries >= WS_MAX_RETRIES) {- startPolling();- return;- }+ wsReconnectTimer = null;+ conn.nextRetryAt = 0;var useDirect = !directFailed;var ws;try {ws = new WebSocket(useDirect ? WS_DIRECT_URL : WS_URL);ws.__direct = useDirect;} catch (_) {- ws = new WebSocket(WS_URL);- ws.__direct = false;+ scheduleReconnect();+ return;}var connectTimer = setTimeout(function() {if (ws.readyState === WebSocket.CONNECTING) {- try { ws.close(); } catch {}- }- }, WS_CONNECT_TIMEOUT_MS);- try {- ws.onopen = function() {- clearTimeout(connectTimer);- if (state.ws !== ws) return;- wsRetries = 0;- stopPolling();- if (wsHasConnected) resyncLiveViews();- wsHasConnected = true;- if (!ws.__direct) {- ws.send(JSON.stringify({- type: 'join',- data: {- subscriptionId: 'viewer-' + Date.now(),- streamName: 'mem-live',- groupId: 'viewer'- }- }));- }- setWsStatus('live', 'connected');- };- ws.onmessage = function(e) {- if (state.ws !== ws) return;- if (!ws.__usable) {- ws.__usable = true;- directFailures = 0;- }- try {- var msg = JSON.parse(e.data);- if (msg.type === 'stream' && msg.event) {- handleStreamEvent(msg);- } else if (msg.event_type && msg.data) {- handleStreamEvent({ event: { type: 'create', data: msg.data, event_type: msg.event_type } });+ try { ws.close(); } catch {}+ }+ }, WS_CONNECT_TIMEOUT_MS);+ ws.onopen = function() {+ clearTimeout(connectTimer);+ if (state.ws !== ws) return;+ wsRetries = 0;+ if (!ws.__direct) {+ ws.send(JSON.stringify({+ type: 'join',+ data: {+ subscriptionId: 'viewer-' + Date.now(),+ streamName: 'mem-live',+ groupId: 'viewer'}- } catch {}- };- ws.onclose = function() {- clearTimeout(connectTimer);- if (state.ws !== ws) return;- directFailures += 1;- if (directFailures >= DIRECT_FAILURE_THRESHOLD) {- directFailed = ws.__direct;- directFailures = 0;+ }));+ }+ var firstConnect = !wsHasConnected;+ wsHasConnected = true;+ wsOpenedAt = Date.now();+ setConnection('live');+ updateFooter();+ resyncAfterConnect(firstConnect);+ };+ ws.onmessage = function(e) {+ if (state.ws !== ws) return;+ if (!ws.__usable) {+ ws.__usable = true;+ directFailures = 0;+ }+ store.lastEventAt = Date.now();+ try {+ var msg = JSON.parse(e.data);+ if (msg.type === 'stream' && msg.event) {+ handleStreamEvent(msg);+ } else if (msg.event_type && msg.data) {+ handleStreamEvent({ event: { type: 'create', data: msg.data, event_type: msg.event_type } });}- wsRetries++;- if (wsRetries < WS_MAX_RETRIES) {- setWsStatus('connecting...', 'disconnected');- wsReconnectTimer = setTimeout(connectWs, 2000 + Math.min(wsRetries * 1000, 8000));- } else {- startPolling();+ } catch {}+ };+ ws.onclose = function() {+ clearTimeout(connectTimer);+ if (state.ws !== ws) return;+ wsOpenedAt = null;+ updateFooter();+ directFailures += 1;+ if (directFailures >= DIRECT_FAILURE_THRESHOLD) {+ directFailed = ws.__direct;+ directFailures = 0;+ }+ scheduleReconnect();+ };+ ws.onerror = function() {+ if (state.ws !== ws) return;+ try { ws.close(); } catch {}+ };+ state.ws = ws;+ }++ var resyncing = null;+ async function resyncAfterConnect(firstConnect) {+ openBootGate();+ if (resyncing) return resyncing;+ var reloadKinds = Object.keys(store.loaded).filter(function(k) { return store.loaded[k]; });+ resyncing = (async function() {+ try {+ await loadSnapshot();+ scheduleHealthStaleCheck();+ if (!firstConnect || reloadKinds.length) {+ reloadKinds.forEach(function(k) { store.loaded[k] = false; });+ await Promise.all(reloadKinds.map(ensureLoaded));+ state.graph.dirty = state.graph.loaded;+ state.activity.loaded = false;+ frontierStale = true;+ TAB_IDS.forEach(function(t) { tabDirty[t] = true; });}- };- ws.onerror = function() {- if (state.ws !== ws) return;- try { ws.close(); } catch {}- };- state.ws = ws;- } catch {- wsRetries++;- if (wsRetries < WS_MAX_RETRIES) {- wsReconnectTimer = setTimeout(connectWs, 2000 + Math.min(wsRetries * 1000, 8000));- } else {- startPolling();+ showTab(state.activeTab);+ updateFooter();+ } finally {+ resyncing = null;}- }+ })();+ return resyncing;}var LIVE_BUFFER_MAX = 200;@@ -4159,90 +7775,188 @@return s && (s.id || s.sessionId);}- function upsertSessionIn(list, session) {- var key = sessionKey(session);- if (!key) return list;- var index = list.findIndex(function(s) { return sessionKey(s) === key; });- if (index >= 0) list[index] = Object.assign({}, list[index], session);- else list.unshift(session);- return list;- }-- function removeSessionFrom(list, key) {- return list.filter(function(s) { return sessionKey(s) !== key; });- }-- function patchSessionCount(list, key, count) {- list.forEach(function(s) {- if (sessionKey(s) === key) s.observationCount = count;- });+ function entityKey(kind, row) {+ if (!row) return '';+ if (kind === 'session') return sessionKey(row) || '';+ return row.id || '';}- var LIVE_SESSION_LOG_MAX = 500;- var liveSessionLog = [];- var liveSessionSeq = 0;-- function applySessionEvent(list, entry) {- if (entry.type === 'session.updated') return upsertSessionIn(list, entry.data.session);- if (entry.type === 'session.deleted') return removeSessionFrom(list, entry.data.sessionId);- patchSessionCount(list, entry.data.sessionId, entry.data.observationCount);- return list;- }+ function applyEntityEvent(entities, kind, action, id, row) {+ var bucket = entities[kind];+ if (!bucket || !id) return false;+ var gone = action === 'deleted' || !row || (kind === 'lesson' && row.deleted === true);+ if (gone) {+ if (!bucket[id]) return false;+ delete bucket[id];+ return true;+ }+ bucket[id] = Object.assign({}, bucket[id] || {}, row);+ return true;+ }++ var ROW_EVENT_KINDS = ['lesson', 'action', 'crystal', 'semantic', 'procedural', 'audit'];++ function reduceLiveEvent(s, type, data) {+ var dot = type.indexOf('.');+ var kind = dot > 0 ? type.slice(0, dot) : type;+ var action = dot > 0 ? type.slice(dot + 1) : '';+ data = data || {};+ if (kind === 'memory') {+ var memId = data.memoryId || (data.memory && data.memory.id) || '';+ var memRow = action === 'deleted' ? null : (data.memory || null);+ if (!memRow && action !== 'deleted') return null;+ applyEntityEvent(s.entities, 'memory', action, memId, memRow);+ return { kind: 'memory', id: memId, action: action, row: memRow };+ }+ if (ROW_EVENT_KINDS.indexOf(kind) >= 0) {+ var row = action === 'deleted' ? null : (data[kind] || null);+ applyEntityEvent(s.entities, kind, action, data.id, row);+ return { kind: kind, id: data.id, action: action, row: row };+ }+ if (kind === 'session') {+ if (action === 'updated' && data.session) {+ var sid = sessionKey(data.session);+ applyEntityEvent(s.entities, 'session', 'updated', sid, data.session);+ return { kind: 'session', id: sid, action: 'updated', row: data.session };+ }+ if (action === 'deleted' && data.sessionId) {+ applyEntityEvent(s.entities, 'session', 'deleted', data.sessionId, null);+ return { kind: 'session', id: data.sessionId, action: 'deleted', row: null };+ }+ if (action === 'activity' && data.sessionId) {+ var existing = s.entities.session[data.sessionId];+ if (existing) {+ existing.observationCount = data.observationCount;+ if (data.updatedAt) existing.updatedAt = data.updatedAt;+ }+ return { kind: 'session', id: data.sessionId, action: 'activity', row: existing || null };+ }+ return null;+ }+ if (type === 'counts.changed' && data.counts) {+ s.counts = data.counts;+ return { kind: 'counts' };+ }+ if (type === 'health') {+ s.status = data.status || s.status;+ if (data.health) s.health = data.health;+ if (data.circuitBreaker !== undefined) s.circuitBreaker = data.circuitBreaker;+ if (Array.isArray(data.functionMetrics)) s.functionMetrics = data.functionMetrics;+ if (data.counts) s.counts = data.counts;+ if (data.indexes) s.indexes = data.indexes;+ if (data.report) s.report = data.report;+ s.lastHealthAt = Date.now();+ return { kind: 'health' };+ }+ if (type === 'graph.changed') {+ if (data.source === 'snapshot') {+ s.graph = { stats: data.stats || null, updatedAt: data.updatedAt, resetAt: data.resetAt || null };+ }+ return { kind: 'graph', source: data.source };+ }+ if (type === 'consolidation.run') {+ s.consolidation = { lastRun: data.lastRun || null };+ if (data.status) s.consolidationStatus = data.status;+ return { kind: 'consolidation' };+ }+ return null;+ }++ var KIND_TABS = {+ memory: ['memories', 'dashboard'],+ session: ['sessions', 'dashboard', 'profile', 'activity', 'replay'],+ lesson: ['lessons', 'crystals', 'sessions'],+ action: ['actions'],+ crystal: ['crystals', 'sessions'],+ semantic: ['dashboard', 'health'],+ procedural: ['dashboard', 'health'],+ audit: ['audit', 'dashboard'],+ counts: ['dashboard', 'memories', 'sessions', 'health'],+ health: ['dashboard', 'health'],+ graph: ['graph', 'dashboard', 'health'],+ consolidation: ['dashboard', 'health']+ };- function replaySessionEvents(list, sinceSeq) {- liveSessionLog.forEach(function(entry) {- if (entry.seq > sinceSeq) list = applySessionEvent(list, entry);+ function feedPush(item) {+ item.fresh = true;+ item.at = item.at || new Date().toISOString();+ store.feed.unshift(item);+ if (store.feed.length > FEED_MAX) store.feed.length = FEED_MAX;+ }++ function auditFeedItem(a) {+ var ids = a.targetIds || [];+ var name = ids.length === 1 ? recordName(ids[0]) : '';+ var targets = name ? '“' + truncate(name, 70) + '”' : ids.length > 1 ? auditTargetSummary(ids) : '';+ var first = ids[0];+ var kind = first && (a.targetIds.length === 1) ? idKind(first) : '';+ var link = kind && kind !== 'observation' ? { kind: kind, id: first } : { kind: 'audit', id: a.id };+ return { at: a.timestamp, tag: String(a.operation || 'audit').replace(/_/g, ' '), badge: OP_BADGES[a.operation] || 'badge-muted', text: auditVerb(a.operation) + (targets ? ': ' + targets : ''), kind: link.kind, id: link.id };+ }++ function seedFeedFromAudit() {+ if (store.feed.length > 0) return;+ sortByTimeDesc(entityList('audit'), ['timestamp']).slice(0, 15).forEach(function(a) {+ var item = auditFeedItem(a);+ item.fresh = false;+ store.feed.push(item);});- return list;- }-- var memoryCountTimer = null;- var memoryCountRequest = 0;- function refreshMemoryCount() {- if (memoryCountTimer) return;- memoryCountTimer = setTimeout(async function() {- memoryCountTimer = null;- var request = ++memoryCountRequest;- var result = await apiGet('memories?latest=true&count=true');- if (request !== memoryCountRequest) return;- if (result && typeof result.total === 'number') {- state.dashboard.memoryTotal = result.total;- if (state.activeTab === 'dashboard' && state.dashboard.loaded) renderDashboard();- }- }, 500);}- var memoriesReloadTimer = null;- var memoriesReloading = false;- var memoriesReloadPending = false;- function scheduleMemoriesReload() {- if (memoriesReloading) {- memoriesReloadPending = true;+ function feedFromChange(change) {+ if (!change || !change.row) {+ if (change && change.kind === 'memory' && change.action === 'deleted') feedPush({ tag: 'forget', badge: 'badge-red', text: 'Memory deleted' });return;}- if (memoriesReloadTimer) return;- memoriesReloadTimer = setTimeout(async function() {- memoriesReloadTimer = null;- if (state.activeTab !== 'memories') return;- memoriesReloading = true;- try {- await loadMemories();- } finally {- memoriesReloading = false;- if (memoriesReloadPending) {- memoriesReloadPending = false;- scheduleMemoriesReload();- }- }- }, 500);+ var r = change.row;+ if (change.kind === 'memory' && change.action === 'created') feedPush({ tag: 'memory', badge: 'badge-green', text: truncate(r.title || r.content || 'Memory saved', 90), kind: 'memory', id: change.id });+ else if (change.kind === 'lesson' && change.action === 'created') feedPush({ tag: 'lesson', badge: 'badge-purple', text: truncate(r.content || 'Lesson learned', 90), kind: 'lesson', id: change.id });+ else if (change.kind === 'action' && change.action === 'created') feedPush({ tag: 'action', badge: 'badge-yellow', text: truncate(r.title || 'Action created', 90), kind: 'action', id: change.id });+ else if (change.kind === 'crystal' && change.action === 'created') feedPush({ tag: 'crystal', badge: 'badge-cyan', text: truncate(r.narrative || 'Crystal saved', 90), kind: 'crystal', id: change.id });+ else if (change.kind === 'audit' && change.action === 'created') feedPush(auditFeedItem(r));+ else if (change.kind === 'session' && change.action === 'updated') {+ var label = r.status === 'completed' ? 'Session ended' : 'Session running';+ feedPush({ tag: 'session', badge: r.status === 'active' ? 'badge-green' : 'badge-blue', text: label + ': ' + sessionDisplayName(r), kind: 'session', id: change.id });+ }+ }++ function recordEvent(type, data) {+ var dot = type.indexOf('.');+ var entry = { seq: ++eventSeq, type: type, kind: dot > 0 ? type.slice(0, dot) : type, data: data };+ eventLog.push(entry);+ if (eventLog.length > EVENT_LOG_MAX) eventLog.shift();+ return entry;}- function resyncLiveViews() {- if (state.dashboard.loaded) loadDashboard();- if (state.sessions.loaded) loadSessions();- tabFetchedAt.memories = 0;- if (state.memories.loaded) scheduleMemoriesReload();- refreshMemoryCount();+ function handleLiveEvent(type, data) {+ recordEvent(type, data);+ var memPrev = null;+ if (type.indexOf('memory.') === 0 && data) {+ var memPrevId = data.memoryId || (data.memory && data.memory.id);+ if (memPrevId && store.entities.memory[memPrevId]) memPrev = Object.assign({}, store.entities.memory[memPrevId]);+ }+ var sesPrev = null;+ if ((type === 'session.updated' || type === 'session.deleted') && data) {+ var sesPrevId = type === 'session.deleted' ? data.sessionId : sessionKey(data.session);+ if (sesPrevId && store.entities.session[sesPrevId]) sesPrev = Object.assign({}, store.entities.session[sesPrevId]);+ }+ var change = reduceLiveEvent(store, type, data);+ if (!change) return;+ if (change.kind === 'memory') {+ noteMemoryChange(memPrev, store.entities.memory[change.id] || null, change.id);+ noteSessionProduced(change);+ }+ if (change.kind === 'audit' && change.action === 'created') state.audit.fresh[change.id] = Date.now();+ if ((change.kind === 'lesson' || change.kind === 'action' || change.kind === 'crystal') && change.action !== 'deleted' && change.id) state.freshRows[change.id] = Date.now();+ if (change.kind === 'session' && change.action !== 'activity') adjustSessionFacets(sesPrev, change.row);+ if (change.kind !== 'session' || change.action !== 'activity') feedFromChange(change);+ if (change.kind === 'action') frontierStale = true;+ if (change.kind === 'graph') handleGraphChange(data);+ if (change.kind === 'consolidation' && !store.consolidationStatus) ensureConsolidationStatus(true);+ if (change.kind === 'health') scheduleHealthStaleCheck();+ if (change.kind === 'counts' || change.kind === 'health') updateCountBadges();+ markDirty(KIND_TABS[change.kind] || []);+ if (state.activeTab === 'dashboard') markDirty(['dashboard']);}var LIVE_RENDER_THROTTLE_MS = 250;@@ -4251,32 +7965,17 @@if (pendingLiveRender) return;pendingLiveRender = setTimeout(function() {pendingLiveRender = null;- if (state.activeTab === 'dashboard' && state.dashboard.loaded) renderDashboard();- if (state.activeTab === 'sessions' && state.sessions.loaded) renderSessions();+ if (tabDirty[state.activeTab]) renderTab(state.activeTab);+ if (state.activeTab === 'actions') ensureFrontier();}, LIVE_RENDER_THROTTLE_MS);}- function handleLiveEvent(type, data) {- if (type === 'memory.updated' || type === 'memory.deleted') {- refreshMemoryCount();- tabFetchedAt.memories = 0;- scheduleMemoriesReload();- return;- }- var isSessionEvent =- (type === 'session.updated' && data.session && sessionKey(data.session)) ||- ((type === 'session.activity' || type === 'session.deleted') && data.sessionId);- if (!isSessionEvent) return;- var entry = { seq: ++liveSessionSeq, type: type, data: data };- liveSessionLog.push(entry);- if (liveSessionLog.length > LIVE_SESSION_LOG_MAX) liveSessionLog.shift();- state.dashboard.sessions = applySessionEvent(state.dashboard.sessions, entry);- state.sessions.items = applySessionEvent(state.sessions.items, entry);- var touched = type === 'session.updated' ? sessionKey(data.session) : data.sessionId;- if (type !== 'session.activity' && touched === state.sessions.selectedId) {- state.sessions.detailStale = true;- }- scheduleLiveRender();+ function updateCountBadges() {+ var c = store.counts || {};+ document.querySelectorAll('.tab-count[data-count]').forEach(function(el) {+ var v = c[el.getAttribute('data-count')];+ el.textContent = typeof v === 'number' ? (v > 9999 ? Math.round(v / 1000) + 'k' : String(v)) : '';+ });}function handleStreamEvent(msg) {@@ -4284,6 +7983,11 @@var observation;if (!evt) return;if (evt.type === 'event' && evt.event && evt.event.type) {+ if (evt.event.type === 'raw_observation') {+ observation = evt.event.data && (evt.event.data.observation || evt.event.data);+ if (looksLikeObservation(observation)) routeWsMessage({ observation: observation });+ return;+ }handleLiveEvent(evt.event.type, evt.event.data || {});return;}@@ -4301,7 +8005,7 @@var payload = evt.data;observation = payload.observation || payload;if (looksLikeObservation(observation)) {- routeWsMessage({ observation: observation });+ routeWsMessage({ observation: observation, fresh: true });}} else if (evt.type === 'sync') {var items = Array.isArray(evt.data) ? evt.data.slice(-LIVE_BUFFER_MAX) : [];@@ -4316,34 +8020,75 @@}function routeWsMessage(msg) {- if (state.activeTab === 'timeline' && msg.observation) {- if (!state.timeline.sessionId || msg.observation.sessionId === state.timeline.sessionId) {- var existing = state.timeline.observations.findIndex(function(o) { return o.id === msg.observation.id; });- if (existing >= 0) {- state.timeline.observations[existing] = msg.observation;- } else {- state.timeline.observations.unshift(msg.observation);- if (state.timeline.observations.length > LIVE_BUFFER_MAX * 4) {- state.timeline.observations.length = LIVE_BUFFER_MAX * 4;- }- }- renderObservations();+ var o = msg.observation;+ if (!o) return;+ if (msg.fresh && (o.title || o.narrative)) {+ var obsSession = store.entities.session[o.sessionId];+ var obsWhat = (o.title || 'Observation') + (o.subtitle ? ': ' + humanizeSubtitle(o.subtitle) : '');+ feedPush({ at: o.timestamp, tag: String(o.type || 'observation').replace(/_/g, ' '), badge: 'badge-blue', text: truncate(obsWhat + (obsSession ? ' (' + sessionDisplayName(obsSession) + ')' : ''), 110), kind: 'session', id: o.sessionId });+ markDirty(['dashboard']);+ }+ liveSessionObservation(o);+ if (state.activity.loaded) {+ var idx = state.activity.observations.findIndex(function(x) { return x.id === o.id; });+ if (idx >= 0) state.activity.observations[idx] = o;+ else state.activity.observations.unshift(o);+ if (state.activity.observations.length > LIVE_BUFFER_MAX * 5) {+ state.activity.observations.length = LIVE_BUFFER_MAX * 5;}+ markDirty(['activity']);}- if (state.activeTab === 'activity' && msg.observation) {- state.activity.observations.unshift(msg.observation);- if (state.activity.observations.length > LIVE_BUFFER_MAX) {- state.activity.observations.length = LIVE_BUFFER_MAX;- }- renderActivity();+ }++ function closeNav() {+ var bar = document.getElementById('tab-bar');+ var toggle = document.getElementById('nav-toggle');+ if (bar) bar.classList.remove('open');+ if (toggle) toggle.setAttribute('aria-expanded', 'false');+ }++ function toggleNav() {+ var bar = document.getElementById('tab-bar');+ var toggle = document.getElementById('nav-toggle');+ if (!bar) return;+ var open = !bar.classList.contains('open');+ bar.classList.toggle('open', open);+ if (toggle) toggle.setAttribute('aria-expanded', open ? 'true' : 'false');+ if (open) {+ var active = bar.querySelector('button.active');+ if (active) active.focus();}}+ document.querySelectorAll('.tab-bar button[data-tab]').forEach(function(b) {+ var panel = document.getElementById('view-' + b.dataset.tab);+ b.id = 'tab-' + b.dataset.tab;+ if (panel) {+ panel.setAttribute('aria-labelledby', b.id);+ panel.removeAttribute('aria-label');+ panel.tabIndex = -1;+ }+ });+document.getElementById('tab-bar').addEventListener('click', function(e) {var btn = e.target instanceof Element ? e.target.closest('button[data-tab]') : null;if (btn) switchTab(btn.dataset.tab);});+ document.getElementById('tab-bar').addEventListener('keydown', function(e) {+ if (e.key !== 'ArrowRight' && e.key !== 'ArrowLeft' && e.key !== 'ArrowDown' && e.key !== 'ArrowUp' && e.key !== 'Home' && e.key !== 'End') return;+ var tabs = Array.prototype.slice.call(this.querySelectorAll('button[data-tab]'));+ var i = tabs.indexOf(document.activeElement);+ if (i < 0) return;+ e.preventDefault();+ var next = i;+ if (e.key === 'ArrowRight' || e.key === 'ArrowDown') next = (i + 1) % tabs.length;+ else if (e.key === 'ArrowLeft' || e.key === 'ArrowUp') next = (i - 1 + tabs.length) % tabs.length;+ else if (e.key === 'Home') next = 0;+ else if (e.key === 'End') next = tabs.length - 1;+ tabs[next].focus();+ });+document.querySelectorAll('[data-tab-link]').forEach(function(link) {link.addEventListener('click', function(e) {if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;@@ -4353,117 +8098,96 @@});function syncTabFromRoute() {- switchTab(tabFromRoute(), { replaceRoute: true });+ var route = parseRoute(window.location.hash);+ if (route.redirect) updateTabRoute(route.tab, true, route.id);+ switchTab(route.tab, { replaceRoute: true, skipRoute: true, id: route.id, obs: route.obs });}window.addEventListener('hashchange', syncTabFromRoute);window.addEventListener('popstate', syncTabFromRoute);- // --- Feature flag banners ---------------------------------------------- function getDismissedFlags() {- if (!state.flagsDismissed) state.flagsDismissed = {};- return state.flagsDismissed;- }- function dismissFlags(keys) {- var dismissed = getDismissedFlags();- keys.forEach(function(key) {- if (key) dismissed[key] = true;- });- }- function renderFlagBanners(cfg) {- var host = document.getElementById('flag-banners');- if (!host) return;- var dismissed = getDismissedFlags();- var banners = [];- // Per-flag banner (only for off flags, affecting current tab or dashboard)- (cfg.flags || []).forEach(function(f) {- if (f.enabled) return;- if (dismissed[f.key]) return;- var tabsAffected = (f.affects || []).map(function(t) { return t.toLowerCase(); });- if (tabsAffected.length && tabsAffected.indexOf(state.activeTab) === -1 && state.activeTab !== 'dashboard') return;- banners.push({- kind: 'warn',- icon: '⚠',- title: f.label,- keyLabel: f.key,- desc: f.description + (f.needsLlm ? ' Requires an LLM provider key (ANTHROPIC_API_KEY, GEMINI_API_KEY, etc.).' : ''),- enable: f.enableHow,- docs: f.docsHref,- dismissKey: f.key,- });- });- if (cfg.provider === 'noop' && !dismissed['__provider_noop']) {- banners.unshift({- kind: 'warn',- icon: '🔒',- title: 'No LLM provider key set',- keyLabel: 'ANTHROPIC_API_KEY',- desc: 'Compression, summarization, and graph extraction stay disabled until a key is provided.',+ function flagItems() {+ var items = [];+ if (store.provider === 'noop') {+ items.push({+ on: false,+ title: 'No LLM provider',+ key: 'ANTHROPIC_API_KEY',+ desc: 'Compression, summaries, consolidation and graph extraction stay off until an LLM key is set. Memories, search and sessions still work.',enable: 'export ANTHROPIC_API_KEY=sk-ant-...\n# then restart: npx @agentmemory/agentmemory',- docs: 'https://github.com/rohitg00/agentmemory#quick-start',- dismissKey: '__provider_noop',+ affects: ['Overview', 'Graph', 'Crystals']});}- if (cfg.embeddingProvider === 'none' && !dismissed['__embedding_none']) {- banners.push({- kind: 'info',- icon: '⚙',- title: 'Running in BM25-only mode',- keyLabel: 'OPENAI_API_KEY',- desc: 'Semantic vector search is off. BM25 keyword search is active and good for exact matches.',+ if (!store.embeddingProvider || store.embeddingProvider === 'none') {+ items.push({+ on: false,+ title: 'No embedding provider',+ key: 'OPENAI_API_KEY',+ desc: 'Search matches exact keywords only. With embeddings it also finds memories by meaning.',enable: 'export OPENAI_API_KEY=sk-...\n# or VOYAGE_API_KEY, COHERE_API_KEY, OLLAMA_HOST',- docs: 'https://github.com/rohitg00/agentmemory#embedding-providers',- dismissKey: '__embedding_none',+ affects: ['Memories', 'Health']});}- if (banners.length === 0) { host.innerHTML = ''; return; }- var warnCount = banners.filter(function(b) { return b.kind === 'warn'; }).length;- var infoCount = banners.filter(function(b) { return b.kind === 'info'; }).length;- var expanded = host.getAttribute('data-expanded') === '1';- var pills = '';- if (warnCount) pills += '<span class="flag-pill">' + warnCount + ' off</span>';- if (infoCount) pills += '<span class="flag-pill info">' + infoCount + ' note</span>';- var escHtml = function(s) {- return String(s).replace(/[<>&"]/g, function(c) {- return { '<': '<', '>': '>', '&': '&', '"': '"' }[c];+ (store.flags || []).forEach(function(f) {+ items.push({+ on: !!f.enabled && !f.inactiveReason,+ partial: !!f.enabled && !!f.inactiveReason,+ title: f.label,+ key: f.key,+ desc: (f.description || '') + (f.inactiveReason ? ' ' + f.inactiveReason : '') + (!f.enabled && f.needsLlm ? ' Needs an LLM provider key.' : ''),+ enable: f.enabled ? '' : f.enableHow,+ affects: f.affects || [],+ docs: f.docsHref});- };- var listHtml = banners.map(function(b) {- return '<div class="flag-banner ' + b.kind + '" data-flag="' + escHtml(b.dismissKey) + '">' +- '<span class="flag-icon">' + b.icon + '</span>' +- '<div class="flag-body">' +- '<div class="flag-title">' + escHtml(b.title) + ' <code>' + escHtml(b.keyLabel) + '</code></div>' +- '<div class="flag-desc">' + escHtml(b.desc) + '</div>' +- '<code class="flag-enable">' + escHtml(b.enable) + '</code>' +- (b.docs ? ' <a class="empty-link" href="' + escHtml(b.docs) + '" target="_blank" rel="noopener">Learn more →</a>' : '') +- '</div>' +- '<button type="button" class="flag-close" data-dismiss-flag="' + escHtml(b.dismissKey) + '" aria-label="Dismiss">×</button>' +- '</div>';- }).join('');- 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" aria-hidden="true">' + (expanded ? '▲' : '▼') + '</span>' +- '</button>' +- '<div class="flag-list' + (expanded ? ' open' : '') + '" id="flag-list">' + listHtml + '</div>';- }- async function fetchFlags() {- var res = await apiGet('config/flags');- if (!res) return;- state.flagsConfig = res;- renderFlagBanners(res);- updateFooter(res);- }- function updateFooter(cfg) {+ });+ return items;+ }++ function renderFlagsChip() {+ var host = document.getElementById('flags-chip');+ if (!host) return;+ var items = flagItems();+ var off = items.filter(function(i) { return !i.on; }).length;+ host.innerHTML = '<button type="button" class="chip ' + (off ? 'chip-warn' : 'chip-ok') + '" data-action="toggle-flags" aria-expanded="' + (state.flagsOpen ? 'true' : 'false') + '" aria-controls="flags-panel" title="Which optional features are on">' ++ (off ? off + ' feature' + (off === 1 ? '' : 's') + ' off' : 'all features on') + '</button>';+ }++ function renderFlagsPanel() {+ var panel = document.getElementById('flags-panel');+ if (!panel) return;+ if (!state.flagsOpen) { panel.hidden = true; return; }+ var items = flagItems();+ var html = '<div class="flags-panel-head"><h2>Features ' + help('flags') + '</h2><p>Off features explain empty panels on the pages listed. Turn one on with its setting, then restart agentmemory.</p><button class="icon-btn" data-action="toggle-flags" aria-label="Close features">close</button></div>';+ html += '<div class="flags-grid">';+ items.sort(function(a, b) { return (a.on ? 1 : 0) - (b.on ? 1 : 0); }).forEach(function(i) {+ html += '<div class="flag-item ' + (i.on ? 'on' : 'off') + '">' ++ '<div class="flag-item-title"><span class="badge ' + (i.on ? 'badge-green' : i.partial ? 'badge-yellow' : 'badge-muted') + '">' + (i.on ? 'on' : i.partial ? 'inactive' : 'off') + '</span>' + esc(i.title) + ' <code style="font-size:10px;color:var(--ink-faint);font-weight:400;">' + esc(i.key) + '</code></div>' ++ '<div class="flag-item-desc">' + esc(i.desc) + '</div>' ++ (i.affects && i.affects.length ? '<div class="flag-item-meta">Affects: ' + esc(i.affects.join(', ')) + '</div>' : '') ++ (i.enable ? cmdBlock(i.enable) : '') ++ (i.docs ? '<a class="empty-link" href="' + esc(i.docs) + '" target="_blank" rel="noopener" style="font-size:11px;">docs →</a>' : '') ++ '</div>';+ });+ html += '</div>';+ panel.innerHTML = html;+ panel.hidden = false;+ }++ function updateFooter() {var vEl = document.getElementById('footer-version');- if (vEl) vEl.textContent = 'v' + (cfg.version || '?');+ if (vEl && store.version) vEl.textContent = 'v' + store.version;+ var sync = document.getElementById('footer-sync');+ if (sync) {+ var syncText = store.snapshotAt ? 'full sync ' + new Date(store.snapshotAt).toLocaleTimeString() : 'waiting for first sync';+ if (store.snapshotAt) syncText += wsOpenedAt ? ', streaming since ' + new Date(wsOpenedAt).toLocaleTimeString() : ', stream reconnecting';+ sync.textContent = syncText;+ }var fbEl = document.getElementById('footer-feedback');if (fbEl) {- var flagSummary = (cfg.flags || []).map(function(f) { return f.key + '=' + (f.enabled ? 'on' : 'off'); }).join(', ');+ var flagSummary = (store.flags || []).map(function(f) { return f.key + '=' + (f.enabled ? 'on' : 'off'); }).join(', ');var body = encodeURIComponent(- '**Version:** ' + (cfg.version || '?') + '\n' +- '**Provider:** ' + (cfg.provider || '?') + '\n' +- '**Embedding:** ' + (cfg.embeddingProvider || '?') + '\n' ++ '**Version:** ' + (store.version || '?') + '\n' ++ '**Provider:** ' + (store.provider || '?') + '\n' ++ '**Embedding:** ' + (store.embeddingProvider || '?') + '\n' +'**Flags:** ' + flagSummary + '\n' +'**User agent:** ' + navigator.userAgent + '\n\n' +'### What went wrong\n\n' +@@ -4475,39 +8199,222 @@encodeURIComponent('[viewer] ') + '&body=' + body;}}- document.addEventListener('click', function(e) {- if (!(e.target instanceof Element)) return;- var btn = e.target.closest('[data-dismiss-flag]');- if (btn) {- e.preventDefault();- e.stopPropagation();- var key = btn.getAttribute('data-dismiss-flag');- dismissFlags([key]);- if (state.flagsConfig) renderFlagBanners(state.flagsConfig);- return;- }- var toggle = e.target.closest('[data-action="toggle-flags"]');- if (toggle) {- var host = document.getElementById('flag-banners');- var cur = host.getAttribute('data-expanded') === '1';- host.setAttribute('data-expanded', cur ? '0' : '1');- if (state.flagsConfig) renderFlagBanners(state.flagsConfig);- }- });- fetchFlags();// Keyboard activation for role="button" cards (session items). Click// delegation alone leaves them unreachable for keyboard and AT users.document.addEventListener('keydown', function(e) {if (e.key !== 'Enter' && e.key !== ' ') return;if (!(e.target instanceof Element)) return;var card = e.target.closest('[data-action][role="button"], [data-action][role="link"]');- if (!card) return;+ if (!card || card !== e.target) return;e.preventDefault();card.click();});+ function copyText(text, btn) {+ function done(ok) {+ if (!btn) return;+ var prev = btn.getAttribute('data-label') || btn.textContent;+ btn.setAttribute('data-label', prev);+ btn.textContent = ok ? 'copied' : 'copy failed';+ btn.classList.toggle('copied', ok);+ setTimeout(function() { btn.textContent = prev; btn.classList.remove('copied'); }, 1400);+ }+ if (navigator.clipboard && navigator.clipboard.writeText) {+ navigator.clipboard.writeText(text).then(function() { done(true); }, function() { done(fallbackCopy(text)); });+ } else {+ done(fallbackCopy(text));+ }+ }++ function fallbackCopy(text) {+ try {+ var ta = document.createElement('textarea');+ ta.value = text;+ ta.setAttribute('readonly', '');+ ta.style.position = 'fixed';+ ta.style.opacity = '0';+ document.body.appendChild(ta);+ ta.select();+ var ok = document.execCommand('copy');+ document.body.removeChild(ta);+ return ok;+ } catch (_) {+ return false;+ }+ }++ var helpAnchor = null;+ function showHelpPop(btn) {+ var key = btn.getAttribute('data-help');+ var g = GLOSSARY[key];+ var pop = document.getElementById('help-pop');+ if (!g || !pop) return;+ pop.innerHTML = '<div class="help-pop-term">' + esc(g.term) + '</div><div>' + esc(g.text) + '</div>';+ pop.hidden = false;+ var r = btn.getBoundingClientRect();+ var w = Math.min(300, window.innerWidth - 24);+ pop.style.maxWidth = w + 'px';+ var left = Math.min(Math.max(12, r.left - 8), window.innerWidth - w - 12);+ var top = r.bottom + 8;+ pop.style.left = left + 'px';+ pop.style.top = top + 'px';+ var ph = pop.getBoundingClientRect().height;+ if (top + ph > window.innerHeight - 8) pop.style.top = Math.max(8, r.top - ph - 8) + 'px';+ helpAnchor = btn;+ btn.setAttribute('aria-describedby', 'help-pop');+ }++ function hideHelpPop() {+ var pop = document.getElementById('help-pop');+ if (pop) pop.hidden = true;+ if (helpAnchor) helpAnchor.removeAttribute('aria-describedby');+ helpAnchor = null;+ }++ function openHelpOverlay() {+ var modal = document.getElementById('modal');+ var overlay = document.getElementById('modal-overlay');+ var html = '<h3>How to read this viewer</h3>';+ html += '<p style="margin-bottom:8px;">Everything on these pages updates live over one streaming connection; nothing refreshes on a timer. Click any <span class="help" style="cursor:default;">?</span> for a short explanation, or use the keys below.</p>';+ html += '<div class="kbd-list">' ++ '<div><kbd>/</kbd> focus search on this page</div>' ++ '<div><kbd>?</kbd> open this help</div>' ++ '<div><kbd>Esc</kbd> close panels and popups</div>' ++ '<div><kbd>1</kbd>–<kbd>9</kbd> jump to a page in order</div>';+ Object.keys(TAB_SHORTCUTS).forEach(function(k) {+ html += '<div><kbd>g</kbd> <kbd>' + k + '</kbd> ' + esc(TAB_LABELS[TAB_SHORTCUTS[k]]) + '</div>';+ });+ html += '</div>';+ html += '<h3 style="font-size:15px;margin-top:6px;">Glossary</h3><div class="glossary-list">';+ Object.keys(GLOSSARY).sort(function(a, b) { return GLOSSARY[a].term.localeCompare(GLOSSARY[b].term); }).forEach(function(k) {+ html += '<div><b>' + esc(GLOSSARY[k].term) + '</b>' + esc(GLOSSARY[k].text) + '</div>';+ });+ html += '</div><div class="modal-actions"><button class="btn btn-primary" data-action="close-modal">Close</button></div>';+ openModal(html);+ modal.classList.add('overlay-panel');+ }++ function focusPageSearch() {+ var view = document.getElementById('view-' + state.activeTab);+ if (!view) return false;+ var input = view.querySelector('input[type="search"], input[type="text"], .graph-search');+ if (!input) return false;+ input.focus();+ if (input.select) input.select();+ return true;+ }++ function closeAllOverlays() {+ var hadOverlay = document.getElementById('modal-overlay').classList.contains('open');+ closeModal();+ hideHelpPop();+ closeNav();+ if (state.flagsOpen) {+ state.flagsOpen = false;+ renderFlagsChip();+ renderFlagsPanel();+ return true;+ }+ return hadOverlay;+ }++ var pendingGAt = 0;+ document.addEventListener('keydown', function(e) {+ if (e.defaultPrevented) return;+ var t = e.target;+ var typing = t && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.tagName === 'SELECT' || t.isContentEditable);+ if (e.key === 'Escape') {+ var closed = closeAllOverlays();+ if (!closed && typing && t.blur) t.blur();+ if (!closed && !typing && state.activeTab === 'memories' && state.memories.selectedId && !state.memories.editing) {+ state.memories.selectedId = null;+ setRouteEntity('memories', '');+ renderMemories();+ } else if (!closed && !typing && state.activeTab === 'lessons' && state.lessons.selectedId) {+ handlePageAction('lesson-close', document.body);+ } else if (!closed && !typing && state.activeTab === 'actions' && state.actions.selectedId) {+ handlePageAction('action-close', document.body);+ } else if (!closed && !typing && state.activeTab === 'audit' && state.audit.selectedIdx) {+ toggleAuditDetail(state.audit.selectedIdx);+ }+ return;+ }+ if (typing || e.metaKey || e.ctrlKey || e.altKey) return;+ if (pendingGAt && Date.now() - pendingGAt < 1500) {+ pendingGAt = 0;+ var jump = TAB_SHORTCUTS[e.key.toLowerCase()];+ if (jump) {+ e.preventDefault();+ switchTab(jump);+ }+ return;+ }+ if (e.key === '/') {+ if (focusPageSearch()) e.preventDefault();+ return;+ }+ if (e.key === '?') {+ e.preventDefault();+ openHelpOverlay();+ return;+ }+ if (e.key === 'g') {+ pendingGAt = Date.now();+ return;+ }+ if (/^[1-9]$/.test(e.key) && state.activeTab !== 'replay') {+ var target = TAB_IDS[parseInt(e.key, 10) - 1];+ if (target) {+ e.preventDefault();+ switchTab(target);+ }+ }+ });++ document.addEventListener('mouseover', function(e) {+ if (!(e.target instanceof Element)) return;+ var btn = e.target.closest('[data-help]');+ if (btn && btn !== helpAnchor) showHelpPop(btn);+ });+ document.addEventListener('focusin', function(e) {+ if (!(e.target instanceof Element)) return;+ if (e.target.matches('[data-help]')) showHelpPop(e.target);+ else if (helpAnchor && !e.target.closest('#help-pop')) hideHelpPop();+ });+ document.addEventListener('mouseout', function(e) {+ if (!(e.target instanceof Element) || !helpAnchor) return;+ var from = e.target.closest('[data-help]');+ var to = e.relatedTarget instanceof Element ? e.relatedTarget.closest('[data-help], #help-pop') : null;+ if (from && !to && document.activeElement !== from) hideHelpPop();+ });+document.addEventListener('click', function(e) {if (!(e.target instanceof Element)) return;+ var copyEl = e.target.closest('[data-copy]');+ if (copyEl) {+ e.preventDefault();+ e.stopPropagation();+ copyText(copyEl.getAttribute('data-copy') || '', copyEl);+ return;+ }+ var helpEl = e.target.closest('[data-help]');+ if (helpEl) {+ e.preventDefault();+ e.stopPropagation();+ if (helpAnchor === helpEl && !document.getElementById('help-pop').hidden) hideHelpPop();+ else showHelpPop(helpEl);+ return;+ }+ if (!e.target.closest('#help-pop')) hideHelpPop();+ var replayLink = e.target.closest('[data-replay-session]');+ if (replayLink) {+ e.preventDefault();+ var replayId = replayLink.getAttribute('data-replay-session');+ switchTab('replay');+ if (replayId) selectReplaySession(replayId);+ return;+ }+ if (!e.target.closest('#tab-bar, #nav-toggle')) closeNav();var target = e.target.closest('[data-action]');if (!target) return;var action = target.getAttribute('data-action');@@ -4517,12 +8424,38 @@toggleTheme();return;}- if (action === 'refresh-dashboard') {- refreshDashboard();+ if (action === 'toggle-nav') {+ toggleNav();+ return;+ }+ if (action === 'open-help') {+ openHelpOverlay();+ return;+ }+ if (action === 'toggle-flags') {+ state.flagsOpen = !state.flagsOpen;+ renderFlagsChip();+ renderFlagsPanel();+ return;+ }+ if (action === 'reconnect-now') {+ reconnectNow();+ return;+ }+ if (action === 'memories-load-more') {+ loadMoreMemories();+ return;+ }+ if (action === 'sessions-load-more') {+ loadMoreSessions();return;}if (action === 'refresh-health') {- loadHealth();+ ensureStatusReport();+ return;+ }+ if (action === 'run-consolidation') {+ runConsolidation();return;}if (action === 'zoom-graph') {@@ -4537,52 +8470,29 @@rebuildGraph();return;}- if (action === 'expand-node') {- var nodeId = target.getAttribute('data-node-id');- if (nodeId) expandNode(nodeId);+ if (action.indexOf('graph-') === 0 && handleGraphAction(action, target)) {return;}- if (action === 'delete-memory') {- deleteMemory(- target.getAttribute('data-memory-id') || '',- target.getAttribute('data-memory-title') || '',- );+ if (action.indexOf('mem-') === 0) {+ handleMemoryAction(action, target);return;}if (action === 'close-modal') {closeModal();return;}- if (action === 'confirm-delete-memory') {- var memoryId = target.getAttribute('data-memory-id');- if (memoryId) confirmDeleteMemory(memoryId);- return;- }if (action === 'save-viewer-token') {var tokenInput = document.getElementById('viewer-auth-token');var token = tokenInput ? tokenInput.value.trim() : '';if (token) {setViewerToken(token);hideViewerAuthPrompt();- // Re-fetch config/flags so the footer version + flag banners- // refresh without a full page reload; fetchFlags() only runs- // during bootstrap and would otherwise stay stale until the- // user reloads.- fetchFlags();- if (state[state.activeTab] && typeof state[state.activeTab] === 'object') {- state[state.activeTab].loaded = false;- }- loadTab(state.activeTab);+ resyncAfterConnect(false);}return;}- if (action === 'timeline-filter') {- setTlTypeFilter(target.getAttribute('data-type-filter') || '');- return;- }- if (action === 'timeline-page') {- var page = parseInt(target.getAttribute('data-page') || '', 10);- if (!Number.isNaN(page)) tlPage(page);+ if (action.indexOf('ses-') === 0) {+ handleSessionAction(action, target);return;}if (action === 'select-session') {@@ -4599,7 +8509,13 @@var lsnId = target.getAttribute('data-lesson-id');if (lsnId) {state.lessons.selectedId = state.lessons.selectedId === lsnId ? null : lsnId;+ state.lessons.notice = null;+ setRouteEntity('lessons', state.lessons.selectedId);renderLessons();+ if (state.lessons.selectedId && window.matchMedia('(max-width: 1100px)').matches) {+ var lsnPanel = document.getElementById('lesson-detail');+ if (lsnPanel && lsnPanel.scrollIntoView) lsnPanel.scrollIntoView({ behavior: 'smooth', block: 'start' });+ }}return;}@@ -4607,24 +8523,25 @@var memId = target.getAttribute('data-memory-id');if (memId) {state.memories.selectedId = state.memories.selectedId === memId ? null : memId;+ if (state.memories.editing && state.memories.editing.id !== state.memories.selectedId) state.memories.editing = null;+ state.memories.error = '';+ setRouteEntity('memories', state.memories.selectedId);renderMemories();+ if (state.memories.selectedId && window.matchMedia('(max-width: 1100px)').matches) {+ var memPanel = document.getElementById('memory-detail');+ if (memPanel && memPanel.scrollIntoView) memPanel.scrollIntoView({ behavior: 'smooth', block: 'start' });+ }}return;}- if (action === 'end-session') {- var endSessionId = target.getAttribute('data-session-id');- if (endSessionId) endSession(endSessionId);- return;- }- if (action === 'summarize-session') {- var summarizeSessionId = target.getAttribute('data-session-id');- if (summarizeSessionId) summarizeSession(summarizeSessionId, target);- return;- }if (action === 'toggle-audit') {- var auditIndex = parseInt(target.getAttribute('data-audit-index') || '', 10);- if (!Number.isNaN(auditIndex)) toggleAuditDetail(auditIndex);+ var auditId = target.getAttribute('data-audit-id');+ if (auditId) toggleAuditDetail(auditId);+ return;}+ if (action === 'audit-load-more') { loadMoreAudit(); return; }+ if (action === 'audit-clear-filters') { clearAuditFilters(); return; }+ if (handlePageAction(action, target)) return;if (action === 'replay-select') {var rSid = target.getAttribute('data-session-id');if (rSid) selectReplaySession(rSid);@@ -4643,153 +8560,209 @@}if (action === 'replay-reset') { resetReplay(); return; }if (action === 'replay-import') { runReplayImport(); return; }- if (action === 'replay-refresh') { refreshReplaySessions(); return; }});document.getElementById('modal-overlay').addEventListener('click', function(e) {if (e.target === this) closeModal();});async function loadReplay() {- var el = document.getElementById('view-replay');- el.innerHTML = '<div class="loading">Loading sessions…</div>';- var res = await apiGet('replay/sessions');- state.replay.sessions = (res && res.sessions) || [];state.replay.loaded = true;- renderReplay();+ await ensureLoaded('session');+ if (state.activeTab === 'replay') renderReplay();}- async function refreshReplaySessions() {- state.replay.loaded = false;- await loadReplay();+ function replaySessions() {+ return sortByTimeDesc(entityList('session').filter(function(s) { return sessionId(s); }), ['startedAt']);}- function renderReplay() {- var el = document.getElementById('view-replay');- var sessions = state.replay.sessions || [];- var options = '<option value="">— pick a session —</option>' + sessions.map(function(s) {- var id = sessionId(s);- var label = sessionDisplayName(s) + ' · ' + (shortSessionId(s, 8) || 'missing id') + ' · ' + (s.observationCount || 0) + ' obs';- return '<option value="' + esc(id) + '"' + (id && id === state.replay.selectedId ? ' selected' : '') + (id ? '' : ' disabled') + '>' + esc(label) + '</option>';- }).join('');+ function replayImportHtml() {+ var r = state.replay;+ var html = '<details class="card" id="replay-import"' + (r.importOpen || !replaySessions().length ? ' open' : '') + ' style="margin-top:16px;"><summary class="card-title" style="cursor:pointer;margin-bottom:0;border-bottom:none;">Import past transcripts</summary>';+ html += '<p class="empty-step-label" style="margin:10px 0;">Agents connected with hooks are recorded live and need no import. Import is for work done before agentmemory was connected: it reads chat transcripts saved as JSONL, one message per line (the format Claude Code keeps under <code>~/.claude/projects</code>; other agents that write the same message format work too). Each file becomes a session with its observations, and agentmemory derives a crystal and lessons from it, so it shows up here, on Sessions and in recall.</p>';+ html += '<div class="toolbar" style="margin-bottom:8px;"><input type="text" id="replay-import-path" placeholder="Path to a .jsonl transcript or a folder of them; empty uses ~/.claude/projects" value="' + esc(r.importPath || '') + '" style="flex:1;min-width:0;" aria-label="Transcript file or folder to import" aria-describedby="replay-import-status">';+ html += '<button type="button" class="btn" data-action="replay-import"' + (r.importing ? ' disabled' : '') + '>' + (r.importing ? 'Importing…' : 'Import') + '</button></div>';+ html += '<div id="replay-import-status" role="status" aria-live="polite">' + (r.importStatus ? '<div class="inline-status' + (r.importStatus.err ? ' err' : ' ok') + '">' + r.importStatus.html + '</div>' : '') + '</div>';+ html += '<div class="empty-step-label">Same call from a terminal:</div>' + cmdBlock(curlPost('replay/import-jsonl', { path: r.importPath || '~/.claude/projects' }));+ return html + '</details>';+ }- var tl = state.replay.timeline;- var hasTl = tl && tl.events && tl.events.length > 0;- var cursorEvent = hasTl ? tl.events[Math.min(state.replay.cursor, tl.events.length - 1)] : null;- var progress = hasTl && tl.totalDurationMs > 0 ? Math.min(100, (state.replay.offsetAt / tl.totalDurationMs) * 100) : 0;-- el.innerHTML =- '<div class="toolbar">' +- '<select id="replay-session-select">' + options + '</select>' +- '<button data-action="replay-refresh">Refresh</button>' +- '<span class="sep"></span>' +- '<input type="text" id="replay-import-path" placeholder="~/.claude/projects or file.jsonl" style="width:280px">' +- '<button data-action="replay-import">Import JSONL</button>' +- '</div>' +- (hasTl- ? '<div class="replay-controls">' +- '<button data-action="replay-step" data-dir="-1" title="Previous (←)">◀</button>' +- '<button data-action="replay-toggle-play" title="Play/Pause (Space)">' + (state.replay.playing ? '❚❚ Pause' : '▶ Play') + '</button>' +- '<button data-action="replay-step" data-dir="1" title="Next (→)">▶</button>' +- '<button data-action="replay-reset" title="Reset">⟲</button>' +- '<span class="sep"></span>' +- '<span>Speed</span>' +- ['0.5', '1', '2', '4'].map(function(sp) {- var active = Math.abs(state.replay.speed - parseFloat(sp)) < 0.01;- return '<button data-action="replay-speed" data-speed="' + sp + '"' + (active ? ' class="active"' : '') + '>' + sp + '×</button>';- }).join('') +- '<span class="sep"></span>' +- '<span>' + (state.replay.cursor + 1) + ' / ' + tl.eventCount + '</span>' +- '</div>' +- '<div class="replay-progress"><div class="replay-progress-bar" style="width:' + progress.toFixed(1) + '%"></div></div>' +- '<div class="replay-grid">' +- '<div class="replay-list" id="replay-list">' +- tl.events.map(function(ev, i) {- var active = i === state.replay.cursor ? ' replay-event-active' : '';- return '<div class="replay-event replay-event-' + esc(ev.kind) + active + '" data-replay-idx="' + i + '">' +- '<span class="replay-event-kind">' + esc(ev.kind) + '</span>' +- '<span class="replay-event-label">' + esc(ev.label) + '</span>' +- '<span class="replay-event-time">' + (ev.offsetMs / 1000).toFixed(1) + 's</span>' +- '</div>';- }).join('') +- '</div>' +- '<div class="replay-detail">' + renderReplayDetail(cursorEvent) + '</div>' +- '</div>'- : '<div class="empty">Pick a session to replay, or import Claude Code JSONL transcripts from ~/.claude/projects.</div>');+ function replayIntroHtml(sessions) {+ var html = '';+ if (!sessions.length) {+ html += emptyState({+ icon: '▶',+ title: 'Nothing to replay yet',+ what: 'Replay ' + help('replay') + ' plays a recorded session back step by step: each prompt, response and tool call in the order it happened, with its real timing.',+ why: 'No session has been recorded or imported on this install yet.',+ steps: [+ { label: 'Connect your agent with hooks so new sessions are recorded (swap in codex, cursor, gemini-cli or another supported agent):', cmd: connectCmd() },+ { label: 'Or import transcripts you already have with the form below.' }+ ]+ });+ return html;+ }+ html += '<div class="section-head"><h2>Pick a session to replay</h2><span class="section-sub">' + fmtNum(sessions.length) + ' loaded, newest first</span></div><div class="session-list">';+ sessions.slice(0, 8).forEach(function(s) {+ var id = sessionId(s);+ html += '<div class="session-item" data-action="replay-select" data-session-id="' + esc(id) + '" role="button" tabindex="0">' ++ '<div class="session-top"><span class="session-project">' + esc(sessionDisplayName(s)) + '</span><span class="session-meta">' + fmtNum(s.observationCount || 0) + ' obs · ' + esc(timeAgo(s.startedAt)) + '</span></div>' ++ (s.firstPrompt ? '<div class="session-preview clamp-2">' + esc(s.firstPrompt) + '</div>' : '<div class="session-preview none">No prompt recorded</div>') ++ '<div class="mem-chips">' + (s.agentId ? '<span class="mem-chip" style="cursor:default;">@' + esc(s.agentId) + '</span>' : '') + '<span class="ses-id-mini" title="' + esc(id) + '">' + esc(shortId(id, 18)) + '</span></div></div>';+ });+ html += '</div>';+ if (sessions.length > 8) html += '<div class="load-more">The picker above lists all ' + fmtNum(sessions.length) + ' loaded sessions.</div>';+ return html;+ }- var sel = document.getElementById('replay-session-select');- if (sel) sel.addEventListener('change', function() { selectReplaySession(sel.value); });+ function replayDetailHtml(ev) {+ if (!ev) return '<div class="empty-step-label">Pick an event on the left.</div>';+ var html = '<div class="mem-detail-head"><span class="badge ' + ({ prompt: 'badge-blue', response: 'badge-green', tool_call: 'badge-orange', tool_error: 'badge-red' }[ev.kind] || 'badge-muted') + '">' + esc(String(ev.kind || '').replace(/_/g, ' ')) + '</span><span>' + esc(ev.label || '') + '</span>' + (ev.ts ? '<span>· ' + esc(formatTime(ev.ts)) + '</span>' : '') + '</div>';+ if (ev.body) html += obsCodeHtml(ev.body, ev.kind === 'prompt' ? 'Prompt' : ev.kind === 'response' ? 'Response' : 'Text');+ if (ev.toolName) html += '<dl class="obs-fields"><dt>tool</dt><dd><code>' + esc(ev.toolName) + '</code></dd></dl>';+ if (ev.toolInput !== undefined && ev.toolInput !== null) {+ var input = ev.toolInput;+ if (typeof input === 'string') { try { var parsed = JSON.parse(input); if (parsed && typeof parsed === 'object') input = parsed; } catch (_) {} }+ html += typeof input === 'object' ? obsFieldsHtml(input, '', '') : obsCodeHtml(input, 'Input');+ }+ if (ev.toolOutput !== undefined && ev.toolOutput !== null) html += obsCodeHtml(typeof ev.toolOutput === 'string' ? ev.toolOutput : JSON.stringify(ev.toolOutput, null, 2), ev.kind === 'tool_error' ? 'Error' : 'Output');+ return html;}- function renderReplayDetail(ev) {- if (!ev) return '<div class="empty">No event selected.</div>';- var blocks = [];- blocks.push('<div class="replay-detail-header"><b>' + esc(ev.label) + '</b> <span class="muted">' + esc(ev.kind) + '</span></div>');- if (ev.ts) blocks.push('<div class="muted">' + esc(formatTime(ev.ts)) + '</div>');- if (ev.body) {- blocks.push('<pre class="replay-body">' + esc(ev.body) + '</pre>');+ function renderReplay() {+ var el = document.getElementById('view-replay');+ var r = state.replay;+ if (!store.loaded.session) { setViewHtml(el, skeleton(8)); return; }+ var sessions = replaySessions();+ var focusAction = document.activeElement && el.contains(document.activeElement) ? document.activeElement.getAttribute('data-action') : '';+ var focusKey = focusAction ? (document.activeElement.getAttribute('data-speed') || document.activeElement.getAttribute('data-dir') || '') : '';+ var html = sessions.length ? '<div class="inline-note"><strong>Replay</strong> ' + help('replay') + ' plays a recorded session back step by step: prompts, responses and tool calls in order, with their real timing. It works for sessions from every connected agent. <kbd>Space</kbd> plays or pauses, <kbd>←</kbd> <kbd>→</kbd> step.</div>' : '';+ if (sessions.length) {+ html += '<div class="toolbar"><select id="replay-session-select" aria-label="Session to replay" style="flex:1;min-width:0;max-width:720px;"><option value="">Pick a session…</option>' + sessions.map(function(s) {+ var id = sessionId(s);+ return '<option value="' + esc(id) + '"' + (id === r.selectedId ? ' selected' : '') + '>' + esc(sessionPickerLabel(s)) + '</option>';+ }).join('') + '</select>';+ if (r.selectedId) html += '<a class="btn" href="' + entityHref('session', r.selectedId) + '">Open session</a>';+ html += '</div>';+ }+ var tl = r.timeline;+ if (r.selectedId && r.loadingTimeline) {+ html += '<div class="inline-status" role="status">Loading the replay for ' + esc(shortId(r.selectedId, 24)) + '…</div>' + skeleton(6);+ } else if (r.selectedId && r.loadError) {+ html += '<div class="inline-status err" role="alert">' + r.loadError + '</div>';+ } else if (r.selectedId && tl && !(tl.events && tl.events.length)) {+ html += emptyState({+ compact: true,+ icon: '▶',+ title: 'This session has nothing to replay',+ what: 'Replay steps through the prompts, responses and tool calls recorded in a session.',+ why: 'No prompt or tool call was captured for this session, so the timeline is empty.',+ steps: [{ label: 'Check its observations from a terminal:', cmd: curlGet('observations?sessionId=' + encodeURIComponent(r.selectedId) + '&limit=20') }]+ });+ } else if (tl && tl.events && tl.events.length) {+ var cursorEvent = tl.events[Math.min(r.cursor, tl.events.length - 1)];+ var progress = tl.totalDurationMs > 0 ? Math.min(100, (r.offsetAt / tl.totalDurationMs) * 100) : 0;+ html += '<div class="replay-controls" role="toolbar" aria-label="Playback">';+ html += '<button type="button" data-action="replay-step" data-dir="-1" aria-label="Previous event">◀</button>';+ html += '<button type="button" data-action="replay-toggle-play" aria-pressed="' + (r.playing ? 'true' : 'false') + '">' + (r.playing ? '❚❚ Pause' : '▶ Play') + '</button>';+ html += '<button type="button" data-action="replay-step" data-dir="1" aria-label="Next event">▶</button>';+ html += '<button type="button" data-action="replay-reset" aria-label="Back to the start">⟲</button><span class="sep"></span><span id="replay-speed-label">Speed</span>';+ ['0.5', '1', '2', '4'].forEach(function(sp) {+ var on = Math.abs(r.speed - parseFloat(sp)) < 0.01;+ html += '<button type="button" data-action="replay-speed" data-speed="' + sp + '" aria-pressed="' + (on ? 'true' : 'false') + '" aria-describedby="replay-speed-label">' + sp + '×</button>';+ });+ html += '<span class="sep"></span><span aria-live="polite">event ' + (r.cursor + 1) + ' of ' + tl.eventCount + ' · ' + (r.offsetAt / 1000).toFixed(1) + 's of ' + (tl.totalDurationMs / 1000).toFixed(1) + 's</span></div>';+ html += '<div class="replay-progress" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="' + Math.round(progress) + '" aria-label="Playback position"><div class="replay-progress-bar" style="width:' + progress.toFixed(1) + '%"></div></div>';+ html += '<div class="replay-grid"><div class="replay-list" id="replay-list">';+ tl.events.forEach(function(ev, i) {+ html += '<button type="button" class="replay-event replay-event-' + esc(ev.kind) + (i === r.cursor ? ' replay-event-active' : '') + '" data-action="replay-jump" data-replay-idx="' + i + '" aria-current="' + (i === r.cursor ? 'step' : 'false') + '">' ++ '<span class="replay-event-kind">' + esc(String(ev.kind || '').replace(/_/g, ' ')) + '</span><span class="replay-event-label">' + esc(ev.label) + '</span><span class="replay-event-time">' + (ev.offsetMs / 1000).toFixed(1) + 's</span></button>';+ });+ html += '</div><div class="replay-detail">' + replayDetailHtml(cursorEvent) + '</div></div>';+ } else {+ html += replayIntroHtml(sessions);}- if (ev.toolName) {- blocks.push('<div class="replay-tool"><b>Tool:</b> ' + esc(ev.toolName) + '</div>');+ html += replayImportHtml();+ setViewHtml(el, html);+ var sel = document.getElementById('replay-session-select');+ if (sel && !sel.__bound) {+ sel.__bound = true;+ sel.addEventListener('change', function() { selectReplaySession(sel.value); });}- if (ev.toolInput !== undefined && ev.toolInput !== null) {- var inp = typeof ev.toolInput === 'string' ? ev.toolInput : JSON.stringify(ev.toolInput, null, 2);- blocks.push('<div class="replay-tool-block"><b>Input</b><pre>' + esc(truncate(inp, 4000)) + '</pre></div>');+ var imp = document.getElementById('replay-import-path');+ if (imp && !imp.__bound) {+ imp.__bound = true;+ imp.addEventListener('input', function() { state.replay.importPath = imp.value; });+ imp.addEventListener('keydown', function(e) { if (e.key === 'Enter') { e.preventDefault(); runReplayImport(); } });+ }+ var details = document.getElementById('replay-import');+ if (details && !details.__bound) {+ details.__bound = true;+ details.addEventListener('toggle', function() { state.replay.importOpen = details.open; });}- if (ev.toolOutput !== undefined && ev.toolOutput !== null) {- var out = typeof ev.toolOutput === 'string' ? ev.toolOutput : JSON.stringify(ev.toolOutput, null, 2);- blocks.push('<div class="replay-tool-block"><b>Output</b><pre>' + esc(truncate(out, 4000)) + '</pre></div>');+ var active = el.querySelector('.replay-event-active');+ var list = document.getElementById('replay-list');+ if (active && list) {+ var top = active.offsetTop - list.offsetTop;+ if (top < list.scrollTop || top > list.scrollTop + list.clientHeight - active.offsetHeight) list.scrollTop = Math.max(0, top - list.clientHeight / 2);+ }+ if (focusAction) {+ var again = el.querySelector('[data-action="' + focusAction + '"]' + (focusKey ? '[data-speed="' + focusKey + '"], [data-action="' + focusAction + '"][data-dir="' + focusKey + '"]' : ''));+ if (again && document.activeElement !== again) again.focus();}- return blocks.join('');}- async function selectReplaySession(sessionId) {+ async function selectReplaySession(id) {+ var r = state.replay;stopReplayTimer();- state.replay.selectedId = sessionId;- state.replay.timeline = null;- state.replay.cursor = 0;- state.replay.offsetAt = 0;- state.replay.playing = false;- if (!sessionId) { renderReplay(); return; }- var el = document.getElementById('view-replay');- el.innerHTML = '<div class="loading">Loading replay…</div>';- var res = await apiGet('replay/load?sessionId=' + encodeURIComponent(sessionId));- if (res && res.success && res.timeline) {- state.replay.timeline = res.timeline;- } else {- state.replay.timeline = { events: [], eventCount: 0, totalDurationMs: 0 };- }+ r.selectedId = id;+ r.timeline = null;+ r.cursor = 0;+ r.offsetAt = 0;+ r.playing = false;+ r.loadError = '';+ if (!id) { renderReplay(); return; }+ r.loadingTimeline = true;+ renderReplay();+ var res = await apiGet('replay/load?sessionId=' + encodeURIComponent(id));+ if (r.selectedId !== id) return;+ r.loadingTimeline = false;+ if (res && res.success && res.timeline) r.timeline = res.timeline;+ else if (res && res.error) r.loadError = 'Could not load this session: ' + esc(res.error) + '.';+ else if (!res) r.loadError = 'The replay request failed. Check that agentmemory is running, then pick the session again.';+ else r.timeline = { events: [], eventCount: 0, totalDurationMs: 0 };renderReplay();}function toggleReplayPlay() {- if (!state.replay.timeline || state.replay.timeline.eventCount === 0) return;- if (state.replay.playing) {- stopReplayTimer();- } else {+ var r = state.replay;+ if (!r.timeline || !r.timeline.eventCount) return;+ if (r.playing) stopReplayTimer();+ else {+ if (r.offsetAt >= r.timeline.totalDurationMs) { r.cursor = 0; r.offsetAt = 0; }startReplayTimer();}renderReplay();}function startReplayTimer() {- state.replay.playing = true;- state.replay.startAt = Date.now();- var baseOffset = state.replay.offsetAt;- if (state.replay.timer) clearInterval(state.replay.timer);- state.replay.timer = setInterval(function() {- if (!state.replay.timeline) return;- var elapsed = (Date.now() - state.replay.startAt) * state.replay.speed;- state.replay.offsetAt = baseOffset + elapsed;- var events = state.replay.timeline.events;- var newCursor = state.replay.cursor;- for (var i = newCursor; i < events.length; i++) {- if (events[i].offsetMs <= state.replay.offsetAt) newCursor = i;+ var r = state.replay;+ r.playing = true;+ r.startAt = Date.now();+ var baseOffset = r.offsetAt;+ if (r.timer) clearInterval(r.timer);+ r.timer = setInterval(function() {+ if (!r.timeline) return;+ r.offsetAt = baseOffset + (Date.now() - r.startAt) * r.speed;+ var events = r.timeline.events;+ var next = r.cursor;+ for (var i = next; i < events.length; i++) {+ if (events[i].offsetMs <= r.offsetAt) next = i;else break;}- var changed = newCursor !== state.replay.cursor;- state.replay.cursor = newCursor;- if (state.replay.offsetAt >= state.replay.timeline.totalDurationMs) {- state.replay.offsetAt = state.replay.timeline.totalDurationMs;+ var changed = next !== r.cursor;+ r.cursor = next;+ if (r.offsetAt >= r.timeline.totalDurationMs) {+ r.offsetAt = r.timeline.totalDurationMs;stopReplayTimer();renderReplay();return;@@ -4806,17 +8779,20 @@}}- function stepReplay(dir) {- if (!state.replay.timeline) return;+ function jumpReplay(idx) {+ var r = state.replay;+ if (!r.timeline || !r.timeline.eventCount) return;stopReplayTimer();- var next = state.replay.cursor + dir;- if (next < 0) next = 0;- if (next >= state.replay.timeline.eventCount) next = state.replay.timeline.eventCount - 1;- state.replay.cursor = next;- state.replay.offsetAt = state.replay.timeline.events[next].offsetMs;+ r.cursor = Math.max(0, Math.min(idx, r.timeline.eventCount - 1));+ r.offsetAt = r.timeline.events[r.cursor].offsetMs;renderReplay();}+ function stepReplay(dir) {+ if (!state.replay.timeline) return;+ jumpReplay(state.replay.cursor + dir);+ }+function setReplaySpeed(sp) {if (!sp || sp <= 0) return;var wasPlaying = state.replay.playing;@@ -4834,37 +8810,42 @@}async function runReplayImport() {+ var r = state.replay;+ if (r.importing) return;var input = document.getElementById('replay-import-path');- var pathVal = input ? input.value.trim() : '';- var body = {};- if (pathVal) body.path = pathVal;- var el = document.getElementById('view-replay');- var prior = el.innerHTML;- el.innerHTML = '<div class="loading">Importing JSONL…</div>';- var res = await apiPost('replay/import-jsonl', body);- if (!res || res.success === false) {- el.innerHTML = prior;- alert((res && res.error) || 'Import failed');- return;+ var pathVal = input ? input.value.trim() : String(r.importPath || '').trim();+ r.importPath = pathVal;+ r.importing = true;+ r.importOpen = true;+ r.importStatus = { html: 'Importing ' + esc(pathVal || '~/.claude/projects') + '… large folders can take a minute.' };+ renderReplay();+ var res = await api('replay/import-jsonl', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(pathVal ? { path: pathVal } : {}), readErrorBody: true });+ r.importing = false;+ if (!res || res.success === false || res.error) {+ var reason = res && res.error ? String(res.error) : 'the request failed. Check that agentmemory is running.';+ var hint = /not found/.test(reason) ? ' Check the path; it is read on the machine agentmemory runs on.' : /\.jsonl/.test(reason) ? ' Point it at one .jsonl file or a folder that contains them.' : '';+ r.importStatus = { err: true, html: 'Import failed: ' + esc(reason.replace(/[.\s]+$/, '')) + '.' + hint };+ } else if (!res.imported) {+ r.importStatus = { err: true, html: 'No .jsonl transcripts found under ' + esc(pathVal || '~/.claude/projects') + '. Nothing was imported.' };+ } else {+ var ids = res.sessionIds || [];+ r.importStatus = { html: 'Imported ' + fmtNum(res.imported) + ' file' + (res.imported === 1 ? '' : 's') + ' with ' + fmtNum(res.observations || 0) + ' observations' + (res.truncated ? ' (stopped at ' + fmtNum(res.maxFiles) + ' files; pass maxFiles to import more)' : '') + '. ' + (ids.length ? 'New sessions: ' + ids.slice(0, 6).map(function(id) { return '<a class="entity-link" href="#replay" data-replay-session="' + esc(id) + '">' + esc(shortId(id, 18)) + '</a>'; }).join(' ') + (ids.length > 6 ? ' +' + (ids.length - 6) + ' more' : '') + '. They also appear on Sessions.' : '') };}- alert('Imported ' + (res.imported || 0) + ' file(s), ' + (res.observations || 0) + ' observation(s)');- await refreshReplaySessions();+ renderReplay();}document.addEventListener('keydown', function(e) {if (state.activeTab !== 'replay') return;- if (e.target && (e.target.tagName === 'INPUT' || e.target.tagName === 'SELECT' || e.target.tagName === 'TEXTAREA')) return;+ var t = e.target;+ if (t && (t.tagName === 'INPUT' || t.tagName === 'SELECT' || t.tagName === 'TEXTAREA' || t.tagName === 'SUMMARY' || (t.tagName === 'BUTTON' && e.key === ' '))) return;+ if (document.getElementById('modal-overlay').classList.contains('open')) return;if (e.key === ' ') { e.preventDefault(); toggleReplayPlay(); }else if (e.key === 'ArrowLeft') { e.preventDefault(); stepReplay(-1); }else if (e.key === 'ArrowRight') { e.preventDefault(); stepReplay(1); }});- switchTab(tabFromRoute(), { replaceRoute: true });- // Resolve the stream WebSocket target from the server before the first- // connect. The old viewerPort-1 arithmetic breaks whenever the viewer- // binds a fallback port (3113 taken → viewer on 3114 → 3113 is another- // HTTP server, not the streams endpoint) — every retry then fails and- // the viewer silently degrades to 10s polling.+ var bootRoute = parseRoute(window.location.hash);+ switchTab(bootRoute.tab, { replaceRoute: true, skipRoute: !!bootRoute.obs && !bootRoute.redirect, id: bootRoute.id, obs: bootRoute.obs });(async function initWs() {try {var live = await api('livez', { signal: AbortSignal.timeout(5000) });@@ -4875,19 +8856,29 @@} catch (_) {}connectWs();})();+ setTimeout(function() {+ if (wsHasConnected) return;+ openBootGate();+ loadSnapshot();+ showTab(state.activeTab);+ }, 4000);document.addEventListener('visibilitychange', function() {if (document.visibilityState !== 'visible') return;var ws = state.ws;if (ws && (ws.readyState === WebSocket.OPEN || ws.readyState === WebSocket.CONNECTING)) return;- if (wsReconnectTimer) clearTimeout(wsReconnectTimer);wsRetries = 0;- directFailures = 0;- directFailed = true;- connectWs();- if (state.activeTab === 'dashboard') scheduleDashboardReload();+ reconnectNow();});+ setInterval(function() {+ document.querySelectorAll('time.rel-time[datetime]').forEach(function(el) {+ var text = timeAgo(el.getAttribute('datetime'));+ if (el.textContent !== text) el.textContent = text;+ });+ if (conn.state === 'live') renderConnection();+ }, 15000);+// Ambient background: an ordered-dither dot field that drifts very// slowly — the print-halftone cousin of the old static dot grid.// Renders at quarter resolution and ~12fps; a single static frame@@ -4936,11 +8927,21 @@}draw();- if (!reduced) {- setInterval(function () {+ var lastFrame = 0;+ function frame(now) {+ if (document.hidden) return;+ if (now - lastFrame >= 85) {+ lastFrame = now;t++;draw();- }, 85);+ }+ requestAnimationFrame(frame);+ }+ if (!reduced) {+ requestAnimationFrame(frame);+ document.addEventListener('visibilitychange', function() {+ if (!document.hidden) requestAnimationFrame(frame);+ });}window.addEventListener('resize', draw);new MutationObserver(draw).observe(document.documentElement, {diff --git a/test/api-graph-node.test.ts b/test/api-graph-node.test.tsnew file mode 100644index 00000000..6ca6d9f8--- /dev/null+++ b/test/api-graph-node.test.ts@@ -0,0 +1,92 @@+import { describe, it, expect, vi } from "vitest";+import { registerApiTriggers } from "../src/triggers/api.js";+import { getSearchIndex } from "../src/functions/search.js";+import { KV } from "../src/state/schema.js";++type Handler = (req: unknown) => Promise<{ status_code: number; body: Record<string, unknown> }>;++function setup(seed: Record<string, Record<string, unknown>>) {+ const store = new Map<string, Map<string, unknown>>();+ for (const [scope, rows] of Object.entries(seed)) store.set(scope, new Map(Object.entries(rows)));+ const kv = {+ get: vi.fn(async (scope: string, key: string) => store.get(scope)?.get(key) ?? null),+ set: vi.fn(async (_scope: string, _key: string, value: unknown) => value),+ delete: vi.fn(async () => {}),+ list: vi.fn(async (scope: string) => Array.from(store.get(scope)?.values() ?? [])),+ };+ const handlers = new Map<string, Handler>();+ const sdk = {+ registerFunction: (id: string, fn: Handler) => handlers.set(id, fn),+ registerTrigger: () => {},+ trigger: vi.fn(async () => ({})),+ on: () => {},+ };+ registerApiTriggers(sdk as never, kv as never);+ return (query_params: Record<string, string>) =>+ handlers.get("api::graph-node")!({ headers: {}, query_params, body: {} });+}++const node = (id: string, name: string, type: string, extra: Record<string, unknown> = {}) => ({+ id, name, type, properties: {}, sourceObservationIds: [], createdAt: "2026-09-01T00:00:00Z", ...extra,+});++describe("GET /agentmemory/graph/node", () => {+ it("returns relations with neighbors and resolves provenance to observations, sessions, projects and memories", async () => {+ const index = getSearchIndex();+ index.add({ id: "obs_gn_1", sessionId: "ses_gn", timestamp: "2026-09-01T00:00:00Z", type: "file_edit", title: "Edit checkout", facts: [], narrative: "edited", concepts: [], files: [], importance: 5 } as never);+ const call = setup({+ [KV.graphNodes]: {+ gn_a: node("gn_a", "/work/web-app/src/components/Checkout.tsx", "file", { sourceObservationIds: ["obs_gn_1"] }),+ gn_b: node("gn_b", "pricing", "concept"),+ gn_c: node("gn_c", "orders.ts", "file", { properties: { source: "graphify", sourceFile: "src/orders.ts" } }),+ },+ [KV.graphEdges]: {+ ge_1: { id: "ge_1", type: "related_to", sourceNodeId: "gn_a", targetNodeId: "gn_b", weight: 0.4, sourceObservationIds: ["obs_gn_1"], createdAt: "t" },+ ge_2: { id: "ge_2", type: "imports", sourceNodeId: "gn_c", targetNodeId: "gn_a", weight: 0.9, sourceObservationIds: [], createdAt: "t" },+ ge_3: { id: "ge_3", type: "uses", sourceNodeId: "gn_b", targetNodeId: "gn_c", weight: 0.9, sourceObservationIds: [], createdAt: "t" },+ },+ [KV.graphNodeDegree]: { gn_a: 2 },+ [KV.observations("ses_gn")]: {+ obs_gn_1: { id: "obs_gn_1", sessionId: "ses_gn", title: "Edit checkout", type: "file_edit", timestamp: "2026-09-01T00:00:00Z" },+ },+ [KV.sessions]: { ses_gn: { id: "ses_gn", project: "web-app", agentId: "coder", status: "completed", startedAt: "2026-09-01T00:00:00Z" } },+ [KV.memories]: {+ mem_1: { id: "mem_1", title: "Coupons first", type: "bug", project: "web-app", isLatest: true, concepts: [], files: [], sourceObservationIds: ["obs_gn_1"] },+ mem_2: { id: "mem_2", title: "Checkout grid", type: "pattern", isLatest: true, concepts: [], files: ["src/components/Checkout.tsx"] },+ mem_3: { id: "mem_3", title: "Old", type: "fact", isLatest: false, concepts: [], files: [], sourceObservationIds: ["obs_gn_1"] },+ mem_4: { id: "mem_4", title: "Unrelated", type: "fact", isLatest: true, concepts: ["deploy"], files: [] },+ },+ });++ const res = await call({ id: "gn_a" });+ expect(res.status_code).toBe(200);+ const body = res.body as Record<string, any>;+ expect(body.node.id).toBe("gn_a");+ expect(body.degree).toBe(2);+ expect(body.relationsTotal).toBe(2);+ expect(body.relations).toEqual([+ { edgeId: "ge_2", type: "imports", direction: "in", weight: 0.9, observationCount: 0, neighbor: { id: "gn_c", name: "orders.ts", type: "file" } },+ { edgeId: "ge_1", type: "related_to", direction: "out", weight: 0.4, observationCount: 1, neighbor: { id: "gn_b", name: "pricing", type: "concept" } },+ ]);+ expect(body.provenance.observations).toEqual([+ { id: "obs_gn_1", sessionId: "ses_gn", title: "Edit checkout", type: "file_edit", timestamp: "2026-09-01T00:00:00Z" },+ ]);+ expect(body.provenance.sessions).toEqual([+ { id: "ses_gn", project: "web-app", agentId: "coder", status: "completed", startedAt: "2026-09-01T00:00:00Z" },+ ]);+ expect(body.provenance.projects).toEqual(["web-app"]);+ expect(body.provenance.memories).toEqual([+ { id: "mem_1", title: "Coupons first", type: "bug", project: "web-app", via: "observation" },+ { id: "mem_2", title: "Checkout grid", type: "pattern", via: "name" },+ ]);+ expect(body.provenance.structural).toBeNull();++ const imported = await call({ id: "gn_c" });+ expect((imported.body as Record<string, any>).provenance.structural).toEqual({ source: "graphify", sourceFile: "src/orders.ts" });+ expect((imported.body as Record<string, any>).provenance.observations).toEqual([]);++ expect((await call({})).status_code).toBe(400);+ expect((await call({ id: "gn_missing" })).status_code).toBe(404);+ index.remove("obs_gn_1");+ });+});diff --git a/test/api-lessons-audit.test.ts b/test/api-lessons-audit.test.tsnew file mode 100644index 00000000..9b717f4f--- /dev/null+++ b/test/api-lessons-audit.test.ts@@ -0,0 +1,73 @@+import { describe, it, expect, vi } from "vitest";+import { registerApiTriggers } from "../src/triggers/api.js";++type Handler = (req: unknown) => Promise<{ status_code: number; body: Record<string, unknown> }>;++function setup() {+ const kv = {+ get: vi.fn(async () => null),+ set: vi.fn(async (_scope: string, _key: string, value: unknown) => value),+ delete: vi.fn(async () => {}),+ list: vi.fn(async () => []),+ };+ const handlers = new Map<string, Handler>();+ const trigger = vi.fn(async (input: { function_id: string; payload: unknown }) => {+ if (input.function_id === "mem::lesson-save") return { success: true, action: "created", lesson: input.payload };+ return [];+ });+ const sdk = {+ registerFunction: (id: string, fn: Handler) => handlers.set(id, fn),+ registerTrigger: () => {},+ trigger,+ on: () => {},+ };+ registerApiTriggers(sdk as never, kv as never);+ const call = (id: string, req: { body?: unknown; query_params?: Record<string, string> }) =>+ handlers.get(id)!({ headers: {}, query_params: {}, body: {}, ...req });+ return { call, trigger };+}++describe("POST /agentmemory/lessons sourceIds", () => {+ it("stores validated sourceIds so a lesson can link to sessions and memories", async () => {+ const { call, trigger } = setup();+ const res = await call("api::lesson-save", {+ body: { content: "Snapshot RDS before upgrades", sourceIds: [" ses_infra_1 ", "mem_abc", "ses_infra_1"] },+ });+ expect(res.status_code).toBe(201);+ const payload = trigger.mock.calls[0][0].payload as Record<string, unknown>;+ expect(payload.sourceIds).toEqual(["ses_infra_1", "mem_abc"]);+ expect(payload.source).toBe("manual");+ });++ it("defaults to no sources and rejects malformed sourceIds", async () => {+ const { call, trigger } = setup();+ expect((await call("api::lesson-save", { body: { content: "No sources" } })).status_code).toBe(201);+ expect((trigger.mock.calls[0][0].payload as Record<string, unknown>).sourceIds).toEqual([]);++ for (const sourceIds of ["ses_1", [42], ["has space"], Array.from({ length: 51 }, (_, i) => `ses_${i}`)]) {+ const res = await call("api::lesson-save", { body: { content: "Bad", sourceIds } });+ expect(res.status_code).toBe(400);+ }+ expect(trigger).toHaveBeenCalledTimes(1);+ });+});++describe("GET /agentmemory/audit filters", () => {+ it("passes operation, date range and target text to the audit query", async () => {+ const { call, trigger } = setup();+ const res = await call("api::audit", {+ query_params: { operation: "forget", dateFrom: "2026-09-01", dateTo: "2026-09-30T23:59:59Z", q: "mem_", limit: "200" },+ });+ expect(res.status_code).toBe(200);+ expect(trigger.mock.calls[0][0]).toEqual({+ function_id: "mem::audit-query",+ payload: { operation: "forget", dateFrom: "2026-09-01", dateTo: "2026-09-30T23:59:59Z", query: "mem_", limit: 200 },+ });+ });++ it("rejects an invalid date", async () => {+ const { call, trigger } = setup();+ expect((await call("api::audit", { query_params: { dateFrom: "not-a-date" } })).status_code).toBe(400);+ expect(trigger).not.toHaveBeenCalled();+ });+});diff --git a/test/api-list-pagination.test.ts b/test/api-list-pagination.test.tsnew file mode 100644index 00000000..3928af80--- /dev/null+++ b/test/api-list-pagination.test.ts@@ -0,0 +1,272 @@+import { describe, it, expect, vi, beforeEach } from "vitest";+import { registerApiTriggers } from "../src/triggers/api.js";+import { getSearchIndex, rankMemoryIds, setVectorIndex, setEmbeddingProvider } from "../src/functions/search.js";+import { VectorIndex } from "../src/state/vector-index.js";+import { memoryToObservation } from "../src/state/memory-utils.js";+import { KV } from "../src/state/schema.js";+import type { Memory } from "../src/types.js";++type Handler = (req: unknown) => Promise<{ status_code: number; body: Record<string, unknown> }>;++function mockKV(seed: Record<string, Record<string, unknown>>) {+ const store = new Map<string, Map<string, unknown>>();+ for (const [scope, rows] of Object.entries(seed)) store.set(scope, new Map(Object.entries(rows)));+ return {+ get: vi.fn(async (scope: string, key: string) => store.get(scope)?.get(key) ?? null),+ set: vi.fn(async (scope: string, key: string, value: unknown) => value),+ delete: vi.fn(async () => {}),+ list: vi.fn(async (scope: string) => Array.from(store.get(scope)?.values() ?? [])),+ };+}++function memory(id: string, updatedAt: string, extra: Partial<Memory> = {}): Memory {+ return {+ id,+ createdAt: updatedAt,+ updatedAt,+ type: "fact",+ title: id,+ content: `content for ${id}`,+ concepts: [],+ files: [],+ sessionIds: [],+ strength: 7,+ version: 1,+ isLatest: true,+ ...extra,+ } as Memory;+}++function setup(seed: Record<string, Record<string, unknown>>) {+ const handlers = new Map<string, Handler>();+ const sdk = {+ registerFunction: (id: string, fn: Handler) => handlers.set(id, fn),+ registerTrigger: () => {},+ trigger: vi.fn(async () => ({})),+ on: () => {},+ };+ const kv = mockKV(seed);+ registerApiTriggers(sdk as never, kv as never);+ return { handlers, kv };+}++async function call(handlers: Map<string, Handler>, id: string, query_params: Record<string, string>) {+ return handlers.get(id)!({ headers: {}, query_params, body: {} });+}++describe("paginated and filtered list endpoints", () => {+ beforeEach(() => {+ setVectorIndex(null);+ setEmbeddingProvider(null);+ });++ it("walks memories with a cursor, newest first, applying project and type filters", async () => {+ const rows: Record<string, Memory> = {};+ for (let i = 0; i < 7; i++) {+ const id = `mem_${i}`;+ rows[id] = memory(id, `2026-09-0${i + 1}T00:00:00Z`, {+ project: i % 2 === 0 ? "web" : "api",+ type: i === 4 ? "bug" : "fact",+ });+ }+ const { handlers } = setup({ [KV.memories]: rows });++ const first = await call(handlers, "api::memories", { project: "web", limit: "2" });+ expect((first.body.memories as Memory[]).map((m) => m.id)).toEqual(["mem_6", "mem_4"]);+ expect(first.body.total).toBe(4);+ const second = await call(handlers, "api::memories", { project: "web", limit: "2", cursor: first.body.nextCursor as string });+ expect((second.body.memories as Memory[]).map((m) => m.id)).toEqual(["mem_2", "mem_0"]);+ expect(second.body.nextCursor).toBeNull();++ const bugs = await call(handlers, "api::memories", { type: "bug" });+ expect((bugs.body.memories as Memory[]).map((m) => m.id)).toEqual(["mem_4"]);++ const legacy = await call(handlers, "api::memories", { limit: "3", offset: "3" });+ expect((legacy.body.memories as Memory[]).map((m) => m.id)).toEqual(["mem_3", "mem_2", "mem_1"]);+ expect(legacy.body.offset).toBe(3);++ const everything = await call(handlers, "api::memories", {});+ expect((everything.body.memories as Memory[]).length).toBe(7);+ expect(everything.body.nextCursor).toBeNull();+ });++ it("ranks memories with the search index when q is set, keeping filters", async () => {+ const auth = memory("mem_auth", "2026-09-01T00:00:00Z", { title: "jwt auth", content: "rotate jwt refresh tokens nightly", project: "web" });+ const other = memory("mem_db", "2026-09-05T00:00:00Z", { title: "db", content: "postgres vacuum schedule", project: "web" });+ const scoped = memory("mem_auth_api", "2026-09-06T00:00:00Z", { title: "jwt", content: "jwt verification in api gateway", project: "api" });+ const index = getSearchIndex();+ for (const m of [auth, other, scoped]) index.add(memoryToObservation(m));+ const { handlers } = setup({ [KV.memories]: { [auth.id]: auth, [other.id]: other, [scoped.id]: scoped } });++ const res = await call(handlers, "api::memories", { q: "jwt", project: "web" });+ expect((res.body.memories as Memory[]).map((m) => m.id)).toEqual(["mem_auth"]);+ expect(res.body.search).toEqual({ query: "jwt", mode: "keyword" });++ const all = await call(handlers, "api::memories", { q: "jwt", limit: "1" });+ expect((all.body.memories as Memory[]).length).toBe(1);+ expect(all.body.nextCursor).toEqual(expect.any(String));+ for (const m of [auth, other, scoped]) index.remove(m.id);+ });++ it("fuses keyword and vector ranks so a meaning-only match still surfaces", async () => {+ const index = getSearchIndex();+ const keywordHit = memory("mem_kw", "2026-09-01T00:00:00Z", { title: "deploy", content: "deploy pipeline uses canary stage" });+ index.add(memoryToObservation(keywordHit));+ const vectors = new VectorIndex();+ vectors.add("mem_vec", "memory", new Float32Array([1, 0, 0]));+ vectors.add("mem_kw", "memory", new Float32Array([0, 1, 0]));+ vectors.add("obs_1", "s1", new Float32Array([1, 0, 0]));+ setVectorIndex(vectors);+ setEmbeddingProvider({+ name: "fake",+ dimensions: 3,+ embed: async () => new Float32Array([1, 0, 0]),+ embedBatch: async (texts: string[]) => texts.map(() => new Float32Array([1, 0, 0])),+ });+ const ranked = await rankMemoryIds("deploy", 10);+ expect(ranked.mode).toBe("hybrid");+ expect(ranked.ids).toEqual(expect.arrayContaining(["mem_kw", "mem_vec"]));+ expect(ranked.ids).not.toContain("obs_1");+ index.remove(keywordHit.id);+ });++ it("returns project, agent and type facets over latest memories and filters by agent", async () => {+ const rows: Record<string, Memory> = {+ a: memory("a", "2026-09-01T00:00:00Z", { project: "web", agentId: "coder", type: "bug" }),+ b: memory("b", "2026-09-02T00:00:00Z", { project: "web", agentId: "reviewer" }),+ c: memory("c", "2026-09-03T00:00:00Z", { project: "infra", agentId: "coder" }),+ old: memory("old", "2026-08-01T00:00:00Z", { project: "legacy", agentId: "ghost", isLatest: false }),+ };+ const { handlers } = setup({ [KV.memories]: rows });++ const res = await call(handlers, "api::memories", { latest: "true", limit: "1", facets: "true", project: "web" });+ expect(res.body.facets).toEqual({+ projects: [{ value: "web", count: 2 }, { value: "infra", count: 1 }],+ agents: [{ value: "coder", count: 2 }, { value: "reviewer", count: 1 }],+ types: [{ value: "fact", count: 2 }, { value: "bug", count: 1 }],+ });+ expect(res.body.total).toBe(2);++ const plain = await call(handlers, "api::memories", { latest: "true" });+ expect(plain.body.facets).toBeUndefined();++ const coder = await call(handlers, "api::memories", { latest: "true", agentId: "coder" });+ expect((coder.body.memories as Memory[]).map((m) => m.id)).toEqual(["c", "a"]);+ });++ it("maps mem::evolve failures to HTTP status codes", async () => {+ const { handlers } = setup({});+ const evolve = handlers.get("api::evolve")!;+ const sdkTrigger = (code: string) => vi.fn(async () => ({ success: false, code, error: code }));+ const run = async (code: string) => {+ const handlersForCode = new Map<string, Handler>();+ const sdk = { registerFunction: (id: string, fn: Handler) => handlersForCode.set(id, fn), registerTrigger: () => {}, trigger: sdkTrigger(code), on: () => {} };+ registerApiTriggers(sdk as never, mockKV({}) as never);+ return handlersForCode.get("api::evolve")!({ headers: {}, query_params: {}, body: { memoryId: "mem_1", newContent: "x" } });+ };+ expect((await run("not_found")).status_code).toBe(404);+ expect((await run("not_latest")).status_code).toBe(409);+ expect((await run("unchanged")).status_code).toBe(400);+ expect((await evolve({ headers: {}, query_params: {}, body: { memoryId: "mem_1" } })).status_code).toBe(400);+ expect((await evolve({ headers: {}, query_params: {}, body: { memoryId: "mem_1", newContent: "y" } })).status_code).toBe(200);+ });++ it("filters and pages sessions, loading summaries only for the returned page", async () => {+ const sessions: Record<string, unknown> = {};+ for (let i = 0; i < 5; i++) {+ sessions[`s${i}`] = {+ id: `s${i}`,+ project: i < 3 ? "web" : "api",+ status: i === 0 ? "active" : "completed",+ startedAt: `2026-09-0${i + 1}T00:00:00Z`,+ firstPrompt: i === 2 ? "Fix the login redirect" : "other",+ };+ }+ const { handlers, kv } = setup({ [KV.sessions]: sessions });++ const page = await call(handlers, "api::sessions", { project: "web", limit: "2" });+ expect((page.body.sessions as Array<{ id: string }>).map((s) => s.id)).toEqual(["s2", "s1"]);+ const summaryReads = kv.get.mock.calls.filter(([scope]) => scope === KV.summaries).length;+ expect(summaryReads).toBe(2);+ const next = await call(handlers, "api::sessions", { project: "web", limit: "2", cursor: page.body.nextCursor as string });+ expect((next.body.sessions as Array<{ id: string }>).map((s) => s.id)).toEqual(["s0"]);+ expect(next.body.nextCursor).toBeNull();++ const active = await call(handlers, "api::sessions", { status: "active" });+ expect((active.body.sessions as Array<{ id: string }>).map((s) => s.id)).toEqual(["s0"]);+ const search = await call(handlers, "api::sessions", { q: "login" });+ expect((search.body.sessions as Array<{ id: string }>).map((s) => s.id)).toEqual(["s2"]);+ });++ it("filters and pages observations inside a session", async () => {+ const observations: Record<string, unknown> = {};+ for (let i = 0; i < 5; i++) {+ observations[`o${i}`] = {+ id: `o${i}`,+ sessionId: "s1",+ timestamp: `2026-09-01T00:00:0${i}Z`,+ type: i % 2 === 0 ? "file_edit" : "command_run",+ title: i === 3 ? "npm test failed" : `step ${i}`,+ importance: i,+ };+ }+ const { handlers } = setup({ [KV.observations("s1")]: observations });++ const missing = await call(handlers, "api::observations", {});+ expect(missing.status_code).toBe(400);++ const first = await call(handlers, "api::observations", { sessionId: "s1", limit: "2" });+ expect((first.body.observations as Array<{ id: string }>).map((o) => o.id)).toEqual(["o4", "o3"]);+ expect(first.body.total).toBe(5);+ const rest = await call(handlers, "api::observations", { sessionId: "s1", limit: "5", cursor: first.body.nextCursor as string });+ expect((rest.body.observations as Array<{ id: string }>).map((o) => o.id)).toEqual(["o2", "o1", "o0"]);++ const edits = await call(handlers, "api::observations", { sessionId: "s1", type: "file_edit", minImportance: "2" });+ expect((edits.body.observations as Array<{ id: string }>).map((o) => o.id).sort()).toEqual(["o2", "o4"]);+ const failed = await call(handlers, "api::observations", { sessionId: "s1", q: "FAILED" });+ expect((failed.body.observations as Array<{ id: string }>).map((o) => o.id)).toEqual(["o3"]);+ });+ it("returns session facets over every session in scope and filters by agent", async () => {+ const sessions: Record<string, unknown> = {+ a: { id: "a", project: "web", agentId: "coder", status: "active", startedAt: "2026-09-01T00:00:00Z" },+ b: { id: "b", project: "web", agentId: "reviewer", status: "completed", startedAt: "2026-09-02T00:00:00Z" },+ c: { id: "c", project: "infra", agentId: "coder", status: "completed", startedAt: "2026-09-03T00:00:00Z" },+ };+ const { handlers } = setup({ [KV.sessions]: sessions });+ const res = await call(handlers, "api::sessions", { agentId: "coder", limit: "10", facets: "true" });+ expect((res.body.sessions as Array<{ id: string }>).map((s) => s.id)).toEqual(["c", "a"]);+ expect(res.body.facets).toEqual({+ projects: [{ value: "web", count: 2 }, { value: "infra", count: 1 }],+ agents: [{ value: "coder", count: 2 }, { value: "reviewer", count: 1 }],+ statuses: [{ value: "completed", count: 2 }, { value: "active", count: 1 }],+ });+ const plain = await call(handlers, "api::sessions", { limit: "10" });+ expect(plain.body.facets).toBeUndefined();+ });++ it("lists the memories produced from one session by session id or source observation", async () => {+ const rows: Record<string, Memory> = {+ direct: memory("direct", "2026-09-01T00:00:00Z", { sessionIds: ["s1"] }),+ viaObs: memory("viaObs", "2026-09-02T00:00:00Z", { sessionIds: [], sourceObservationIds: ["o1"] } as Partial<Memory>),+ other: memory("other", "2026-09-03T00:00:00Z", { sessionIds: ["s2"], sourceObservationIds: ["o9"] } as Partial<Memory>),+ unrelated: memory("unrelated", "2026-09-04T00:00:00Z"),+ };+ const { handlers } = setup({+ [KV.memories]: rows,+ [KV.observations("s1")]: { o1: { id: "o1", sessionId: "s1", timestamp: "2026-09-01T00:00:00Z" } },+ });+ const res = await call(handlers, "api::memories", { latest: "true", sessionId: "s1", limit: "20" });+ expect((res.body.memories as Memory[]).map((m) => m.id)).toEqual(["viaObs", "direct"]);+ expect(res.body.total).toBe(2);+ });+ it("locates the session of observation ids through the search index", async () => {+ const index = getSearchIndex();+ index.add({ id: "obs_locate_1", sessionId: "ses_x", timestamp: "2026-09-01T00:00:00Z", type: "file_read", title: "Read", facts: [], narrative: "read a file", concepts: [], files: [], importance: 5 } as never);+ const { handlers } = setup({});+ const res = await call(handlers, "api::observations-locate", { ids: "obs_locate_1,obs_missing" });+ expect(res.body.sessions).toEqual({ obs_locate_1: "ses_x" });+ const bad = await call(handlers, "api::observations-locate", {});+ expect(bad.status_code).toBe(400);+ index.remove("obs_locate_1");+ });+});diff --git a/test/audit.test.ts b/test/audit.test.tsindex 12cb6610..b98faea8 100644--- a/test/audit.test.ts+++ b/test/audit.test.ts@@ -95,6 +95,16 @@ describe("Audit Functions", () => {expect(entriesBefore[0].operation).toBe("observe");});+ it("queryAudit filters by target id or function text", async () => {+ await recordAudit(kv as never, "forget", "mem::forget", ["mem_abc", "ses_1"]);+ await recordAudit(kv as never, "observe", "mem::observe", ["obs_9"]);+ await recordAudit(kv as never, "lesson_save", "mem::lesson-save", ["lsn_1"]);++ expect((await queryAudit(kv as never, { query: "MEM_AB" })).map((e) => e.targetIds[0])).toEqual(["mem_abc"]);+ expect((await queryAudit(kv as never, { query: "lesson-save" })).map((e) => e.targetIds[0])).toEqual(["lsn_1"]);+ expect(await queryAudit(kv as never, { query: "nothing" })).toEqual([]);+ });+it("queryAudit respects limit", async () => {for (let i = 0; i < 10; i++) {await recordAudit(kv as never, "observe", `fn${i}`, [], {});diff --git a/test/auto-compress.test.ts b/test/auto-compress.test.tsindex fdcced8f..13d25ce4 100644--- a/test/auto-compress.test.ts+++ b/test/auto-compress.test.ts@@ -207,11 +207,51 @@ describe("buildSyntheticCompression", () => {toolInput: { file_path: "/app/src/bar.ts", pattern: "foo" },raw: {},});- expect(synth.files).toContain("/app/src/bar.ts");- expect(synth.files).toContain("foo");+ expect(synth.files).toEqual(["/app/src/bar.ts"]);expect(synth.type).toBe("file_edit");});+ it("does not record search paths or patterns as files", async () => {+ const { buildSyntheticCompression } = await import(+ "../src/functions/compress-synthetic.js"+ );+ const base = {+ sessionId: "ses_1",+ timestamp: new Date().toISOString(),+ hookType: "post_tool_use" as const,+ raw: {},+ };+ const grep = buildSyntheticCompression({+ ...base,+ id: "obs_grep",+ toolName: "Grep",+ toolInput: { path: "infra", pattern: "computeTotal" },+ });+ const glob = buildSyntheticCompression({+ ...base,+ id: "obs_glob",+ toolName: "Glob",+ toolInput: { path: "src", pattern: "**/*.ts" },+ });+ const read = buildSyntheticCompression({+ ...base,+ id: "obs_read",+ toolName: "read_file",+ toolInput: { path: "/app/src/foo.ts" },+ });+ const notebook = buildSyntheticCompression({+ ...base,+ id: "obs_nb",+ toolName: "NotebookEdit",+ toolInput: { notebook_path: "/app/analysis.ipynb" },+ });++ expect(grep.files).toEqual([]);+ expect(glob.files).toEqual([]);+ expect(read.files).toEqual(["/app/src/foo.ts"]);+ expect(notebook.files).toEqual(["/app/analysis.ipynb"]);+ });+it("truncates long narratives so it can't blow up the index", async () => {const { buildSyntheticCompression } = await import("../src/functions/compress-synthetic.js"diff --git a/test/consolidation-default.test.ts b/test/consolidation-default.test.tsindex d7a7d5da..416b0e5e 100644--- a/test/consolidation-default.test.ts+++ b/test/consolidation-default.test.ts@@ -14,6 +14,7 @@ const ENV_KEYS = ["GOOGLE_API_KEY","MINIMAX_API_KEY","OPENAI_BASE_URL",+ "AGENTMEMORY_ALLOW_AGENT_SDK",];const ORIGINAL_HOME = process.env["HOME"];@@ -74,16 +75,58 @@ describe("isConsolidationEnabled default behavior", () => {expect(cfg.isConsolidationEnabled()).toBe(true);});- it("returns true by default when OPENAI_BASE_URL is set (local OpenAI-compatible)", async () => {- writeEnv("OPENAI_BASE_URL=http://localhost:1234/v1");+ it("returns true for a local OpenAI-compatible server with a key", async () => {+ writeEnv("OPENAI_API_KEY=local\nOPENAI_BASE_URL=http://localhost:1234/v1");const cfg = await freshConfig();expect(cfg.isConsolidationEnabled()).toBe(true);});- it("returns true by default when AGENTMEMORY_PROVIDER=agent-sdk", async () => {- writeEnv("AGENTMEMORY_PROVIDER=agent-sdk");+ it("returns false when OPENAI_BASE_URL is set without an LLM key, matching the provider", async () => {+ writeEnv("OPENAI_BASE_URL=http://localhost:1234/v1");+ const cfg = await freshConfig();+ expect(cfg.isConsolidationEnabled()).toBe(false);+ expect(cfg.detectLlmProviderKind()).toBe("noop");+ expect(cfg.loadConfig().provider.provider).toBe("noop");+ });++ it("returns false when OPENAI_BASE_URL serves embeddings only", async () => {+ writeEnv("OPENAI_API_KEY=sk-test\nOPENAI_API_KEY_FOR_LLM=false\nOPENAI_BASE_URL=http://localhost:1234/v1");+ const cfg = await freshConfig();+ expect(cfg.isConsolidationEnabled()).toBe(false);+ expect(cfg.loadConfig().provider.provider).toBe("noop");+ });++ it("returns true when the agent-sdk fallback is allowed", async () => {+ writeEnv("AGENTMEMORY_ALLOW_AGENT_SDK=true");const cfg = await freshConfig();expect(cfg.isConsolidationEnabled()).toBe(true);+ expect(cfg.loadConfig().provider.provider).toBe("agent-sdk");+ });++ it("agrees with the provider actually loaded for every provider setup", async () => {+ const setups = [+ "",+ "OPENAI_BASE_URL=http://localhost:1234/v1",+ "OPENAI_API_KEY=sk\nOPENAI_API_KEY_FOR_LLM=false",+ "OPENAI_API_KEY=sk",+ "ANTHROPIC_API_KEY=sk",+ "GEMINI_API_KEY=g",+ "GOOGLE_API_KEY=g",+ "OPENROUTER_API_KEY=o",+ "MINIMAX_API_KEY=m",+ "ANTHROPIC_API_KEY= ",+ "AGENTMEMORY_ALLOW_AGENT_SDK=true",+ ];+ for (const setup of setups) {+ writeEnv(setup);+ const cfg = await freshConfig();+ const hasLlm = cfg.loadConfig().provider.provider !== "noop";+ expect({ setup, consolidation: cfg.isConsolidationEnabled(), kind: cfg.detectLlmProviderKind() }).toEqual({+ setup,+ consolidation: hasLlm,+ kind: hasLlm ? "llm" : "noop",+ });+ }});it("explicit CONSOLIDATION_ENABLED=false overrides provider-based default", async () => {diff --git a/test/consolidation-status.test.ts b/test/consolidation-status.test.tsindex 305d0ee9..8a705a2c 100644--- a/test/consolidation-status.test.ts+++ b/test/consolidation-status.test.ts@@ -43,7 +43,7 @@ describe("describeConsolidation", () => {const status = describeConsolidation(input({ summaries: 3, recurringPatterns: 1 }));expect(tier(status, "semantic")).toMatchObject({state: "waiting",- detail: "Waiting: 3 of 5 session summaries needed.",+ detail: "Waiting: 3 of 5 session summaries needed. A summary is written when a session ends.",});const procedural = tier(status, "procedural");expect(procedural.state).toBe("waiting");@@ -51,6 +51,17 @@ describe("describeConsolidation", () => {expect(procedural.detail).toMatch(/you have 1/);});+ it("exposes the thresholds, schedule and inputs behind each state", () => {+ const status = describeConsolidation(+ input({ summaries: 3, recurringPatterns: 1, schedule: { intervalMs: 7200000, cooldownMs: 300000, decayDays: 30 } }),+ );+ expect(status.thresholds).toEqual({ semanticMinSummaries: 5, proceduralMinPatterns: 2, proceduralMinSessionsPerPattern: 2 });+ expect(status.schedule).toEqual({ intervalMs: 7200000, cooldownMs: 300000, decayDays: 30 });+ expect(status.summaries).toBe(3);+ expect(status.recurringPatterns).toBe(1);+ expect(status.lastRun).toBeNull();+ });+it("reports ready once the inputs are there and nothing has run yet", () => {const status = describeConsolidation(input({ summaries: 8, recurringPatterns: 2 }));expect(tier(status, "semantic").state).toBe("ready");@@ -179,19 +190,26 @@ describe("consolidation status wiring", () => {});it("status requests share one set of store scans instead of listing every scope per request", () => {- expect(api).toMatch(/const sharedConsolidationCounts = singleFlight\(async \(\) => \{/);- expect(api).toMatch(/\}, CONSOLIDATION_COUNTS_REUSE_MS\);/);+ const reader = api.slice(api.indexOf("export function createConsolidationStatusReader"), api.indexOf("function statusViewerUrl"));+ expect(reader).toMatch(/const counts = singleFlight\(async \(\) => \{/);+ expect(reader).toMatch(/\}, CONSOLIDATION_COUNTS_REUSE_MS\);/);const handler = api.slice(api.indexOf('registerFunction("api::consolidation-status"'),api.indexOf('function_id: "api::consolidation-status"'),);- expect(handler).toMatch(/sharedConsolidationCounts\(\)/);+ expect(handler).toMatch(/await consolidationStatus\(\)/);expect(handler).not.toMatch(/kv\.list\(/);});+ it("the snapshot and every consolidation.run event carry the full status", () => {+ const streams = readFileSync("src/triggers/viewer-streams.ts", "utf-8");+ expect(streams).toContain("status: await consolidationStatus({ lastRun }).catch(() => null),");+ expect(streams).toContain("status: await consolidationStatus({ lastRun: lastRun ?? null }).catch(() => null),");+ });+it("the dashboard shows one Memory layers panel instead of the three separate cards", () => {expect(viewer).toMatch(/apiGet\('consolidation\/status'\)/);- expect(viewer).toMatch(/html \+= renderMemoryLayers\(d\.consolidation, semFacts, procItems\);/);+ expect(viewer).toMatch(/html \+= renderMemoryLayers\(store\.consolidationStatus, entityList\('semantic'\), entityList\('procedural'\)\);/);expect(viewer).not.toMatch(/card-title">Semantic Memory|card-title">Procedural Memory|card-title">Consolidation Status/);expect(viewer).not.toMatch(/consolidation-row/);});diff --git a/test/lessons.test.ts b/test/lessons.test.tsindex b55fb597..17213256 100644--- a/test/lessons.test.ts+++ b/test/lessons.test.ts@@ -4,7 +4,7 @@ vi.mock("../src/logger.js", () => ({logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },}));-import { registerLessonsFunctions } from "../src/functions/lessons.js";+import { normalizeLessonSourceIds, registerLessonsFunctions } from "../src/functions/lessons.js";import type { Lesson } from "../src/types.js";function mockKV() {@@ -129,6 +129,33 @@ describe("Lessons", () => {expect(result.lesson.sourceIds).toEqual(["crys_123"]);expect(result.lesson.confidence).toBe(0.6);});++ it("merges new sourceIds into an existing lesson when it is strengthened", async () => {+ await sdk.trigger("mem::lesson-save", { content: "Run tsc first", sourceIds: ["ses_a", "mem_1"] });+ const result = (await sdk.trigger("mem::lesson-save", {+ content: "Run tsc first",+ sourceIds: ["mem_1", "ses_b"],+ })) as { action: string; lesson: Lesson };++ expect(result.action).toBe("strengthened");+ expect(result.lesson.sourceIds).toEqual(["ses_a", "mem_1", "ses_b"]);+ });+ });++ describe("normalizeLessonSourceIds", () => {+ it("trims, dedupes and accepts a missing value", () => {+ expect(normalizeLessonSourceIds(undefined)).toEqual([]);+ expect(normalizeLessonSourceIds([" ses_1 ", "ses_1", "mem_2"])).toEqual(["ses_1", "mem_2"]);+ });++ it("rejects anything that is not a short list of id strings", () => {+ expect(normalizeLessonSourceIds("ses_1")).toBeNull();+ expect(normalizeLessonSourceIds([1])).toBeNull();+ expect(normalizeLessonSourceIds([""])).toBeNull();+ expect(normalizeLessonSourceIds(["two words"])).toBeNull();+ expect(normalizeLessonSourceIds(["x".repeat(201)])).toBeNull();+ expect(normalizeLessonSourceIds(Array.from({ length: 51 }, (_, i) => `ses_${i}`))).toBeNull();+ });});describe("mem::lesson-recall", () => {diff --git a/test/list-query.test.ts b/test/list-query.test.tsnew file mode 100644index 00000000..a409b4b1--- /dev/null+++ b/test/list-query.test.ts@@ -0,0 +1,83 @@+import { describe, it, expect } from "vitest";+import {+ LIST_PAGE_MAX,+ decodeCursor,+ encodeCursor,+ matchesText,+ pageAfterCursor,+ pageByOffset,+ parseListQuery,+ sortByKeyDesc,+} from "../src/state/list-query.js";++type Row = { id: string; at: string };+const keyOf = (r: Row) => r.at;+const idOf = (r: Row) => r.id;++function rows(): Row[] {+ return sortByKeyDesc(+ [+ { id: "a", at: "2026-01-01" },+ { id: "b", at: "2026-01-03" },+ { id: "c", at: "2026-01-02" },+ { id: "d", at: "2026-01-03" },+ { id: "e", at: "2026-01-05" },+ ],+ keyOf,+ idOf,+ );+}++describe("list query helpers", () => {+ it("parses filters and clamps the page size", () => {+ const q = parseListQuery({ limit: "9999", project: " web ", type: "fact", q: " ", cursor: "abc", status: "active" });+ expect(q).toEqual({ limit: LIST_PAGE_MAX, cursor: "abc", project: "web", type: "fact", status: "active", q: undefined });+ expect(parseListQuery({ limit: "0" }).limit).toBeUndefined();+ expect(parseListQuery({ limit: "abc" }).limit).toBeUndefined();+ expect(parseListQuery(undefined)).toEqual({});+ });++ it("sorts newest first with id as the tiebreak", () => {+ expect(rows().map((r) => r.id)).toEqual(["e", "d", "b", "c", "a"]);+ });++ it("walks every row exactly once across cursor pages", () => {+ const sorted = rows();+ const seen: string[] = [];+ let cursor: string | undefined;+ for (let i = 0; i < 10; i++) {+ const { page, nextCursor } = pageAfterCursor(sorted, keyOf, idOf, cursor, 2);+ seen.push(...page.map((r) => r.id));+ if (!nextCursor) break;+ cursor = nextCursor;+ }+ expect(seen).toEqual(["e", "d", "b", "c", "a"]);+ });++ it("keeps the next page stable when a newer row arrives between requests", () => {+ const first = pageAfterCursor(rows(), keyOf, idOf, undefined, 2);+ const grown = sortByKeyDesc([...rows(), { id: "z", at: "2026-02-01" }], keyOf, idOf);+ const second = pageAfterCursor(grown, keyOf, idOf, first.nextCursor ?? undefined, 2);+ expect(second.page.map((r) => r.id)).toEqual(["b", "c"]);+ });++ it("pages by offset for relevance-ordered results", () => {+ const ordered = ["x", "y", "z"];+ const first = pageByOffset(ordered, undefined, 2);+ expect(first.page).toEqual(["x", "y"]);+ const second = pageByOffset(ordered, first.nextCursor ?? undefined, 2);+ expect(second).toEqual({ page: ["z"], nextCursor: null });+ });++ it("ignores malformed cursors", () => {+ expect(decodeCursor("not-base64-json")).toBeNull();+ expect(decodeCursor(encodeCursor({ offset: -1 }))).toEqual({});+ expect(pageAfterCursor(rows(), keyOf, idOf, "garbage", 2).page.map((r) => r.id)).toEqual(["e", "d"]);+ });++ it("matches text case-insensitively across fields", () => {+ expect(matchesText("AUTH", "fix auth bug", undefined)).toBe(true);+ expect(matchesText("auth", null, "other")).toBe(false);+ expect(matchesText(undefined, "anything")).toBe(true);+ });+});diff --git a/test/memories-pagination.test.ts b/test/memories-pagination.test.tsindex 4259b088..de05d1d7 100644--- a/test/memories-pagination.test.ts+++ b/test/memories-pagination.test.ts@@ -35,18 +35,19 @@ describe("memories + export pagination (#544)", () => {);});- it("viewer dashboard counts memories via count=true and the tab caps its fetch", () => {+ it("viewer pages memories by cursor and takes counts from the stream instead of re-counting", () => {const viewer = readFileSync("src/viewer/index.html", "utf-8");- expect(viewer).toMatch(/memories\?latest=true&count=true/);- expect(viewer).not.toMatch(/memories\?latest=true&limit=500/);- expect(viewer).toMatch(/memories\?latest=true&limit=2000/);+ expect(viewer).toMatch(/var path = 'memories\?latest=true&limit=100';/);+ expect(viewer).toMatch(/memoryQueryPath\('&cursor=' \+ encodeURIComponent\(cursor\)\)/);+ expect(viewer).toMatch(/memoryQueryPath\('&q=' \+ encodeURIComponent\(query\)\)/);+ expect(viewer).not.toMatch(/memories\?latest=true&count=true/);+ expect(viewer).not.toMatch(/memories\?latest=true&limit=2000/);});it("api::memories orders the list newest first before slicing a page", () => {- expect(api).toMatch(- /filtered\.sort\(\(a, b\) =>\s*\(b\.updatedAt \|\| b\.createdAt \|\| ""\)\.localeCompare\(/,- );- expect(api.indexOf("filtered.sort(")).toBeLessThan(+ expect(api).toMatch(/sortByKeyDesc\(filtered, memorySortKey, \(m\) => m\.id\)/);+ expect(api).toMatch(/return m\.updatedAt \|\| m\.createdAt \|\| "";/);+ expect(api.indexOf("sortByKeyDesc(filtered, memorySortKey")).toBeLessThan(api.indexOf("filtered.slice(offset"),);});diff --git a/test/profile.test.ts b/test/profile.test.tsindex fbc7b017..36dc34e3 100644--- a/test/profile.test.ts+++ b/test/profile.test.ts@@ -14,6 +14,7 @@ import type {function mockKV() {const store = new Map<string, Map<string, unknown>>();return {+ store,get: async <T>(scope: string, key: string): Promise<T | null> => {return (store.get(scope)?.get(key) as T) ?? null;},@@ -130,6 +131,46 @@ describe("Profile Function", () => {expect(result.profile.topFiles[0].frequency).toBe(2);});+ it("counts concepts from the project's latest memories", async () => {+ await kv.set("mem:memories", "mem_1", {+ id: "mem_1",+ project: "my-project",+ concepts: ["caching", "typescript"],+ isLatest: true,+ });+ await kv.set("mem:memories", "mem_2", {+ id: "mem_2",+ project: "my-project",+ concepts: ["caching"],+ isLatest: false,+ });+ await kv.set("mem:memories", "mem_3", {+ id: "mem_3",+ project: "other-project",+ concepts: ["caching"],+ isLatest: true,+ });++ const result = (await sdk.trigger("mem::profile", {+ project: "my-project",+ })) as { profile: ProjectProfile };++ const concepts = Object.fromEntries(+ result.profile.topConcepts.map((c) => [c.concept, c.frequency]),+ );+ expect(concepts["typescript"]).toBe(3);+ expect(concepts["caching"]).toBe(1);+ });++ it("does not write an audit entry when it builds a profile", async () => {+ await sdk.trigger("mem::profile", { project: "my-project", refresh: true });++ const auditScopes = Array.from(kv.store.keys()).filter((scope) =>+ scope.startsWith("mem:audit"),+ );+ expect(auditScopes).toEqual([]);+ });+it("extracts conventions from file patterns", async () => {const result = (await sdk.trigger("mem::profile", {project: "my-project",@@ -151,6 +192,59 @@ describe("Profile Function", () => {expect(result.cached).toBe(true);});+ it("drops search paths and patterns that older observations recorded as files", async () => {+ await kv.set("mem:obs:ses_1", "obs_4", {+ id: "obs_4",+ sessionId: "ses_1",+ timestamp: "2026-02-01T13:00:00Z",+ type: "search",+ title: "Grep",+ facts: [],+ narrative: "search",+ concepts: [],+ files: ["/tmp/my-project", "/tmp/my-project/", "computeTotal", "web-app", "src/**/*.ts", "/project/src/components", "Dockerfile", "/project/.env"],+ importance: 3,+ });++ const result = (await sdk.trigger("mem::profile", {+ project: "my-project",+ refresh: true,+ })) as { profile: ProjectProfile };++ expect(result.profile.topFiles.map((f) => f.file).sort()).toEqual([+ "/project/.env",+ "/project/src/auth.ts",+ "/project/src/db.ts",+ "/project/src/middleware.ts",+ "Dockerfile",+ ]);+ });++ it("cleans a cached profile built before search paths were filtered", async () => {+ await kv.set("mem:profiles", "my-project", {+ project: "my-project",+ updatedAt: new Date().toISOString(),+ topConcepts: [],+ topFiles: [+ { file: "web-app", frequency: 5 },+ { file: "computeTotal", frequency: 5 },+ { file: "src/api/orders.ts", frequency: 4 },+ ],+ conventions: ["TypeScript project"],+ commonErrors: [],+ recentActivity: [],+ sessionCount: 1,+ totalObservations: 3,+ });++ const result = (await sdk.trigger("mem::profile", {+ project: "my-project",+ })) as { profile: ProjectProfile; cached: boolean };++ expect(result.cached).toBe(true);+ expect(result.profile.topFiles).toEqual([{ file: "src/api/orders.ts", frequency: 4 }]);+ });+it("returns null profile for unknown project", async () => {const result = (await sdk.trigger("mem::profile", {project: "nonexistent",diff --git a/test/relations.test.ts b/test/relations.test.tsindex bf6025e7..6f40a97f 100644--- a/test/relations.test.ts+++ b/test/relations.test.ts@@ -5,6 +5,8 @@ vi.mock("../src/logger.js", () => ({}));import { registerRelationsFunction } from "../src/functions/relations.js";+import { getSearchIndex } from "../src/functions/search.js";+import { memoryToObservation } from "../src/state/memory-utils.js";import type { Memory } from "../src/types.js";function mockKV() {@@ -156,6 +158,40 @@ describe("Relations Functions", () => {expect((result as { success: boolean }).success).toBe(false);});++ it("refuses to fork an older version, an unchanged edit or an unknown type", async () => {+ await kv.set("mem:memories", "mem_old", makeMemory({ id: "mem_old", isLatest: false }));+ await kv.set("mem:memories", "mem_cur", makeMemory({ id: "mem_cur" }));++ const older = (await sdk.trigger("mem::evolve", { memoryId: "mem_old", newContent: "x" })) as { success: boolean; code: string };+ expect(older).toMatchObject({ success: false, code: "not_latest" });+ const same = (await sdk.trigger("mem::evolve", { memoryId: "mem_cur", newContent: "This is a test memory" })) as { success: boolean; code: string };+ expect(same).toMatchObject({ success: false, code: "unchanged" });+ const badType = (await sdk.trigger("mem::evolve", { memoryId: "mem_cur", newContent: "y", newType: "nope" })) as { success: boolean };+ expect(badType.success).toBe(false);+ expect((await kv.get<Memory>("mem:memories", "mem_cur"))!.isLatest).toBe(true);+ });++ it("re-derives a content-derived title, applies a new type and moves the search entry", async () => {+ const content = "Checkout applies coupons before shipping thresholds";+ await kv.set("mem:memories", "mem_t", makeMemory({ id: "mem_t", title: content, content, type: "fact" }));+ getSearchIndex().add(memoryToObservation(makeMemory({ id: "mem_t", title: content, content })));++ const result = (await sdk.trigger("mem::evolve", {+ memoryId: "mem_t",+ newContent: "Checkout applies gift cards after coupons",+ newType: "bug",+ })) as { success: boolean; memory: Memory };++ expect(result.success).toBe(true);+ expect(result.memory.title).toBe("Checkout applies gift cards after coupons");+ expect(result.memory.type).toBe("bug");+ expect(result.memory.supersedes).toEqual(["mem_t"]);+ const hits = getSearchIndex().search("gift cards", 5).map((h) => h.obsId);+ expect(hits).toContain(result.memory.id);+ expect(getSearchIndex().search("thresholds", 5).map((h) => h.obsId)).not.toContain("mem_t");+ getSearchIndex().remove(result.memory.id);+ });});describe("mem::get-related", () => {diff --git a/test/replay.test.ts b/test/replay.test.tsindex f5dfb9a6..1ebc0d91 100644--- a/test/replay.test.ts+++ b/test/replay.test.ts@@ -3,6 +3,7 @@ import { readFileSync } from "node:fs";import { join } from "node:path";import { parseJsonlText } from "../src/replay/jsonl-parser.js";import { projectTimeline } from "../src/replay/timeline.js";+import { rawFromCompressed } from "../src/functions/replay.js";const fx = (name: string) =>readFileSync(join(__dirname, "fixtures/jsonl", name), "utf-8");@@ -143,3 +144,26 @@ describe("projectTimeline", () => {});});+describe("rawFromCompressed", () => {+ const base = { sessionId: "ses_1", facts: [], concepts: [], files: [], importance: 5 };++ it("replays hook-captured sessions with prompts, tool names, inputs and outputs", () => {+ const timeline = projectTimeline([+ rawFromCompressed({ ...base, id: "o1", timestamp: "2026-09-01T00:00:00Z", type: "conversation", title: "prompt_submit", narrative: "Fix the checkout total" } as never),+ rawFromCompressed({ ...base, id: "o2", timestamp: "2026-09-01T00:00:05Z", type: "file_read", title: "Read", narrative: '{"file_path":"src/a.ts"} | export const a = 1' } as never),+ rawFromCompressed({ ...base, id: "o3", timestamp: "2026-09-01T00:00:09Z", type: "error", title: "Bash", narrative: '{"command":"npm test"} | exit 1' } as never),+ rawFromCompressed({ ...base, id: "o4", timestamp: "2026-09-01T00:00:12Z", type: "decision", title: "Chose jose", narrative: "The API validates JWTs with jose." } as never),+ ]);+ expect(timeline.events.map((e) => [e.kind, e.label])).toEqual([+ ["prompt", "Fix the checkout total"],+ ["tool_result", "Read ▸ result"],+ ["tool_error", "Bash ▸ error"],+ ["tool_result", "Chose jose ▸ result"],+ ]);+ expect(timeline.events[0].body).toBe("Fix the checkout total");+ expect(timeline.events[1].toolInput).toEqual({ file_path: "src/a.ts" });+ expect(timeline.events[1].toolOutput).toBe("export const a = 1");+ expect(timeline.events[3].toolOutput).toBe("The API validates JWTs with jose.");+ });+});+diff --git a/test/search-index.test.ts b/test/search-index.test.tsindex 805faec4..50cef88a 100644--- a/test/search-index.test.ts+++ b/test/search-index.test.ts@@ -29,6 +29,15 @@ describe("SearchIndex", () => {index = new SearchIndex();});+ it("counts memory and lesson documents apart from observations", () => {+ index.add(makeObs({ id: "obs_1" }));+ index.add(makeObs({ id: "mem_1", sessionId: "memory" }));+ index.add(makeObs({ id: "mem_2", sessionId: "ses_1" }));+ index.add(makeObs({ id: "lsn_1", sessionId: "lesson" }));++ expect(index.documentKindCounts()).toEqual({ memories: 2, lessons: 1 });+ });+it("starts empty", () => {expect(index.size).toBe(0);});diff --git a/test/status.test.ts b/test/status.test.tsindex 2160a65f..2448640d 100644--- a/test/status.test.ts+++ b/test/status.test.ts@@ -2,6 +2,8 @@ import { describe, it, expect } from "vitest";import { readFileSync } from "node:fs";import {evaluateStatus,+ markLlmFunctions,+ describeHealthAlert,prefersHtml,renderStatusHtml,singleFlight,@@ -78,7 +80,9 @@ describe("evaluateStatus", () => {);const critical = evaluateStatus(inputs({ health: { status: "critical", alerts: ["kv unreachable"] } }));expect(critical.status).toBe("error");- expect(codes(critical)).toEqual(["health-critical", "health-alert"]);+ expect(codes(critical)).toEqual(["health-alert"]);+ const bare = evaluateStatus(inputs({ health: { status: "critical", alerts: [] } }));+ expect(codes(bare)).toEqual(["health-critical"]);});it("warns about observations missing from the search index and says how to fix it", () => {@@ -140,6 +144,89 @@ describe("evaluateStatus", () => {});});+describe("status without an LLM provider", () => {+ const llmFlag = {+ key: "CONSOLIDATION_ENABLED",+ label: "Memory consolidation",+ enabled: true,+ needsLlm: true,+ enableHow: "Set CONSOLIDATION_ENABLED=true",+ };+ const plainFlag = {+ key: "AGENTMEMORY_REFLECT",+ label: "Reflect",+ enabled: true,+ needsLlm: false,+ enableHow: "Set AGENTMEMORY_REFLECT=true",+ };++ it("shows LLM functions as off instead of failing and raises no failure warning", () => {+ const report = evaluateStatus(+ inputs({+ provider: "noop",+ functionMetrics: [+ { functionId: "mem::summarize", totalCalls: 12, successCount: 0, failureCount: 12, avgLatencyMs: 3 },+ { functionId: "mem::search", totalCalls: 10, successCount: 2, failureCount: 8, avgLatencyMs: 3 },+ ],+ }),+ );+ const summarize = report.functions.find((f) => f.functionId === "mem::summarize");+ expect(summarize?.offWithoutLlm).toBe(true);+ const failing = report.problems.filter((p) => p.code === "function-failing");+ expect(failing.map((p) => p.message)).toEqual(["mem::search failed 8 of 10 calls (80%)."]);+ const html = renderStatusHtml(report, "n");+ expect(html).toContain("off, no LLM provider");+ });++ it("marks an enabled feature that needs an LLM as inactive, not simply on", () => {+ const report = evaluateStatus(inputs({ provider: "noop", flags: [llmFlag, plainFlag] }));+ expect(report.flags[0].inactiveReason).toBe("needs an LLM provider, none is configured");+ expect(report.flags[1].inactiveReason).toBeUndefined();+ const html = renderStatusHtml(report, "n");+ expect(html).toContain("on, inactive: needs an LLM provider, none is configured");+ expect(html).not.toMatch(/<td>Memory consolidation<\/td><td>on<\/td>/);+ });++ it("keeps enabled LLM features plainly on when a provider exists", () => {+ const report = evaluateStatus(inputs({ flags: [llmFlag] }));+ expect(report.flags[0].inactiveReason).toBeUndefined();+ expect(renderStatusHtml(report, "n")).toMatch(/<td>Memory consolidation<\/td><td><code>CONSOLIDATION_ENABLED<\/code><\/td><td>on<\/td><td>Set CONSOLIDATION_ENABLED=false and restart to turn it off.<\/td>/);+ });+});++describe("status page wording", () => {+ it("explains why the BM25 count differs from observations", () => {+ const report = evaluateStatus(+ inputs({ index: { ...inputs().index, bm25Documents: 211, observationsIndexed: 185, memoriesIndexed: 26, lessonsIndexed: 2 } }),+ );+ expect(renderStatusHtml(report, "n")).toContain("211 (183 observations, 26 memories, 2 lessons)");+ });++ it("pluralizes counts and drops the manual refresh link", () => {+ const report = evaluateStatus(+ inputs({+ indexPersistence: {+ saveIntervalMs: 600000,+ saving: false,+ buckets: 1,+ pendingChanges: 1,+ vector: { lastSavedAt: "2026-09-24T11:59:00.000Z", dirtySince: null, lastError: null, lastErrorAt: null },+ vectorCountShortfall: null,+ },+ }),+ );+ const html = renderStatusHtml(report, "n");+ expect(html).toContain("1 bucket, 1 unsaved change");+ expect(html).not.toContain(">refresh</a>");+ });++ it("does not show a bare healthy process next to a warning badge", () => {+ const report = evaluateStatus(inputs({ index: { ...inputs().index, missingObservations: 3 } }));+ const html = renderStatusHtml(report, "n");+ expect(html).toContain("<th>Process health</th><td>healthy (memory, CPU and engine checks only;");+ });+});+describe("missing health snapshot", () => {it("says the health check was not run instead of reporting ok", () => {const report = evaluateStatus(inputs({ health: null }));@@ -212,12 +299,81 @@ describe("renderStatusHtml", () => {);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"]) {+ for (const heading of ["Problems", "Engine and connection", "LLM and embeddings", "Search index", "Knowledge graph", "Features", "Process", "Functions"]) {expect(html).toContain(`<h2>${heading}</h2>`);}});});+describe("status for beginners", () => {+ it("turns health alert slugs into sentences with a fix", () => {+ const report = evaluateStatus(+ inputs({ health: { status: "degraded", alerts: ["event_loop_lag_warn_240ms"], connectionState: "connected" } }),+ );+ expect(report.problems).toHaveLength(1);+ expect(report.problems[0]).toMatchObject({ level: "warn", code: "health-alert" });+ expect(report.problems[0].message).toMatch(/240 ms behind/);+ expect(report.problems[0].fix).toMatch(/restart agentmemory/);+ expect(describeHealthAlert("memory_critical_97%_rss900mb").level).toBe("error");+ expect(describeHealthAlert("connection_disconnected").message).toMatch(/iii engine is disconnected/);+ });++ it("gives every problem a fix", () => {+ const report = evaluateStatus(+ inputs({+ health: null,+ provider: "noop",+ circuitBreaker: { state: "open", failures: 3 },+ index: { ...inputs().index, missingObservations: null, bm25Incomplete: true, pendingVectorBackfill: 4 },+ graph: { totalNodes: 1, totalEdges: 0, fromSnapshot: true, updatedAt: "2026-09-20T00:00:00.000Z", dirty: true },+ }),+ );+ expect(report.problems.length).toBeGreaterThan(5);+ for (const p of report.problems) expect(p.fix, p.code).toBeTruthy();+ });++ it("states the verdict in one plain sentence", () => {+ expect(evaluateStatus(inputs()).headline).toMatch(/^Every check passed/);+ expect(evaluateStatus(inputs({ provider: "noop" })).headline).toBe("Working normally. 1 note below about features that are off or checks that did not run.");+ const report = evaluateStatus(inputs({ provider: "noop", index: { ...inputs().index, missingObservations: 2 } }));+ expect(report.status).toBe("warn");+ expect(report.headline).toMatch(/^Working, but needs attention: 2 stored observations are not in the search index/);+ expect(report.headline).toMatch(/1 more item below/);+ });++ it("breaks the keyword index down and lists what is off without an LLM", () => {+ const report = evaluateStatus(+ inputs({+ provider: "noop",+ index: { ...inputs().index, bm25Documents: 211, observationsIndexed: 185, memoriesIndexed: 26, lessonsIndexed: 2 },+ }),+ );+ expect(report.index.breakdown).toEqual({ observations: 183, memories: 26, lessons: 2 });+ expect(report.provider.offWithoutLlm).toContain("session summaries");+ expect(evaluateStatus(inputs()).provider.offWithoutLlm).toEqual([]);+ });++ it("links to the live viewer page, shows the curl call and explains the process numbers", () => {+ const report = evaluateStatus(+ inputs({+ health: {+ status: "healthy",+ alerts: [],+ connectionState: "connected",+ memory: { heapUsed: 50 * 1048576, heapTotal: 80 * 1048576, heapLimit: 4096 * 1048576, rss: 140 * 1048576 },+ eventLoopLagMs: 1.25,+ },+ }),+ );+ const html = renderStatusHtml(report, "n", { viewerUrl: "http://127.0.0.1:3113/#health" });+ expect(html).toContain('<a href="http://127.0.0.1:3113/#health">Open the live version in the viewer');+ expect(html).toContain("curl -s http://localhost:3111/agentmemory/status");+ expect(html).toContain("50 MB of 4096 MB (1%)");+ expect(html).toContain("1.3 ms");+ expect(renderStatusHtml(report, "n")).toContain('href="/agentmemory/viewer#health"');+ });+});+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);@@ -240,10 +396,24 @@ describe("status wiring", () => {});it("time-boxes every status probe so a slow store cannot hang the page", () => {+ const reporter = api.slice(api.indexOf("export function createStatusReporter"), api.indexOf("export function createConsolidationStatusReader"));+ expect(reporter.match(/valueWithin\(/g)?.length).toBe(4);+ expect(reporter).toMatch(/valueWithin\(scan\.run\(\), STATUS_CHECK_TIMEOUT_MS\)/);+ expect(api).toMatch(/run: singleFlight\(async \(\) => \{\s*const value = await findUnindexedObservations\(kv\);/);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\);/);+ expect(handler).toContain("const report = await statusReport();");+ });++ it("streams the same report to the viewer on every health tick and in the snapshot", () => {+ const streams = readFileSync("src/triggers/viewer-streams.ts", "utf-8");+ expect(streams).toMatch(/statusReport\(\{ health: snapshot, scanMaxAgeMs \}\)/);+ expect(streams).toContain("healthPayload(payload.new_value ?? null, HEALTH_TICK_SCAN_MAX_AGE_MS)");+ expect(streams).toContain("healthPayload(health ?? null, UNINDEXED_SCAN_REUSE_MS)");+ });++ it("names the embedding provider instead of a generic label", () => {+ expect(api).not.toContain('? "embeddings" : "none"');+ expect(api.match(/describeEmbeddingProvider\(\)/g)?.length).toBe(3);});it("config flags and status share one flag list", () => {@@ -252,10 +422,29 @@ describe("status wiring", () => {});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(/<button type="button" role="tab" data-tab="health"[^>]*>Health<\/button>/);+ expect(viewer).toContain('<div id="view-health" class="view" role="tabpanel" aria-label="Health"></div>');+ expect(viewer).toMatch(/'activity', 'profile', 'health', 'audit'\];/);+ expect(viewer).toMatch(/case 'health': renderHealth\(\); break;/);+ expect(viewer).toContain("s.report = data.report;");+ expect(viewer).not.toMatch(/if \(tab === 'health'\) ensureStatusReport\(\);/);expect(viewer).toMatch(/api\('status', \{ headers: \{ Accept: 'application\/json' \} \}\)/);});});++describe("markLlmFunctions", () => {+ const metrics = [+ { functionId: "mem::summarize", totalCalls: 12, successCount: 0, failureCount: 12, avgLatencyMs: 1 },+ { functionId: "mem::observe", totalCalls: 40, successCount: 40, failureCount: 0, avgLatencyMs: 2 },+ ];++ it("marks LLM functions off when no provider is configured", () => {+ const marked = markLlmFunctions(metrics, "noop");+ expect(marked.map((m) => m.offWithoutLlm)).toEqual([true, false]);+ expect(marked[0].failureCount).toBe(12);+ });++ it("leaves every function on when an LLM provider is configured", () => {+ expect(markLlmFunctions(metrics, "llm").some((m) => m.offWithoutLlm)).toBe(false);+ });+});diff --git a/test/summarize.test.ts b/test/summarize.test.tsindex 4723da87..f8f550e2 100644--- a/test/summarize.test.ts+++ b/test/summarize.test.ts@@ -125,6 +125,7 @@ async function setupHandler(opts: {sessionId: string;obsCount: number;provider: MemoryProvider;+ metricsStore?: unknown;}) {const sdk = mockSdk();const kv = mockKV();@@ -141,7 +142,7 @@ async function setupHandler(opts: {const o = makeObs(i, opts.sessionId);await kv.set(`obs:${opts.sessionId}`, o.id, o);}- registerSummarizeFunction(sdk as any, kv as any, opts.provider);+ registerSummarizeFunction(sdk as any, kv as any, opts.provider, opts.metricsStore as any);const handler = sdk.functions.get("mem::summarize")!;return { handler, kv };}@@ -480,3 +481,22 @@ describe("mem::summarize chunking", () => {expect(result.error).toBe("parse_failed");});});++describe("mem::summarize without an LLM provider", () => {+ it("skips a wrapped noop provider without recording a failed call", async () => {+ const { ResilientProvider } = await import("../src/providers/resilient.js");+ const { NoopProvider } = await import("../src/providers/noop.js");+ const record = vi.fn(async () => {});+ const { handler } = await setupHandler({+ sessionId: "ses_noop",+ obsCount: 3,+ provider: new ResilientProvider(new NoopProvider()),+ metricsStore: { record },+ });++ const result = (await handler({ sessionId: "ses_noop" })) as { success: boolean; error?: string };++ expect(result).toMatchObject({ success: false, error: "no_provider" });+ expect(record).not.toHaveBeenCalled();+ });+});diff --git a/test/viewer-dashboard-reliability.test.ts b/test/viewer-dashboard-reliability.test.tsindex 16fe12bd..e5a8e435 100644--- a/test/viewer-dashboard-reliability.test.ts+++ b/test/viewer-dashboard-reliability.test.ts@@ -21,48 +21,206 @@ function load<T>(name: string): T {return new Function(`${extractFunction(name)}\nreturn ${name};`)() as T;}-describe("viewer dashboard reliability", () => {- it("observations never reload the dashboard; pushed session and memory events update it in place", () => {- const router = extractFunction("routeWsMessage");- expect(router).not.toMatch(/loadDashboard\(\)|scheduleDashboardReload\(\)/);- const live = extractFunction("handleLiveEvent");- expect(live).not.toMatch(/loadDashboard\(\)/);- expect(live).toMatch(/type === 'session\.updated'/);- expect(live).toMatch(/type === 'session\.activity'/);- expect(live).toMatch(/type === 'session\.deleted'/);- expect(live).toMatch(/type === 'memory\.updated' \|\| type === 'memory\.deleted'/);- expect(live).toMatch(/scheduleLiveRender\(\);\s*\}$/);- expect(viewer).toMatch(/var LIVE_RENDER_THROTTLE_MS = 250;/);- expect(extractFunction("handleStreamEvent")).toMatch(- /evt\.type === 'event' && evt\.event && evt\.event\.type\) \{\s*handleLiveEvent\(evt\.event\.type, evt\.event\.data \|\| \{\}\);/,- );+function callbackBodies(marker: string): string[] {+ const bodies: string[] = [];+ let from = 0;+ for (;;) {+ const at = viewer.indexOf(marker, from);+ if (at < 0) return bodies;+ const open = viewer.indexOf("{", at);+ let depth = 0;+ for (let i = open; i < viewer.length; i++) {+ if (viewer[i] === "{") depth++;+ if (viewer[i] === "}") {+ depth--;+ if (depth === 0) {+ bodies.push(viewer.slice(at, i + 1));+ break;+ }+ }+ }+ from = at + marker.length;+ }+}++type Store = {+ entities: Record<string, Record<string, Record<string, unknown>>>;+ counts?: unknown;+ status?: string;+ health?: unknown;+ circuitBreaker?: unknown;+ functionMetrics?: unknown[];+ indexes?: unknown;+ lastHealthAt?: number;+ graph?: unknown;+ consolidation?: unknown;+};++function reducer() {+ const deps = ["sessionKey", "applyEntityEvent", "reduceLiveEvent"].map(extractFunction).join("\n");+ return new Function(+ `var ROW_EVENT_KINDS = ['lesson', 'action', 'crystal', 'semantic', 'procedural', 'audit'];\n${deps}\nreturn reduceLiveEvent;`,+ )() as (s: Store, type: string, data: Record<string, unknown>) => Record<string, unknown> | null;+}++function emptyStore(): Store {+ return {+ entities: { memory: {}, session: {}, lesson: {}, action: {}, crystal: {}, semantic: {}, procedural: {}, audit: {} },+ };+}++describe("viewer streams instead of polling", () => {+ it("has no polling or refetch loops left", () => {+ for (const name of [+ "startPolling",+ "POLL_INTERVAL_MS",+ "scheduleStaleRetry",+ "STALE_RETRY_MS",+ "scheduleDashboardReload",+ "refreshMemoryCount",+ "scheduleMemoriesReload",+ "TAB_FRESH_MS",+ "tabFetchedAt",+ ]) {+ expect(viewer, name).not.toContain(name);+ }+ });++ it("no interval timer touches the network", () => {+ const intervals = callbackBodies("setInterval(function");+ expect(intervals.length).toBeGreaterThan(0);+ for (const body of intervals) {+ expect(body).not.toMatch(/\bapi(Get|Post|Delete)?\(|\bfetch\(|\bload[A-Z]\w*\(|ensure\w+\(/);+ }+ });++ it("the ambient background renders on animation frames and pauses while the tab is hidden", () => {+ const dither = viewer.slice(viewer.indexOf("(function ditherField()"));+ expect(dither).toMatch(/requestAnimationFrame\(frame\)/);+ expect(dither).toMatch(/if \(document\.hidden\) return;/);+ expect(dither).not.toMatch(/setInterval/);});- it("no timer re-fetches the dashboard and no refresh path blanks a loaded view", () => {- expect(viewer).not.toMatch(/startDashboardAutoRefresh|dashboardTimer|Auto-refresh 30s/);- expect(extractFunction("refreshDashboard")).not.toMatch(/loaded = false/);- expect(extractFunction("startPolling")).not.toMatch(/loaded = false/);- expect(extractFunction("endSession")).not.toMatch(/loaded = false/);- expect(extractFunction("confirmDeleteMemory")).not.toMatch(/loaded = false/);- });-- it("session events upsert, patch and remove sessions by id", () => {- const deps = ["sessionKey", "upsertSessionIn", "removeSessionFrom", "patchSessionCount"]- .map(extractFunction)- .join("\n");- const api = new Function(`${deps}\nreturn { upsertSessionIn, removeSessionFrom, patchSessionCount };`)() as {- upsertSessionIn: (l: Array<Record<string, unknown>>, s: Record<string, unknown>) => Array<Record<string, unknown>>;- removeSessionFrom: (l: Array<Record<string, unknown>>, k: string) => Array<Record<string, unknown>>;- patchSessionCount: (l: Array<Record<string, unknown>>, k: string, c: number) => void;- };- const list: Array<Record<string, unknown>> = [{ id: "a", status: "active", observationCount: 1 }];- api.upsertSessionIn(list, { id: "a", status: "completed" });- expect(list).toEqual([{ id: "a", status: "completed", observationCount: 1 }]);- api.upsertSessionIn(list, { id: "b", status: "active" });- expect(list.map((s) => s.id)).toEqual(["b", "a"]);- api.patchSessionCount(list, "a", 7);- expect(list[1].observationCount).toBe(7);- expect(api.removeSessionFrom(list, "b").map((s) => s.id)).toEqual(["a"]);+ it("fetches the snapshot once per connection and replays events that arrived during a list load", () => {+ const resync = extractFunction("resyncAfterConnect");+ expect(resync).toMatch(/await loadSnapshot\(\);/);+ expect(resync).toMatch(/reloadKinds\.forEach\(function\(k\) \{ store\.loaded\[k\] = false; \}\);/);+ expect(extractFunction("loadSnapshot")).toMatch(/apiGet\('viewer\/snapshot'\)/);+ const ensure = extractFunction("ensureLoaded");+ expect(ensure).toMatch(/var seqAtStart = eventSeq;/);+ expect(ensure).toMatch(/replayEventsSince\(seqAtStart, kind\);/);+ expect(viewer).toMatch(/ws\.onopen = function\(\) \{[\s\S]{0,700}resyncAfterConnect\(firstConnect\);/);+ });++ it("reconnects with capped exponential backoff and never falls back to polling", () => {+ const delay = load<(n: number) => number>("reconnectDelay");+ expect([1, 2, 3, 4, 5, 6, 7, 10].map(delay)).toEqual([1000, 2000, 4000, 8000, 16000, 30000, 30000, 30000]);+ expect(extractFunction("scheduleReconnect")).toMatch(/wsReconnectTimer = setTimeout\(connectWs, delay\);/);+ expect(viewer).toMatch(/var directFailed = true;/);+ expect(viewer).toMatch(/if \(directFailures >= DIRECT_FAILURE_THRESHOLD\) \{\s*directFailed = ws\.__direct;/);+ expect(viewer).toMatch(/addEventListener\('visibilitychange'[\s\S]{0,300}reconnectNow\(\);/);+ });++ it("shows an explicit reconnecting and offline state and marks data stale", () => {+ const render = extractFunction("renderConnection");+ expect(render).toMatch(/'reconnecting'/);+ expect(render).toMatch(/'offline'/);+ expect(render).toMatch(/Showing data as of/);+ expect(extractFunction("setConnection")).toMatch(/classList\.toggle\('is-stale'/);+ });+});++describe("viewer live event reducer", () => {+ it("upserts, updates and removes memories from the full row in the event", () => {+ const reduce = reducer();+ const s = emptyStore();+ reduce(s, "memory.created", { memoryId: "mem_1", memory: { id: "mem_1", title: "a", isLatest: true } });+ expect(s.entities.memory.mem_1).toEqual({ id: "mem_1", title: "a", isLatest: true });+ reduce(s, "memory.updated", { memoryId: "mem_1", memory: { id: "mem_1", isLatest: false } });+ expect(s.entities.memory.mem_1.isLatest).toBe(false);+ expect(s.entities.memory.mem_1.title).toBe("a");+ const change = reduce(s, "memory.deleted", { memoryId: "mem_1" });+ expect(s.entities.memory.mem_1).toBeUndefined();+ expect(change).toMatchObject({ kind: "memory", action: "deleted", id: "mem_1" });+ });++ it("treats a soft-deleted lesson as removed and patches other row kinds by id", () => {+ const reduce = reducer();+ const s = emptyStore();+ reduce(s, "lesson.created", { id: "lsn_1", lesson: { id: "lsn_1", content: "x" } });+ reduce(s, "lesson.updated", { id: "lsn_1", lesson: { id: "lsn_1", content: "x", deleted: true } });+ expect(s.entities.lesson.lsn_1).toBeUndefined();+ reduce(s, "action.created", { id: "act_1", action: { id: "act_1", status: "pending" } });+ reduce(s, "action.updated", { id: "act_1", action: { id: "act_1", status: "done" } });+ expect(s.entities.action.act_1.status).toBe("done");+ reduce(s, "audit.created", { id: "aud_1", audit: { id: "aud_1", operation: "remember" } });+ expect(Object.keys(s.entities.audit)).toEqual(["aud_1"]);+ });++ it("applies session updates, activity counts and deletes", () => {+ const reduce = reducer();+ const s = emptyStore();+ reduce(s, "session.updated", { session: { id: "a", status: "active", observationCount: 1 } });+ reduce(s, "session.activity", { sessionId: "a", observationCount: 9 });+ expect(s.entities.session.a.observationCount).toBe(9);+ reduce(s, "session.activity", { sessionId: "missing", observationCount: 3 });+ expect(s.entities.session.missing).toBeUndefined();+ reduce(s, "session.deleted", { sessionId: "a" });+ expect(s.entities.session.a).toBeUndefined();+ });++ it("takes counts, health and graph stats straight from the events", () => {+ const reduce = reducer();+ const s = emptyStore();+ reduce(s, "counts.changed", { counts: { memories: 4 } });+ expect(s.counts).toEqual({ memories: 4 });+ reduce(s, "health", { status: "degraded", health: { status: "degraded" }, circuitBreaker: { state: "open" }, functionMetrics: [{ functionId: "f" }], counts: { memories: 5 }, indexes: { bm25Documents: 2 } });+ expect(s.status).toBe("degraded");+ expect(s.counts).toEqual({ memories: 5 });+ expect(s.lastHealthAt).toBeGreaterThan(0);+ const g = reduce(s, "graph.changed", { source: "snapshot", stats: { totalNodes: 3 }, updatedAt: "t" });+ expect(g).toMatchObject({ kind: "graph", source: "snapshot" });+ expect(s.graph).toEqual({ stats: { totalNodes: 3 }, updatedAt: "t", resetAt: null });+ expect(reduce(s, "unknown.thing", {})).toBeNull();+ });+});++describe("viewer navigation and shared components", () => {+ it("parses deep links into a tab and an entity id", () => {+ const deps = ["normalizeTab", "decodePart", "parseRoute"].map(extractFunction).join("\n");+ const parse = new Function(+ `var TAB_IDS = ${viewer.match(/var TAB_IDS = (\[[^\]]*\]);/)?.[1]};\nvar TAB_ALIASES = ${viewer.match(/var TAB_ALIASES = (\{[^}]*\});/)?.[1]};\n${deps}\nreturn parseRoute;`,+ )() as (h: string) => { tab: string; id: string; obs: string; redirect: boolean };+ expect(parse("#memories/mem_abc")).toMatchObject({ tab: "memories", id: "mem_abc", obs: "", redirect: false });+ expect(parse("#sessions/ses%2Fone")).toMatchObject({ tab: "sessions", id: "ses/one" });+ expect(parse("#health")).toMatchObject({ tab: "health", id: "" });+ expect(parse("#nope/x")).toMatchObject({ tab: "dashboard", id: "x" });+ expect(parse("#sessions/ses_1?obs=obs%3A9")).toMatchObject({ tab: "sessions", id: "ses_1", obs: "obs:9" });+ expect(parse("#timeline/ses_1")).toMatchObject({ tab: "sessions", id: "ses_1", redirect: true });+ });++ it("every help tooltip used on a page has a glossary entry", () => {+ const glossaryBlock = viewer.slice(viewer.indexOf("var GLOSSARY = {"), viewer.indexOf("var state = {"));+ const keys = new Set([...glossaryBlock.matchAll(/^\s{6}(\w+): \{ term:/gm)].map((m) => m[1]));+ expect(keys.size).toBeGreaterThan(40);+ const used = new Set([...viewer.matchAll(/help\('(\w+)'\)/g)].map((m) => m[1]));+ for (const key of used) expect(keys.has(key), key).toBe(true);+ });++ it("empty states explain what, why and how, with commands aimed at the live origin", () => {+ const empty = extractFunction("emptyState");+ expect(empty).toMatch(/What this is/);+ expect(empty).toMatch(/Why it is empty/);+ expect(empty).toMatch(/How to fill it/);+ expect(extractFunction("apiBase")).toMatch(/return REST \+ '\/agentmemory';/);+ expect(viewer).not.toMatch(/localhost:3111/);+ });++ it("offers keyboard shortcuts for search, help and jumping between pages", () => {+ expect(viewer).toMatch(/if \(e\.key === '\/'\) \{\s*if \(focusPageSearch\(\)\) e\.preventDefault\(\);/);+ expect(viewer).toMatch(/if \(e\.key === '\?'\) \{\s*e\.preventDefault\(\);\s*openHelpOverlay\(\);/);+ expect(viewer).toMatch(/var jump = TAB_SHORTCUTS\[e\.key\.toLowerCase\(\)\];/);+ expect(viewer).toMatch(/role="tablist"/);});it("re-rendering identical HTML leaves the DOM alone, but a placeholder in between forces a render", () => {@@ -85,28 +243,6 @@ describe("viewer dashboard reliability", () => {expect(writes).toBe(3);});- it("connects with the join mode first and flips mode after two failures of either", () => {- expect(viewer).toMatch(/var directFailed = true;/);- expect(viewer).toMatch(/if \(directFailures >= DIRECT_FAILURE_THRESHOLD\) \{\s*directFailed = ws\.__direct;/);- });-- it("loadDashboard never runs twice at once and replays a request that arrived mid-flight", () => {- const loader = extractFunction("loadDashboard");- expect(loader).toMatch(/if \(dashboardLoading\) \{\s*dashboardReloadPending = true;\s*return;/);- expect(loader).toMatch(/finally \{\s*dashboardLoading = false;/);- });-- it("a failed refresh keeps the last data instead of showing the new-install hero", () => {- const loader = extractFunction("loadDashboard");- expect(loader).toMatch(/if \(sessionsOk\) d\.sessions = replaySessionEvents\(results\[1\]\.sessions, seqAtStart\);/);- expect(loader).toMatch(/if \(!sessionsOk && !d\.loaded\)/);- const listOr = load<(p: unknown[], r: unknown, k: string, f?: string) => unknown[]>("listOr");- expect(listOr([1, 2], null, "items")).toEqual([1, 2]);- expect(listOr([1, 2], { items: [3] }, "items")).toEqual([3]);- expect(listOr([1], { other: [4] }, "items", "other")).toEqual([4]);- expect(listOr([1], {}, "items")).toEqual([]);- });-it("token savings only counts sessions that produced observations", () => {const estimate = load<(s: Array<{ observationCount?: number }>, b: number) => { percent: number; saved: number }>("estimateTokenSavings",@@ -149,89 +285,22 @@ describe("viewer dashboard reliability", () => {expect(rebuild).toMatch(/window\.confirm\(/);expect(rebuild).toMatch(/result && result\.success/);expect(rebuild).toMatch(/finally \{\s*graphRebuilding = false;/);+ expect(rebuild).toMatch(/New ones arrive on the live stream\./);+ expect(rebuild).not.toMatch(/loadGraph\(/);});- it("a session list fetched while live events arrive replays them so deletes and updates stick", () => {- const deps = ["sessionKey", "upsertSessionIn", "removeSessionFrom", "patchSessionCount", "applySessionEvent", "replaySessionEvents"]- .map(extractFunction)- .join("\n");- const replay = new Function(- "liveSessionLog",- `${deps}\nreturn replaySessionEvents;`,- )([- { seq: 1, type: "session.deleted", data: { sessionId: "old" } },- { seq: 2, type: "session.deleted", data: { sessionId: "a" } },- { seq: 3, type: "session.updated", data: { session: { id: "c", status: "active" } } },- { seq: 4, type: "session.activity", data: { sessionId: "b", observationCount: 9 } },- ]) as (l: Array<Record<string, unknown>>, since: number) => Array<Record<string, unknown>>;- const fetched = [- { id: "a", observationCount: 1 },- { id: "b", observationCount: 2 },- { id: "old", observationCount: 0 },- ];- expect(replay(fetched, 1)).toEqual([- { id: "c", status: "active" },- { id: "b", observationCount: 9 },- { id: "old", observationCount: 0 },- ]);- expect(extractFunction("loadSessions")).toMatch(/replaySessionEvents\(result\.sessions, seqAtStart\)/);- });-- it("count updates rerender the session list without refetching or blanking the open detail", () => {- const render = extractFunction("renderSessions");- expect(render).toMatch(/cached\.id === state\.sessions\.selectedId && !state\.sessions\.detailStale/);- const detail = extractFunction("renderSessionDetail");- expect(detail).toMatch(/if \(!cached \|\| cached\.id !== id\) \{\s*panel\.innerHTML = '<div class="detail-panel"><h3>Loading/);- expect(detail).toMatch(/if \(request !== sessionDetailRequest \|\| state\.sessions\.selectedId !== id\) return;/);- expect(extractFunction("handleLiveEvent")).toMatch(- /if \(type !== 'session\.activity' && touched === state\.sessions\.selectedId\) \{\s*state\.sessions\.detailStale = true;/,- );- });-- it("memory events coalesce list reloads and only the newest count response wins", () => {- const reload = extractFunction("scheduleMemoriesReload");- expect(reload).toMatch(/if \(memoriesReloading\) \{\s*memoriesReloadPending = true;\s*return;/);- expect(reload).toMatch(/finally \{\s*memoriesReloading = false;/);- expect(extractFunction("handleLiveEvent")).not.toMatch(/loadMemories\(\)/);- expect(extractFunction("refreshMemoryCount")).toMatch(- /var request = \+\+memoryCountRequest;[\s\S]*if \(request !== memoryCountRequest\) return;/,- );- });-- it("a reconnect resyncs loaded views, and only a delivered message clears the failure count", () => {- expect(viewer).toMatch(/if \(wsHasConnected\) resyncLiveViews\(\);\s*wsHasConnected = true;/);- const resync = extractFunction("resyncLiveViews");- expect(resync).toMatch(/if \(state\.dashboard\.loaded\) loadDashboard\(\);/);- expect(resync).toMatch(/if \(state\.sessions\.loaded\) loadSessions\(\);/);- expect(viewer).toMatch(/if \(!ws\.__usable\) \{\s*ws\.__usable = true;\s*directFailures = 0;/);- const onopen = viewer.slice(viewer.indexOf("ws.onopen = function"), viewer.indexOf("ws.onmessage = function"));- expect(onopen).toMatch(/wsRetries = 0;/);- expect(onopen).not.toMatch(/directFailures = 0;/);- });-- it("a stale dashboard retries on its own slower timer, once at a time", () => {- expect(viewer).toMatch(/var STALE_RETRY_MS = 15000;/);- const retry = extractFunction("scheduleStaleRetry");- expect(retry).toMatch(/if \(staleRetryTimer\) return;/);- expect(retry).toMatch(/state\.dashboard\.stale\) loadDashboard\(\);/);- expect(extractFunction("loadDashboard")).toMatch(/if \(d\.stale\) scheduleStaleRetry\(\);/);- });-- it("the dashboard applies its memory total only when no newer count request started", () => {- const loader = extractFunction("loadDashboard");- expect(loader).toMatch(/var countToken = \+\+memoryCountRequest;/);- expect(loader).toMatch(/if \(countToken === memoryCountRequest && results\[2\]/);- });-- it("a rebuild whose graph refresh fails says so instead of reporting success", () => {- expect(extractFunction("rebuildGraph")).toMatch(- /await loadGraph\(\);\s*if \(state\.graph\.queryError && state\.graph\.rebuildResult\) \{\s*state\.graph\.rebuildResult = 'The rebuild finished, but the graph could not be refreshed/,- );- expect(viewer).toMatch(/consolidated ' \+ esc\(formatTime\(status\.lastRunAt\)\)/);+ it("the graph never builds itself: loading only reads, a rebuild is always a user click", () => {+ const loader = extractFunction("loadGraph");+ expect(loader).not.toMatch(/graph\/build/);+ expect(loader).toMatch(/apiPost\('graph\/query', \{ limit: GRAPH_LIMIT \}\)/);});- it("returning to the tab reconnects a dropped live stream (#1370)", () => {- expect(viewer).toMatch(/addEventListener\('visibilitychange'/);- expect(viewer).toMatch(/visibilityState !== 'visible'[\s\S]{0,400}connectWs\(\);/);+ it("graph.changed patches the loaded graph from the event payload and refetches only when it must", () => {+ const handler = extractFunction("handleGraphChange");+ expect(handler).toMatch(/if \(data\.delta && applyGraphDelta\(data\.delta\)\)/);+ expect(handler).toMatch(/if \(data\.source === 'items' && !data\.coveredBySnapshot\) scheduleGraphReload\(\);/);+ const reload = extractFunction("scheduleGraphReload");+ expect(reload).toMatch(/clearTimeout\(graphReloadTimer\)/);+ expect(reload).toMatch(/loadGraph\(\{ quiet: true \}\)/);});});diff --git a/test/viewer-graph-cooldown.test.ts b/test/viewer-graph-cooldown.test.tsindex 267301f9..869afeaa 100644--- a/test/viewer-graph-cooldown.test.ts+++ b/test/viewer-graph-cooldown.test.ts@@ -1,38 +1,30 @@import { describe, it, expect } from "vitest";import { readFileSync } from "node:fs";-// viewer graph kept bouncing on >1000 nodes because damping-// alone could not bleed off the per-frame force pile-up. Cool-down-// adds tick-decayed damping, a per-node velocity cap, and parks the-// raf loop when total kinetic energy drops below an epsilon.-describe("viewer graph cool-down", () => {+describe("viewer graph layout and rendering", () => {const viewer = readFileSync("src/viewer/index.html", "utf-8");- it("tracks a tickCount that grows each simulation step", () => {- expect(viewer).toMatch(/graphSim\.tickCount\s*=\s*\(graphSim\.tickCount\s*\|\|\s*0\)\s*\+\s*1/);+ it("settles the first layout in a bounded loop before drawing", () => {+ expect(viewer).toMatch(/for \(var i = 0; i < 320 && graphSim\.alpha > 0\.004; i\+\+\) graphTick\(\);/);});- it("adds tick-decay to damping (coolBoost scales with tickCount)", () => {- expect(viewer).toMatch(/coolBoost\s*=\s*Math\.min\(0\.4,\s*graphSim\.tickCount\s*\/\s*1500\)/);- expect(viewer).toMatch(/damping\s*=\s*0\.9\s*-\s*coolBoost/);+ it("cools the simulation and caps per-node speed", () => {+ expect(viewer).toMatch(/graphSim\.alpha \*= 0\.975;/);+ expect(viewer).toMatch(/if \(sp > 30\) \{ s\.vx \*= 30 \/ sp; s\.vy \*= 30 \/ sp; \}/);});- it("caps per-node velocity by node-count band", () => {- expect(viewer).toMatch(- /velocityCap\s*=\s*nodeCount\s*>\s*1000\s*\?\s*6/,- );- expect(viewer).toMatch(/nvx\s*>\s*velocityCap/);- expect(viewer).toMatch(/nvy\s*>\s*velocityCap/);+ it("stops the animation frame loop once the layout is cool", () => {+ expect(viewer).toMatch(/if \(graphSim\.alpha > 0\.01 \|\| graphSim\.drag\) graphSim\.raf = requestAnimationFrame\(graphFrame\);/);});- it("parks the raf loop once the layout is quiet for 30 ticks", () => {- expect(viewer).toMatch(/rmsVelocity/);- expect(viewer).toMatch(/quietTicks/);- expect(viewer).toMatch(/if\s*\(graphSim\.quietTicks\s*>\s*30\)/);+ it("draws crisp: device pixel ratio transform and no canvas blur", () => {+ expect(viewer).toMatch(/canvas\.width = Math\.round\(w \* dpr\);/);+ expect(viewer).toMatch(/ctx\.setTransform\(dpr, 0, 0, dpr, 0, 0\);/);+ expect(viewer).not.toMatch(/shadowBlur/);});- it("wakes the parked loop on mousedown so drag still responds", () => {- expect(viewer).toMatch(/graphSim\.quietTicks\s*=\s*0/);- expect(viewer).toMatch(/if\s*\(graphSim\.running\s*&&\s*!graphSim\.raf\)/);+ it("labels nodes at rest by degree with collision checks", () => {+ expect(viewer).toMatch(/graphDegree\(q\.id\) - graphDegree\(p\.id\)/);+ expect(viewer).toMatch(/if \(strong \|\| free\(rect\)\) \{ spot = rect; break; \}/);});});diff --git a/test/viewer-live-events.test.ts b/test/viewer-live-events.test.tsindex 058df7a2..f70d7a87 100644--- a/test/viewer-live-events.test.ts+++ b/test/viewer-live-events.test.ts@@ -80,26 +80,26 @@ describe("viewer live events", () => {}});- it("pushes a slim memory.updated or memory.deleted on memory writes", async () => {+ it("pushes memory.created, memory.updated and memory.deleted with the full row", async () => {const { handlers, triggers, sent } = setup();expect(triggers).toContainEqual(expect.objectContaining({ type: "state", function_id: "event::memory::changed", config: { scope: "mem:memories" } }),);const handler = handlers.get("event::memory::changed")!;- await handler({- key: "m1",- event_type: "state:created",- new_value: { id: "m1", type: "fact", title: "t", content: "long body", isLatest: true, updatedAt: "2026-09-24T00:00:00Z" },- });- await handler({ key: "m1", event_type: "state:deleted", new_value: null });- expect(sent.map((e) => e.type)).toEqual(["memory.updated", "memory.deleted"]);+ const row = { id: "m1", type: "fact", title: "t", content: "long body", isLatest: true, updatedAt: "2026-09-24T00:00:00Z" };+ await handler({ key: "m1", event_type: "state:created", new_value: row });+ await handler({ key: "m1", event_type: "state:updated", old_value: row, new_value: { ...row, isLatest: false } });+ await handler({ key: "m1", event_type: "state:deleted", old_value: { ...row, isLatest: false }, new_value: null });+ expect(sent.map((e) => e.type)).toEqual(["memory.created", "memory.updated", "memory.deleted"]);expect(sent[0].data).toEqual({memoryId: "m1",type: "fact",title: "t",isLatest: true,updatedAt: "2026-09-24T00:00:00Z",+ memory: row,});- expect(sent[1].data).toEqual({ memoryId: "m1" });+ expect(sent[1].data.memory).toMatchObject({ id: "m1", isLatest: false, content: "long body" });+ expect(sent[2].data).toEqual({ memoryId: "m1", isLatest: false });});});diff --git a/test/viewer-memories-page.test.ts b/test/viewer-memories-page.test.tsnew file mode 100644index 00000000..b3a85547--- /dev/null+++ b/test/viewer-memories-page.test.ts@@ -0,0 +1,73 @@+import { describe, it, expect } from "vitest";+import { readFileSync } from "node:fs";++const viewer = readFileSync("src/viewer/index.html", "utf-8");++function extractFunction(name: string): string {+ const start = viewer.indexOf(`function ${name}(`);+ if (start < 0) throw new Error(`function ${name} not found in viewer`);+ let depth = 0;+ for (let i = viewer.indexOf("{", start); i < viewer.length; i++) {+ if (viewer[i] === "{") depth++;+ if (viewer[i] === "}") {+ depth--;+ if (depth === 0) return viewer.slice(start, i + 1);+ }+ }+ throw new Error(`function ${name} is not balanced`);+}++const esc = "function esc(s) { return String(s || '').replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>'); }";++const memoryHeadline = new Function(`${extractFunction("memoryHeadline")}\nreturn memoryHeadline;`)() as (m: {+ title?: string;+ content?: string;+}) => { head: string; excerpt: string };++const diffWordsHtml = new Function(`${esc}\n${extractFunction("diffWordsHtml")}\nreturn diffWordsHtml;`)() as (+ a: string,+ b: string,+) => { html: string; added: number; removed: number } | null;++describe("viewer memories page", () => {+ it("never repeats the title as the excerpt", () => {+ const content = "Checkout totals must apply coupons before free-shipping thresholds; the reverse order under-charges orders.";+ const derived = memoryHeadline({ title: content.slice(0, 80), content });+ expect(derived.head).toBe("Checkout totals must apply coupons before free-shipping thresholds");+ expect(derived.excerpt).toBe("the reverse order under-charges orders.");++ const clause = memoryHeadline({ title: "", content: "The orders endpoint returns 409 when the cart is stale: the client must refetch." });+ expect(clause.head).toBe("The orders endpoint returns 409 when the cart is stale: the client must refetch.");+ const colonTitle = memoryHeadline({ title: "Deploy steps:", content: "Build, push, helm upgrade." });+ expect(colonTitle.head).toBe("Deploy steps");++ const short = memoryHeadline({ title: "Prefer React Query", content: "Prefer React Query" });+ expect(short).toEqual({ head: "Prefer React Query", excerpt: "" });++ const custom = memoryHeadline({ title: "Auth", content: "JWTs are validated with jose" });+ expect(custom).toEqual({ head: "Auth", excerpt: "JWTs are validated with jose" });++ const long = "word ".repeat(80).trim();+ const cut = memoryHeadline({ title: long.slice(0, 80), content: long });+ expect(cut.head.endsWith("…")).toBe(true);+ expect(cut.excerpt.startsWith("…")).toBe(true);+ });++ it("marks removed and added words between two versions", () => {+ const diff = diffWordsHtml("watch rollout for 5 minutes", "watch rollout for 10 minutes <b>");+ expect(diff).not.toBeNull();+ expect(diff!.html).toContain("<del>5</del>");+ expect(diff!.html).toContain("<ins>10</ins>");+ expect(diff!.html).toContain("<b>");+ expect(diff!.added).toBe(2);+ expect(diff!.removed).toBe(1);+ expect(diffWordsHtml("same", "same")).toMatchObject({ added: 0, removed: 0 });+ });++ it("routes edits through evolve and forgets through governance delete, with no per-row delete", () => {+ expect(extractFunction("saveMemoryEdit")).toMatch(/api\('evolve'/);+ expect(extractFunction("forgetMemories")).toMatch(/apiDelete\('governance\/memories'/);+ expect(extractFunction("memoryRowHtml")).not.toMatch(/btn-danger|forget/i);+ expect(viewer).toMatch(/memory: \{ path: 'memories\?latest=true&limit=100&facets=true'/);+ });+});diff --git a/test/viewer-memories-sort.test.ts b/test/viewer-memories-sort.test.tsindex 865b6417..2803bb2d 100644--- a/test/viewer-memories-sort.test.ts+++ b/test/viewer-memories-sort.test.ts@@ -1,32 +1,38 @@import { describe, it, expect } from "vitest";import { readFileSync } from "node:fs";-// Viewer Memories tab used to render in KV-insertion order, hiding new-// entries at the bottom of long lists (#674). loadMemories() now sorts-// the response newest-first on `createdAt` (fallback `updatedAt`) before-// renderMemories sees it. Matches the pattern already used by Sessions-// and Metrics tabs which sort on `startedAt` desc via localeCompare.-describe("viewer Memories tab sorts newest first (#674)", () => {+describe("viewer lists sort newest first (#674)", () => {const viewer = readFileSync("src/viewer/index.html", "utf-8");- it("loadMemories sorts items by createdAt desc before storing in state", () => {- expect(viewer).toMatch(- /loadMemories[\s\S]*?items\.sort\(function\(a,\s*b\)\s*\{[\s\S]*?bc\.localeCompare\(ac\)/,- );- });+ function extractFunction(name: string): string {+ const start = viewer.indexOf(`function ${name}(`);+ let depth = 0;+ for (let i = viewer.indexOf("{", start); i < viewer.length; i++) {+ if (viewer[i] === "{") depth++;+ if (viewer[i] === "}") {+ depth--;+ if (depth === 0) return viewer.slice(start, i + 1);+ }+ }+ throw new Error(`function ${name} is not balanced`);+ }++ const sortByTimeDesc = new Function(`${extractFunction("sortByTimeDesc")}\nreturn sortByTimeDesc;`)() as (+ list: Array<Record<string, string>>,+ keys: string[],+ ) => Array<Record<string, string>>;- it("sort falls back to updatedAt when createdAt is missing", () => {- expect(viewer).toMatch(- /\(a && a\.createdAt\) \|\| \(a && a\.updatedAt\)/,- );- expect(viewer).toMatch(- /\(b && b\.createdAt\) \|\| \(b && b\.updatedAt\)/,- );+ it("sorts on the first present key, newest first", () => {+ const rows = [+ { id: "a", createdAt: "2026-01-01" },+ { id: "b", updatedAt: "2026-03-01", createdAt: "2025-01-01" },+ { id: "c", createdAt: "2026-02-01" },+ ];+ expect(sortByTimeDesc(rows, ["updatedAt", "createdAt"]).map((r) => r.id)).toEqual(["b", "c", "a"]);});- it("Memories sort mirrors the Sessions/Metrics localeCompare descending pattern", () => {- expect(viewer).toMatch(- /sessions\.sort\(function\(a, b\) \{ return \(b\.startedAt \|\| ''\)\.localeCompare\(a\.startedAt \|\| ''\); \}\)/,- );+ it("memories fall back from updatedAt to createdAt and sessions sort on startedAt", () => {+ expect(extractFunction("memoryRows")).toMatch(/sortByTimeDesc\([\s\S]*?\['updatedAt', 'createdAt'\]\)/);+ expect(extractFunction("sessionRows")).toMatch(/sortByTimeDesc\(entityList\('session'\)[\s\S]*?\['startedAt'\]\)/);});});diff --git a/test/viewer-session-id.test.ts b/test/viewer-session-id.test.tsindex a671df88..30f77481 100644--- a/test/viewer-session-id.test.ts+++ b/test/viewer-session-id.test.ts@@ -60,6 +60,8 @@ function loadViewerSandbox() {attributes.delete(name);},querySelectorAll: () => [],+ querySelector: () => null,+ closest: () => null,};};const getElement = (id: string) => {@@ -69,23 +71,24 @@ function loadViewerSandbox() {const tabs = ["dashboard",- "graph","memories",- "timeline",- "sessions","lessons",- "actions","crystals",- "audit",+ "graph",+ "sessions",+ "timeline",+ "actions",+ "replay","activity","profile",- "replay",+ "health",+ "audit",];const tabButtons = tabs.map((tab) => ({ ...createMockElement(), dataset: { tab } }));const views = tabs.map((tab) => ({ ...createMockElement(`view-${tab}`), id: `view-${tab}` }));const checkboxes = [createMockElement(), createMockElement()].map((el) => ({ ...el, checked: false }));const querySelectorAll = (selector: string) => {- if (selector === ".tab-bar button") return tabButtons;+ if (selector === ".tab-bar button[data-tab]") return tabButtons;if (selector === ".view") return views;if (selector === 'input[type="checkbox"]') return checkboxes;return [];@@ -93,6 +96,7 @@ function loadViewerSandbox() {const document = {documentElement: { dataset: {} },+ body: createMockElement("body"),createElement: () => {let text = "";return {@@ -206,35 +210,31 @@ describe("viewer session rendering", () => {expect(prompt.innerHTML).not.toContain("/data/.hmac");});- it("does not throw when dashboard sessions are missing ids", () => {+ it("drops sessions without an id instead of throwing, and renders the rest", () => {const { sandbox, getElement } = loadViewerSandbox();- sandbox.state.dashboard = {- loaded: true,- health: { status: "healthy", health: {} },- sessions: [{ status: "active", observationCount: 3, startedAt: "2026-05-13T12:00:00Z" }],- memories: [],- graphStats: null,- recentAudit: [],- lessons: [],- crystals: [],- };+ sandbox.store.snapshot = { version: "1" };+ sandbox.store.counts = { sessions: 2, activeSessions: 2, memories: 0, latestMemories: 0 };+ sandbox.replaceBucket("session", [+ { status: "active", observationCount: 3, startedAt: "2026-05-13T12:00:00Z" },+ { id: "ses_ok", project: "/work/web-app", status: "active", observationCount: 2, startedAt: "2026-05-13T13:00:00Z" },+ ]);+ sandbox.store.loaded.session = true;+ expect(Object.keys(sandbox.store.entities.session)).toEqual(["ses_ok"]);expect(() => sandbox.renderDashboard()).not.toThrow();- expect(getElement("view-dashboard").innerHTML).toContain("Unknown session");+ expect(getElement("view-dashboard").innerHTML).toContain("web-app");});- it("does not throw when timeline and sessions tabs receive sessions missing ids", () => {+ it("renders sessions without a project, and switches tabs", () => {const { sandbox, getElement } = loadViewerSandbox();- const sessions = [{ status: "active", observationCount: 1, startedAt: "2026-05-13T12:00:00Z" }];-- expect(() => sandbox.renderTimelineToolbar(sessions)).not.toThrow();- expect(getElement("view-timeline").innerHTML).toContain("Unknown session");+ sandbox.store.snapshot = { version: "1" };+ sandbox.replaceBucket("session", [{ id: "ses_no_project_123456", status: "active", observationCount: 1, startedAt: "2026-05-13T12:00:00Z" }]);+ sandbox.store.loaded.session = true;- sandbox.state.sessions.items = sessions;expect(() => sandbox.renderSessions()).not.toThrow();- expect(getElement("view-sessions").innerHTML).toContain("Unknown session");+ expect(getElement("session-list").innerHTML).toContain("123456");- const tabButtons = sandbox.document.querySelectorAll(".tab-bar button");+ const tabButtons = sandbox.document.querySelectorAll(".tab-bar button[data-tab]");expect(tabButtons.length).toBeGreaterThan(0);expect(() => sandbox.switchTab("sessions")).not.toThrow();expect(tabButtons.some((button: any) => button.classList.contains("active"))).toBe(true);diff --git a/test/viewer-streams.test.ts b/test/viewer-streams.test.tsnew file mode 100644index 00000000..752e1727--- /dev/null+++ b/test/viewer-streams.test.ts@@ -0,0 +1,373 @@+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";+import { registerViewerStreamTriggers } from "../src/triggers/viewer-streams.js";+import { registerEventTriggers } from "../src/triggers/events.js";+import { getViewerCounts, resetViewerCounts } from "../src/state/viewer-counts.js";+import { KV } from "../src/state/schema.js";++type Handler = (payload: unknown) => Promise<unknown>;+type Sent = { type: string; group_id: string; data: Record<string, unknown> };++function mockKV(seed: Record<string, Record<string, unknown>> = {}) {+ const store = new Map<string, Map<string, unknown>>();+ for (const [scope, rows] of Object.entries(seed)) {+ store.set(scope, new Map(Object.entries(rows)));+ }+ return {+ store,+ get: vi.fn(async (scope: string, key: string) => store.get(scope)?.get(key) ?? null),+ set: vi.fn(async (scope: string, key: string, value: unknown) => {+ if (!store.has(scope)) store.set(scope, new Map());+ store.get(scope)!.set(key, value);+ return value;+ }),+ delete: vi.fn(async (scope: string, key: string) => {+ store.get(scope)?.delete(key);+ }),+ list: vi.fn(async (scope: string) => Array.from(store.get(scope)?.values() ?? [])),+ };+}++function setup(kv = mockKV(), deps: Record<string, unknown> = {}) {+ const handlers = new Map<string, Handler>();+ const triggers: Array<{ type: string; function_id: string; config: Record<string, unknown> }> = [];+ const sent: Sent[] = [];+ const sdk = {+ registerFunction: (id: string, fn: Handler) => handlers.set(id, fn),+ registerTrigger: (t: (typeof triggers)[number]) => triggers.push(t),+ trigger: vi.fn(async (req: { function_id: string; payload: Record<string, unknown> }) => {+ if (req.function_id === "stream::send") sent.push(req.payload as unknown as Sent);+ return {};+ }),+ };+ registerEventTriggers(sdk as never, kv as never);+ registerViewerStreamTriggers(sdk as never, kv as never, deps);+ return { handlers, triggers, sent, kv };+}++const seeded = () =>+ mockKV({+ [KV.sessions]: {+ s1: { id: "s1", status: "active", observationCount: 4 },+ s2: { id: "s2", status: "completed", observationCount: 6 },+ },+ [KV.memories]: {+ m1: { id: "m1", isLatest: true },+ m2: { id: "m2", isLatest: false },+ },+ [KV.lessons]: {+ l1: { id: "l1", content: "a" },+ l2: { id: "l2", content: "b", deleted: true },+ },+ [KV.actions]: { a1: { id: "a1" } },+ [KV.graphSnapshot]: {+ current: { stats: { totalNodes: 12, totalEdges: 7, nodesByType: {}, edgesByType: {} }, updatedAt: "t" },+ },+ });++describe("viewer stream triggers", () => {+ beforeEach(() => resetViewerCounts());+ afterEach(() => {+ vi.useRealTimers();+ resetViewerCounts();+ });++ it("registers a state trigger for every scope the viewer shows", () => {+ const { triggers } = setup();+ const scopes = triggers.filter((t) => t.type === "state").map((t) => t.config.scope);+ for (const scope of [+ KV.sessions,+ KV.memories,+ KV.lessons,+ KV.actions,+ KV.crystals,+ KV.semantic,+ KV.procedural,+ KV.audit,+ KV.graphSnapshot,+ KV.graphNodes,+ KV.graphEdges,+ KV.config,+ KV.health,+ ]) {+ expect(scopes).toContain(scope);+ }+ const http = triggers.filter((t) => t.type === "http").map((t) => t.config.api_path);+ expect(http).toEqual(expect.arrayContaining(["/agentmemory/viewer/snapshot", "/agentmemory/counts"]));+ });++ it("pushes created, updated and deleted rows for lessons, actions, crystals, semantic, procedural and audit", async () => {+ const { handlers, sent } = setup();+ const lesson = { id: "l9", content: "use pnpm", confidence: 0.6 };+ await handlers.get("event::viewer::lesson-changed")!({ key: "l9", event_type: "state:created", new_value: lesson });+ await handlers.get("event::viewer::lesson-changed")!({+ key: "l9",+ event_type: "state:updated",+ old_value: lesson,+ new_value: { ...lesson, confidence: 0.8 },+ });+ await handlers.get("event::viewer::lesson-changed")!({ key: "l9", event_type: "state:deleted", old_value: lesson, new_value: null });+ await handlers.get("event::viewer::action-changed")!({ key: "a1", event_type: "state:created", new_value: { id: "a1", title: "t" } });+ await handlers.get("event::viewer::crystal-changed")!({ key: "c1", event_type: "state:created", new_value: { id: "c1" } });+ await handlers.get("event::viewer::semantic-changed")!({ key: "f1", event_type: "state:created", new_value: { id: "f1" } });+ await handlers.get("event::viewer::procedural-changed")!({ key: "p1", event_type: "state:created", new_value: { id: "p1" } });+ await handlers.get("event::viewer::audit-changed")!({+ key: "au1",+ event_type: "state:created",+ new_value: { id: "au1", operation: "forget", targetIds: ["m1"] },+ });+ expect(sent.map((e) => e.type)).toEqual([+ "lesson.created",+ "lesson.updated",+ "lesson.deleted",+ "action.created",+ "crystal.created",+ "semantic.created",+ "procedural.created",+ "audit.created",+ ]);+ expect(sent.every((e) => e.group_id === "viewer")).toBe(true);+ expect(sent[1].data).toEqual({ id: "l9", lesson: { ...lesson, confidence: 0.8 } });+ expect(sent[2].data).toEqual({ id: "l9", lesson: null });+ expect(sent[7].data.audit).toMatchObject({ operation: "forget", targetIds: ["m1"] });+ });++ it("pushes graph.changed from the snapshot and coalesces node and edge writes", async () => {+ vi.useFakeTimers();+ const { handlers, sent } = setup();+ await handlers.get("event::viewer::graph-snapshot-changed")!({+ key: "current",+ event_type: "state:updated",+ new_value: { stats: { totalNodes: 3, totalEdges: 2, nodesByType: { file: 3 }, edgesByType: {} }, updatedAt: "u1" },+ });+ await handlers.get("event::viewer::graph-snapshot-changed")!({ key: "other", event_type: "state:updated", new_value: {} });+ for (let i = 0; i < 5; i++) await handlers.get("event::viewer::graph-nodes-changed")!({ key: `n${i}` });+ for (let i = 0; i < 3; i++) await handlers.get("event::viewer::graph-edges-changed")!({ key: `e${i}` });+ expect(sent.map((e) => e.type)).toEqual(["graph.changed"]);+ expect(sent[0].data).toMatchObject({ source: "snapshot", stats: { totalNodes: 3, totalEdges: 2 } });+ await vi.advanceTimersByTimeAsync(1000);+ expect(sent.map((e) => e.type)).toEqual(["graph.changed", "graph.changed"]);+ expect(sent[1].data).toMatchObject({ source: "items", nodesChanged: 5, edgesChanged: 3 });+ });++ it("carries the changed subgraph on graph.changed so the viewer patches without a fetch", async () => {+ vi.useFakeTimers();+ const { handlers, sent } = setup();+ const n1 = { id: "n1", type: "file", name: "a.ts", properties: {}, sourceObservationIds: ["o1"], createdAt: "t" };+ const n2 = { id: "n2", type: "concept", name: "auth", properties: {}, sourceObservationIds: ["o1"], createdAt: "t" };+ const n3 = { id: "n3", type: "file", name: "b.ts", properties: {}, sourceObservationIds: ["o2"], createdAt: "t" };+ const e1 = { id: "e1", type: "related_to", sourceNodeId: "n1", targetNodeId: "n2", weight: 0.4, sourceObservationIds: ["o1"], createdAt: "t" };+ const e2 = { id: "e2", type: "related_to", sourceNodeId: "n2", targetNodeId: "n3", weight: 0.4, sourceObservationIds: ["o2"], createdAt: "t" };+ const stats = { totalNodes: 2, totalEdges: 1, nodesByType: {}, edgesByType: {} };+ const before = { topNodes: [n1, n2], topEdges: [e1], topDegrees: { n1: 1, n2: 1 }, stats, updatedAt: "u1" };+ const after = { topNodes: [n2, n3], topEdges: [e2], topDegrees: { n2: 1, n3: 1 }, stats, updatedAt: "u2" };+ await handlers.get("event::viewer::graph-snapshot-changed")!({ key: "current", event_type: "state:updated", old_value: before, new_value: after });+ expect(sent[0].data.delta).toEqual({+ full: false,+ nodes: [n3],+ edges: [e2],+ removedNodeIds: ["n1"],+ removedEdgeIds: ["e1"],+ degrees: { n3: 1 },+ });+ await handlers.get("event::viewer::graph-snapshot-changed")!({ key: "current", event_type: "state:created", new_value: after });+ expect(sent[1].data.delta).toMatchObject({ full: true, nodes: [n2, n3], removedNodeIds: [] });++ await handlers.get("event::viewer::graph-nodes-changed")!({ key: "n3" });+ await vi.advanceTimersByTimeAsync(1000);+ expect(sent[2].data).toMatchObject({ source: "items", nodesChanged: 1, coveredBySnapshot: true });++ await vi.advanceTimersByTimeAsync(5000);+ await handlers.get("event::viewer::graph-edges-changed")!({ key: "e9" });+ await vi.advanceTimersByTimeAsync(1000);+ expect(sent[3].data).toMatchObject({ source: "items", edgesChanged: 1, coveredBySnapshot: false });+ });++ it("drops the delta when the changed subgraph is too large to push", async () => {+ const { handlers, sent } = setup();+ const topNodes = Array.from({ length: 250 }, (_, i) => ({ id: `n${i}`, type: "file", name: `f${i}`, properties: {}, sourceObservationIds: [], createdAt: "t" }));+ await handlers.get("event::viewer::graph-snapshot-changed")!({+ key: "current",+ event_type: "state:updated",+ old_value: { topNodes: [], topEdges: [], topDegrees: {}, stats: {}, updatedAt: "u0" },+ new_value: { topNodes, topEdges: [], topDegrees: {}, stats: { totalNodes: 250, totalEdges: 0, nodesByType: {}, edgesByType: {} }, updatedAt: "u1" },+ });+ expect(sent[0].data.delta).toBeNull();+ });++ it("pushes consolidation.run only for the last pipeline run key", async () => {+ const { handlers, sent } = setup();+ await handlers.get("event::viewer::consolidation-changed")!({ key: "consolidation:lastRun", event_type: "state:updated", new_value: { at: "x" } });+ await handlers.get("event::viewer::consolidation-changed")!({+ key: "consolidation:lastPipelineRun",+ event_type: "state:updated",+ new_value: { at: "2026-09-28T00:00:00Z", tier: "all", results: {} },+ });+ expect(sent).toEqual([+ expect.objectContaining({+ type: "consolidation.run",+ data: expect.objectContaining({ lastRun: { at: "2026-09-28T00:00:00Z", tier: "all", results: {} } }),+ }),+ ]);+ const status = (sent[0].data as { status: { lastRunAt: string; tiers: Array<{ id: string }>; thresholds: unknown } }).status;+ expect(status.lastRunAt).toBe("2026-09-28T00:00:00Z");+ expect(status.tiers.map((t) => t.id)).toEqual(["semantic", "procedural", "relations"]);+ expect(status.thresholds).toMatchObject({ semanticMinSummaries: 5 });+ });++ it("pushes a health event with counts, indexes and the circuit breaker when the health monitor writes", async () => {+ const metricsStore = { getAll: vi.fn(async () => [{ functionId: "mem::observe", totalCalls: 3 }]) };+ const { handlers, sent } = setup(seeded(), { metricsStore, provider: { circuitState: { state: "closed" } } });+ await handlers.get("event::viewer::health-changed")!({ key: "_probe", event_type: "state:updated", new_value: { ts: 1 } });+ await handlers.get("event::viewer::health-changed")!({+ key: "latest",+ event_type: "state:updated",+ new_value: { status: "degraded", alerts: ["heap"], memory: { heapUsed: 1 } },+ });+ expect(sent.map((e) => e.type)).toEqual(["health"]);+ expect(sent[0].data).toMatchObject({+ status: "degraded",+ health: { alerts: ["heap"] },+ circuitBreaker: { state: "closed" },+ functionMetrics: [{ functionId: "mem::observe", totalCalls: 3 }],+ counts: { sessions: 2, observations: 10, memories: 2, latestMemories: 1, lessons: 1, actions: 1, graphNodes: 12, graphEdges: 7 },+ indexes: { bm25Documents: expect.any(Number), vectorDocuments: expect.any(Number) },+ });+ const report = (sent[0].data as { report: { status: string; headline: string; problems: Array<{ code: string; fix?: string }> } | null }).report;+ expect(report).not.toBeNull();+ expect(report!.problems.map((p) => p.code)).toContain("health-alert");+ expect(report!.problems.every((p) => !!p.fix)).toBe(true);+ expect(report!.headline).toMatch(/^Working, but needs attention/);+ });++ it("serves one snapshot with counts, health, flags, graph and consolidation state", async () => {+ const kv = seeded();+ kv.store.set(KV.health, new Map([["latest", { status: "healthy", alerts: [] }]]));+ kv.store.set(KV.config, new Map([["consolidation:lastPipelineRun", { at: "t", tier: "all", results: {} }]]));+ const { handlers } = setup(kv);+ const res = (await handlers.get("api::viewer-snapshot")!({ headers: {}, query_params: {} })) as {+ status_code: number;+ body: Record<string, unknown>;+ };+ expect(res.status_code).toBe(200);+ expect(res.body).toMatchObject({+ service: "agentmemory",+ status: "healthy",+ counts: { sessions: 2, activeSessions: 1, memories: 2 },+ graph: { stats: { totalNodes: 12 } },+ consolidation: { lastRun: { tier: "all" } },+ embeddingProvider: expect.any(String),+ });+ expect(Array.isArray(res.body.flags)).toBe(true);+ });++ it("rejects the snapshot and counts endpoints without the bearer when a secret is set", async () => {+ const { handlers } = setup(mockKV(), { secret: "s3cret" });+ const denied = (await handlers.get("api::counts")!({ headers: {} })) as { status_code: number };+ expect(denied.status_code).toBe(401);+ const allowed = (await handlers.get("api::counts")!({ headers: { authorization: "Bearer s3cret" } })) as {+ status_code: number;+ };+ expect(allowed.status_code).toBe(200);+ const snapshot = (await handlers.get("api::viewer-snapshot")!({ headers: {} })) as { status_code: number };+ expect(snapshot.status_code).toBe(401);+ });+});++describe("viewer counts", () => {+ beforeEach(() => resetViewerCounts());+ afterEach(() => {+ vi.useRealTimers();+ vi.unstubAllEnvs();+ resetViewerCounts();+ });++ it("loads once, then keeps counts current from trigger deltas and pushes counts.changed", async () => {+ vi.useFakeTimers();+ const kv = seeded();+ const { handlers, sent } = setup(kv);+ const first = await getViewerCounts(kv as never);+ expect(first).toMatchObject({ sessions: 2, activeSessions: 1, observations: 10, memories: 2, latestMemories: 1, lessons: 1 });+ const listCalls = kv.list.mock.calls.length;++ await handlers.get("event::session::observation-count-changed")!({+ key: "s1",+ event_type: "state:updated",+ old_value: { id: "s1", status: "active", observationCount: 4 },+ new_value: { id: "s1", status: "completed", observationCount: 5 },+ });+ await handlers.get("event::memory::changed")!({ key: "m3", event_type: "state:created", new_value: { id: "m3", isLatest: true } });+ await handlers.get("event::memory::changed")!({+ key: "m1",+ event_type: "state:updated",+ old_value: { id: "m1", isLatest: true },+ new_value: { id: "m1", isLatest: false },+ });+ await handlers.get("event::viewer::lesson-changed")!({+ key: "l1",+ event_type: "state:updated",+ old_value: { id: "l1" },+ new_value: { id: "l1", deleted: true },+ });+ await handlers.get("event::viewer::graph-snapshot-changed")!({+ key: "current",+ event_type: "state:updated",+ new_value: { stats: { totalNodes: 20, totalEdges: 9, nodesByType: {}, edgesByType: {} }, updatedAt: "u" },+ });++ const after = await getViewerCounts(kv as never);+ expect(kv.list.mock.calls.length).toBe(listCalls);+ expect(after).toMatchObject({+ sessions: 2,+ activeSessions: 0,+ observations: 11,+ memories: 3,+ latestMemories: 1,+ lessons: 0,+ graphNodes: 20,+ graphEdges: 9,+ });++ await vi.advanceTimersByTimeAsync(500);+ const pushes = sent.filter((e) => e.type === "counts.changed");+ expect(pushes).toHaveLength(1);+ expect(pushes[0].data.counts).toMatchObject({ observations: 11, memories: 3, lessons: 0 });+ });++ it("re-reads when a write lands while the first load is in flight", async () => {+ const kv = seeded();+ const { handlers } = setup(kv);+ let release!: () => void;+ const gate = new Promise<void>((resolve) => (release = resolve));+ const originalList = kv.list.getMockImplementation()!;+ kv.list.mockImplementationOnce(async (scope: string) => {+ await gate;+ return originalList(scope);+ });+ const pending = getViewerCounts(kv as never);+ kv.store.get(KV.sessions)!.set("s3", { id: "s3", status: "active", observationCount: 1 });+ await handlers.get("event::session::observation-count-changed")!({+ key: "s3",+ event_type: "state:created",+ new_value: { id: "s3", status: "active", observationCount: 1 },+ });+ release();+ const counts = await pending;+ expect(counts).toMatchObject({ sessions: 3, observations: 11 });+ });++ it("counts only in-scope sessions and memories when agent scope is isolated", async () => {+ vi.stubEnv("AGENT_ID", "agent-a");+ vi.stubEnv("AGENTMEMORY_AGENT_SCOPE", "isolated");+ const kv = mockKV({+ [KV.sessions]: {+ s1: { id: "s1", agentId: "agent-a", status: "active", observationCount: 2 },+ s2: { id: "s2", agentId: "agent-b", status: "active", observationCount: 9 },+ },+ [KV.memories]: { m1: { id: "m1", agentId: "agent-b", isLatest: true } },+ });+ const { handlers } = setup(kv);+ expect(await getViewerCounts(kv as never)).toMatchObject({ sessions: 1, observations: 2, memories: 0 });+ await handlers.get("event::memory::changed")!({ key: "m2", event_type: "state:created", new_value: { id: "m2", agentId: "agent-b" } });+ expect(await getViewerCounts(kv as never)).toMatchObject({ memories: 0 });+ });+});