{
  "markdown": "# NaN Forget\n\n**Long-term memory for AI coding tools.**\n\nYour AI forgets everything when the session ends. NaN Forget fixes that.\n\n---\n\n## Install (3 steps)\n\n```bash\nnpx nan-forget setup\n```\n\nThat's it. The wizard installs Ollama, embeddings, Claude hooks, MCP config, and a project `AGENTS.md` for Codex-style agents. Restart Claude Code or reopen Codex. Your AI now remembers.\n\nNo API keys needed. No Docker needed. Runs locally. Free forever.\n\n---\n\n## How It Works\n\n```mermaid\nflowchart LR\n    A[\"You talk to your AI tool\"] --> B[\"It learns things\"]\n    B --> C[\"nan-forget saves to SQLite\"]\n    C --> D[\"Session ends\"]\n    D --> E[\"New session starts\"]\n    E --> F[\"nan-forget loads context\"]\n    F --> G[\"Your AI remembers\"]\n```\n\n1. **You work normally.** Your agent saves decisions, preferences, and facts to a local SQLite memory database as you go.\n2. **Session ends.** Memories persist in `~/.nan-forget/memories.db`. Aging memories get automatically compacted into long-term entries.\n3. **New session starts.** nan-forget loads context from past sessions. Auth decisions from 3 months ago on Project A surface when you work on Project B today.\n\n---\n\n## Automatic Memory Handling\n\nYou never call save or search manually. Here's what happens behind the scenes:\n\n### Claude Code (fully automatic)\n\n| Event | What fires | What happens |\n|-------|-----------|--------------|\n| Session starts | `memory_sync` | Lightweight handshake — checks health, loads stats, lists projects. No heavy search. |\n| You send a message | UserPromptSubmit hook | `nan-forget recall` auto-searches memory for relevant context and injects it into the conversation. |\n| You discuss a topic | `memory_search` | Claude searches the DB dynamically whenever relevant context might exist — like how you recall things on-demand. |\n| Claude learns something | `memory_save` | Claude saves decisions, preferences, and facts immediately. Tool descriptions tell Claude \"you MUST call this.\" |\n| Claude writes a `.md` file | PostToolUse hook | `memory-sync.js` intercepts the write, parses frontmatter, and auto-saves it to SQLite via `nan-forget add`. |\n| Session ends | SessionEnd hook | `session-end.js` scans the conversation transcript for unsaved decisions/facts and saves the top 5 to the DB. |\n| Every 10 saves or 24h | Auto-consolidate | Aging memories get clustered and compacted into long-term entries. Originals are archived. |\n\nFour layers of protection ensure nothing is lost:\n1. **Auto-recall on every message** (UserPromptSubmit hook)\n2. **Claude saves proactively** (directive tool descriptions)\n3. **Hook catches .md writes** (PostToolUse intercept)\n4. **End-of-session sweep** (SessionEnd transcript scan)\n\n### Codex, Cursor, and other tools\n\nCodex and similar agents work well with nan-forget, but they usually need instruction files or shell/API fallbacks instead of Claude's hook model:\n\n1. **Run setup**: `npx nan-forget setup`\n2. **Use the generated `AGENTS.md`** in your repo. It tells Codex-style agents to `sync`, `search`, `save`, and `checkpoint` automatically.\n3. **Use REST or CLI fallback** during conversation. Agents can call the REST API on `localhost:3456` or local commands like `nan-forget sync`, `nan-forget search`, `nan-forget add`, and `nan-forget checkpoint`.\n\nThe REST API and CLI now mirror the important memory workflows closely enough that memories saved by Claude are searchable from Codex and vice versa.\n\n```bash\n# Start the REST API\nnan-forget api\n\n# The system prompt tells your agent exactly what endpoints to call\nnan-forget prompt\n```\n\n---\n\n## Slash Commands\n\nType these in Claude Code:\n\n| Command | What it does |\n|---------|-------------|\n| `/nan-forget` | Load context from past sessions |\n| `/nan-forget stats` | Show memory health |\n| `/nan-forget clean` | Run garbage collection |\n| `/nan-forget compact` | Force memory consolidation |\n| `/nan-forget health` | Check if services are running |\n| `/nan-forget start` | Start all services |\n\n---\n\n## Works with Any LLM\n\nClaude uses MCP. Codex can use `AGENTS.md` plus CLI/REST fallback:\n\n```bash\n# Start the API\nnan-forget api\n\n# Get the system prompt for your agent\nnan-forget prompt\n```\n\nCodex, Cursor, and Claude all share the same memory database.\n\n```bash\ncurl http://localhost:3456/memories/search?q=auth\ncurl -X POST http://localhost:3456/memories/sync -d '{\"project\":\"my-app\"}'\ncurl -X POST http://localhost:3456/memories/checkpoint \\\n  -H 'content-type: application/json' \\\n  -d '{\"task_summary\":\"Fixed auth regression\",\"problem\":\"Expired tokens were not refreshed\",\"solution\":\"Added refresh handling in middleware\",\"files\":[\"src/auth.ts\"],\"concepts\":[\"auth\",\"jwt\"],\"project\":\"my-app\"}'\n```\n\n---\n\n## Quick Start (CLI)\n\n```bash\nnan-forget add \"We use FastAPI, not Django. Railway deploys faster.\"\nnan-forget add --type decision \"Auth is Clerk, not custom JWT\"\nnan-forget search \"what auth system\"\nnan-forget stats\n```\n\n---\n\n# Architecture (Expert Section)\n\nEverything below is for developers who want to understand how nan-forget works under the hood.\n\n---\n\n## The Problem\n\nLLMs have no memory between sessions. Every conversation starts from zero. You re-explain your stack, Claude contradicts decisions from last month, and context disappears when the session ends.\n\nExisting solutions (Mem0) target app developers embedding memory into products. We target you — the developer using AI tools daily who wants AI that just remembers.\n\n## Design: Brain-Inspired Two-Layer Memory\n\n```mermaid\nflowchart TB\n    subgraph Short[\"Short-Term Memory\"]\n        MD[\".md files<br/>Current session context<br/>Disposable scratch paper\"]\n    end\n    subgraph Long[\"Long-Term Memory\"]\n        DB[\"SQLite + sqlite-vec<br/>~/.nan-forget/memories.db<br/>Semantic search + decay\"]\n    end\n    subgraph Auto[\"Automatic Processes\"]\n        Hook[\"Hooks (3)<br/>PostToolUse: .md → DB<br/>UserPromptSubmit: auto-recall<br/>SessionEnd: transcript sweep\"]\n        Consolidate[\"Consolidation Engine<br/>Clusters + summarizes aging memories\"]\n        GC[\"Garbage Collection<br/>Decay, dedup, expiry\"]\n    end\n    MD -->|\"hook intercepts\"| Hook\n    Hook -->|\"nan-forget add\"| DB\n    DB --> Consolidate\n    Consolidate --> DB\n    DB --> GC\n```\n\n**Short-term memory** = Claude's built-in `.md` files. Disposable. Current session only.\n\n**Long-term memory** = SQLite database with sqlite-vec vector search. Single file. Permanent. Searchable across all sessions, all projects, all LLM tools.\n\nThree hooks handle memory automatically:\n- **PostToolUse** intercepts `.md` file writes and saves them to the DB.\n- **UserPromptSubmit** runs `nan-forget recall` on every user message, auto-searching memory for relevant context.\n- **SessionEnd** scans the conversation transcript for unsaved decisions and saves the top 5.\n\n## Three-Stage Retrieval Pipeline\n\nMemory search follows the same path as human recall:\n\n```mermaid\nflowchart LR\n    Q[\"Query\"] --> S1[\"Stage 1: Recognition<br/>Fast vector match<br/>Returns summaries only\"]\n    S1 --> S2[\"Stage 2: Recall<br/>Full content fetch<br/>Cross-project expansion\"]\n    S2 --> S3[\"Stage 3: Association<br/>Spreading activation<br/>Related memories surface\"]\n    S3 --> R[\"Results ranked by<br/>similarity x decay x frequency x confidence\"]\n```\n\n| Stage | What happens | Cost |\n|-------|-------------|------|\n| **Recognition** (blur) | Prefetch 50 candidates, return top 5 summaries. Cheap. | 1 vector search |\n| **Recall** (clarity) | Fetch full content. Expand search cross-project (no project filter). | N point lookups |\n| **Association** | Centroid-based related-memory search over `sqlite-vec`. Spreading activation from positive IDs. | 1 vector search |\n\n**Scoring formula:**\n\n```\nfinal_score = vector_similarity * decay_weight * frequency_boost * confidence_boost\ndecay_weight = (0.5 ^ (days / 30)) ^ (1 - confidence)\nfrequency_boost = log2(access_count + 1) / 10 + 1\nconfidence_boost = 0.5 + 0.5 * confidence\n```\n\nHigh-confidence memories (debate-validated, human-approved) decay much slower and rank higher. A core memory at 0.85 confidence decays at ~15% of normal rate — effectively permanent unless superseded. Cross-project search means auth decisions from Project A surface when you work on Project B.\n\n## Consolidation Engine\n\nAging memories don't just get deleted — they get compacted into long-term entries:\n\n```mermaid\nflowchart TB\n    A[\"10+ aging memories<br/>about the same topic\"] --> B[\"Cluster by project + type<br/>+ vector similarity > 0.8\"]\n    B --> C{\"OpenAI key<br/>available?\"}\n    C -->|\"Yes\"| D[\"LLM summarizes cluster<br/>into 1-2 sentences\"]\n    C -->|\"No\"| E[\"Deterministic merge<br/>concatenate + deduplicate\"]\n    D --> F[\"Save consolidated entry<br/>with fresh vector embedding\"]\n    E --> F\n    F --> G[\"Archive originals<br/>with backlink\"]\n```\n\n**Triggers automatically** after every 10 saves or 24 hours. No user action needed.\n\n## 13 MCP Tools\n\n| Tool | Purpose |\n|------|---------|\n| `memory_sync` | Lightweight session handshake: health check + stats + project list |\n| `memory_save` | Save a memory (auto-called by Claude, proactively) |\n| `memory_search` | Semantic search with 3-stage retrieval (depth 1-3) |\n| `memory_get` | Fetch a specific memory by ID |\n| `memory_update` | Change content, type, or tags |\n| `memory_archive` | Soft-delete (hidden from search, never truly deleted) |\n| `memory_consolidate` | Force consolidation of aging memories |\n| `memory_clean` | Garbage collection (decay, dedup, expiry, MEMORY.md sync) |\n| `memory_stats` | Memory health dashboard |\n| `memory_health` | Check if Ollama, REST API are running |\n| `memory_start` | Boot Ollama + REST API |\n| `memory_checkpoint` | Save full problem→solution context after completing a task |\n| `memory_compress` | Compress persisted `.md` memory files to minimal stubs |\n\n## Structured Memories\n\n`memory_save` accepts structured fields for richer vector representation:\n\n| Field | Type | Purpose |\n|-------|------|---------|\n| `content` | string | Full description (required) |\n| `type` | string | `fact`, `decision`, `preference`, `task`, `context` |\n| `project` | string | Project name |\n| `problem` | string | What was the challenge |\n| `solution` | string | How it was solved |\n| `concepts` | string[] | Searchable tags (`[\"auth\", \"jwt\", \"middleware\"]`) |\n| `files` | string[] | Files involved (`[\"src/auth.ts\"]`) |\n| `confidence` | number | Trust level 0.0–1.0 (default based on provenance) |\n| `provenance` | string | `save`, `checkpoint`, `debate`, `human` |\n| `tier` | string | `regular` or `core` (auto-derived from provenance) |\n\nAll fields are embedded together into a single vector. Searches for \"JWT auth bug\" find memories tagged with those concepts even if the content text doesn't match literally.\n\n### Memory Tiers\n\nNot all memories are equal. Debate-validated and human-approved memories are **core** — they decay slower, rank higher in search, and survive garbage collection longer.\n\n| Provenance | Default Confidence | Auto Tier | Decay Rate |\n|-----------|-------------------|-----------|------------|\n| `save` | 0.5 | regular | Normal (30-day half-life) |\n| `checkpoint` | 0.65 | regular | ~35% slower |\n| `debate` | 0.85 | **core** | ~85% slower |\n| `human` | 0.95 | **core** | ~95% slower |\n\nCore memories are designed for the upcoming **nan-debate** system — multi-AI debate results validated by human approval get persisted as high-trust knowledge that almost never fades.\n\n### Checkpoint Workflow\n\nAfter completing a task, call `memory_checkpoint` with `task_summary`, `problem`, `solution`, `files`, `concepts`, and `project`. Saves the full problem→solution context to long-term memory. Every completed task = one checkpoint.\n\n### Memory Compression\n\n`memory_compress` scans `.claude/projects/*/memory/` for `.md` files already persisted to the DB. Persisted files are replaced with minimal stubs. Reduces context window bloat.\n\n## REST API (for non-MCP LLMs)\n\nShares the same SQLite database as the MCP server — memories saved by Claude are searchable from Codex and vice versa.\n\n```\nPOST   /memories              — Save a memory (supports problem/solution/files/concepts)\nPOST   /memories/checkpoint   — Save completed-task context\nPOST   /memories/sync         — Lightweight session handshake\nGET    /memories/search?q=... — Semantic search\nGET    /memories/:id          — Get by ID\nPATCH  /memories/:id          — Update\nDELETE /memories/:id          — Archive\nPOST   /memories/consolidate  — Compact aging memories\nPOST   /memories/clean        — Garbage collection\nGET    /memories/stats        — Memory health\nGET    /memories/instructions — System prompt for LLMs\n```\n\nGet the system prompt for any LLM:\n\n```bash\nnan-forget prompt\n# or\ncurl http://localhost:3456/memories/instructions\n```\n\n## Embeddings\n\n| Provider | Model | Dimensions | Cost |\n|----------|-------|-----------|------|\n| Ollama (default) | nomic-embed-text | 768 | Free, local |\n| OpenAI | text-embedding-3-small | 1536 | Your API key |\n\nAuto-detection: Ollama running? Use it. Not running? Check for `OPENAI_API_KEY`. No config needed.\n\n## Data Storage\n\nAll data lives in a single SQLite file at `~/.nan-forget/memories.db`. No Docker, no services, no data loss on updates.\n\n- **Vector search**: [sqlite-vec](https://github.com/asg017/sqlite-vec) extension (cosine distance, embedded in process)\n- **Metadata**: Standard SQL tables with indexes on `user_id`, `status`, `project`, `type`\n- **Backup**: Copy one file. **Restore**: Put it back.\n- **Export**: `nan-forget export` dumps all memories as JSON.\n\n## Memory Lifecycle\n\n```mermaid\nflowchart TB\n    A[\"New memory saved\"] --> B[\"Active in SQLite<br/>Searchable, scored\"]\n    B --> C{\"Accessed<br/>recently?\"}\n    C -->|\"Yes\"| D[\"Score stays high<br/>frequency_boost increases\"]\n    C -->|\"No\"| E[\"Decay weight drops<br/>0.5^(days/30)\"]\n    E --> F{\"Decay < 0.3?\"}\n    F -->|\"Yes\"| G[\"Consolidation candidate<br/>Clustered + summarized\"]\n    F -->|\"No\"| B\n    G --> H[\"New consolidated entry<br/>Originals archived\"]\n    D --> B\n    E --> I{\"Decay < 0.1?\"}\n    I -->|\"Yes\"| J[\"Archived by GC\"]\n    I -->|\"No\"| F\n```\n\n## Garbage Collection (Zero LLM Cost)\n\nAll cleanup is deterministic. No API calls. No LLM inference.\n\n- **Decay GC**: Archives memories below 0.1 decay weight (~100 days for regular, ~600+ days for core)\n- **Expiration**: Archives memories past `expires_at` date\n- **Interference resolution**: Deduplicates >0.95 similarity matches, keeps higher access count\n- **MEMORY.md sync**: Refreshes working memory with top 5 scored memories per project\n\nCore memories (confidence ≥ 0.85) survive GC far longer than regular ones because their decay formula dampens the time factor: `decay^(1 - confidence)`. A 0.85-confidence memory at 200 days still has a decay weight above 0.1.\n\n## Design Philosophy\n\nNaN Forget is built around three principles: **lightweight**, **automatic**, and **local**.\n\n### Lightweight\n\nNo Docker. No cloud services. No background processes eating RAM. The entire storage layer is a single SQLite file (~3 MB). Embeddings run through Ollama, which you likely already have. Memory operations (save, search, dedup, GC) use zero LLM calls — all deterministic.\n\n### Automatic\n\nFour hooks capture context at every stage of a session — you never call save manually:\n\n1. **UserPromptSubmit** searches memory on every message you send\n2. **Tool descriptions** instruct Claude to save decisions and facts as they happen\n3. **PostToolUse** intercepts `.md` file writes and persists them\n4. **SessionEnd** sweeps the transcript for anything missed\n\nAging memories consolidate automatically. Duplicates merge. Unused memories decay on a 30-day half-life. No maintenance required.\n\n### Local\n\nYour data stays on your machine in `~/.nan-forget/memories.db`. No accounts, no API keys required (Ollama is free and local), no telemetry. Backup is copying one file. Works across Claude Code (MCP), Codex/Cursor (REST API), and the terminal (CLI) — same database, same memories.\n\n### How it differs from other memory tools\n\nMost AI memory solutions (Mem0, claude-mem) are designed for app developers embedding memory into products, or require Docker/cloud services to run. NaN Forget is designed for **you** — the developer using AI tools daily who wants context that persists across sessions without managing infrastructure.\n\nKey design differences:\n\n- **Retrieval**: Three-stage pipeline (recognition → recall → spreading activation) with decay-weighted scoring, rather than flat vector search\n- **Structure**: Memories carry `problem`, `solution`, `concepts`, and `files` fields — searches find related context even when keywords don't match\n- **Cost**: Memory operations (save, search, dedup, consolidation, GC) are all deterministic — no LLM calls, no API costs\n- **Setup**: One command (`npx nan-forget setup`), no Docker, no containers, no services to manage\n\n## Source Structure\n\n```\nsrc/\n  sqlite.ts         SQLite + sqlite-vec storage layer (schema, CRUD, vector search)\n  embeddings.ts     OpenAI / Ollama abstraction\n  writer.ts         Memory writer with dedup (>0.92 = merge)\n  retriever.ts      Three-stage retrieval pipeline\n  consolidator.ts   LLM summarization + deterministic fallback\n  cleaner.ts        GC: decay, expiry, dedup, MEMORY.md sync\n  services.ts       Service management (Ollama, REST API)\n  memory-md.ts      MEMORY.md manager\n  types.ts          Shared types (Memory, MemoryType, etc.)\n  mcp/server.ts     MCP server, 13 tools\n  api/server.ts     REST API server\n  cli/index.ts      CLI commands + hook helpers\n  setup/index.ts    Setup wizard (Ollama, hooks, MCP config)\n\n.claude/\n  commands/nan-forget.md   Slash command for manual control\n  hooks/memory-sync.js     PostToolUse hook (auto-saves .md → SQLite)\n  hooks/session-end.js     SessionEnd hook (transcript sweep for unsaved memories)\n  settings.json            Hook config (PostToolUse + SessionEnd + UserPromptSubmit)\n```\n\n---\n\n## Built by NaN Logic LLC\n\n- [NaN Mesh](https://nanmesh.ai) — trust network for AI agents\n- **NaN Forget** — long-term memory for any LLM\n\nMIT License.\n",
  "bytes": 18072,
  "sha": "12debd7b9cdbec8ffde3a60c9ef91c7059c49d02927eb9bb24ecd9169c8fd401",
  "repo_slug": "nanmesh/nan-forget",
  "fonte": "repo",
  "truncated": false,
  "api": "https://agentalog.com/api/listings/mcp_io_github_nanmesh_nan_forget_e5cd875e/readme"
}