Skip to content

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

feat: v0.7.0 — lessons, tool visibility, auto-consolidation, obsidian export, npx bootstrap (#82)

Rohit Ghumaree8f410b53725
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
new file mode 100644
index 00000000..ab430f5a
--- /dev/null
+++ b/.github/workflows/ci.yml
@@ -0,0 +1,22 @@
+name: CI
+
+on:
+ push:
+ branches: [main]
+ pull_request:
+ branches: [main]
+
+jobs:
+ test:
+ runs-on: ubuntu-latest
+ strategy:
+ matrix:
+ node-version: [20, 22]
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-node@v4
+ with:
+ node-version: ${{ matrix.node-version }}
+ - run: npm ci --legacy-peer-deps
+ - run: npm run build
+ - run: npm test
diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml
new file mode 100644
index 00000000..a8b2fb5c
--- /dev/null
+++ b/.github/workflows/publish.yml
@@ -0,0 +1,28 @@
+name: Publish to npm
+
+on:
+ release:
+ types: [published]
+
+permissions:
+ contents: read
+ id-token: write
+
+jobs:
+ publish:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+
+ - uses: actions/setup-node@v4
+ with:
+ node-version: 22
+ registry-url: https://registry.npmjs.org
+
+ - run: npm ci --legacy-peer-deps
+ - run: npm run build
+ - run: npm test
+
+ - run: npm publish --provenance --access public
+ env:
+ NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
diff --git a/AGENTS.md b/AGENTS.md
new file mode 100644
index 00000000..7b24ab91
--- /dev/null
+++ b/AGENTS.md
@@ -0,0 +1,113 @@
+# agentmemory — Agent Instructions
+
+## Architecture
+
+agentmemory is a persistent memory system for AI coding agents, built on iii-engine's three primitives (Worker/Function/Trigger). Everything goes through `registerFunction`/`registerTrigger`/`sdk.trigger()` — never bypass iii-engine with standalone SQLite or in-process alternatives.
+
+- **Engine**: iii-sdk (WebSocket to iii-engine on port 49134)
+- **State**: File-based SQLite via iii-engine's StateModule (`./data/state_store.db`)
+- **Build**: TypeScript → ESM via tsdown, output to `dist/`
+- **Test**: vitest (`npm test` excludes integration tests)
+
+## Consistency Rules
+
+**When adding or removing MCP tools, you MUST update ALL of the following:**
+1. `src/mcp/tools-registry.ts` — tool definition + `getAllTools()` array
+2. `src/mcp/server.ts` — handler case in the `mcp::tools::call` switch
+3. `src/triggers/api.ts` — REST endpoint registration
+4. `src/index.ts` — function registration + endpoint count in the log line
+5. `test/mcp-standalone.test.ts` — tool count assertion
+6. `README.md` — tool counts (search for "MCP tools")
+7. `plugin/.claude-plugin/plugin.json` — tool count in description
+
+**When adding REST endpoints, you MUST update:**
+1. `src/triggers/api.ts` — endpoint registration
+2. `src/index.ts` — endpoint count in the log line
+3. `README.md` — endpoint count (search for "REST endpoints" and "endpoints on port")
+
+**When bumping version, you MUST update ALL of the following:**
+1. `package.json` — version field
+2. `src/version.ts` — VERSION constant and type union
+3. `src/types.ts` — ExportData version union
+4. `src/functions/export-import.ts` — supportedVersions set
+5. `test/export-import.test.ts` — version assertion
+6. `plugin/.claude-plugin/plugin.json` — version field
+
+**When adding new KV scopes:**
+1. `src/state/schema.ts` — add to the KV object
+2. `src/types.ts` — add the corresponding interface
+
+**When adding new audit operations:**
+1. `src/types.ts` — add to AuditEntry.operation union type
+
+## Code Patterns
+
+### Function Registration
+```typescript
+sdk.registerFunction(
+ { id: "mem::your-function" },
+ async (data: { ... }) => {
+ // validate inputs
+ // do work via kv.get/kv.set/kv.list
+ // record audit via recordAudit()
+ return { success: true, ... };
+ },
+);
+```
+
+### REST Endpoint Registration
+```typescript
+sdk.registerFunction({ id: "api::your-endpoint" }, async (req: ApiRequest) => {
+ const denied = checkAuth(req, secret);
+ if (denied) return denied;
+ const body = req.body as Record<string, unknown>;
+ // validate + whitelist fields (never pass raw body to sdk.trigger)
+ const result = await sdk.trigger("mem::your-function", { ... });
+ return { status_code: 200, body: result };
+});
+sdk.registerTrigger({
+ type: "http",
+ function_id: "api::your-endpoint",
+ config: { api_path: "/agentmemory/your-path", http_method: "POST" },
+});
+```
+
+### MCP Tool Handler
+```typescript
+case "memory_your_tool": {
+ // validate args with typeof checks
+ // parse CSV args: args.field.split(",").map(t => t.trim()).filter(Boolean)
+ const result = await sdk.trigger("mem::your-function", { ... });
+ return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] } };
+}
+```
+
+### Hook Scripts
+Hook scripts in `src/hooks/` are standalone Node.js scripts (no iii-sdk import). They read JSON from stdin, make HTTP calls to the REST API, and exit. Always use `try/catch` with `AbortSignal.timeout()` for best-effort calls.
+
+## Coding Standards
+
+- TypeScript, ESM only (`"type": "module"`)
+- No code comments explaining WHAT — use clear naming instead
+- Use `fingerprintId()` for content-addressable dedup, `generateId()` for unique IDs
+- Parallel operations where possible (`Promise.all` for independent kv writes/reads)
+- Input validation at system boundaries (MCP handlers, REST endpoints)
+- REST endpoints must whitelist fields — never pass raw request body to `sdk.trigger()`
+- Use `recordAudit()` for state-changing operations
+- Timestamps: capture once with `new Date().toISOString()` and reuse
+
+## Testing
+
+- All tests must pass before PR: `npm test` (573+ tests)
+- Mock pattern: `vi.mock("iii-sdk")` with mock `sdk.trigger`, `kv.get/set/list`
+- Test files go in `test/` with `.test.ts` extension
+- Follow existing patterns in `test/crystallize.test.ts` for function tests
+
+## Current Stats (v0.7.0)
+
+- 41 MCP tools (7 visible by default, `AGENTMEMORY_TOOLS=all` for all)
+- 100 REST endpoints
+- 6 MCP resources, 3 MCP prompts
+- 12 hooks, 4 skills
+- 50+ iii functions
+- 573 tests
diff --git a/README.md b/README.md
index 027c2b8f..e41364f0 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 — 38 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. 573 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 — 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. 573 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.
@@ -133,7 +133,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 38 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 41 tools, 6 resources, and 3 prompts. The agent actively queries and saves memory through MCP calls.
| Agent | How to connect |
|---|---|
@@ -145,7 +145,7 @@ Any agent that connects to MCP servers can use agentmemory's 38 tools, 6 resourc
### REST API (any agent, any language)
-Agents without hooks or MCP can integrate via 93 REST endpoints directly. This works with any agent, language, or framework.
+Agents without hooks or MCP can integrate via 100 REST endpoints directly. This works with any agent, language, or framework.
```bash
POST /agentmemory/observe # Capture what the agent did
@@ -620,7 +620,7 @@ ANTHROPIC_API_KEY=sk-ant-...
## API
-95 endpoints on port `3111` (89 core + 6 MCP protocol). Protected endpoints require `Authorization: Bearer <secret>` when `AGENTMEMORY_SECRET` is set. The table below shows a representative subset; see `src/api.ts` for the full endpoint list.
+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.
| Method | Path | Description |
|--------|------|-------------|
@@ -683,7 +683,7 @@ ANTHROPIC_API_KEY=sk-ant-...
/plugin install agentmemory
```
-Restart Claude Code. All 12 hooks, 4 skills, and 38 MCP tools are registered automatically.
+Restart Claude Code. All 12 hooks, 4 skills, and 41 MCP tools are registered automatically.
### Plugin Commands
diff --git a/package.json b/package.json
index 0a28eeb6..57c7f5d3 100644
--- a/package.json
+++ b/package.json
@@ -1,16 +1,16 @@
{
"name": "agentmemory",
- "version": "0.5.0",
+ "version": "0.7.0",
"description": "Persistent memory for AI coding agents, powered by iii-engine's three primitives",
"type": "module",
"main": "dist/index.mjs",
"types": "dist/index.d.mts",
"bin": {
- "agentmemory": "dist/index.mjs",
+ "agentmemory": "dist/cli.mjs",
"agentmemory-mcp": "dist/standalone.mjs"
},
"scripts": {
- "build": "tsdown",
+ "build": "tsdown && (cp iii-config.yaml dist/ 2>/dev/null || true) && (cp docker-compose.yml dist/ 2>/dev/null || true)",
"dev": "tsx src/index.ts",
"start": "node dist/index.mjs",
"migrate": "node dist/functions/migrate.js",
@@ -50,6 +50,6 @@
"vitest": "^3.0.0"
},
"engines": {
- "node": ">=18.0.0"
+ "node": ">=20.0.0"
}
}
diff --git a/plugin/.claude-plugin/plugin.json b/plugin/.claude-plugin/plugin.json
index c2a2857b..da1b41a1 100644
--- a/plugin/.claude-plugin/plugin.json
+++ b/plugin/.claude-plugin/plugin.json
@@ -1,7 +1,7 @@
{
"name": "agentmemory",
- "version": "0.6.1",
- "description": "Persistent memory for AI coding agents -- captures tool usage, compresses via LLM, injects context into future sessions. 12 hooks, 5 MCP tools, 4 skills, real-time viewer.",
+ "version": "0.7.0",
+ "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.",
"author": "Rohit Ghumare",
"license": "Apache-2.0",
"homepage": "https://github.com/rohitg00/agentmemory",
diff --git a/plugin/scripts/session-end.mjs b/plugin/scripts/session-end.mjs
index aa29ad1c..ed4936e1 100755
--- a/plugin/scripts/session-end.mjs
+++ b/plugin/scripts/session-end.mjs
@@ -25,6 +25,27 @@ async function main() {
signal: AbortSignal.timeout(5e3)
});
} catch {}
+ if (process.env["CONSOLIDATION_ENABLED"] === "true") {
+ try {
+ await fetch(`${REST_URL}/agentmemory/crystals/auto`, {
+ method: "POST",
+ headers: authHeaders(),
+ body: JSON.stringify({ olderThanDays: 0 }),
+ signal: AbortSignal.timeout(15e3)
+ });
+ } catch {}
+ try {
+ await fetch(`${REST_URL}/agentmemory/consolidate-pipeline`, {
+ method: "POST",
+ headers: authHeaders(),
+ body: JSON.stringify({
+ tier: "all",
+ force: true
+ }),
+ signal: AbortSignal.timeout(3e4)
+ });
+ } catch {}
+ }
if (process.env["CLAUDE_MEMORY_BRIDGE"] === "true") try {
await fetch(`${REST_URL}/agentmemory/claude-bridge/sync`, {
method: "POST",
diff --git a/src/cli.ts b/src/cli.ts
new file mode 100644
index 00000000..d68d84fa
--- /dev/null
+++ b/src/cli.ts
@@ -0,0 +1,159 @@
+#!/usr/bin/env node
+
+import { spawn, execFileSync } from "node:child_process";
+import { existsSync } from "node:fs";
+import { join, dirname } from "node:path";
+import { fileURLToPath } from "node:url";
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+
+const args = process.argv.slice(2);
+
+if (args.includes("--help") || args.includes("-h")) {
+ console.log(`
+agentmemory — persistent memory for AI coding agents
+
+Usage: agentmemory [options]
+
+Options:
+ --help, -h Show this help
+ --tools all|core Tool visibility (default: core = 7 tools)
+ --no-engine Skip auto-starting iii-engine
+ --port <N> Override REST port (default: 3111)
+
+Environment:
+ AGENTMEMORY_TOOLS=all Expose all 41 MCP tools
+ AGENTMEMORY_SECRET=xxx Auth secret for REST/MCP
+ CONSOLIDATION_ENABLED=true Enable auto-consolidation (off by default)
+ OBSIDIAN_AUTO_EXPORT=true Auto-export on consolidation
+
+Quick start:
+ npx agentmemory # auto-starts iii-engine, runs worker
+ npx agentmemory-mcp # standalone MCP server (no engine needed)
+`);
+ process.exit(0);
+}
+
+const toolsIdx = args.indexOf("--tools");
+if (toolsIdx !== -1 && args[toolsIdx + 1]) {
+ process.env["AGENTMEMORY_TOOLS"] = args[toolsIdx + 1];
+}
+
+const portIdx = args.indexOf("--port");
+if (portIdx !== -1 && args[portIdx + 1]) {
+ process.env["III_REST_PORT"] = args[portIdx + 1];
+}
+
+const skipEngine = args.includes("--no-engine");
+
+function getRestPort(): number {
+ return parseInt(process.env["III_REST_PORT"] || "3111", 10) || 3111;
+}
+
+async function isEngineRunning(): Promise<boolean> {
+ try {
+ const res = await fetch(`http://localhost:${getRestPort()}/agentmemory/livez`, {
+ signal: AbortSignal.timeout(2000),
+ });
+ return res.ok;
+ } catch {
+ return false;
+ }
+}
+
+function findIiiConfig(): string {
+ const candidates = [
+ join(__dirname, "iii-config.yaml"),
+ join(__dirname, "..", "iii-config.yaml"),
+ join(process.cwd(), "iii-config.yaml"),
+ ];
+ for (const c of candidates) {
+ if (existsSync(c)) return c;
+ }
+ return "";
+}
+
+function whichBinary(name: string): string | null {
+ const cmd = process.platform === "win32" ? "where" : "which";
+ try {
+ return execFileSync(cmd, [name], { encoding: "utf-8" }).trim().split("\n")[0];
+ } catch {
+ return null;
+ }
+}
+
+async function startEngine(): Promise<boolean> {
+ const configPath = findIiiConfig();
+
+ const iiiBin = whichBinary("iii");
+ if (iiiBin && configPath) {
+ console.log(`[agentmemory] Starting iii-engine: ${iiiBin} --config ${configPath}`);
+ const child = spawn(iiiBin, ["--config", configPath], {
+ detached: true,
+ stdio: "ignore",
+ });
+ child.unref();
+ return true;
+ }
+
+ const dockerCompose = join(__dirname, "..", "docker-compose.yml");
+ const dcExists = existsSync(dockerCompose) || existsSync(join(process.cwd(), "docker-compose.yml"));
+ const dockerBin = whichBinary("docker");
+
+ if (dockerBin && dcExists) {
+ const composeFile = existsSync(dockerCompose) ? dockerCompose : join(process.cwd(), "docker-compose.yml");
+ console.log(`[agentmemory] Starting iii-engine via Docker...`);
+ const child = spawn(dockerBin, ["compose", "-f", composeFile, "up", "-d"], {
+ detached: true,
+ stdio: "ignore",
+ });
+ child.unref();
+ return true;
+ }
+
+ return false;
+}
+
+async function waitForEngine(timeoutMs: number): Promise<boolean> {
+ const start = Date.now();
+ while (Date.now() - start < timeoutMs) {
+ if (await isEngineRunning()) return true;
+ await new Promise((r) => setTimeout(r, 500));
+ }
+ return false;
+}
+
+async function main() {
+ if (!skipEngine && !(await isEngineRunning())) {
+ const started = await startEngine();
+ if (!started) {
+ console.error(`
+[agentmemory] iii-engine is not running and could not be auto-started.
+
+Install one of:
+ 1. iii CLI: npm install -g iii-engine
+ 2. Docker: docker compose up -d (with docker-compose.yml)
+
+Or run with --no-engine to connect to a remote engine.
+`);
+ process.exit(1);
+ }
+
+ console.log(`[agentmemory] Waiting for iii-engine to start...`);
+ const ready = await waitForEngine(15000);
+ if (!ready) {
+ const port = getRestPort();
+ console.error(`[agentmemory] iii-engine did not become ready within 15s.`);
+ console.error(`[agentmemory] Check that ports ${port}, ${port + 1}, 49134 are available.`);
+ process.exit(1);
+ }
+ console.log(`[agentmemory] iii-engine is ready.`);
+ }
+
+ await import("./index.js");
+}
+
+main().catch((err) => {
+ console.error(`[agentmemory] Fatal:`, err);
+ process.exit(1);
+});
diff --git a/src/functions/consolidation-pipeline.ts b/src/functions/consolidation-pipeline.ts
index 23042ab0..bc65fca0 100644
--- a/src/functions/consolidation-pipeline.ts
+++ b/src/functions/consolidation-pipeline.ts
@@ -16,7 +16,7 @@ import {
buildProceduralExtractionPrompt,
} from "../prompts/consolidation.js";
import { recordAudit } from "./audit.js";
-import { getConsolidationDecayDays } from "../config.js";
+import { getConsolidationDecayDays, isConsolidationEnabled } from "../config.js";
function applyDecay(
items: Array<{
@@ -49,7 +49,10 @@ export function registerConsolidationPipelineFunction(
): void {
sdk.registerFunction(
{ id: "mem::consolidate-pipeline" },
- async (data?: { tier?: string }) => {
+ async (data?: { tier?: string; force?: boolean }) => {
+ if (!data?.force && !isConsolidationEnabled()) {
+ return { success: false, skipped: true, reason: "CONSOLIDATION_ENABLED is not set to true" };
+ }
const ctx = getContext();
const tier = data?.tier || "all";
const decayDays = getConsolidationDecayDays();
@@ -232,6 +235,17 @@ export function registerConsolidationPipelineFunction(
};
}
+ if (process.env["OBSIDIAN_AUTO_EXPORT"] === "true") {
+ try {
+ await sdk.trigger("mem::obsidian-export", {});
+ results.obsidianExport = { success: true };
+ } catch (err) {
+ const msg = err instanceof Error ? err.message : String(err);
+ ctx.logger.warn("Obsidian auto-export failed", { error: msg });
+ results.obsidianExport = { success: false, error: msg };
+ }
+ }
+
await recordAudit(kv, "consolidate", "mem::consolidate-pipeline", [], {
tier,
results,
diff --git a/src/functions/crystallize.ts b/src/functions/crystallize.ts
index b0bea552..2ec6ce3f 100644
--- a/src/functions/crystallize.ts
+++ b/src/functions/crystallize.ts
@@ -72,6 +72,20 @@ export function registerCrystallizeFunction(
await kv.set(KV.crystals, crystal.id, crystal);
+ await Promise.all(
+ digest.lessons.map((lesson) =>
+ sdk.trigger("mem::lesson-save", {
+ content: lesson,
+ context: crystal.narrative,
+ confidence: 0.6,
+ project: data.project,
+ tags: [],
+ source: "crystal",
+ sourceIds: [crystal.id],
+ }).catch(() => {}),
+ ),
+ );
+
for (const action of actions) {
const updated = { ...action, crystallizedInto: crystal.id };
await kv.set(KV.actions, action.id, updated);
diff --git a/src/functions/export-import.ts b/src/functions/export-import.ts
index 8a69284b..90e2a5cb 100644
--- a/src/functions/export-import.ts
+++ b/src/functions/export-import.ts
@@ -20,6 +20,7 @@ import type {
Sketch,
Crystal,
Facet,
+ Lesson,
ExportPagination,
} from "../types.js";
import { KV } from "../state/schema.js";
@@ -80,6 +81,7 @@ export function registerExportImportFunction(sdk: ISdk, kv: StateKV): void {
sketches,
crystals,
facets,
+ lessons,
routines,
signals,
checkpoints,
@@ -94,6 +96,7 @@ export function registerExportImportFunction(sdk: ISdk, kv: StateKV): void {
kv.list<Sketch>(KV.sketches).catch(() => []),
kv.list<Crystal>(KV.crystals).catch(() => []),
kv.list<Facet>(KV.facets).catch(() => []),
+ kv.list<Lesson>(KV.lessons).catch(() => []),
kv.list<Routine>(KV.routines).catch(() => []),
kv.list<Signal>(KV.signals).catch(() => []),
kv.list<Checkpoint>(KV.checkpoints).catch(() => []),
@@ -119,6 +122,7 @@ export function registerExportImportFunction(sdk: ISdk, kv: StateKV): void {
sketches: sketches.length > 0 ? sketches : undefined,
crystals: crystals.length > 0 ? crystals : undefined,
facets: facets.length > 0 ? facets : undefined,
+ lessons: lessons.length > 0 ? lessons : undefined,
routines: routines.length > 0 ? routines : undefined,
signals: signals.length > 0 ? signals : undefined,
checkpoints: checkpoints.length > 0 ? checkpoints : undefined,
@@ -162,7 +166,7 @@ export function registerExportImportFunction(sdk: ISdk, kv: StateKV): void {
const strategy = data.strategy || "merge";
const importData = data.exportData;
- const supportedVersions = new Set(["0.3.0", "0.4.0", "0.5.0", "0.6.0", "0.6.1"]);
+ const supportedVersions = new Set(["0.3.0", "0.4.0", "0.5.0", "0.6.0", "0.6.1", "0.7.0"]);
if (!supportedVersions.has(importData.version)) {
return {
success: false,
@@ -294,6 +298,9 @@ export function registerExportImportFunction(sdk: ISdk, kv: StateKV): void {
for (const f of await kv.list<Facet>(KV.facets).catch(() => [])) {
await kv.delete(KV.facets, f.id);
}
+ for (const l of await kv.list<Lesson>(KV.lessons).catch(() => [])) {
+ await kv.delete(KV.lessons, l.id);
+ }
for (const n of await kv.list<{ id: string }>(KV.graphNodes).catch(() => [])) {
await kv.delete(KV.graphNodes, n.id);
}
@@ -484,6 +491,15 @@ export function registerExportImportFunction(sdk: ISdk, kv: StateKV): void {
await kv.set(KV.facets, facet.id, facet);
}
}
+ if (importData.lessons) {
+ for (const lesson of importData.lessons) {
+ if (strategy === "skip") {
+ const existing = await kv.get(KV.lessons, lesson.id).catch(() => null);
+ if (existing) { stats.skipped++; continue; }
+ }
+ await kv.set(KV.lessons, lesson.id, lesson);
+ }
+ }
ctx.logger.info("Import complete", { strategy, ...stats });
return { success: true, strategy, ...stats };
diff --git a/src/functions/lessons.ts b/src/functions/lessons.ts
new file mode 100644
index 00000000..2329391e
--- /dev/null
+++ b/src/functions/lessons.ts
@@ -0,0 +1,253 @@
+import type { ISdk } from "iii-sdk";
+import type { StateKV } from "../state/kv.js";
+import { KV, fingerprintId } from "../state/schema.js";
+import type { Lesson } from "../types.js";
+import { recordAudit } from "./audit.js";
+
+function reinforceLesson(lesson: Lesson): void {
+ const now = new Date().toISOString();
+ lesson.reinforcements++;
+ lesson.confidence = Math.min(
+ 1.0,
+ lesson.confidence + 0.1 * (1 - lesson.confidence),
+ );
+ lesson.lastReinforcedAt = now;
+ lesson.updatedAt = now;
+}
+
+export function registerLessonsFunctions(sdk: ISdk, kv: StateKV): void {
+ sdk.registerFunction(
+ { id: "mem::lesson-save" },
+ async (data: {
+ content: string;
+ context?: string;
+ confidence?: number;
+ project?: string;
+ tags?: string[];
+ source?: "crystal" | "manual" | "consolidation";
+ sourceIds?: string[];
+ }) => {
+ if (!data.content?.trim()) {
+ return { success: false, error: "content is required" };
+ }
+
+ const fp = fingerprintId("lsn", data.content.trim().toLowerCase());
+ const existing = await kv.get<Lesson>(KV.lessons, fp);
+
+ if (existing && !existing.deleted) {
+ reinforceLesson(existing);
+ if (data.context && !existing.context) {
+ existing.context = data.context;
+ }
+ await kv.set(KV.lessons, existing.id, existing);
+
+ try {
+ await recordAudit(kv, "lesson_strengthen", "mem::lesson-save", [
+ existing.id,
+ ]);
+ } catch {}
+
+ return {
+ success: true,
+ action: "strengthened",
+ lesson: existing,
+ };
+ }
+
+ const confidence =
+ typeof data.confidence === "number" &&
+ data.confidence >= 0 &&
+ data.confidence <= 1
+ ? data.confidence
+ : 0.5;
+
+ const now = new Date().toISOString();
+ const lesson: Lesson = {
+ id: fp,
+ content: data.content.trim(),
+ context: data.context?.trim() || "",
+ confidence,
+ reinforcements: 0,
+ source: data.source || "manual",
+ sourceIds: data.sourceIds || [],
+ project: data.project,
+ tags: data.tags || [],
+ createdAt: now,
+ updatedAt: now,
+ decayRate: 0.05,
+ };
+
+ await kv.set(KV.lessons, lesson.id, lesson);
+
+ try {
+ await recordAudit(kv, "lesson_save", "mem::lesson-save", [lesson.id]);
+ } catch {}
+
+ return { success: true, action: "created", lesson };
+ },
+ );
+
+ sdk.registerFunction(
+ { id: "mem::lesson-recall" },
+ 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 lessons = await kv.list<Lesson>(KV.lessons);
+
+ lessons = lessons.filter(
+ (l) => !l.deleted && l.confidence >= minConfidence,
+ );
+
+ if (data.project) {
+ lessons = lessons.filter((l) => l.project === data.project);
+ }
+
+ const scored = lessons
+ .map((l) => {
+ const text = `${l.content} ${l.context} ${l.tags.join(" ")}`.toLowerCase();
+ const terms = query.split(/\s+/).filter((t) => t.length > 1);
+ const matchCount = terms.filter((t) => text.includes(t)).length;
+ if (matchCount === 0) return null;
+
+ const relevance = matchCount / terms.length;
+ const daysSinceReinforced = l.lastReinforcedAt
+ ? (Date.now() - new Date(l.lastReinforcedAt).getTime()) /
+ (1000 * 60 * 60 * 24)
+ : (Date.now() - new Date(l.createdAt).getTime()) /
+ (1000 * 60 * 60 * 24);
+ const recencyBoost = 1 / (1 + daysSinceReinforced * 0.01);
+ const score = l.confidence * relevance * recencyBoost;
+
+ return { lesson: l, score };
+ })
+ .filter(Boolean) as Array<{ lesson: Lesson; score: number }>;
+
+ scored.sort((a, b) => b.score - a.score);
+
+ try {
+ await recordAudit(kv, "lesson_recall", "mem::lesson-recall", [], {
+ query: data.query,
+ resultCount: scored.length,
+ });
+ } catch {}
+
+ return {
+ success: true,
+ lessons: scored.slice(0, limit).map((s) => ({
+ ...s.lesson,
+ score: Math.round(s.score * 1000) / 1000,
+ })),
+ };
+ },
+ );
+
+ sdk.registerFunction(
+ { id: "mem::lesson-list" },
+ async (data: {
+ project?: string;
+ source?: string;
+ minConfidence?: number;
+ limit?: number;
+ }) => {
+ const limit = data.limit ?? 50;
+ const minConfidence = data.minConfidence ?? 0;
+ let lessons = await kv.list<Lesson>(KV.lessons);
+
+ lessons = lessons.filter(
+ (l) => !l.deleted && l.confidence >= minConfidence,
+ );
+
+ if (data.project) {
+ lessons = lessons.filter((l) => l.project === data.project);
+ }
+ if (data.source) {
+ lessons = lessons.filter((l) => l.source === data.source);
+ }
+
+ lessons.sort((a, b) => b.confidence - a.confidence);
+
+ return { success: true, lessons: lessons.slice(0, limit) };
+ },
+ );
+
+ sdk.registerFunction(
+ { id: "mem::lesson-strengthen" },
+ async (data: { lessonId: string }) => {
+ if (!data.lessonId) {
+ return { success: false, error: "lessonId is required" };
+ }
+
+ const lesson = await kv.get<Lesson>(KV.lessons, data.lessonId);
+ if (!lesson || lesson.deleted) {
+ return { success: false, error: "lesson not found" };
+ }
+
+ reinforceLesson(lesson);
+
+ await kv.set(KV.lessons, lesson.id, lesson);
+
+ try {
+ await recordAudit(kv, "lesson_strengthen", "mem::lesson-strengthen", [
+ lesson.id,
+ ]);
+ } catch {}
+
+ return { success: true, lesson };
+ },
+ );
+
+ sdk.registerFunction(
+ { id: "mem::lesson-decay-sweep" },
+ async () => {
+ const lessons = await kv.list<Lesson>(KV.lessons);
+ let decayed = 0;
+ let softDeleted = 0;
+ const now = Date.now();
+ const timestamp = new Date().toISOString();
+ const dirty: Lesson[] = [];
+
+ for (const lesson of lessons) {
+ if (lesson.deleted) continue;
+
+ const baseline = lesson.lastDecayedAt || lesson.lastReinforcedAt || lesson.createdAt;
+ const weeksSinceBaseline =
+ (now - new Date(baseline).getTime()) / (1000 * 60 * 60 * 24 * 7);
+
+ if (weeksSinceBaseline < 1) continue;
+
+ const decay = lesson.decayRate * weeksSinceBaseline;
+ const newConfidence = Math.max(0.05, lesson.confidence - decay);
+
+ if (newConfidence !== lesson.confidence) {
+ lesson.confidence = Math.round(newConfidence * 1000) / 1000;
+ lesson.lastDecayedAt = timestamp;
+ lesson.updatedAt = timestamp;
+
+ if (lesson.confidence <= 0.1 && lesson.reinforcements === 0) {
+ lesson.deleted = true;
+ softDeleted++;
+ } else {
+ decayed++;
+ }
+
+ dirty.push(lesson);
+ }
+ }
+
+ await Promise.all(dirty.map((l) => kv.set(KV.lessons, l.id, l)));
+
+ return { success: true, decayed, softDeleted, total: lessons.length };
+ },
+ );
+}
diff --git a/src/functions/obsidian-export.ts b/src/functions/obsidian-export.ts
new file mode 100644
index 00000000..cb541511
--- /dev/null
+++ b/src/functions/obsidian-export.ts
@@ -0,0 +1,310 @@
+import { mkdir, writeFile } from "node:fs/promises";
+import { join } from "node:path";
+import { homedir } from "node:os";
+import type { ISdk } from "iii-sdk";
+import type { StateKV } from "../state/kv.js";
+import { KV } from "../state/schema.js";
+import type {
+ Memory,
+ Lesson,
+ Crystal,
+ Session,
+} from "../types.js";
+import { recordAudit } from "./audit.js";
+
+const DEFAULT_VAULT = join(homedir(), ".agentmemory", "vault");
+
+function sanitize(name: string): string {
+ return name.replace(/[<>:"/\\|?*\x00-\x1f]/g, "_").slice(0, 100);
+}
+
+function toFrontmatter(obj: Record<string, unknown>): string {
+ const lines = ["---"];
+ for (const [key, value] of Object.entries(obj)) {
+ if (value === undefined || value === null) continue;
+ if (Array.isArray(value)) {
+ lines.push(`${key}: [${value.map((v) => JSON.stringify(String(v))).join(", ")}]`);
+ } else {
+ lines.push(`${key}: ${JSON.stringify(value)}`);
+ }
+ }
+ lines.push("---");
+ return lines.join("\n");
+}
+
+function memoryToMd(m: Memory): string {
+ const fm = toFrontmatter({
+ id: m.id,
+ type: m.type,
+ created: m.createdAt,
+ updated: m.updatedAt,
+ strength: m.strength,
+ version: m.version,
+ concepts: m.concepts,
+ files: m.files,
+ });
+
+ const related = (m.relatedIds || [])
+ .map((id) => `- [[${id}]]`)
+ .join("\n");
+ const supersedes = (m.supersedes || [])
+ .map((id) => `- [[${id}]] (superseded)`)
+ .join("\n");
+
+ const sections = [
+ fm,
+ "",
+ `# ${m.title}`,
+ "",
+ m.content,
+ ];
+
+ if (m.concepts.length > 0) {
+ sections.push("", "## Concepts", m.concepts.map((c) => `#${c.replace(/\s+/g, "-")}`).join(" "));
+ }
+ if (related) {
+ sections.push("", "## Related", related);
+ }
+ if (supersedes) {
+ sections.push("", "## Supersedes", supersedes);
+ }
+
+ return sections.join("\n");
+}
+
+function lessonToMd(l: Lesson): string {
+ const fm = toFrontmatter({
+ id: l.id,
+ type: "lesson",
+ source: l.source,
+ confidence: l.confidence,
+ reinforcements: l.reinforcements,
+ created: l.createdAt,
+ updated: l.updatedAt,
+ project: l.project,
+ tags: l.tags,
+ decayRate: l.decayRate,
+ });
+
+ const sourceLinks = l.sourceIds
+ .map((id) => `- [[${id}]]`)
+ .join("\n");
+
+ const sections = [
+ fm,
+ "",
+ `# Lesson: ${l.content.slice(0, 80)}`,
+ "",
+ l.content,
+ ];
+
+ if (l.context) {
+ sections.push("", "## Context", l.context);
+ }
+ if (l.tags.length > 0) {
+ sections.push("", "## Tags", l.tags.map((t) => `#${t.replace(/\s+/g, "-")}`).join(" "));
+ }
+ if (sourceLinks) {
+ sections.push("", "## Sources", sourceLinks);
+ }
+
+ return sections.join("\n");
+}
+
+function crystalToMd(c: Crystal): string {
+ const fm = toFrontmatter({
+ id: c.id,
+ type: "crystal",
+ created: c.createdAt,
+ project: c.project,
+ sessionId: c.sessionId,
+ filesAffected: c.filesAffected,
+ });
+
+ const actionLinks = c.sourceActionIds
+ .map((id) => `- [[${id}]]`)
+ .join("\n");
+
+ const sections = [
+ fm,
+ "",
+ `# Crystal: ${c.narrative.slice(0, 80)}`,
+ "",
+ c.narrative,
+ "",
+ "## Key Outcomes",
+ ...c.keyOutcomes.map((o) => `- ${o}`),
+ ];
+
+ if (c.lessons.length > 0) {
+ sections.push("", "## Lessons", ...c.lessons.map((l) => `- ${l}`));
+ }
+ if (c.filesAffected.length > 0) {
+ sections.push("", "## Files", ...c.filesAffected.map((f) => `- \`${f}\``));
+ }
+ if (actionLinks) {
+ sections.push("", "## Source Actions", actionLinks);
+ }
+
+ return sections.join("\n");
+}
+
+function sessionToMd(s: Session): string {
+ const fm = toFrontmatter({
+ id: s.id,
+ type: "session",
+ project: s.project,
+ status: s.status,
+ started: s.startedAt,
+ ended: s.endedAt,
+ observations: s.observationCount,
+ });
+
+ return [
+ fm,
+ "",
+ `# Session: ${s.project}`,
+ "",
+ `**Status:** ${s.status}`,
+ `**Started:** ${s.startedAt}`,
+ s.endedAt ? `**Ended:** ${s.endedAt}` : "",
+ `**Observations:** ${s.observationCount}`,
+ `**CWD:** \`${s.cwd}\``,
+ ]
+ .filter(Boolean)
+ .join("\n");
+}
+
+interface ExportError {
+ id: string;
+ path: string;
+ error: string;
+}
+
+export function registerObsidianExportFunction(
+ sdk: ISdk,
+ kv: StateKV,
+): void {
+ sdk.registerFunction(
+ { id: "mem::obsidian-export" },
+ async (data: { vaultDir?: string; types?: string[] }) => {
+ const vaultDir = data.vaultDir || DEFAULT_VAULT;
+ const exportTypes = new Set(
+ data.types || ["memories", "lessons", "crystals", "sessions"],
+ );
+
+ const dirs = {
+ memories: join(vaultDir, "memories"),
+ lessons: join(vaultDir, "lessons"),
+ crystals: join(vaultDir, "crystals"),
+ sessions: join(vaultDir, "sessions"),
+ };
+
+ await Promise.all(
+ Object.values(dirs).map((dir) => mkdir(dir, { recursive: true })),
+ );
+
+ const stats = { memories: 0, lessons: 0, crystals: 0, sessions: 0 };
+ const errors: ExportError[] = [];
+ const memoryMoc: string[] = [];
+ const lessonMoc: string[] = [];
+ const crystalMoc: string[] = [];
+ const sessionMoc: string[] = [];
+
+ const [memories, lessons, crystals, sessions] = await Promise.all([
+ exportTypes.has("memories") ? kv.list<Memory>(KV.memories) : Promise.resolve([] as Memory[]),
+ exportTypes.has("lessons") ? kv.list<Lesson>(KV.lessons) : Promise.resolve([] as Lesson[]),
+ exportTypes.has("crystals") ? kv.list<Crystal>(KV.crystals) : Promise.resolve([] as Crystal[]),
+ exportTypes.has("sessions") ? kv.list<Session>(KV.sessions) : Promise.resolve([] as Session[]),
+ ]);
+
+ for (const m of memories.filter((m) => m.isLatest)) {
+ const filename = `${sanitize(m.id)}.md`;
+ const filepath = join(dirs.memories, filename);
+ try {
+ await writeFile(filepath, memoryToMd(m));
+ stats.memories++;
+ memoryMoc.push(`- [[memories/${sanitize(m.id)}|${m.title}]] (${m.type}, strength: ${m.strength})`);
+ } catch (err) {
+ errors.push({ id: m.id, path: filepath, error: err instanceof Error ? err.message : String(err) });
+ }
+ }
+
+ for (const l of lessons.filter((l) => !l.deleted)) {
+ const filename = `${sanitize(l.id)}.md`;
+ const filepath = join(dirs.lessons, filename);
+ try {
+ await writeFile(filepath, lessonToMd(l));
+ stats.lessons++;
+ lessonMoc.push(`- [[lessons/${sanitize(l.id)}|${l.content.slice(0, 60)}]] (confidence: ${l.confidence})`);
+ } catch (err) {
+ errors.push({ id: l.id, path: filepath, error: err instanceof Error ? err.message : String(err) });
+ }
+ }
+
+ for (const c of crystals) {
+ const filename = `${sanitize(c.id)}.md`;
+ const filepath = join(dirs.crystals, filename);
+ try {
+ await writeFile(filepath, crystalToMd(c));
+ stats.crystals++;
+ crystalMoc.push(`- [[crystals/${sanitize(c.id)}|${c.narrative.slice(0, 60)}]]`);
+ } catch (err) {
+ errors.push({ id: c.id, path: filepath, error: err instanceof Error ? err.message : String(err) });
+ }
+ }
+
+ const recent = sessions
+ .sort(
+ (a, b) =>
+ new Date(b.startedAt).getTime() -
+ new Date(a.startedAt).getTime(),
+ )
+ .slice(0, 50);
+ for (const s of recent) {
+ const filename = `${sanitize(s.id)}.md`;
+ const filepath = join(dirs.sessions, filename);
+ try {
+ await writeFile(filepath, sessionToMd(s));
+ stats.sessions++;
+ sessionMoc.push(`- [[sessions/${sanitize(s.id)}|${s.project} (${s.status})]]`);
+ } catch (err) {
+ errors.push({ id: s.id, path: filepath, error: err instanceof Error ? err.message : String(err) });
+ }
+ }
+
+ const exportedAt = new Date().toISOString();
+ const moc = [
+ "---",
+ "type: moc",
+ `exported: ${exportedAt}`,
+ "---",
+ "",
+ "# agentmemory vault",
+ "",
+ `Exported: ${exportedAt}`,
+ "",
+ `## Memories (${stats.memories})`,
+ ...memoryMoc,
+ "",
+ `## Lessons (${stats.lessons})`,
+ ...lessonMoc,
+ "",
+ `## Crystals (${stats.crystals})`,
+ ...crystalMoc,
+ "",
+ `## Sessions (${stats.sessions})`,
+ ...sessionMoc,
+ ].join("\n");
+
+ await writeFile(join(vaultDir, "MOC.md"), moc);
+
+ await recordAudit(kv, "obsidian_export", "mem::obsidian-export", [], {
+ vaultDir,
+ stats,
+ });
+
+ return { success: true, exported: stats, errors: errors.length > 0 ? errors : undefined, vaultDir };
+ },
+ );
+}
diff --git a/src/hooks/session-end.ts b/src/hooks/session-end.ts
index 6ea0dffe..dd02f28a 100644
--- a/src/hooks/session-end.ts
+++ b/src/hooks/session-end.ts
@@ -35,6 +35,26 @@ async function main() {
// best-effort
}
+ if (process.env["CONSOLIDATION_ENABLED"] === "true") {
+ try {
+ await fetch(`${REST_URL}/agentmemory/crystals/auto`, {
+ method: "POST",
+ headers: authHeaders(),
+ body: JSON.stringify({ olderThanDays: 0 }),
+ signal: AbortSignal.timeout(15000),
+ });
+ } catch {}
+
+ try {
+ await fetch(`${REST_URL}/agentmemory/consolidate-pipeline`, {
+ method: "POST",
+ headers: authHeaders(),
+ body: JSON.stringify({ tier: "all", force: true }),
+ signal: AbortSignal.timeout(30000),
+ });
+ } catch {}
+ }
+
if (process.env["CLAUDE_MEMORY_BRIDGE"] === "true") {
try {
await fetch(`${REST_URL}/agentmemory/claude-bridge/sync`, {
diff --git a/src/index.ts b/src/index.ts
index 353791c6..15d8d1b1 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -64,6 +64,8 @@ import { registerDiagnosticsFunction } from "./functions/diagnostics.js";
import { registerFacetsFunction } from "./functions/facets.js";
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 { registerSlidingWindowFunction } from "./functions/sliding-window.js";
import { registerQueryExpansionFunction } from "./functions/query-expansion.js";
import { registerTemporalGraphFunctions } from "./functions/temporal-graph.js";
@@ -162,10 +164,8 @@ async function main() {
console.log(`[agentmemory] Knowledge graph: extraction enabled`);
}
- if (isConsolidationEnabled()) {
- registerConsolidationPipelineFunction(sdk, kv, provider);
- console.log(`[agentmemory] Consolidation pipeline: enabled`);
- }
+ registerConsolidationPipelineFunction(sdk, kv, provider);
+ console.log(`[agentmemory] Consolidation pipeline: registered (CONSOLIDATION_ENABLED=${isConsolidationEnabled() ? "true" : "false"})`);
const teamConfig = loadTeamConfig();
if (teamConfig) {
@@ -192,6 +192,8 @@ async function main() {
registerDiagnosticsFunction(sdk, kv);
registerFacetsFunction(sdk, kv);
registerVerifyFunction(sdk, kv);
+ registerLessonsFunctions(sdk, kv);
+ registerObsidianExportFunction(sdk, kv);
registerCascadeFunction(sdk, kv);
registerSlidingWindowFunction(sdk, kv, provider);
@@ -273,7 +275,7 @@ async function main() {
`[agentmemory] Ready. ${embeddingProvider ? "Triple-stream (BM25+Vector+Graph)" : "BM25+Graph"} search active.`,
);
console.log(
- `[agentmemory] Endpoints: 93 REST + 46 MCP tools + 6 MCP resources + 3 MCP prompts`,
+ `[agentmemory] Endpoints: 100 REST + 41 MCP tools + 6 MCP resources + 3 MCP prompts`,
);
const viewerPort = config.restPort + 2;
@@ -298,7 +300,17 @@ async function main() {
console.log(`[agentmemory] Auto-forget: enabled (every ${autoForgetIntervalMs / 60000}m)`);
}
- if (process.env.CONSOLIDATION_ENABLED === "true") {
+ if (process.env.LESSON_DECAY_ENABLED !== "false") {
+ const lessonDecayTimer = setInterval(async () => {
+ try {
+ await sdk.trigger("mem::lesson-decay-sweep", {});
+ } catch {}
+ }, 86400000);
+ lessonDecayTimer.unref();
+ console.log(`[agentmemory] Lesson decay sweep: enabled (every 24h)`);
+ }
+
+ if (isConsolidationEnabled()) {
const consolidationTimer = setInterval(async () => {
try {
await sdk.trigger("mem::consolidate-pipeline", {});
diff --git a/src/mcp/server.ts b/src/mcp/server.ts
index c6b5141b..32461796 100644
--- a/src/mcp/server.ts
+++ b/src/mcp/server.ts
@@ -8,7 +8,7 @@ import type {
GraphNode,
GraphEdge,
} from "../types.js";
-import { getAllTools } from "./tools-registry.js";
+import { getVisibleTools } from "./tools-registry.js";
import { timingSafeCompare } from "../auth.js";
type McpResponse = {
@@ -40,7 +40,7 @@ export function registerMcpEndpoints(
async (req: ApiRequest): Promise<McpResponse> => {
const authErr = checkAuth(req, secret);
if (authErr) return authErr;
- return { status_code: 200, body: { tools: getAllTools() } };
+ return { status_code: 200, body: { tools: getVisibleTools() } };
},
);
sdk.registerTrigger({
@@ -923,6 +923,48 @@ export function registerMcpEndpoints(
return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(verifyResult, null, 2) }] } };
}
+ case "memory_lesson_save": {
+ if (typeof args.content !== "string" || !args.content.trim()) {
+ return { status_code: 400, body: { error: "content is required" } };
+ }
+ const lessonTags = typeof args.tags === "string" && args.tags.trim()
+ ? args.tags.split(",").map((t: string) => t.trim()).filter(Boolean)
+ : [];
+ const lessonSaveResult = await sdk.trigger("mem::lesson-save", {
+ content: args.content,
+ context: args.context || "",
+ confidence: args.confidence,
+ project: args.project,
+ tags: lessonTags,
+ source: "manual",
+ });
+ return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(lessonSaveResult, null, 2) }] } };
+ }
+
+ case "memory_lesson_recall": {
+ if (typeof args.query !== "string" || !args.query.trim()) {
+ return { status_code: 400, body: { error: "query is required" } };
+ }
+ const lessonRecallResult = await sdk.trigger("mem::lesson-recall", {
+ query: args.query,
+ project: args.project,
+ minConfidence: args.minConfidence,
+ limit: args.limit,
+ });
+ return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(lessonRecallResult, 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)
+ : undefined;
+ const obsidianResult = await sdk.trigger("mem::obsidian-export", {
+ vaultDir: args.vaultDir,
+ types: exportTypes,
+ });
+ return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(obsidianResult, null, 2) }] } };
+ }
+
default:
return {
status_code: 400,
diff --git a/src/mcp/standalone.ts b/src/mcp/standalone.ts
index 2922fa53..87afdfca 100644
--- a/src/mcp/standalone.ts
+++ b/src/mcp/standalone.ts
@@ -2,7 +2,7 @@
import { InMemoryKV } from "./in-memory-kv.js";
import { createStdioTransport } from "./transport.js";
-import { getAllTools } from "./tools-registry.js";
+import { getVisibleTools } from "./tools-registry.js";
import { getStandalonePersistPath } from "../config.js";
import { VERSION } from "../version.js";
@@ -136,7 +136,7 @@ const transport = createStdioTransport(async (method, params) => {
case "tools/list":
return {
- tools: getAllTools().filter((t) => IMPLEMENTED_TOOLS.has(t.name)),
+ tools: getVisibleTools().filter((t) => IMPLEMENTED_TOOLS.has(t.name)),
};
case "tools/call": {
diff --git a/src/mcp/tools-registry.ts b/src/mcp/tools-registry.ts
index 64227797..2052de2e 100644
--- a/src/mcp/tools-registry.ts
+++ b/src/mcp/tools-registry.ts
@@ -684,6 +684,86 @@ export const V061_TOOLS: McpToolDef[] = [
},
];
+export const V070_TOOLS: McpToolDef[] = [
+ {
+ name: "memory_lesson_save",
+ description:
+ "Save a lesson learned from this session. Lessons have confidence scores that strengthen when reinforced and decay when not used. Duplicate content auto-strengthens the existing lesson.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ content: {
+ type: "string",
+ description: "The lesson learned (what worked, what to avoid, when to use X approach)",
+ },
+ context: {
+ type: "string",
+ description: "When/where this lesson applies",
+ },
+ confidence: {
+ type: "number",
+ description: "Initial confidence 0.0-1.0 (default 0.5)",
+ },
+ project: { type: "string", description: "Project this lesson is about" },
+ tags: { type: "string", description: "Comma-separated tags" },
+ },
+ required: ["content"],
+ },
+ },
+ {
+ name: "memory_lesson_recall",
+ description:
+ "Search lessons by query. Returns lessons sorted by confidence and recency. Use to check what the agent has learned before making decisions.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ query: { type: "string", description: "Search query" },
+ project: { type: "string", description: "Filter by project" },
+ minConfidence: {
+ type: "number",
+ description: "Minimum confidence threshold (default 0.1)",
+ },
+ limit: { type: "number", description: "Max results (default 10)" },
+ },
+ required: ["query"],
+ },
+ },
+ {
+ name: "memory_obsidian_export",
+ description:
+ "Export memories, lessons, and crystals as Obsidian-compatible Markdown files with YAML frontmatter and wikilinks for graph view.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ vaultDir: {
+ type: "string",
+ description: "Output directory (default ~/.agentmemory/vault/)",
+ },
+ types: {
+ type: "string",
+ description: "Comma-separated types to export: memories,lessons,crystals,sessions (default all)",
+ },
+ },
+ },
+ },
+];
+
+const ESSENTIAL_TOOLS = new Set([
+ "memory_save",
+ "memory_recall",
+ "memory_consolidate",
+ "memory_smart_search",
+ "memory_sessions",
+ "memory_diagnose",
+ "memory_lesson_save",
+]);
+
export function getAllTools(): McpToolDef[] {
- return [...CORE_TOOLS, ...V040_TOOLS, ...V050_TOOLS, ...V051_TOOLS, ...V061_TOOLS];
+ return [...CORE_TOOLS, ...V040_TOOLS, ...V050_TOOLS, ...V051_TOOLS, ...V061_TOOLS, ...V070_TOOLS];
+}
+
+export function getVisibleTools(): McpToolDef[] {
+ const mode = process.env["AGENTMEMORY_TOOLS"] || "core";
+ if (mode === "all") return getAllTools();
+ return getAllTools().filter((t) => ESSENTIAL_TOOLS.has(t.name));
}
diff --git a/src/state/schema.ts b/src/state/schema.ts
index fd1b8fe3..b7389d34 100644
--- a/src/state/schema.ts
+++ b/src/state/schema.ts
@@ -34,6 +34,7 @@ export const KV = {
facets: "mem:facets",
sentinels: "mem:sentinels",
crystals: "mem:crystals",
+ lessons: "mem:lessons",
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 4f7568eb..97f2018e 100644
--- a/src/triggers/api.ts
+++ b/src/triggers/api.ts
@@ -1838,4 +1838,67 @@ export function registerApiTriggers(
return { status_code: 200, body: result };
});
sdk.registerTrigger({ type: "http", function_id: "api::cascade-update", config: { api_path: "/agentmemory/cascade-update", http_method: "POST" } });
+
+ sdk.registerFunction({ id: "api::lesson-save" }, async (req: ApiRequest) => {
+ const denied = checkAuth(req, secret);
+ if (denied) return denied;
+ 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 result = await sdk.trigger("mem::lesson-save", {
+ content: body.content,
+ context: body.context || "",
+ confidence: typeof body.confidence === "number" ? body.confidence : undefined,
+ project: typeof body.project === "string" ? body.project : undefined,
+ tags,
+ source: "manual",
+ }) as { action?: string };
+ const statusCode = result?.action === "created" ? 201 : 200;
+ return { status_code: statusCode, body: result };
+ });
+ sdk.registerTrigger({ type: "http", function_id: "api::lesson-save", config: { api_path: "/agentmemory/lessons", http_method: "POST" } });
+
+ sdk.registerFunction({ id: "api::lesson-list" }, async (req: ApiRequest) => {
+ const denied = checkAuth(req, secret);
+ if (denied) return denied;
+ const params = req.query_params || {};
+ const result = await sdk.trigger("mem::lesson-list", {
+ project: params.project,
+ source: params.source,
+ 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::lesson-list", config: { api_path: "/agentmemory/lessons", http_method: "GET" } });
+
+ sdk.registerFunction({ id: "api::lesson-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::lesson-recall", body);
+ return { status_code: 200, body: result };
+ });
+ sdk.registerTrigger({ type: "http", function_id: "api::lesson-search", config: { api_path: "/agentmemory/lessons/search", http_method: "POST" } });
+
+ sdk.registerFunction({ id: "api::lesson-strengthen" }, async (req: ApiRequest) => {
+ const denied = checkAuth(req, secret);
+ if (denied) return denied;
+ const body = req.body as Record<string, unknown>;
+ if (!body?.lessonId || typeof body.lessonId !== "string") return { status_code: 400, body: { error: "lessonId is required" } };
+ const result = await sdk.trigger("mem::lesson-strengthen", { lessonId: body.lessonId });
+ return { status_code: 200, body: result };
+ });
+ sdk.registerTrigger({ type: "http", function_id: "api::lesson-strengthen", config: { api_path: "/agentmemory/lessons/strengthen", http_method: "POST" } });
+
+ sdk.registerFunction({ id: "api::obsidian-export" }, async (req: ApiRequest) => {
+ const denied = checkAuth(req, secret);
+ if (denied) return denied;
+ const body = (req.body as Record<string, unknown>) || {};
+ const types = typeof body.types === "string" ? body.types.split(",").map((t: string) => t.trim()).filter(Boolean) : undefined;
+ const result = await sdk.trigger("mem::obsidian-export", { vaultDir: body.vaultDir, types });
+ return { status_code: 200, body: result };
+ });
+ sdk.registerTrigger({ type: "http", function_id: "api::obsidian-export", config: { api_path: "/agentmemory/obsidian/export", http_method: "POST" } });
}
diff --git a/src/types.ts b/src/types.ts
index bfa8d979..e97172e5 100644
--- a/src/types.ts
+++ b/src/types.ts
@@ -249,7 +249,7 @@ export interface ExportPagination {
}
export interface ExportData {
- version: "0.3.0" | "0.4.0" | "0.5.0" | "0.6.0" | "0.6.1";
+ version: "0.3.0" | "0.4.0" | "0.5.0" | "0.6.0" | "0.6.1" | "0.7.0";
exportedAt: string;
sessions: Session[];
observations: Record<string, CompressedObservation[]>;
@@ -269,6 +269,7 @@ export interface ExportData {
sketches?: Sketch[];
crystals?: Crystal[];
facets?: Facet[];
+ lessons?: Lesson[];
pagination?: ExportPagination;
}
@@ -459,7 +460,11 @@ export interface AuditEntry {
| "crystallize"
| "diagnose"
| "heal"
- | "facet_tag";
+ | "facet_tag"
+ | "lesson_save"
+ | "lesson_recall"
+ | "lesson_strengthen"
+ | "obsidian_export";
userId?: string;
functionId: string;
targetIds: string[];
@@ -649,6 +654,24 @@ export interface Crystal {
createdAt: string;
}
+export interface Lesson {
+ id: string;
+ content: string;
+ context: string;
+ confidence: number;
+ reinforcements: number;
+ source: "crystal" | "manual" | "consolidation";
+ sourceIds: 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/src/version.ts b/src/version.ts
index b910864b..ee5e4d34 100644
--- a/src/version.ts
+++ b/src/version.ts
@@ -1 +1 @@
-export const VERSION: "0.3.0" | "0.4.0" | "0.5.0" | "0.6.0" | "0.6.1" = "0.6.1";
+export const VERSION: "0.3.0" | "0.4.0" | "0.5.0" | "0.6.0" | "0.6.1" | "0.7.0" = "0.7.0";
diff --git a/test/consistency.test.ts b/test/consistency.test.ts
new file mode 100644
index 00000000..092f51ae
--- /dev/null
+++ b/test/consistency.test.ts
@@ -0,0 +1,61 @@
+import { describe, it, expect, vi } from "vitest";
+import { readFileSync } from "node:fs";
+import { join } from "node:path";
+
+vi.mock("iii-sdk", () => ({
+ getContext: () => ({
+ logger: { info: vi.fn(), error: vi.fn(), warn: vi.fn() },
+ }),
+}));
+
+import { getAllTools } from "../src/mcp/tools-registry.js";
+import { VERSION } from "../src/version.js";
+
+const ROOT = join(import.meta.dirname, "..");
+
+function readText(relativePath: string): string {
+ return readFileSync(join(ROOT, relativePath), "utf-8");
+}
+
+describe("Consistency checks", () => {
+ const toolCount = getAllTools().length;
+
+ it("version.ts matches package.json", () => {
+ const pkg = JSON.parse(readText("package.json"));
+ expect(VERSION).toBe(pkg.version);
+ });
+
+ it("plugin.json version matches package.json", () => {
+ const pkg = JSON.parse(readText("package.json"));
+ const plugin = JSON.parse(readText("plugin/.claude-plugin/plugin.json"));
+ expect(plugin.version).toBe(pkg.version);
+ });
+
+ it("export-import.ts supports current version", () => {
+ const src = readText("src/functions/export-import.ts");
+ expect(src).toContain(`"${VERSION}"`);
+ });
+
+ it("README mentions correct MCP tool count", () => {
+ const readme = readText("README.md");
+ const toolCountPattern = new RegExp(`${toolCount}\\s+MCP tools`);
+ expect(readme).toMatch(toolCountPattern);
+ const toolResourcePattern = new RegExp(`${toolCount}\\s+tools,\\s+6\\s+resources`);
+ expect(readme).toMatch(toolResourcePattern);
+ });
+
+ it("all tool names are unique", () => {
+ const tools = getAllTools();
+ const names = new Set(tools.map((t) => t.name));
+ expect(names.size).toBe(tools.length);
+ });
+
+ it("all tools have name, description, and inputSchema", () => {
+ for (const tool of getAllTools()) {
+ expect(tool.name).toBeTruthy();
+ expect(tool.description).toBeTruthy();
+ expect(tool.inputSchema).toBeDefined();
+ expect(tool.inputSchema.type).toBe("object");
+ }
+ });
+});
diff --git a/test/consolidation-pipeline.test.ts b/test/consolidation-pipeline.test.ts
index 46cab447..ff031f92 100644
--- a/test/consolidation-pipeline.test.ts
+++ b/test/consolidation-pipeline.test.ts
@@ -8,9 +8,11 @@ vi.mock("iii-sdk", () => ({
vi.mock("../src/config.js", () => ({
getConsolidationDecayDays: () => 30,
+ isConsolidationEnabled: vi.fn(() => true),
}));
import { registerConsolidationPipelineFunction } from "../src/functions/consolidation-pipeline.js";
+import { isConsolidationEnabled } from "../src/config.js";
import type { SessionSummary, Memory, SemanticMemory, ProceduralMemory } from "../src/types.js";
function mockKV() {
@@ -206,4 +208,44 @@ describe("Consolidation Pipeline", () => {
const audits = await kv.list("mem:audit");
expect(audits.length).toBe(1);
});
+
+ it("pipeline returns early when consolidation is disabled", async () => {
+ vi.mocked(isConsolidationEnabled).mockReturnValue(false);
+ const provider = {
+ name: "test",
+ compress: vi.fn(),
+ summarize: vi.fn(),
+ };
+ registerConsolidationPipelineFunction(sdk as never, kv as never, provider as never);
+
+ const result = (await sdk.trigger("mem::consolidate-pipeline", {})) as {
+ success: boolean;
+ skipped?: boolean;
+ reason?: string;
+ };
+
+ expect(result.success).toBe(false);
+ expect(result.skipped).toBe(true);
+ expect(result.reason).toContain("CONSOLIDATION_ENABLED");
+ expect(provider.summarize).not.toHaveBeenCalled();
+ vi.mocked(isConsolidationEnabled).mockReturnValue(true);
+ });
+
+ it("pipeline proceeds with force=true even when consolidation is disabled", async () => {
+ vi.mocked(isConsolidationEnabled).mockReturnValue(false);
+ const provider = {
+ name: "test",
+ compress: vi.fn(),
+ summarize: vi.fn(),
+ };
+ registerConsolidationPipelineFunction(sdk as never, kv as never, provider as never);
+
+ const result = (await sdk.trigger("mem::consolidate-pipeline", {
+ force: true,
+ })) as { success: boolean; results: Record<string, unknown> };
+
+ expect(result.success).toBe(true);
+ expect(result.results).toBeDefined();
+ vi.mocked(isConsolidationEnabled).mockReturnValue(true);
+ });
});
diff --git a/test/export-import.test.ts b/test/export-import.test.ts
index 11043ae2..ad44d72f 100644
--- a/test/export-import.test.ts
+++ b/test/export-import.test.ts
@@ -118,7 +118,7 @@ describe("Export/Import Functions", () => {
it("export produces valid ExportData structure", async () => {
const result = (await sdk.trigger("mem::export", {})) as ExportData;
- expect(result.version).toBe("0.6.1");
+ expect(result.version).toBe("0.7.0");
expect(result.exportedAt).toBeDefined();
expect(result.sessions.length).toBe(1);
expect(result.sessions[0].id).toBe("ses_1");
diff --git a/test/mcp-standalone.test.ts b/test/mcp-standalone.test.ts
index d5a2223e..90f47c2c 100644
--- a/test/mcp-standalone.test.ts
+++ b/test/mcp-standalone.test.ts
@@ -22,10 +22,21 @@ import { InMemoryKV } from "../src/mcp/in-memory-kv.js";
import { writeFileSync } from "node:fs";
describe("Tools Registry", () => {
- it("getAllTools returns 38 tools including memory_verify", () => {
+ it("getAllTools returns all tools with unique names", () => {
const tools = getAllTools();
- expect(tools.length).toBe(38);
- expect(tools.some((t) => t.name === "memory_verify")).toBe(true);
+ expect(tools.length).toBeGreaterThanOrEqual(41);
+ const names = new Set(tools.map((t) => t.name));
+ expect(names.size).toBe(tools.length);
+ for (const required of [
+ "memory_verify",
+ "memory_lesson_save",
+ "memory_lesson_recall",
+ "memory_obsidian_export",
+ "memory_save",
+ "memory_recall",
+ ]) {
+ expect(tools.some((t) => t.name === required)).toBe(true);
+ }
});
it("CORE_TOOLS has 10 items", () => {
diff --git a/tsdown.config.ts b/tsdown.config.ts
index 80b2fdf4..9ffa3c5c 100644
--- a/tsdown.config.ts
+++ b/tsdown.config.ts
@@ -15,39 +15,48 @@ const hookEntries = [
"src/hooks/session-end.ts",
];
+const shared = {
+ format: ["esm"] as const,
+ target: "node20" as const,
+ inlineOnly: false as const,
+};
+
export default defineConfig([
{
entry: ["src/index.ts"],
outDir: "dist",
- format: ["esm"],
+ ...shared,
dts: true,
clean: true,
sourcemap: true,
- target: "node18",
banner: { js: "#!/usr/bin/env node" },
},
+ {
+ entry: ["src/cli.ts"],
+ outDir: "dist",
+ ...shared,
+ clean: false,
+ sourcemap: false,
+ },
{
entry: ["src/mcp/standalone.ts"],
outDir: "dist",
- format: ["esm"],
+ ...shared,
clean: false,
sourcemap: false,
- target: "node18",
},
{
entry: hookEntries,
outDir: "dist/hooks",
- format: ["esm"],
+ ...shared,
clean: false,
sourcemap: false,
- target: "node18",
},
{
entry: hookEntries,
outDir: "plugin/scripts",
- format: ["esm"],
+ ...shared,
clean: false,
sourcemap: false,
- target: "node18",
},
]);