Skip to content

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

feat: implement reflect — auto-synthesize insights from memory clusters (#89)

Rohit Ghumare9c27eff610d9
diff --git a/AGENTS.md b/AGENTS.md
index 6b34419a..ee13ce45 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -105,9 +105,9 @@ Hook scripts in `src/hooks/` are standalone Node.js scripts (no iii-sdk import).
## Current Stats (v0.7.0)
-- 41 MCP tools (7 visible by default, `AGENTMEMORY_TOOLS=all` for all)
-- 100 REST endpoints
+- 43 MCP tools (8 visible by default, `AGENTMEMORY_TOOLS=all` for all)
+- 103 REST endpoints
- 6 MCP resources, 3 MCP prompts
- 12 hooks, 4 skills
- 50+ iii functions
-- 614 tests
+- 627 tests
diff --git a/README.md b/README.md
index db31f6b0..1fc456dc 100644
--- a/README.md
+++ b/README.md
@@ -26,7 +26,7 @@
---
-Every AI coding agent has the same blind spot. Session ends, memory vanishes. You re-explain architecture. You re-discover bugs. You re-teach preferences. Built-in memory files like CLAUDE.md and .cursorrules are 200-line sticky notes that overflow and go stale. agentmemory replaces that with a searchable, versioned, cross-agent database — 41 MCP tools, triple-stream retrieval (BM25 + vector + knowledge graph), 4-tier memory consolidation, provenance-tracked citations, and cascading staleness so retired facts never pollute your context again. One instance serves Claude Code, Cursor, Codex, Windsurf, and any MCP client simultaneously. 614 tests. Zero external DB dependencies.
+Every AI coding agent has the same blind spot. Session ends, memory vanishes. You re-explain architecture. You re-discover bugs. You re-teach preferences. Built-in memory files like CLAUDE.md and .cursorrules are 200-line sticky notes that overflow and go stale. agentmemory replaces that with a searchable, versioned, cross-agent database — 43 MCP tools, triple-stream retrieval (BM25 + vector + knowledge graph), 4-tier memory consolidation, provenance-tracked citations, and cascading staleness so retired facts never pollute your context again. One instance serves Claude Code, Cursor, Codex, Windsurf, and any MCP client simultaneously. 627 tests. Zero external DB dependencies.
The result is measurable. On 240 real observations across 30 sessions, agentmemory hits 64% Recall@10 and perfect MRR while using 92% fewer tokens than dumping everything into context. When an agent searches "database performance optimization," it finds the N+1 fix you made three weeks ago — something keyword grep literally cannot do. Memories version automatically, supersede each other, propagate staleness to related graph nodes, and sync across agent instances via P2P mesh. Your agents stop repeating mistakes. Your context stays clean. Your sessions start fast.
@@ -131,7 +131,7 @@ These agents support hooks natively. agentmemory captures tool usage automatical
### MCP support (any MCP-compatible agent)
-Any agent that connects to MCP servers can use agentmemory's 41 tools, 6 resources, and 3 prompts. The agent actively queries and saves memory through MCP calls.
+Any agent that connects to MCP servers can use agentmemory's 43 tools, 6 resources, and 3 prompts. The agent actively queries and saves memory through MCP calls.
| Agent | How to connect |
|---|---|
@@ -143,7 +143,7 @@ Any agent that connects to MCP servers can use agentmemory's 41 tools, 6 resourc
### REST API (any agent, any language)
-Agents without hooks or MCP can integrate via 100 REST endpoints directly. This works with any agent, language, or framework.
+Agents without hooks or MCP can integrate via 103 REST endpoints directly. This works with any agent, language, or framework.
```bash
POST /agentmemory/observe # Capture what the agent did
@@ -161,7 +161,7 @@ GET /agentmemory/profile # Get project intelligence
| Claude Code user | Plugin install (hooks + MCP + skills) |
| Building a custom agent with Claude SDK | AgentSDKProvider (zero config) |
| Using Cursor, Windsurf, or any MCP client | MCP server (41 tools + 6 resources + 3 prompts) |
-| Building your own agent framework | REST API (100 endpoints) |
+| Building your own agent framework | REST API (103 endpoints) |
| Sharing memory across multiple agents | All agents point to the same iii-engine instance |
## Quick Start
@@ -632,7 +632,7 @@ ANTHROPIC_API_KEY=sk-ant-...
## API
-106 endpoints on port `3111` (100 core + 6 MCP protocol). Protected endpoints require `Authorization: Bearer <secret>` when `AGENTMEMORY_SECRET` is set. The table below shows a representative subset; see `src/triggers/api.ts` for the full endpoint list.
+109 endpoints on port `3111` (103 core + 6 MCP protocol). Protected endpoints require `Authorization: Bearer <secret>` when `AGENTMEMORY_SECRET` is set. The table below shows a representative subset; see `src/triggers/api.ts` for the full endpoint list.
| Method | Path | Description |
|--------|------|-------------|
@@ -700,7 +700,7 @@ ANTHROPIC_API_KEY=sk-ant-...
/plugin install agentmemory
```
-Restart Claude Code. All 12 hooks, 4 skills, and 41 MCP tools are registered automatically.
+Restart Claude Code. All 12 hooks, 4 skills, and 43 MCP tools are registered automatically.
### Plugin Commands
@@ -724,7 +724,7 @@ agentmemory is built on iii-engine's three primitives:
| Prometheus / Grafana | iii OTEL + built-in health monitor |
| Redis (circuit breaker) | In-process circuit breaker + fallback chain |
-**113 source files. ~20,000 LOC. 614 tests. Zero external DB dependencies.**
+**113 source files. ~20,000 LOC. 627 tests. Zero external DB dependencies.**
### Functions (89 mem:: functions)
@@ -808,7 +808,7 @@ agentmemory is built on iii-engine's three primitives:
```bash
npm run dev # Hot reload
npm run build # Production build (~425KB)
-npm test # Unit tests (614 tests, ~1.5s)
+npm test # Unit tests (627 tests, ~1.5s)
npm run test:integration # API tests (requires running services)
```
diff --git a/plugin/.claude-plugin/plugin.json b/plugin/.claude-plugin/plugin.json
index 99de63c3..4bb59734 100644
--- a/plugin/.claude-plugin/plugin.json
+++ b/plugin/.claude-plugin/plugin.json
@@ -1,7 +1,7 @@
{
"name": "agentmemory",
"version": "0.7.3",
- "description": "Persistent memory for AI coding agents -- captures tool usage, compresses via LLM, injects context into future sessions. 12 hooks, 41 MCP tools, 4 skills, real-time viewer.",
+ "description": "Persistent memory for AI coding agents -- captures tool usage, compresses via LLM, injects context into future sessions. 12 hooks, 43 MCP tools, 4 skills, real-time viewer.",
"author": "Rohit Ghumare",
"license": "Apache-2.0",
"homepage": "https://github.com/rohitg00/agentmemory",
diff --git a/src/functions/consolidation-pipeline.ts b/src/functions/consolidation-pipeline.ts
index bc65fca0..34d032d4 100644
--- a/src/functions/consolidation-pipeline.ts
+++ b/src/functions/consolidation-pipeline.ts
@@ -49,7 +49,7 @@ export function registerConsolidationPipelineFunction(
): void {
sdk.registerFunction(
{ id: "mem::consolidate-pipeline" },
- async (data?: { tier?: string; force?: boolean }) => {
+ async (data?: { tier?: string; force?: boolean; project?: string }) => {
if (!data?.force && !isConsolidationEnabled()) {
return { success: false, skipped: true, reason: "CONSOLIDATION_ENABLED is not set to true" };
}
@@ -135,6 +135,20 @@ export function registerConsolidationPipelineFunction(
}
}
+ if (tier === "all" || tier === "reflect") {
+ try {
+ const reflectResult = await sdk.trigger("mem::reflect", {
+ maxClusters: 10,
+ project: data?.project,
+ });
+ results.reflect = reflectResult;
+ } catch (err) {
+ const msg = err instanceof Error ? err.message : String(err);
+ ctx.logger.warn("Reflect tier failed", { error: msg });
+ results.reflect = { error: msg };
+ }
+ }
+
if (tier === "all" || tier === "procedural") {
const memories = await kv.list<Memory>(KV.memories);
const patterns = memories
diff --git a/src/functions/export-import.ts b/src/functions/export-import.ts
index b5dd17f3..d2c87add 100644
--- a/src/functions/export-import.ts
+++ b/src/functions/export-import.ts
@@ -21,6 +21,7 @@ import type {
Crystal,
Facet,
Lesson,
+ Insight,
ExportPagination,
} from "../types.js";
import { KV } from "../state/schema.js";
@@ -82,6 +83,7 @@ export function registerExportImportFunction(sdk: ISdk, kv: StateKV): void {
crystals,
facets,
lessons,
+ insights,
routines,
signals,
checkpoints,
@@ -97,6 +99,7 @@ export function registerExportImportFunction(sdk: ISdk, kv: StateKV): void {
kv.list<Crystal>(KV.crystals).catch(() => []),
kv.list<Facet>(KV.facets).catch(() => []),
kv.list<Lesson>(KV.lessons).catch(() => []),
+ kv.list<Insight>(KV.insights).catch(() => []),
kv.list<Routine>(KV.routines).catch(() => []),
kv.list<Signal>(KV.signals).catch(() => []),
kv.list<Checkpoint>(KV.checkpoints).catch(() => []),
@@ -123,6 +126,7 @@ export function registerExportImportFunction(sdk: ISdk, kv: StateKV): void {
crystals: crystals.length > 0 ? crystals : undefined,
facets: facets.length > 0 ? facets : undefined,
lessons: lessons.length > 0 ? lessons : undefined,
+ insights: insights.length > 0 ? insights : undefined,
routines: routines.length > 0 ? routines : undefined,
signals: signals.length > 0 ? signals : undefined,
checkpoints: checkpoints.length > 0 ? checkpoints : undefined,
@@ -301,6 +305,9 @@ export function registerExportImportFunction(sdk: ISdk, kv: StateKV): void {
for (const l of await kv.list<Lesson>(KV.lessons).catch(() => [])) {
await kv.delete(KV.lessons, l.id);
}
+ for (const i of await kv.list<Insight>(KV.insights).catch(() => [])) {
+ await kv.delete(KV.insights, i.id);
+ }
for (const n of await kv.list<{ id: string }>(KV.graphNodes).catch(() => [])) {
await kv.delete(KV.graphNodes, n.id);
}
@@ -500,6 +507,15 @@ export function registerExportImportFunction(sdk: ISdk, kv: StateKV): void {
await kv.set(KV.lessons, lesson.id, lesson);
}
}
+ if (importData.insights) {
+ for (const insight of importData.insights) {
+ if (strategy === "skip") {
+ const existing = await kv.get(KV.insights, insight.id).catch(() => null);
+ if (existing) { stats.skipped++; continue; }
+ }
+ await kv.set(KV.insights, insight.id, insight);
+ }
+ }
ctx.logger.info("Import complete", { strategy, ...stats });
return { success: true, strategy, ...stats };
diff --git a/src/functions/reflect.ts b/src/functions/reflect.ts
new file mode 100644
index 00000000..a7c47852
--- /dev/null
+++ b/src/functions/reflect.ts
@@ -0,0 +1,474 @@
+import type { ISdk } from "iii-sdk";
+import type { StateKV } from "../state/kv.js";
+import { KV, fingerprintId } from "../state/schema.js";
+import type {
+ Insight,
+ GraphNode,
+ GraphEdge,
+ SemanticMemory,
+ Lesson,
+ Crystal,
+ MemoryProvider,
+} from "../types.js";
+import { recordAudit } from "./audit.js";
+import { REFLECT_SYSTEM, buildReflectPrompt } from "../prompts/reflect.js";
+
+interface ConceptCluster {
+ concepts: string[];
+ facts: Array<{ fact: string; confidence: number }>;
+ lessons: Array<{ content: string; confidence: number }>;
+ crystalNarratives: string[];
+ factIds: string[];
+ lessonIds: string[];
+ crystalIds: string[];
+}
+
+function reinforceInsight(insight: Insight): void {
+ const now = new Date().toISOString();
+ insight.reinforcements++;
+ insight.confidence = Math.min(
+ 1.0,
+ insight.confidence + 0.1 * (1 - insight.confidence),
+ );
+ insight.lastReinforcedAt = now;
+ insight.updatedAt = now;
+}
+
+function buildGraphClusters(
+ nodes: GraphNode[],
+ edges: GraphEdge[],
+ maxClusters: number,
+): string[][] {
+ const conceptNodes = nodes.filter(
+ (n) => n.type === "concept" && !n.stale,
+ );
+ if (conceptNodes.length === 0) return [];
+
+ const edgeMap = new Map<string, Set<string>>();
+ for (const edge of edges) {
+ if (edge.stale) continue;
+ if (!edgeMap.has(edge.sourceNodeId))
+ edgeMap.set(edge.sourceNodeId, new Set());
+ if (!edgeMap.has(edge.targetNodeId))
+ edgeMap.set(edge.targetNodeId, new Set());
+ edgeMap.get(edge.sourceNodeId)!.add(edge.targetNodeId);
+ edgeMap.get(edge.targetNodeId)!.add(edge.sourceNodeId);
+ }
+
+ const degree = new Map<string, number>();
+ for (const node of conceptNodes) {
+ degree.set(node.id, edgeMap.get(node.id)?.size || 0);
+ }
+
+ const sorted = [...conceptNodes].sort(
+ (a, b) => (degree.get(b.id) || 0) - (degree.get(a.id) || 0),
+ );
+
+ const visited = new Set<string>();
+ const clusters: string[][] = [];
+ const conceptNodeIds = new Set(conceptNodes.map((n) => n.id));
+
+ for (const seed of sorted) {
+ if (visited.has(seed.id) || clusters.length >= maxClusters) break;
+
+ const cluster: string[] = [];
+ const queue = [seed.id];
+ const seen = new Set<string>();
+ let depth = 0;
+
+ while (queue.length > 0 && depth <= 2) {
+ const levelCount = queue.length;
+ for (let i = 0; i < levelCount; i++) {
+ const current = queue.shift()!;
+ if (seen.has(current)) continue;
+ seen.add(current);
+
+ if (conceptNodeIds.has(current)) {
+ const node = conceptNodes.find((n) => n.id === current);
+ if (node) cluster.push(node.name);
+ visited.add(current);
+ }
+
+ const neighbors = edgeMap.get(current) || new Set();
+ for (const neighbor of neighbors) {
+ if (!seen.has(neighbor)) queue.push(neighbor);
+ }
+ }
+ depth++;
+ }
+
+ if (cluster.length >= 2) clusters.push(cluster);
+ }
+
+ return clusters;
+}
+
+function buildJaccardClusters(
+ semanticMemories: SemanticMemory[],
+ lessons: Lesson[],
+ maxClusters: number,
+): string[][] {
+ const allConcepts = new Map<string, Set<string>>();
+
+ for (const sem of semanticMemories) {
+ const terms = sem.fact.toLowerCase().split(/\s+/).filter((t) => t.length > 3);
+ for (const term of terms) {
+ if (!allConcepts.has(term)) allConcepts.set(term, new Set());
+ allConcepts.get(term)!.add(sem.id);
+ }
+ }
+ for (const lesson of lessons) {
+ for (const tag of lesson.tags) {
+ const key = tag.toLowerCase();
+ if (!allConcepts.has(key)) allConcepts.set(key, new Set());
+ allConcepts.get(key)!.add(lesson.id);
+ }
+ }
+
+ const conceptList = [...allConcepts.keys()].filter(
+ (k) => (allConcepts.get(k)?.size || 0) >= 2,
+ );
+
+ const visited = new Set<string>();
+ const clusters: string[][] = [];
+
+ for (const concept of conceptList) {
+ if (visited.has(concept) || clusters.length >= maxClusters) break;
+
+ const cluster = [concept];
+ visited.add(concept);
+
+ const docsA = allConcepts.get(concept) || new Set();
+ for (const other of conceptList) {
+ if (visited.has(other)) continue;
+ const docsB = allConcepts.get(other) || new Set();
+ let intersection = 0;
+ for (const d of docsA) {
+ if (docsB.has(d)) intersection++;
+ }
+ const union = docsA.size + docsB.size - intersection;
+ const similarity = union > 0 ? intersection / union : 0;
+ if (similarity > 0.3) {
+ cluster.push(other);
+ visited.add(other);
+ }
+ }
+
+ if (cluster.length >= 2) clusters.push(cluster);
+ }
+
+ return clusters;
+}
+
+export function registerReflectFunctions(
+ sdk: ISdk,
+ kv: StateKV,
+ provider: MemoryProvider,
+): void {
+ sdk.registerFunction(
+ { id: "mem::reflect" },
+ async (data: { maxClusters?: number; project?: string }) => {
+ const maxClusters = Math.min(data?.maxClusters ?? 10, 20);
+ const maxInsightsPerCluster = 5;
+ const maxTotal = 50;
+
+ const [graphNodes, graphEdges, semanticMemories, lessons, crystals] =
+ await Promise.all([
+ kv.list<GraphNode>(KV.graphNodes).catch(() => []),
+ kv.list<GraphEdge>(KV.graphEdges).catch(() => []),
+ kv.list<SemanticMemory>(KV.semantic).catch(() => []),
+ kv.list<Lesson>(KV.lessons).catch(() => []),
+ kv.list<Crystal>(KV.crystals).catch(() => []),
+ ]);
+
+ let activeLessons = lessons.filter((l) => !l.deleted);
+ if (data?.project) {
+ activeLessons = activeLessons.filter((l) => l.project === data.project);
+ }
+
+ let conceptClusters = buildGraphClusters(
+ graphNodes,
+ graphEdges,
+ maxClusters,
+ );
+
+ const usedFallback = conceptClusters.length === 0;
+ if (usedFallback) {
+ conceptClusters = buildJaccardClusters(
+ semanticMemories,
+ activeLessons,
+ maxClusters,
+ );
+ }
+
+ let newInsights = 0;
+ let reinforced = 0;
+ let clustersSkipped = 0;
+ let totalInsights = 0;
+
+ for (const conceptNames of conceptClusters) {
+ if (totalInsights >= maxTotal) break;
+
+ const conceptSet = new Set(conceptNames.map((c) => c.toLowerCase()));
+
+ const clusterFacts = semanticMemories.filter((s) => {
+ const factTerms = s.fact.toLowerCase().split(/\s+/);
+ return factTerms.some((t) => conceptSet.has(t));
+ });
+
+ const clusterLessons = activeLessons.filter((l) =>
+ l.tags.some((t) => conceptSet.has(t.toLowerCase())) ||
+ conceptNames.some((c) =>
+ l.content.toLowerCase().includes(c.toLowerCase()),
+ ),
+ );
+
+ const clusterCrystals = crystals.filter((c) =>
+ (c.lessons || []).some((l) =>
+ conceptNames.some((cn) =>
+ l.toLowerCase().includes(cn.toLowerCase()),
+ ),
+ ),
+ );
+
+ const totalItems =
+ clusterFacts.length + clusterLessons.length + clusterCrystals.length;
+ if (totalItems < 3) {
+ clustersSkipped++;
+ continue;
+ }
+
+ const cluster: ConceptCluster = {
+ concepts: conceptNames,
+ facts: clusterFacts.map((f) => ({
+ fact: f.fact,
+ confidence: f.confidence,
+ })),
+ lessons: clusterLessons.map((l) => ({
+ content: l.content,
+ confidence: l.confidence,
+ })),
+ crystalNarratives: clusterCrystals.map((c) => c.narrative),
+ factIds: clusterFacts.map((f) => f.id),
+ lessonIds: clusterLessons.map((l) => l.id),
+ crystalIds: clusterCrystals.map((c) => c.id),
+ };
+
+ try {
+ const prompt = buildReflectPrompt(cluster);
+ const response = await provider.summarize(REFLECT_SYSTEM, prompt);
+
+ const insightRegex =
+ /<insight\s+confidence="([^"]+)"\s+title="([^"]+)">([\s\S]*?)<\/insight>/g;
+ let match;
+ let clusterCount = 0;
+
+ while (
+ (match = insightRegex.exec(response)) !== null &&
+ clusterCount < maxInsightsPerCluster &&
+ totalInsights < maxTotal
+ ) {
+ const parsedConf = parseFloat(match[1]);
+ const confidence = Number.isNaN(parsedConf)
+ ? 0.5
+ : Math.max(0, Math.min(1, parsedConf));
+ const title = match[2].trim();
+ const content = match[3].trim();
+
+ if (!content) continue;
+
+ const fp = fingerprintId("ins", content.trim().toLowerCase());
+ const existing = await kv.get<Insight>(KV.insights, fp);
+
+ if (existing && !existing.deleted) {
+ reinforceInsight(existing);
+ await kv.set(KV.insights, existing.id, existing);
+ reinforced++;
+ } else {
+ const now = new Date().toISOString();
+ const insight: Insight = {
+ id: fp,
+ title,
+ content,
+ confidence,
+ reinforcements: 0,
+ sourceConceptCluster: conceptNames,
+ sourceMemoryIds: cluster.factIds,
+ sourceLessonIds: cluster.lessonIds,
+ sourceCrystalIds: cluster.crystalIds,
+ project: data?.project,
+ tags: conceptNames,
+ createdAt: now,
+ updatedAt: now,
+ decayRate: 0.05,
+ };
+ await kv.set(KV.insights, insight.id, insight);
+ newInsights++;
+ }
+
+ clusterCount++;
+ totalInsights++;
+ }
+ } catch {
+ continue;
+ }
+ }
+
+ try {
+ await recordAudit(kv, "reflect", "mem::reflect", [], {
+ newInsights,
+ reinforced,
+ clustersProcessed: conceptClusters.length - clustersSkipped,
+ clustersSkipped,
+ usedFallback,
+ });
+ } catch {}
+
+ return {
+ success: true,
+ newInsights,
+ reinforced,
+ clustersProcessed: conceptClusters.length - clustersSkipped,
+ clustersSkipped,
+ usedFallback,
+ };
+ },
+ );
+
+ sdk.registerFunction(
+ { id: "mem::insight-list" },
+ async (data: {
+ project?: string;
+ minConfidence?: number;
+ limit?: number;
+ }) => {
+ const limit = data?.limit ?? 50;
+ const minConfidence = data?.minConfidence ?? 0;
+ let items = await kv.list<Insight>(KV.insights);
+
+ items = items.filter(
+ (i) => !i.deleted && i.confidence >= minConfidence,
+ );
+
+ if (data?.project) {
+ items = items.filter((i) => i.project === data.project);
+ }
+
+ items.sort((a, b) => b.confidence - a.confidence);
+
+ return { success: true, insights: items.slice(0, limit) };
+ },
+ );
+
+ sdk.registerFunction(
+ { id: "mem::insight-search" },
+ async (data: {
+ query: string;
+ project?: string;
+ minConfidence?: number;
+ limit?: number;
+ }) => {
+ if (!data?.query?.trim()) {
+ return { success: false, error: "query is required" };
+ }
+
+ const query = data.query.toLowerCase();
+ const minConfidence = data.minConfidence ?? 0.1;
+ const limit = data.limit ?? 10;
+
+ let items = await kv.list<Insight>(KV.insights);
+ items = items.filter(
+ (i) => !i.deleted && i.confidence >= minConfidence,
+ );
+
+ if (data.project) {
+ items = items.filter((i) => i.project === data.project);
+ }
+
+ const terms = query.split(/\s+/).filter((t) => t.length > 1);
+ const scored = items
+ .map((i) => {
+ const text =
+ `${i.title} ${i.content} ${i.tags.join(" ")}`.toLowerCase();
+ const matchCount = terms.filter((t) => text.includes(t)).length;
+ if (matchCount === 0) return null;
+
+ const relevance = matchCount / terms.length;
+ const daysSince = i.lastReinforcedAt
+ ? (Date.now() - new Date(i.lastReinforcedAt).getTime()) /
+ (1000 * 60 * 60 * 24)
+ : (Date.now() - new Date(i.createdAt).getTime()) /
+ (1000 * 60 * 60 * 24);
+ const recencyBoost = 1 / (1 + daysSince * 0.01);
+ const score = i.confidence * relevance * recencyBoost;
+
+ return { insight: i, score };
+ })
+ .filter(Boolean) as Array<{ insight: Insight; score: number }>;
+
+ scored.sort((a, b) => b.score - a.score);
+
+ try {
+ await recordAudit(kv, "insight_search", "mem::insight-search", [], {
+ query: data.query,
+ resultCount: scored.length,
+ });
+ } catch {}
+
+ return {
+ success: true,
+ insights: scored.slice(0, limit).map((s) => ({
+ ...s.insight,
+ score: Math.round(s.score * 1000) / 1000,
+ })),
+ };
+ },
+ );
+
+ sdk.registerFunction(
+ { id: "mem::insight-decay-sweep" },
+ async () => {
+ const items = await kv.list<Insight>(KV.insights);
+ let decayed = 0;
+ let softDeleted = 0;
+ const now = Date.now();
+ const timestamp = new Date().toISOString();
+ const dirty: Insight[] = [];
+
+ for (const insight of items) {
+ if (insight.deleted) continue;
+
+ const baseline =
+ insight.lastDecayedAt ||
+ insight.lastReinforcedAt ||
+ insight.createdAt;
+ const weeksSince =
+ (now - new Date(baseline).getTime()) / (1000 * 60 * 60 * 24 * 7);
+
+ if (weeksSince < 1) continue;
+
+ const decay = insight.decayRate * weeksSince;
+ const newConfidence = Math.max(0.05, insight.confidence - decay);
+
+ if (newConfidence !== insight.confidence) {
+ insight.confidence = Math.round(newConfidence * 1000) / 1000;
+ insight.lastDecayedAt = timestamp;
+ insight.updatedAt = timestamp;
+
+ if (insight.confidence <= 0.1 && insight.reinforcements === 0) {
+ insight.deleted = true;
+ softDeleted++;
+ } else {
+ decayed++;
+ }
+
+ dirty.push(insight);
+ }
+ }
+
+ await Promise.all(dirty.map((i) => kv.set(KV.insights, i.id, i)));
+
+ return { success: true, decayed, softDeleted, total: items.length };
+ },
+ );
+}
diff --git a/src/index.ts b/src/index.ts
index 15d8d1b1..3b83f884 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -66,6 +66,7 @@ import { registerVerifyFunction } from "./functions/verify.js";
import { registerCascadeFunction } from "./functions/cascade.js";
import { registerLessonsFunctions } from "./functions/lessons.js";
import { registerObsidianExportFunction } from "./functions/obsidian-export.js";
+import { registerReflectFunctions } from "./functions/reflect.js";
import { registerSlidingWindowFunction } from "./functions/sliding-window.js";
import { registerQueryExpansionFunction } from "./functions/query-expansion.js";
import { registerTemporalGraphFunctions } from "./functions/temporal-graph.js";
@@ -194,6 +195,7 @@ async function main() {
registerVerifyFunction(sdk, kv);
registerLessonsFunctions(sdk, kv);
registerObsidianExportFunction(sdk, kv);
+ registerReflectFunctions(sdk, kv, provider);
registerCascadeFunction(sdk, kv);
registerSlidingWindowFunction(sdk, kv, provider);
@@ -275,7 +277,7 @@ async function main() {
`[agentmemory] Ready. ${embeddingProvider ? "Triple-stream (BM25+Vector+Graph)" : "BM25+Graph"} search active.`,
);
console.log(
- `[agentmemory] Endpoints: 100 REST + 41 MCP tools + 6 MCP resources + 3 MCP prompts`,
+ `[agentmemory] Endpoints: 103 REST + 43 MCP tools + 6 MCP resources + 3 MCP prompts`,
);
const viewerPort = config.restPort + 2;
@@ -310,6 +312,15 @@ async function main() {
console.log(`[agentmemory] Lesson decay sweep: enabled (every 24h)`);
}
+ if (process.env.INSIGHT_DECAY_ENABLED !== "false") {
+ const insightDecayTimer = setInterval(async () => {
+ try {
+ await sdk.trigger("mem::insight-decay-sweep", {});
+ } catch {}
+ }, 86400000);
+ insightDecayTimer.unref();
+ }
+
if (isConsolidationEnabled()) {
const consolidationTimer = setInterval(async () => {
try {
diff --git a/src/mcp/server.ts b/src/mcp/server.ts
index 32461796..d565b698 100644
--- a/src/mcp/server.ts
+++ b/src/mcp/server.ts
@@ -954,6 +954,23 @@ export function registerMcpEndpoints(
return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(lessonRecallResult, null, 2) }] } };
}
+ case "memory_reflect": {
+ const reflectResult = await sdk.trigger("mem::reflect", {
+ project: args.project,
+ maxClusters: args.maxClusters,
+ });
+ return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(reflectResult, null, 2) }] } };
+ }
+
+ case "memory_insight_list": {
+ const insightListResult = await sdk.trigger("mem::insight-list", {
+ project: args.project,
+ minConfidence: args.minConfidence,
+ limit: args.limit,
+ });
+ return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(insightListResult, null, 2) }] } };
+ }
+
case "memory_obsidian_export": {
const exportTypes = typeof args.types === "string" && args.types.trim()
? args.types.split(",").map((t: string) => t.trim()).filter(Boolean)
diff --git a/src/mcp/tools-registry.ts b/src/mcp/tools-registry.ts
index 2052de2e..06a9466c 100644
--- a/src/mcp/tools-registry.ts
+++ b/src/mcp/tools-registry.ts
@@ -748,6 +748,40 @@ export const V070_TOOLS: McpToolDef[] = [
},
];
+export const V073_TOOLS: McpToolDef[] = [
+ {
+ name: "memory_reflect",
+ description:
+ "Traverse the knowledge graph, group related memories by concept clusters, and synthesize higher-order insights via LLM. Returns new and reinforced insights.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ project: { type: "string", description: "Filter by project" },
+ maxClusters: {
+ type: "number",
+ description: "Max concept clusters to process (default 10, max 20)",
+ },
+ },
+ },
+ },
+ {
+ name: "memory_insight_list",
+ description:
+ "List synthesized insights — higher-order observations derived from patterns across memories, lessons, and crystals.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ project: { type: "string", description: "Filter by project" },
+ minConfidence: {
+ type: "number",
+ description: "Minimum confidence threshold (default 0)",
+ },
+ limit: { type: "number", description: "Max results (default 50)" },
+ },
+ },
+ },
+];
+
const ESSENTIAL_TOOLS = new Set([
"memory_save",
"memory_recall",
@@ -756,10 +790,11 @@ const ESSENTIAL_TOOLS = new Set([
"memory_sessions",
"memory_diagnose",
"memory_lesson_save",
+ "memory_reflect",
]);
export function getAllTools(): McpToolDef[] {
- return [...CORE_TOOLS, ...V040_TOOLS, ...V050_TOOLS, ...V051_TOOLS, ...V061_TOOLS, ...V070_TOOLS];
+ return [...CORE_TOOLS, ...V040_TOOLS, ...V050_TOOLS, ...V051_TOOLS, ...V061_TOOLS, ...V070_TOOLS, ...V073_TOOLS];
}
export function getVisibleTools(): McpToolDef[] {
diff --git a/src/prompts/reflect.ts b/src/prompts/reflect.ts
new file mode 100644
index 00000000..6de84351
--- /dev/null
+++ b/src/prompts/reflect.ts
@@ -0,0 +1,55 @@
+export const REFLECT_SYSTEM = `You are a higher-order reasoning engine. Given a cluster of related concepts, facts, lessons, and action outcomes, synthesize cross-cutting insights that span multiple individual memories.
+
+Output format (XML):
+<insights>
+ <insight confidence="0.0-1.0" title="Short descriptive title">
+ The higher-order observation or principle. Should be actionable and non-obvious — something that only becomes visible when viewing multiple memories together.
+ </insight>
+</insights>
+
+Rules:
+- Identify patterns, principles, or strategies that span 2+ source items
+- Confidence reflects how well-supported the insight is across sources
+- Title should be a concise label (under 60 chars)
+- Content should be the actual observation (1-3 sentences)
+- Prefer actionable insights over abstract summaries
+- Skip insights that merely restate a single source item
+- Always emit confidence attribute before title attribute`;
+
+export function buildReflectPrompt(cluster: {
+ concepts: string[];
+ facts: Array<{ fact: string; confidence: number }>;
+ lessons: Array<{ content: string; confidence: number }>;
+ crystalNarratives: string[];
+}): string {
+ const sections: string[] = [];
+
+ sections.push(`## Concept Cluster: ${cluster.concepts.join(", ")}`);
+
+ if (cluster.facts.length > 0) {
+ sections.push(
+ "\n## Known Facts",
+ ...cluster.facts.map(
+ (f) => `- [confidence=${f.confidence}] ${f.fact}`,
+ ),
+ );
+ }
+
+ if (cluster.lessons.length > 0) {
+ sections.push(
+ "\n## Lessons Learned",
+ ...cluster.lessons.map(
+ (l) => `- [confidence=${l.confidence}] ${l.content}`,
+ ),
+ );
+ }
+
+ if (cluster.crystalNarratives.length > 0) {
+ sections.push(
+ "\n## Completed Work Summaries",
+ ...cluster.crystalNarratives.map((n) => `- ${n}`),
+ );
+ }
+
+ return `Synthesize higher-order insights from this cluster of related memories:\n\n${sections.join("\n")}`;
+}
diff --git a/src/state/schema.ts b/src/state/schema.ts
index b7389d34..3571e010 100644
--- a/src/state/schema.ts
+++ b/src/state/schema.ts
@@ -35,6 +35,7 @@ export const KV = {
sentinels: "mem:sentinels",
crystals: "mem:crystals",
lessons: "mem:lessons",
+ insights: "mem:insights",
graphEdgeHistory: "mem:graph:edge-history",
enrichedChunks: (sessionId: string) => `mem:enriched:${sessionId}`,
latentEmbeddings: (obsId: string) => `mem:latent:${obsId}`,
diff --git a/src/triggers/api.ts b/src/triggers/api.ts
index 97f2018e..817adf70 100644
--- a/src/triggers/api.ts
+++ b/src/triggers/api.ts
@@ -1901,4 +1901,44 @@ export function registerApiTriggers(
return { status_code: 200, body: result };
});
sdk.registerTrigger({ type: "http", function_id: "api::obsidian-export", config: { api_path: "/agentmemory/obsidian/export", http_method: "POST" } });
+
+ sdk.registerFunction({ id: "api::reflect" }, async (req: ApiRequest) => {
+ const denied = checkAuth(req, secret);
+ if (denied) return denied;
+ const body = (req.body as Record<string, unknown>) || {};
+ const result = await sdk.trigger("mem::reflect", {
+ project: typeof body.project === "string" ? body.project : undefined,
+ maxClusters: typeof body.maxClusters === "number" ? body.maxClusters : undefined,
+ });
+ return { status_code: 200, body: result };
+ });
+ sdk.registerTrigger({ type: "http", function_id: "api::reflect", config: { api_path: "/agentmemory/reflect", http_method: "POST" } });
+
+ sdk.registerFunction({ id: "api::insight-list" }, async (req: ApiRequest) => {
+ const denied = checkAuth(req, secret);
+ if (denied) return denied;
+ const params = req.query_params || {};
+ const result = await sdk.trigger("mem::insight-list", {
+ project: params.project,
+ minConfidence: params.minConfidence ? parseFloat(params.minConfidence as string) : undefined,
+ limit: params.limit ? parseInt(params.limit as string, 10) : undefined,
+ });
+ return { status_code: 200, body: result };
+ });
+ sdk.registerTrigger({ type: "http", function_id: "api::insight-list", config: { api_path: "/agentmemory/insights", http_method: "GET" } });
+
+ sdk.registerFunction({ id: "api::insight-search" }, async (req: ApiRequest) => {
+ const denied = checkAuth(req, secret);
+ if (denied) return denied;
+ const body = req.body as Record<string, unknown>;
+ if (!body?.query || typeof body.query !== "string") return { status_code: 400, body: { error: "query is required" } };
+ const result = await sdk.trigger("mem::insight-search", {
+ query: body.query,
+ project: typeof body.project === "string" ? body.project : undefined,
+ minConfidence: typeof body.minConfidence === "number" ? body.minConfidence : undefined,
+ limit: typeof body.limit === "number" ? body.limit : undefined,
+ });
+ return { status_code: 200, body: result };
+ });
+ sdk.registerTrigger({ type: "http", function_id: "api::insight-search", config: { api_path: "/agentmemory/insights/search", http_method: "POST" } });
}
diff --git a/src/types.ts b/src/types.ts
index 3b0c561d..b73d7889 100644
--- a/src/types.ts
+++ b/src/types.ts
@@ -270,6 +270,7 @@ export interface ExportData {
crystals?: Crystal[];
facets?: Facet[];
lessons?: Lesson[];
+ insights?: Insight[];
pagination?: ExportPagination;
}
@@ -464,7 +465,9 @@ export interface AuditEntry {
| "lesson_save"
| "lesson_recall"
| "lesson_strengthen"
- | "obsidian_export";
+ | "obsidian_export"
+ | "reflect"
+ | "insight_search";
userId?: string;
functionId: string;
targetIds: string[];
@@ -672,6 +675,26 @@ export interface Lesson {
deleted?: boolean;
}
+export interface Insight {
+ id: string;
+ title: string;
+ content: string;
+ confidence: number;
+ reinforcements: number;
+ sourceConceptCluster: string[];
+ sourceMemoryIds: string[];
+ sourceLessonIds: string[];
+ sourceCrystalIds: string[];
+ project?: string;
+ tags: string[];
+ createdAt: string;
+ updatedAt: string;
+ lastReinforcedAt?: string;
+ lastDecayedAt?: string;
+ decayRate: number;
+ deleted?: boolean;
+}
+
export interface DiagnosticCheck {
name: string;
category: string;
diff --git a/test/reflect.test.ts b/test/reflect.test.ts
new file mode 100644
index 00000000..d4e54c0a
--- /dev/null
+++ b/test/reflect.test.ts
@@ -0,0 +1,351 @@
+import { describe, it, expect, beforeEach, vi } from "vitest";
+
+vi.mock("iii-sdk", () => ({
+ getContext: () => ({
+ logger: { info: vi.fn(), error: vi.fn(), warn: vi.fn() },
+ }),
+}));
+
+import { registerReflectFunctions } from "../src/functions/reflect.js";
+import type { Insight, GraphNode, GraphEdge, SemanticMemory, Lesson, Crystal } from "../src/types.js";
+
+function mockKV() {
+ const store = new Map<string, Map<string, unknown>>();
+ return {
+ get: async <T>(scope: string, key: string): Promise<T | null> => {
+ return (store.get(scope)?.get(key) as T) ?? null;
+ },
+ set: async <T>(scope: string, key: string, data: T): Promise<T> => {
+ if (!store.has(scope)) store.set(scope, new Map());
+ store.get(scope)!.set(key, data);
+ return data;
+ },
+ delete: async (scope: string, key: string): Promise<void> => {
+ store.get(scope)?.delete(key);
+ },
+ list: async <T>(scope: string): Promise<T[]> => {
+ const entries = store.get(scope);
+ return entries ? (Array.from(entries.values()) as T[]) : [];
+ },
+ };
+}
+
+function mockSdk() {
+ const functions = new Map<string, Function>();
+ return {
+ registerFunction: (opts: { id: string }, handler: Function) => {
+ functions.set(opts.id, handler);
+ },
+ registerTrigger: () => {},
+ trigger: async (id: string, data: unknown) => {
+ const fn = functions.get(id);
+ if (!fn) throw new Error(`No function: ${id}`);
+ return fn(data);
+ },
+ };
+}
+
+function makeConceptNode(name: string): GraphNode {
+ return {
+ id: `node_${name}`,
+ type: "concept",
+ name,
+ properties: {},
+ sourceObservationIds: [],
+ createdAt: "2026-04-01T00:00:00Z",
+ };
+}
+
+function makeEdge(src: string, tgt: string): GraphEdge {
+ return {
+ id: `edge_${src}_${tgt}`,
+ type: "related_to",
+ sourceNodeId: `node_${src}`,
+ targetNodeId: `node_${tgt}`,
+ weight: 1,
+ sourceObservationIds: [],
+ createdAt: "2026-04-01T00:00:00Z",
+ };
+}
+
+function makeSemantic(fact: string, id?: string): SemanticMemory {
+ return {
+ id: id || `sem_${fact.slice(0, 8)}`,
+ fact,
+ confidence: 0.8,
+ sourceSessionIds: [],
+ sourceMemoryIds: [],
+ accessCount: 1,
+ lastAccessedAt: "2026-04-01T00:00:00Z",
+ strength: 0.8,
+ createdAt: "2026-04-01T00:00:00Z",
+ updatedAt: "2026-04-01T00:00:00Z",
+ };
+}
+
+function makeLesson(content: string, tags: string[]): Lesson {
+ return {
+ id: `lsn_${content.slice(0, 8)}`,
+ content,
+ context: "",
+ confidence: 0.7,
+ reinforcements: 0,
+ source: "manual",
+ sourceIds: [],
+ tags,
+ createdAt: "2026-04-01T00:00:00Z",
+ updatedAt: "2026-04-01T00:00:00Z",
+ decayRate: 0.05,
+ };
+}
+
+function makeCrystal(narrative: string, lessons: string[]): Crystal {
+ return {
+ id: `crys_${narrative.slice(0, 8)}`,
+ narrative,
+ keyOutcomes: [],
+ filesAffected: [],
+ lessons,
+ sourceActionIds: [],
+ createdAt: "2026-04-01T00:00:00Z",
+ };
+}
+
+const XML_RESPONSE = `<insights>
+<insight confidence="0.85" title="Defense in Depth">
+Security requires layered protection: input validation, safe APIs, and deny-lists together.
+</insight>
+<insight confidence="0.7" title="Testing at Boundaries">
+Focus test effort on system boundaries where trust transitions occur.
+</insight>
+</insights>`;
+
+describe("Reflect", () => {
+ let sdk: ReturnType<typeof mockSdk>;
+ let kv: ReturnType<typeof mockKV>;
+ let provider: { name: string; compress: ReturnType<typeof vi.fn>; summarize: ReturnType<typeof vi.fn> };
+
+ beforeEach(() => {
+ sdk = mockSdk();
+ kv = mockKV();
+ provider = {
+ name: "test",
+ compress: vi.fn(),
+ summarize: vi.fn().mockResolvedValue(XML_RESPONSE),
+ };
+ registerReflectFunctions(sdk as never, kv as never, provider as never);
+ });
+
+ describe("mem::reflect", () => {
+ it("returns empty when no graph nodes or memories exist", async () => {
+ const result = (await sdk.trigger("mem::reflect", {})) as {
+ success: boolean;
+ newInsights: number;
+ clustersProcessed: number;
+ };
+
+ expect(result.success).toBe(true);
+ expect(result.newInsights).toBe(0);
+ expect(result.clustersProcessed).toBe(0);
+ });
+
+ it("synthesizes insights from graph concept clusters", async () => {
+ await kv.set("mem:graph:nodes", "node_security", makeConceptNode("security"));
+ await kv.set("mem:graph:nodes", "node_validation", makeConceptNode("validation"));
+ await kv.set("mem:graph:nodes", "node_testing", makeConceptNode("testing"));
+ await kv.set("mem:graph:edges", "edge_1", makeEdge("security", "validation"));
+ await kv.set("mem:graph:edges", "edge_2", makeEdge("security", "testing"));
+
+ await kv.set("mem:semantic", "sem_1", makeSemantic("Always validate security inputs"));
+ await kv.set("mem:semantic", "sem_2", makeSemantic("Testing improves security coverage"));
+ await kv.set("mem:semantic", "sem_3", makeSemantic("Validation prevents injection attacks"));
+ await kv.set("mem:lessons", "lsn_1", makeLesson("Use execFile for security", ["security"]));
+
+ const result = (await sdk.trigger("mem::reflect", {})) as {
+ success: boolean;
+ newInsights: number;
+ };
+
+ expect(result.success).toBe(true);
+ expect(result.newInsights).toBe(2);
+ expect(provider.summarize).toHaveBeenCalled();
+
+ const insights = await kv.list<Insight>("mem:insights");
+ expect(insights.length).toBe(2);
+ expect(insights[0].title).toBeTruthy();
+ expect(insights[0].sourceConceptCluster.length).toBeGreaterThan(0);
+ });
+
+ it("skips clusters with fewer than 3 supporting items", async () => {
+ await kv.set("mem:graph:nodes", "node_sparse", makeConceptNode("sparse"));
+ await kv.set("mem:graph:nodes", "node_topic", makeConceptNode("topic"));
+ await kv.set("mem:graph:edges", "edge_1", makeEdge("sparse", "topic"));
+ await kv.set("mem:semantic", "sem_1", makeSemantic("One sparse fact"));
+
+ const result = (await sdk.trigger("mem::reflect", {})) as {
+ clustersSkipped: number;
+ newInsights: number;
+ };
+
+ expect(result.clustersSkipped).toBe(1);
+ expect(result.newInsights).toBe(0);
+ expect(provider.summarize).not.toHaveBeenCalled();
+ });
+
+ it("deduplicates insights by fingerprint", async () => {
+ await kv.set("mem:graph:nodes", "node_security", makeConceptNode("security"));
+ await kv.set("mem:graph:nodes", "node_validation", makeConceptNode("validation"));
+ await kv.set("mem:graph:edges", "edge_1", makeEdge("security", "validation"));
+ await kv.set("mem:semantic", "sem_1", makeSemantic("Always validate security inputs"));
+ await kv.set("mem:semantic", "sem_2", makeSemantic("Testing improves security coverage"));
+ await kv.set("mem:semantic", "sem_3", makeSemantic("Validation prevents injection"));
+
+ await sdk.trigger("mem::reflect", {});
+ const first = await kv.list<Insight>("mem:insights");
+ expect(first.length).toBe(2);
+
+ const result = (await sdk.trigger("mem::reflect", {})) as {
+ reinforced: number;
+ newInsights: number;
+ };
+
+ expect(result.reinforced).toBe(2);
+ expect(result.newInsights).toBe(0);
+
+ const after = await kv.list<Insight>("mem:insights");
+ expect(after.length).toBe(2);
+ expect(after[0].reinforcements).toBe(1);
+ });
+
+ it("falls back to Jaccard grouping when graph is empty", async () => {
+ await kv.set("mem:semantic", "sem_1", makeSemantic("security validation is important"));
+ await kv.set("mem:semantic", "sem_2", makeSemantic("security testing prevents bugs"));
+ await kv.set("mem:semantic", "sem_3", makeSemantic("validation testing framework"));
+ await kv.set("mem:lessons", "lsn_1", makeLesson("Use security headers", ["security", "validation"]));
+
+ const result = (await sdk.trigger("mem::reflect", {})) as {
+ success: boolean;
+ usedFallback: boolean;
+ };
+
+ expect(result.success).toBe(true);
+ expect(result.usedFallback).toBe(true);
+ });
+
+ it("handles LLM failure gracefully", async () => {
+ provider.summarize.mockRejectedValue(new Error("LLM timeout"));
+
+ await kv.set("mem:graph:nodes", "node_a", makeConceptNode("concept_a"));
+ await kv.set("mem:graph:nodes", "node_b", makeConceptNode("concept_b"));
+ await kv.set("mem:graph:edges", "edge_1", makeEdge("concept_a", "concept_b"));
+ await kv.set("mem:semantic", "sem_1", makeSemantic("fact about concept_a"));
+ await kv.set("mem:semantic", "sem_2", makeSemantic("fact about concept_b"));
+ await kv.set("mem:semantic", "sem_3", makeSemantic("concept_a and concept_b together"));
+
+ const result = (await sdk.trigger("mem::reflect", {})) as {
+ success: boolean;
+ newInsights: number;
+ };
+
+ expect(result.success).toBe(true);
+ expect(result.newInsights).toBe(0);
+ });
+ });
+
+ describe("mem::insight-list", () => {
+ beforeEach(async () => {
+ const now = new Date().toISOString();
+ await kv.set("mem:insights", "ins_1", {
+ id: "ins_1", title: "Insight A", content: "Content A", confidence: 0.9,
+ reinforcements: 2, sourceConceptCluster: ["security"], sourceMemoryIds: [],
+ sourceLessonIds: [], sourceCrystalIds: [], project: "/app",
+ tags: ["security"], createdAt: now, updatedAt: now, decayRate: 0.05,
+ });
+ await kv.set("mem:insights", "ins_2", {
+ id: "ins_2", title: "Insight B", content: "Content B", confidence: 0.4,
+ reinforcements: 0, sourceConceptCluster: ["testing"], sourceMemoryIds: [],
+ sourceLessonIds: [], sourceCrystalIds: [], project: "/other",
+ tags: ["testing"], createdAt: now, updatedAt: now, decayRate: 0.05,
+ });
+ });
+
+ it("lists all non-deleted insights sorted by confidence", async () => {
+ const result = (await sdk.trigger("mem::insight-list", {})) as { insights: Insight[] };
+ expect(result.insights.length).toBe(2);
+ expect(result.insights[0].confidence).toBe(0.9);
+ });
+
+ it("filters by project", async () => {
+ const result = (await sdk.trigger("mem::insight-list", { project: "/app" })) as { insights: Insight[] };
+ expect(result.insights.length).toBe(1);
+ });
+
+ it("filters by minConfidence", async () => {
+ const result = (await sdk.trigger("mem::insight-list", { minConfidence: 0.5 })) as { insights: Insight[] };
+ expect(result.insights.length).toBe(1);
+ });
+ });
+
+ describe("mem::insight-search", () => {
+ beforeEach(async () => {
+ const now = new Date().toISOString();
+ await kv.set("mem:insights", "ins_1", {
+ id: "ins_1", title: "Defense in Depth", content: "Security requires layered protection",
+ confidence: 0.85, reinforcements: 1, sourceConceptCluster: ["security"],
+ sourceMemoryIds: [], sourceLessonIds: [], sourceCrystalIds: [],
+ tags: ["security"], createdAt: now, updatedAt: now, decayRate: 0.05,
+ });
+ });
+
+ it("finds insights matching query", async () => {
+ const result = (await sdk.trigger("mem::insight-search", {
+ query: "security layered protection",
+ })) as { insights: Array<Insight & { score: number }> };
+
+ expect(result.insights.length).toBe(1);
+ expect(result.insights[0].title).toBe("Defense in Depth");
+ });
+
+ it("rejects empty query", async () => {
+ const result = (await sdk.trigger("mem::insight-search", { query: "" })) as { success: boolean };
+ expect(result.success).toBe(false);
+ });
+ });
+
+ describe("mem::insight-decay-sweep", () => {
+ it("decays old insights incrementally", async () => {
+ await kv.set("mem:insights", "ins_old", {
+ id: "ins_old", title: "Old", content: "Old insight", confidence: 0.8,
+ reinforcements: 1, sourceConceptCluster: [], sourceMemoryIds: [],
+ sourceLessonIds: [], sourceCrystalIds: [], tags: [],
+ createdAt: new Date(Date.now() - 21 * 86400000).toISOString(),
+ updatedAt: new Date(Date.now() - 21 * 86400000).toISOString(),
+ decayRate: 0.05,
+ });
+
+ const result = (await sdk.trigger("mem::insight-decay-sweep", {})) as { decayed: number };
+ expect(result.decayed).toBe(1);
+
+ const after = await kv.get<Insight>("mem:insights", "ins_old");
+ expect(after!.confidence).toBeLessThan(0.8);
+ expect(after!.lastDecayedAt).toBeDefined();
+ });
+
+ it("soft-deletes low-confidence unreinforced insights", async () => {
+ await kv.set("mem:insights", "ins_weak", {
+ id: "ins_weak", title: "Weak", content: "Weak insight", confidence: 0.12,
+ reinforcements: 0, sourceConceptCluster: [], sourceMemoryIds: [],
+ sourceLessonIds: [], sourceCrystalIds: [], tags: [],
+ createdAt: new Date(Date.now() - 21 * 86400000).toISOString(),
+ updatedAt: new Date(Date.now() - 21 * 86400000).toISOString(),
+ decayRate: 0.05,
+ });
+
+ const result = (await sdk.trigger("mem::insight-decay-sweep", {})) as { softDeleted: number };
+ expect(result.softDeleted).toBe(1);
+
+ const after = await kv.get<Insight>("mem:insights", "ins_weak");
+ expect(after!.deleted).toBe(true);
+ });
+ });
+});