Skip to main content
Glama
README.md
<p align="center">
  <picture>
    <source media="(prefers-color-scheme: dark)" srcset="docs/assets/logo-dark.svg">
    <img src="docs/assets/logo-light.svg" alt="MemoryForge" width="360">
  </picture>
</p>

<p align="center">
  <strong>Local memory for coding agents.</strong><br>
  OpenCode, Cursor, Claude Code, and any other MCP client read and write the same short facts.<br>
  One SQLite file on your machine. No account, no cloud, no model needed to search.
</p>

<p align="center">
  <a href="LICENSE"><img alt="License: MIT" src="https://img.shields.io/badge/license-MIT-ff7a1a"></a>
  <img alt="Python 3.10+" src="https://img.shields.io/badge/python-3.10%2B-3776ab">
  <img alt="MCP: stdio and HTTP" src="https://img.shields.io/badge/MCP-stdio%20%7C%20HTTP-14161b">
</p>

<p align="center"><a href="README.de.md">Deutsche Anleitung</a></p>

![Search inside one repository: two matches, the pinned global preference first](docs/screenshots/search.png)

## Why

Agents forget everything between sessions. You repeat the same preferences, the same port, the same "we use pnpm here". MemoryForge keeps those facts in one local place and hands them to every agent at session start, scoped to the repository you are in.

It stores short facts that should still be true next week: a preference, a decision, a convention, a lesson from a bug. Not chat logs, not the current task, not secrets.

## Features

- **One memory for every agent.** stdio and HTTP MCP with nine tools; the CLI and the notebook use the same database.
- **Scopes per repository.** `global` facts follow you everywhere, `project:host/owner/repo` facts stay in their repo. The scope is read from `git remote get-url origin`.
- **Local hybrid search.** Embeddings (`BAAI/bge-small-en-v1.5` via fastembed, the optional `embed` extra) plus SQLite FTS5. Weak vector-only hits are dropped, so an unrelated query returns nothing instead of everything.
- **Session card.** `memory_brief` returns persona, directives, pinned and recent facts as one block an agent reads first.
- **Readable vault.** A Markdown projection (`USER.md`, `MEMORY.md`, daily notes, `DREAMS.md`) in the layout of OpenClaw and Claude Code.
- **Secrets stay out.** Common key and token formats are redacted before anything is stored; `memoryforge scrub` cleans data written by older versions.
- **Optional model.** Off by default. When on, it condenses long notes and merges duplicates ("dreaming"). It never invents facts and never runs during search.
- **Move machines with one zip.** Backup and restore with checks against path tricks and unknown formats.
- **Notebook UI** in English or German, keyboard friendly, works on a phone.

## Quickstart

Requirements: Python 3.10+, [uv](https://docs.astral.sh/uv/), Git for project scopes.

```bash
git clone https://github.com/pierelucas/MemoryForge.git
cd MemoryForge
./install.sh                 # installs uv if missing, then memoryforge with local embeddings
memoryforge                  # starts the local service and prints the URL
```

Connect your agent. `connect` prints a ready config and the instructions to paste into your project rules. It writes no files.

```bash
memoryforge connect opencode   # or: cursor, claude, http
```

Store and find a first fact:

```bash
memoryforge add "Prefer pnpm over npm."
memoryforge search "package manager"
```

`./install.sh --minimal` skips fastembed and onnxruntime; search then runs on the hash embedder plus full text. With pip: `pip install 'memoryforge[embed]'` or plain `pip install memoryforge` for the minimal install. Adding the extra later: install it, then run `memoryforge reembed`.

The notebook runs at <http://127.0.0.1:4737/>. `./install.sh --yes --service` also installs a login service (systemd on Linux, launchd on macOS). On Windows, run `memoryforge serve` in the foreground. To keep the Linux service running without a login, run `loginctl enable-linger "$USER"` once.

## How it works

```mermaid
flowchart LR
  A[Agent via MCP<br/>stdio or HTTP] --> S
  C[CLI] --> S
  N[Notebook<br/>FastAPI + Jinja] --> S
  S[MemoryService<br/>redact · scope · rank] --> D[(SQLite<br/>FTS5 + vectors)]
  S -. optional .-> L[OpenAI-compatible model]
  D --> V[Markdown vault<br/>projection, read-only]
```

SQLite is the source of truth. The vault under the data directory is rewritten when a memory changes; editing a file does not change memory.

| Layer | File | Role |
|---|---|---|
| Identity | `IDENTITY.md` | name, vibe, mark. Evergreen. Not a fact. |
| Voice | `SOUL.md` | tone and boundaries. Project wins over global. |
| Profile | `USER.md` | evergreen preferences, written as directives |
| Durable | `MEMORY.md` | evergreen facts, decisions, conventions, lessons |
| Daily | `memory/YYYY-MM-DD.md` | working notes, 30-day half-life |
| Review | `DREAMS.md` | dream diary, not searched, not injected |

Each fact has a scope.

| Scope | Means |
|---|---|
| `global` | about you, in every repo |
| `project:host/owner/repo` | about that repository |

A project search also returns `global`. A global search does not return project facts. Writing, replacing, and dreaming stay inside one scope, so a repo fact cannot overwrite a preference.

If you omit the scope, the CLI and a stdio MCP session run `git remote get-url origin` in the working directory.

| Remote | Scope |
|---|---|
| `git@github.com:owner/repo.git` | `project:github.com/owner/repo` |
| `https://github.com/owner/repo.git` | same |
| no git, or no `origin` | `global` |

The HTTP server cannot see your repo. Pass `scope` yourself.

Search combines cosine similarity (72 %) and BM25 full text (28 %), weighted by importance and, for daily notes, by age. A keyword hit always counts; a hit that only the vector index found must clear a similarity floor and stay close to the best hit. Without `fastembed` (minimal install), a hash embedder plus full text keeps search working with weaker recall; `doctor --check` notes it.

> **To verify with real data:** the vector floor (0.6) and window (0.08) for BGE-small, and 0.35 for the hash embedder, were tuned on a small mixed English/German sample (`SIMILARITY` in `src/memoryforge/embed.py`). They are a heuristic until checked against real memories.

## Agents and MCP

stdio is the one to use: the client starts the process in the project directory, MemoryForge reads `origin`, and both sides use the same database as the notebook.

```bash
memoryforge connect opencode
```

```json
{
  "$schema": "https://opencode.ai/config.json",
  "mcp": {
    "servers": {
      "memoryforge": {
        "type": "local",
        "command": ["memoryforge", "mcp"]
      }
    }
  }
}
```

`connect` prints the command with absolute paths, so GUI apps without your shell `PATH` find it. Older OpenCode configs use `"mcp": {"memoryforge": {"type": "local", "command": [...], "enabled": true}}` without `servers`.

The tools do nothing if the agent never calls them. Put this in the project instructions (`AGENTS.md`, `CLAUDE.md`, `.cursor/rules`):

```text
At session start call memory_brief. Read card first. Pass scope project:<host/owner/repo> when you know the git remote, otherwise omit it.
Global persona applies in every repo. Project persona wins if they conflict.
Call memory_persona_set when the user states a name, vibe, or voice. slot is identity or soul.
Call memory_add for a durable preference, decision, convention, or debug lesson, one or a few sentences. Preferences land in USER.md. Other durable facts land in MEMORY.md.
Call memory_note for a working note that should stay in memory/YYYY-MM-DD.md until dreaming promotes it.
When a stored fact changed and you know its id, call memory_update instead of adding a second copy.
Do not store secrets, tokens, or ephemeral task state.
Do not edit the vault files. They are a projection. SQLite is the source of truth. DREAMS.md is review only.
```

| Tool | Use |
|---|---|
| `memory_brief` | session start: read `card` first. Persona, directives, standing facts, recent notes |
| `memory_persona_set` | set `identity` or `soul` for a scope. Empty text clears it |
| `memory_search` | meaning plus full text |
| `memory_add` | store a durable fact |
| `memory_note` | store a daily note; dreaming may promote it later |
| `memory_update` | replace the text of one row, or move it |
| `memory_list` | active rows |
| `memory_pin` | pin or unpin |
| `memory_forget` | hide a row |

A client that cannot start a process uses HTTP at `http://127.0.0.1:4737/mcp` (`memoryforge connect http`) after `memoryforge serve --detach`.

## Notebook

![The notebook for one repository: the composer, then its durable facts and daily notes](docs/screenshots/notebook.png)

| | |
|---|---|
| **Sidebar** | the scope list. **All** shows everything, **Global** only global facts. |
| **Layer tabs** | durable facts, daily notes, and the dream diary. |
| **Remember** | stores one fact in the selected scope. **Other scope** creates a new one; a git URL is normalized. |
| **Pin / Forget / Edit** | pin keeps a fact on the session card; forget hides it (the row stays); edit replaces the text and can move it to another scope. |
| **Persona** | identity and voice per scope, with a live preview of the session card. |
| **Files** | the Markdown projection. Read-only. |
| **Settings** | model, language, connection test, dreaming, backup download. |

Keys: `/` focuses search, Ctrl+Enter or Cmd+Enter submits the note you are typing.

**Delete scope** on a project page removes that scope after a confirmation page: memories (also forgotten ones), dreams, persona, and vault files, from the database and from disk. **All** is a view, **Global** a scope that stays; neither can be deleted. **Reset** on the Global page clears Global. Existing backups are not rewritten.

<p align="center"><img src="docs/screenshots/mobile.png" alt="The notebook on a phone" width="300"></p>

## CLI

```bash
memoryforge                       # start the service if it is down, print the URL
memoryforge ui                    # open the notebook
memoryforge serve [--detach]      # foreground or background
memoryforge stop
memoryforge connect opencode      # client config + agent instructions
memoryforge doctor [--check]      # paths, counts; --check exits 1 on problems

memoryforge add "Prefer pnpm over npm."
memoryforge add --scope global "Answers may be in German."
echo "a fact" | memoryforge add -
memoryforge note "Checked the port today."      # daily note, no model call
memoryforge search "package manager" [--scope global]
memoryforge list [--scope global]
memoryforge pin <id> [--off]
memoryforge forget <id>
memoryforge persona set soul "Be precise. No filler." --scope global

memoryforge dream [--scope global]    # needs the model
memoryforge vault                     # rewrite the Markdown projection
memoryforge reembed                   # after changing the embedding model
memoryforge scrub [--apply]           # find and redact stored secrets
memoryforge export -o memories.json
memoryforge import memories.json
memoryforge backup [--without-secrets] [-o file.zip]
memoryforge restore file.zip
```

The CLI and the notebook follow `ui.lang` (`en` or `de`). Missing, unknown, or unreadable: English.

## Configuration

`~/.config/memoryforge/config.toml` (mode `0600`):

```toml
[server]
autostart = false
host = "127.0.0.1"
port = 4737
open_browser = false

[llm]
enabled = false
provider = "deepseek"
base_url = "https://api.deepseek.com"
model = "deepseek-flash"
thinking = false
api_key = ""

[embed]
model = "BAAI/bge-small-en-v1.5"

[ui]
lang = "en"
```

`memoryforge config set section.field value`, `memoryforge config show` (masks the key). Booleans: `true`, `false`, `ja`, `nein`, `an`, `aus`. `ui.lang` takes `en` or `de`.

| Path | Default |
|---|---|
| Config | `~/.config/memoryforge/config.toml` |
| Database | `~/.local/share/memoryforge/memory.db` |
| Vault | `~/.local/share/memoryforge/vault/` |
| Service log | `~/.local/share/memoryforge/serve.log` |

| Variable | Effect |
|---|---|
| `XDG_CONFIG_HOME`, `XDG_DATA_HOME` | replace the roots above |
| `MEMORYFORGE_CONFIG_DIR`, `MEMORYFORGE_DATA_DIR` | replace the two directories directly |
| `MEMORYFORGE_EMBED=hash` | use the offline hash embedder |
| `MEMORYFORGE_MCP_DETECT=0` | stdio MCP: do not read the git remote |

### Model

Off is the default; `add` then stores the text as written. On: a short sentence with no close neighbor is still stored as written. Longer notes, and notes that sit next to a similar fact, go to the model. If the API fails, the original text is stored anyway. Search never calls the API.

Providers: DeepSeek, OpenCode Go, OpenAI, OpenRouter, xAI, Groq, Mistral, Gemini, Cerebras, Together, Fireworks, Moonshot, DashScope, GitHub Models, Hugging Face, NVIDIA, Ollama, LM Studio, and any other OpenAI-compatible API. Choosing a provider fills the API base; the model menu loads the provider's ids. OpenCode Go and OpenRouter publish their catalogs without a key, Ollama and LM Studio need none. A stored key is only sent to the saved API base or the provider's default. Leave `thinking` off for extraction.

```bash
memoryforge config models --live
memoryforge config set llm.enabled true
memoryforge config set llm.provider opencode-go
memoryforge config set llm.api_key sk-...
```


Dreaming, with the model on, runs three phases: light (stage near-duplicates), REM (one review sentence, marked as reflection), deep (merge duplicates, promote a qualified daily note verbatim). The diary lands in `DREAMS.md`. With the model off, dreaming changes nothing.

The embedding model is separate from the chat model. After changing `embed.model`, run `memoryforge reembed`; `doctor --check` reports vectors that do not match.

## Security and privacy

- **Local only by default.** The service binds to `127.0.0.1`. There is no authentication on that port; do not bind it to a shared network.
- **Browser guard.** On loopback the notebook rejects foreign `Host` headers (DNS rebinding) and cross-site form posts. Pages send a strict Content-Security-Policy, `frame-ancestors 'none'`, `X-Frame-Options: DENY`, `nosniff`, and a `same-origin` referrer policy (nothing is sent to other sites; `no-referrer` would make browsers send `Origin: null` on form posts).
- **Redaction before storage.** `api_key=…` and `*_TOKEN=…` style assignments, bearer headers, passwords in URLs, private keys, and token shapes of OpenAI, Anthropic, GitHub, GitLab, Slack, AWS, Google, Stripe, Hugging Face, npm, xAI, and JWTs. False positives are accepted on purpose. Do not put secrets in memory anyway.
- **Clean up old data.** `memoryforge scrub` lists stored texts that the current rules would redact (ids only, never the text); `--apply` redacts them in place, including forgotten rows, dreams, and personas, and rewrites the database file so no old copy stays in free pages, the WAL, or the full-text index. Backups and exports made earlier still contain the values: rotate affected keys.
- **Private files.** Config and backups are `0600`, new data directories `0700`. `doctor --check` reports loose permissions.

## Move to another machine

```bash
memoryforge backup                                # includes the API key
memoryforge backup --without-secrets -o ~/merk.zip
```

The zip holds `manifest.json`, `config.toml`, and `memory.db` (an SQLite backup, not a live WAL). Program, model cache, and logs are not included. With the key, the archive holds it in plain text: do not send that file around.

On the new machine:

```bash
./install.sh --restore memoryforge-backup-20261019-1504.zip
# or, with the command already installed:
memoryforge restore memoryforge-backup-20261019-1504.zip
```

Restore stops a running server first and writes to the usual directories on this machine. Archives with extra paths, `..`, or an unknown format version are rejected before anything is overwritten. Restore also rewrites the vault. If the embedding model differs, run `memoryforge reembed`. The notebook offers the same zip under **Settings → Move**.

## Uninstall

```bash
./uninstall.sh            # remove the service and the command, keep the data
./uninstall.sh --purge    # also remove config and database
```

The script leaves `uv` and your agent configs untouched; remove the `memoryforge` entry there yourself. By hand: `memoryforge stop`, `uv tool uninstall memoryforge`, `rm -rf ~/.config/memoryforge ~/.local/share/memoryforge`, and on Linux `systemctl --user disable --now memoryforge`.

## Development

```bash
uv venv
uv pip install -e ".[dev]"    # add ,embed for local semantic search
pytest                       # forces the hash embedder, never touches your real data
ruff check src tests scripts
uv build
memoryforge serve
```

| Path | Contents |
|---|---|
| `src/memoryforge/` | package: `cli.py`, `service.py`, `db.py`, `server.py`, `mcp_server.py`, `vault.py`, `safety.py`, `health.py`, `connect.py` |
| `src/memoryforge/templates/`, `static/` | notebook (Jinja, plain CSS and JS, no build step) |
| `tests/` | pytest suite |
| `docs/assets/` | logo (SVG, PNG); rebuild the SVGs with `scripts/build_logo.py` |

## Roadmap

Ideas, not promises:

- Continuous integration: a workflow (ruff, shellcheck, pytest on Python 3.10–3.13, build) is ready but not in the repository yet; pushing it needs a token with the `workflow` scope.
- Check the search thresholds against real data (see *How it works*).
- Normalize old scope names in dreams and personas, not only in memories.
- Optional token for the HTTP port, for setups that cannot stay on loopback.

## Changelog

See [CHANGELOG.md](CHANGELOG.md).

## License

MIT. See [LICENSE](LICENSE). The bundled fonts Fraunces and Source Sans 3 are under the SIL Open Font License 1.1; see [`src/memoryforge/static/fonts/`](src/memoryforge/static/fonts/README.md).

TDQS

B3.2/5.0

Scored across 9 tools

Disambiguation4/5

The tools mostly target clearly distinct memory operations: search/list/brief for retrieval, add/note/update for storage, and forget/pin/persona_set for specific lifecycle actions. The boundary between memory_add and memory_note is subtle, but the descriptions clarify durable fact vs. working note; search/list/brief also overlap slightly as retrieval surfaces but remain distinguishable.

Naming Consistency4/5

All tools use a consistent memory_ prefix with snake_case, making the set predictable. Minor deviations exist because memory_brief is noun-like rather than verb_noun, and memory_persona_set uses a three-part compound unlike the other two-part names.

Tool Count5/5

Nine tools is a well-scoped size for a memory/persona management server. Each tool maps to a distinct lifecycle action without obvious bloat or redundancy.

Completeness4/5

The surface covers the core memory lifecycle: add/note, search/list/brief, update, forget, pin, and persona configuration. A minor gap is that memory_brief mentions directives, but there is no dedicated tool to set or manage directives, and there is no direct get-by-id operation.