#1 Persistent memory for AI coding agents based on real-world benchmarks
TypeScript agentmemoryagentsaiclaudeclaudecodecodexcopilotcursorgenaiharnesshermesmemoryompopenclawopencodepi
add integration tests, polish README, simplify code
Rohit Ghumarefeffc5a362b7
diff --git a/README.md b/README.mdindex 4bb9d7d9..15801e6d 100644--- a/README.md+++ b/README.md@@ -1,16 +1,27 @@-# agentmemory+<p align="center">+ <h1 align="center">agentmemory</h1>+ <p align="center">Persistent memory for AI coding agents.<br/>Powered by <a href="https://iii.dev">iii-engine</a>.</p>+</p>-Persistent memory for AI coding agents, powered by [iii-engine](https://iii.dev)'s three primitives (Worker / Function / Trigger).+<p align="center">+ <a href="#quick-start">Quick Start</a> •+ <a href="#how-it-works">How It Works</a> •+ <a href="#configuration">Configuration</a> •+ <a href="#api">API</a> •+ <a href="#plugin-install">Plugin Install</a>+</p>-agentmemory captures tool usage during coding sessions, compresses observations via LLM, and injects relevant context into future sessions. Your AI agent remembers what it did yesterday.+----## How It Works+Your AI coding agent forgets everything between sessions. agentmemory fixes that.++It silently captures tool usage during coding sessions, compresses observations via LLM, and injects relevant context into future sessions. No manual notes. No copy-pasting. The agent just *knows*.```Session 1: "Add auth to the API"Claude Code writes code, runs tests, fixes bugsagentmemory silently captures every tool use- Session ends -> LLM compresses observations into structured memory+ Session ends -> observations compressed into structured memorySession 2: "Now add rate limiting"agentmemory injects context from Session 1:@@ -20,108 +31,96 @@ Session 2: "Now add rate limiting"Claude Code starts with full project awareness```-No manual notes. No copy-pasting. The agent just knows.--## Architecture+## Quick Start-agentmemory replaces the traditional memory stack with iii-engine's three primitives:+```bash+git clone https://github.com/rohitg00/agentmemory.git+cd agentmemory-| Traditional Stack | agentmemory |-|---|---|-| Express.js server | iii Worker + HTTP Triggers |-| SQLite + FTS5 | iii KV State |-| SSE streaming | iii Streams (WebSocket) |-| Process manager (pm2/systemd) | iii-engine manages workers |-| 20+ REST endpoints | API Triggers -> Functions |+# Start iii-engine+docker compose up -d-**27 source files. 1,808 lines of code. 35KB bundled.**+# Install, build, run+npm install && npm run build && npm start+```-Scalable from day one -- iii-engine handles orchestration, state persistence, and real-time streaming natively.+agentmemory connects to iii-engine on `ws://localhost:49134` and exposes its API on port `3111`.-## Quick Start+### Verify it works```bash-# 1. Start iii-engine-docker compose up -d--# 2. Install and build-npm install && npm run build--# 3. Start agentmemory worker-npm start+curl http://localhost:3111/agentmemory/health+# {"status":"ok","service":"agentmemory","version":"0.1.0"}```-That's it. agentmemory connects to iii-engine on `ws://localhost:49134` and exposes REST endpoints on port `3111`.--### Configure Claude Code Hooks+### Connect to Claude Code-Add to your `~/.claude/settings.json`:+Add to `~/.claude/settings.json`:```json{"hooks": {- "SessionStart": [{ "type": "command", "command": "node /path/to/agentmemory/dist/hooks/session-start.mjs" }],- "UserPromptSubmit": [{ "type": "command", "command": "node /path/to/agentmemory/dist/hooks/prompt-submit.mjs" }],- "PostToolUse": [{ "type": "command", "command": "node /path/to/agentmemory/dist/hooks/post-tool-use.mjs" }],- "Stop": [{ "type": "command", "command": "node /path/to/agentmemory/dist/hooks/stop.mjs" }],- "SessionEnd": [{ "type": "command", "command": "node /path/to/agentmemory/dist/hooks/session-end.mjs" }]+ "SessionStart": [{ "type": "command", "command": "node ~/agentmemory/dist/hooks/session-start.mjs" }],+ "UserPromptSubmit": [{ "type": "command", "command": "node ~/agentmemory/dist/hooks/prompt-submit.mjs" }],+ "PostToolUse": [{ "type": "command", "command": "node ~/agentmemory/dist/hooks/post-tool-use.mjs" }],+ "Stop": [{ "type": "command", "command": "node ~/agentmemory/dist/hooks/stop.mjs" }],+ "SessionEnd": [{ "type": "command", "command": "node ~/agentmemory/dist/hooks/session-end.mjs" }]}}```-Or install as a Claude Code plugin (see [Plugin Install](#claude-code-plugin)).+Or install as a [Claude Code plugin](#plugin-install) for automatic hook registration.-## Observation Pipeline+That's it. Start a Claude Code session and agentmemory begins capturing. Start another session and it injects context from all previous sessions.++## How It Works-Every tool use flows through a four-stage pipeline:+### Observation Pipeline++Every tool use flows through this pipeline:```-Claude Code PostToolUse hook- |- v-mem::observe Store raw observation to KV, push to real-time stream- |- v-mem::compress LLM extracts structured data (type, facts, narrative, concepts, files)- | Runs async -- doesn't block the coding session- v-mem::summarize End-of-session: LLM generates session summary from all observations+PostToolUse hook fires+ -> mem::privacy Strip secrets, API keys, <private> tags+ -> mem::observe Store raw observation, push to real-time stream+ -> mem::compress LLM extracts: type, facts, narrative, concepts, files+ (async -- never blocks your session)+```++### Context Injection++On `SessionStart`, agentmemory builds context from your history:++```+SessionStart hook fires+ -> mem::context Load recent sessions for this project+ Prefer summaries, fall back to high-importance observations+ Apply token budget (default: 2000 tokens)+ Return formatted context block+ -> stdout Claude Code injects it into the conversation```### What Gets Captured-| Hook | Data |-|------|------|+| Hook | Captures |+|------|----------|| `SessionStart` | Project path, session ID, working directory || `UserPromptSubmit` | User prompts (privacy-filtered) || `PostToolUse` | Tool name, input, output (Read, Write, Edit, Bash, etc.) |-| `Stop` | Triggers session summarization |+| `Stop` | Triggers end-of-session summary || `SessionEnd` | Marks session complete |### Privacy-All observations pass through `mem::privacy` before storage:-- `<private>...</private>` blocks are stripped-- API keys, tokens, and secrets are redacted (`ANTHROPIC_API_KEY`, `GITHUB_TOKEN`, etc.)--## Context Injection--On `SessionStart`, agentmemory builds a context block from previous sessions:--```-mem::context- |- +-- Load recent sessions for this project (up to 10)- +-- For each: prefer session summary, fall back to high-importance observations- +-- Apply token budget (default: 2000 tokens)- +-- Return formatted <agentmemory-context> block-```+All data passes through `mem::privacy` before storage:+- `<private>...</private>` tags are stripped+- API keys (`sk-*`, `ghp_*`, `xoxb-*`, `AKIA*`), JWTs, and secrets are redacted-The hook writes the context to stdout, and Claude Code injects it into the conversation.+## Configuration-## LLM Providers+### LLM Providers-agentmemory uses LLM calls for two operations: compressing observations and generating session summaries. Four providers are supported:+agentmemory needs an LLM for two things: compressing observations and generating session summaries.| Provider | Config | Cost ||----------|--------|------|@@ -130,14 +129,14 @@ agentmemory uses LLM calls for two operations: compressing observations and gene| **Gemini** | `GEMINI_API_KEY` | Per-token || **OpenRouter** | `OPENROUTER_API_KEY` | Per-token |-Provider is auto-detected. No API key configured = subscription mode via `@anthropic-ai/claude-agent-sdk`.+No API key? agentmemory uses your Claude subscription automatically via `@anthropic-ai/claude-agent-sdk`. Zero config.-### Configure+### Environment VariablesCreate `~/.agentmemory/.env`:```env-# Pick one (or leave empty for subscription mode)+# LLM provider -- pick one (or leave empty for subscription mode)ANTHROPIC_API_KEY=sk-ant-...# GEMINI_API_KEY=...# OPENROUTER_API_KEY=...@@ -147,201 +146,136 @@ ANTHROPIC_API_KEY=sk-ant-...# GEMINI_MODEL=gemini-2.0-flash# OPENROUTER_MODEL=anthropic/claude-sonnet-4-20250514-# Optional: engine connection (defaults shown)+# Optional: bearer token for API auth+# AGENTMEMORY_SECRET=your-secret-here++# Optional: engine connection# III_ENGINE_URL=ws://localhost:49134# III_REST_PORT=3111# III_STREAMS_PORT=3112-# Optional: memory settings+# Optional: memory tuning# TOKEN_BUDGET=2000# MAX_OBS_PER_SESSION=500```-## API Endpoints+## API-All endpoints are served via iii-engine's REST API on port `3111`.+All endpoints on port `3111`. Protected endpoints require `Authorization: Bearer <secret>` when `AGENTMEMORY_SECRET` is set.| Method | Path | Description ||--------|------|-------------|-| `GET` | `/agentmemory/health` | Health check |-| `POST` | `/agentmemory/session/start` | Start session, return context from previous sessions |+| `GET` | `/agentmemory/health` | Health check (always public) |+| `POST` | `/agentmemory/session/start` | Start session + get context || `POST` | `/agentmemory/session/end` | Mark session complete |-| `POST` | `/agentmemory/observe` | Capture a tool-use observation |-| `POST` | `/agentmemory/context` | Generate context for a project |-| `POST` | `/agentmemory/search` | Search observations by keyword |+| `POST` | `/agentmemory/observe` | Capture observation |+| `POST` | `/agentmemory/context` | Generate context |+| `POST` | `/agentmemory/search` | Search observations || `POST` | `/agentmemory/summarize` | Generate session summary || `GET` | `/agentmemory/sessions` | List all sessions |-| `GET` | `/agentmemory/observations?sessionId=X` | Get observations for a session |+| `GET` | `/agentmemory/observations?sessionId=X` | Session observations || `GET` | `/agentmemory/viewer` | Real-time web viewer |-| `POST` | `/agentmemory/migrate` | Import from SQLite database |+| `POST` | `/agentmemory/migrate` | Import from SQLite |### Examples```bash-# Health check-curl http://localhost:3111/agentmemory/health+# Start a session+curl -X POST http://localhost:3111/agentmemory/session/start \+ -H "Content-Type: application/json" \+ -d '{"sessionId": "ses-1", "project": "/my/project", "cwd": "/my/project"}'-# Search observations+# Capture an observation+curl -X POST http://localhost:3111/agentmemory/observe \+ -H "Content-Type: application/json" \+ -d '{+ "hookType": "post_tool_use",+ "sessionId": "ses-1",+ "project": "/my/project",+ "cwd": "/my/project",+ "timestamp": "2026-02-25T12:00:00Z",+ "data": {"tool": "Edit", "file": "src/auth.ts", "content": "Added JWT validation"}+ }'++# Search across all observationscurl -X POST http://localhost:3111/agentmemory/search \-H "Content-Type: application/json" \-d '{"query": "authentication middleware", "limit": 10}'-# Get context for a project+# Get context for a new sessioncurl -X POST http://localhost:3111/agentmemory/context \-H "Content-Type: application/json" \- -d '{"sessionId": "current", "project": "/path/to/project"}'+ -d '{"sessionId": "ses-2", "project": "/my/project"}'-# List all sessions+# List sessionscurl http://localhost:3111/agentmemory/sessions```## Real-Time Viewer-Open `http://localhost:3111/agentmemory/viewer` in your browser.--The viewer connects to iii-engine's WebSocket stream on port `3112` and shows observations as they flow in -- raw captures first, then structured data after LLM compression.+Open [http://localhost:3111/agentmemory/viewer](http://localhost:3111/agentmemory/viewer) to watch observations flow in real-time.-Dark theme. Timeline layout. Filter by session. Auto-scrolls.+Connects to iii-engine's WebSocket stream. Dark theme, timeline layout, session filtering, auto-scroll.-## Claude Code Plugin+## Plugin Install-Install as a plugin for automatic hook registration:+Install as a Claude Code plugin for zero-config hook registration:```bash-# Build first-npm run build--# Option 1: Symlink the plugin directory+# Symlink into Claude Code pluginsln -s /path/to/agentmemory/plugin ~/.claude/plugins/agentmemory--# Option 2: Copy plugin manifest-cp -r plugin/ ~/.claude/plugins/agentmemory```-The plugin registers all 5 hooks automatically via `hooks.json`.+All 5 hooks are registered automatically via `hooks.json`.## Migration-Import data from existing SQLite-based memory systems:+Import from existing SQLite-based memory systems :```bash+npm install better-sqlite3+curl -X POST http://localhost:3111/agentmemory/migrate \-H "Content-Type: application/json" \- -d '{"dbPath": "/path/to/memory.db"}'+ -d '{"dbPath": "~/.agentmemory/memory.db"}'```-Reads `sessions`, `observations`/`compressed_observations`, and `session_summaries` tables. Requires `better-sqlite3` as an optional dependency:+Imports sessions, observations, and summaries.-```bash-npm install better-sqlite3-```+## Architecture-## iii-engine Functions--agentmemory registers these iii Functions:--| Function ID | Description |-|-------------|-------------|-| `mem::observe` | Capture and store a tool-use observation |-| `mem::compress` | LLM compression of raw observation into structured data |-| `mem::privacy` | Strip private data, secrets, and API keys |-| `mem::search` | Keyword search across compressed observations |-| `mem::context` | Generate token-budgeted context from past sessions |-| `mem::summarize` | LLM-generated end-of-session summary |-| `mem::migrate` | Import data from SQLite databases |-| `api::health` | Health check endpoint |-| `api::session::start` | Session start + context retrieval |-| `api::session::end` | Mark session complete |-| `api::observe` | HTTP -> `mem::observe` |-| `api::context` | HTTP -> `mem::context` |-| `api::search` | HTTP -> `mem::search` |-| `api::summarize` | HTTP -> `mem::summarize` |-| `api::sessions` | List all sessions |-| `api::observations` | Get session observations |-| `api::viewer` | Serve web viewer |-| `api::migrate` | HTTP -> `mem::migrate` |--Event triggers (queue type) handle async lifecycle events: `session.started`, `observation`, `session.stopped`, `session.ended`.--## KV State Schema--| Scope | Key | Data |-|-------|-----|------|-| `mem:sessions` | `{session_id}` | Session metadata, project, timestamps |-| `mem:obs:{session_id}` | `{obs_id}` | Compressed observations |-| `mem:summaries` | `{session_id}` | End-of-session summaries |-| `mem:memories` | `{memory_id}` | Long-term memories |-| `mem:config` | `{key}` | Plugin settings |+agentmemory is built on iii-engine's three primitives:-## Project Structure+| What you'd normally need | What agentmemory uses |+|---|---|+| Express.js / Fastify | iii HTTP Triggers |+| SQLite / Postgres | iii KV State |+| SSE / Socket.io | iii Streams (WebSocket) |+| pm2 / systemd | iii-engine worker management |-```-agentmemory/-├── src/-│ ├── index.ts # Worker entry: init SDK, register all-│ ├── types.ts # TypeScript interfaces-│ ├── config.ts # Env vars, provider auto-detection-│ ├── hooks/ # 5 Claude Code hook scripts-│ │ ├── session-start.ts # Start session, inject context (stdout)-│ │ ├── prompt-submit.ts # Capture user prompts-│ │ ├── post-tool-use.ts # Capture tool usage-│ │ ├── stop.ts # Trigger session summarization-│ │ └── session-end.ts # Mark session complete-│ ├── providers/ # LLM provider abstraction-│ │ ├── index.ts # Factory + auto-detection-│ │ ├── agent-sdk.ts # Claude subscription (Agent SDK)-│ │ ├── anthropic.ts # Direct Anthropic API-│ │ └── openrouter.ts # OpenRouter + Gemini-│ ├── functions/ # iii Functions (core logic)-│ │ ├── observe.ts # Capture + store + stream-│ │ ├── compress.ts # LLM compression-│ │ ├── privacy.ts # Secret/tag stripping-│ │ ├── search.ts # Keyword search-│ │ ├── context.ts # Context generation-│ │ ├── summarize.ts # Session summary-│ │ └── migrate.ts # SQLite import-│ ├── triggers/ # Trigger registrations-│ │ ├── api.ts # 11 HTTP endpoints-│ │ └── events.ts # 4 queue event handlers-│ ├── state/ # State helpers-│ │ ├── kv.ts # Typed KV wrapper-│ │ ├── schema.ts # Scope constants + ID generators-│ │ └── search-index.ts # In-memory keyword index-│ ├── prompts/ # LLM prompts-│ │ ├── compression.ts # Observation compression prompt-│ │ └── summary.ts # Session summary prompt-│ └── viewer/-│ └── index.html # Single-file dark-theme viewer-├── plugin/ # Claude Code plugin-│ ├── .claude-plugin/-│ │ └── plugin.json-│ └── hooks/-│ └── hooks.json-├── docker-compose.yml # iii-engine container-├── package.json-├── tsconfig.json-├── tsdown.config.ts-└── LICENSE # Apache-2.0-```+**~30 source files. ~1,800 LOC. 37KB bundled.**-## Prerequisites+### Data Model-- **Node.js** >= 18-- **Docker** (for iii-engine)-- **Claude Code** (for hook integration)+| Scope | Key | Stores |+|-------|-----|--------|+| `mem:sessions` | `{session_id}` | Session metadata, project, timestamps |+| `mem:obs:{session_id}` | `{obs_id}` | Compressed observations |+| `mem:summaries` | `{session_id}` | End-of-session summaries |## Development```bash-# Dev mode with hot reload-npm run dev+npm run dev # Hot reload+npm run build # Production build+npm test # Unit tests (45 tests, ~250ms)+npm run test:integration # API tests (requires running services)+```-# Build-npm run build+### Prerequisites-# Run tests-npm test-```+- Node.js >= 18+- Docker## Licensediff --git a/package.json b/package.jsonindex f61a8b47..bda8e0bc 100644--- a/package.json+++ b/package.json@@ -13,8 +13,10 @@"dev": "tsx src/index.ts","start": "node dist/index.js","migrate": "node dist/functions/migrate.js",- "test": "vitest run",- "test:watch": "vitest"+ "test": "vitest run --exclude test/integration.test.ts",+ "test:watch": "vitest --exclude test/integration.test.ts",+ "test:integration": "vitest run test/integration.test.ts",+ "test:all": "vitest run"},"keywords": ["ai",diff --git a/src/index.ts b/src/index.tsindex af645fa0..18216172 100644--- a/src/index.ts+++ b/src/index.ts@@ -65,16 +65,13 @@ async function main() {console.log(` GET /agentmemory/viewer - Web viewer`);console.log(` POST /agentmemory/migrate - Import from SQLite`);- process.on("SIGINT", async () => {+ const shutdown = async () => {console.log(`\n[agentmemory] Shutting down...`);await sdk.shutdown();process.exit(0);- });-- process.on("SIGTERM", async () => {- await sdk.shutdown();- process.exit(0);- });+ };+ process.on("SIGINT", shutdown);+ process.on("SIGTERM", shutdown);}main().catch((err) => {diff --git a/src/state/search-index.ts b/src/state/search-index.tsindex bda1e810..bc40255b 100644--- a/src/state/search-index.ts+++ b/src/state/search-index.ts@@ -3,7 +3,6 @@ import type { CompressedObservation } from "../types.js";interface IndexEntry {obsId: string;sessionId: string;- terms: Set<string>;}export class SearchIndex {@@ -12,12 +11,7 @@ export class SearchIndex {add(obs: CompressedObservation): void {const terms = this.extractTerms(obs);- const entry: IndexEntry = {- obsId: obs.id,- sessionId: obs.sessionId,- terms,- };- this.entries.set(obs.id, entry);+ this.entries.set(obs.id, { obsId: obs.id, sessionId: obs.sessionId });for (const term of terms) {if (!this.invertedIndex.has(term)) {diff --git a/src/triggers/api.ts b/src/triggers/api.tsindex db45a152..4daff670 100644--- a/src/triggers/api.ts+++ b/src/triggers/api.ts@@ -12,6 +12,9 @@ type Response = {body: unknown;};+const VIEWER_CSP =+ "default-src 'self'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; connect-src 'self' ws://localhost:* wss://localhost:*";+function checkAuth(req: ApiRequest,secret: string | undefined,@@ -217,8 +220,7 @@ export function registerApiTriggers(status_code: 200,headers: {"Content-Type": "text/html",- "Content-Security-Policy":- "default-src 'self'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; connect-src 'self' ws://localhost:* wss://localhost:*",+ "Content-Security-Policy": VIEWER_CSP,},body: html,};@@ -227,8 +229,7 @@ export function registerApiTriggers(status_code: 200,headers: {"Content-Type": "text/html",- "Content-Security-Policy":- "default-src 'self'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; connect-src 'self' ws://localhost:* wss://localhost:*",+ "Content-Security-Policy": VIEWER_CSP,},body: "<!DOCTYPE html><html><body><h1>agentmemory</h1></body></html>",};diff --git a/test/integration.test.ts b/test/integration.test.tsnew file mode 100644index 00000000..561bac87--- /dev/null+++ b/test/integration.test.ts@@ -0,0 +1,269 @@+import { describe, it, expect, beforeAll, afterAll } from "vitest";++const BASE_URL = process.env["AGENTMEMORY_URL"] || "http://localhost:3111";+const SECRET = process.env["AGENTMEMORY_SECRET"] || "";++const SESSION_ID = `test_${Date.now()}`;+const PROJECT = "/tmp/test-project";++function url(path: string): string {+ return `${BASE_URL}${path}`;+}++function authHeaders(): Record<string, string> {+ const headers: Record<string, string> = {+ "Content-Type": "application/json",+ };+ if (SECRET) {+ headers["Authorization"] = `Bearer ${SECRET}`;+ }+ return headers;+}++async function json(res: Response): Promise<unknown> {+ const text = await res.text();+ try {+ return JSON.parse(text);+ } catch {+ return text;+ }+}++describe("agentmemory integration", () => {+ beforeAll(async () => {+ const res = await fetch(url("/agentmemory/health")).catch(() => null);+ if (!res || !res.ok) {+ throw new Error(+ `agentmemory is not running at ${BASE_URL}. Start it with: docker compose up -d && npm start`,+ );+ }+ });++ describe("health", () => {+ it("returns ok", async () => {+ const res = await fetch(url("/agentmemory/health"));+ expect(res.status).toBe(200);+ const body = (await json(res)) as { status: string; service: string };+ expect(body.status).toBe("ok");+ expect(body.service).toBe("agentmemory");+ });+ });++ describe("session lifecycle", () => {+ it("starts a session", async () => {+ const res = await fetch(url("/agentmemory/session/start"), {+ method: "POST",+ headers: authHeaders(),+ body: JSON.stringify({+ sessionId: SESSION_ID,+ project: PROJECT,+ cwd: PROJECT,+ }),+ });+ expect(res.status).toBe(200);+ const body = (await json(res)) as {+ session: { id: string; status: string };+ context: string;+ };+ expect(body.session.id).toBe(SESSION_ID);+ expect(body.session.status).toBe("active");+ expect(typeof body.context).toBe("string");+ });++ it("lists sessions including the new one", async () => {+ const res = await fetch(url("/agentmemory/sessions"));+ expect(res.status).toBe(200);+ const body = (await json(res)) as {+ sessions: Array<{ id: string }>;+ };+ expect(Array.isArray(body.sessions)).toBe(true);+ const found = body.sessions.find((s) => s.id === SESSION_ID);+ expect(found).toBeDefined();+ });++ it("ends the session", async () => {+ const res = await fetch(url("/agentmemory/session/end"), {+ method: "POST",+ headers: authHeaders(),+ body: JSON.stringify({ sessionId: SESSION_ID }),+ });+ expect(res.status).toBe(200);+ const body = (await json(res)) as { success: boolean };+ expect(body.success).toBe(true);+ });++ it("session is marked completed", async () => {+ const res = await fetch(url("/agentmemory/sessions"));+ const body = (await json(res)) as {+ sessions: Array<{ id: string; status: string; endedAt?: string }>;+ };+ const session = body.sessions.find((s) => s.id === SESSION_ID);+ expect(session).toBeDefined();+ expect(session!.status).toBe("completed");+ expect(session!.endedAt).toBeDefined();+ });+ });++ describe("observations", () => {+ const OBS_SESSION = `test_obs_${Date.now()}`;++ beforeAll(async () => {+ await fetch(url("/agentmemory/session/start"), {+ method: "POST",+ headers: authHeaders(),+ body: JSON.stringify({+ sessionId: OBS_SESSION,+ project: PROJECT,+ cwd: PROJECT,+ }),+ });+ });++ afterAll(async () => {+ await fetch(url("/agentmemory/session/end"), {+ method: "POST",+ headers: authHeaders(),+ body: JSON.stringify({ sessionId: OBS_SESSION }),+ });+ });++ it("captures an observation", async () => {+ const res = await fetch(url("/agentmemory/observe"), {+ method: "POST",+ headers: authHeaders(),+ body: JSON.stringify({+ hookType: "post_tool_use",+ sessionId: OBS_SESSION,+ project: PROJECT,+ cwd: PROJECT,+ timestamp: new Date().toISOString(),+ data: {+ tool: "Edit",+ file: "src/auth.ts",+ content: "Added JWT token validation middleware",+ },+ }),+ });+ expect(res.status).toBe(201);+ });++ it("captures a second observation", async () => {+ const res = await fetch(url("/agentmemory/observe"), {+ method: "POST",+ headers: authHeaders(),+ body: JSON.stringify({+ hookType: "post_tool_use",+ sessionId: OBS_SESSION,+ project: PROJECT,+ cwd: PROJECT,+ timestamp: new Date().toISOString(),+ data: {+ tool: "Bash",+ command: "npm test",+ output: "Tests: 12 passed, 0 failed",+ },+ }),+ });+ expect(res.status).toBe(201);+ });++ it("lists observations for the session", async () => {+ const res = await fetch(+ url(`/agentmemory/observations?sessionId=${OBS_SESSION}`),+ );+ expect(res.status).toBe(200);+ const body = (await json(res)) as {+ observations: Array<{ id: string; sessionId: string }>;+ };+ expect(Array.isArray(body.observations)).toBe(true);+ });++ it("returns 400 without sessionId", async () => {+ const res = await fetch(url("/agentmemory/observations"));+ expect(res.status).toBe(400);+ const body = (await json(res)) as { error: string };+ expect(body.error).toBe("sessionId required");+ });+ });++ describe("search", () => {+ it("searches observations", async () => {+ const res = await fetch(url("/agentmemory/search"), {+ method: "POST",+ headers: authHeaders(),+ body: JSON.stringify({ query: "auth", limit: 5 }),+ });+ expect(res.status).toBe(200);+ const body = await json(res);+ expect(body).toBeDefined();+ });++ it("returns results for empty limit", async () => {+ const res = await fetch(url("/agentmemory/search"), {+ method: "POST",+ headers: authHeaders(),+ body: JSON.stringify({ query: "test" }),+ });+ expect(res.status).toBe(200);+ });+ });++ describe("context", () => {+ it("generates context for a project", async () => {+ const res = await fetch(url("/agentmemory/context"), {+ method: "POST",+ headers: authHeaders(),+ body: JSON.stringify({+ sessionId: "ctx-test",+ project: PROJECT,+ }),+ });+ expect(res.status).toBe(200);+ const body = (await json(res)) as { context: string };+ expect(typeof body.context).toBe("string");+ });+ });++ describe("viewer", () => {+ it("serves the viewer HTML", async () => {+ const res = await fetch(url("/agentmemory/viewer"));+ expect(res.status).toBe(200);+ const contentType = res.headers.get("content-type");+ expect(contentType).toContain("text/html");+ const csp = res.headers.get("content-security-policy");+ expect(csp).toContain("default-src");+ const body = await res.text();+ expect(body).toContain("<html");+ });+ });++ describe("auth", () => {+ it("health endpoint is always public", async () => {+ const res = await fetch(url("/agentmemory/health"));+ expect(res.status).toBe(200);+ });++ if (SECRET) {+ it("rejects unauthenticated requests", async () => {+ const res = await fetch(url("/agentmemory/search"), {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ query: "test" }),+ });+ expect(res.status).toBe(401);+ });++ it("rejects wrong bearer token", async () => {+ const res = await fetch(url("/agentmemory/search"), {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ Authorization: "Bearer wrong-token",+ },+ body: JSON.stringify({ query: "test" }),+ });+ expect(res.status).toBe(401);+ });+ }+ });+});