@codrihub/memora 2.1.9 → 2.1.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- [{"file":"README.md","slug":"get-started","title":"Get started","text":"<p align=\"center\">\n <img src=\"docs/assets/memora-logo.png\" alt=\"Memora\" width=\"96\" height=\"96\">\n</p>\n\n<h1 align=\"center\">Memora</h1>\n\n<p align=\"center\"><b>Second brain for your AI.</b><br>Long-term memory for AI agents, on your own server.</p>\n\n<p align=\"center\">\n <a href=\"https://github.com/Codrihub/memora/releases/latest\"><img src=\"https://img.shields.io/github/v/release/Codrihub/memora?sort=semver\" alt=\"Latest release\"></a>\n <a href=\"https://www.npmjs.com/package/@codrihub/memora\"><img src=\"https://img.shields.io/npm/v/@codrihub/memora?logo=npm&label=npm\" alt=\"npm: @codrihub/memora\"></a>\n <a href=\"https://github.com/Codrihub/memora/actions/workflows/ci.yml\"><img src=\"https://github.com/Codrihub/memora/actions/workflows/ci.yml/badge.svg\" alt=\"CI\"></a>\n <a href=\"LICENSE\"><img src=\"https://img.shields.io/github/license/Codrihub/memora\" alt=\"License: AGPL-3.0\"></a>\n <a href=\"https://github.com/Codrihub/memora/pkgs/container/memora\"><img src=\"https://img.shields.io/badge/ghcr.io-codrihub%2Fmemora-blue?logo=docker\" alt=\"Docker image\"></a>\n</p>\n\n<p align=\"center\">\n <a href=\"https://memora.codrihub.tech\">Website</a> ·\n <a href=\"https://memora.codrihub.tech/docs\">Documentation</a> ·\n <a href=\"#quick-start\">Quick start</a> ·\n <a href=\"https://www.npmjs.com/package/@codrihub/memora\">npm</a> ·\n <a href=\"https://github.com/Codrihub/memora/releases\">Releases</a>\n</p>\n\n<p align=\"center\"><code>npm install -g @codrihub/memora</code></p>\n\nMemora is a self-hosted memory vault for AI agents. Notes are plain markdown\nfiles in a git-backed folder. Agents read and write them over the Model Context\nProtocol (MCP); you browse, edit and govern them in a web UI. One Rust binary\nserves the HTTP API, the MCP endpoint, the web UI and realtime updates on a\nsingle port, with all server state in one embedded SQLite database.\n\n## Screenshots\n\n![Overview](docs/screenshots/overview.jpg)\n\n| | |\n|---|---|\n| ![Brain](docs/screenshots/brain.jpg) **Brain**: every folder is a region, every note a node | ![Node card](docs/screenshots/brain-node.jpg) **Node card**: links, backlinks and a preview |\n| ![Graph](docs/screenshots/graph.jpg) **Graph**: force, radial or cluster layouts | ![Canvas](docs/screenshots/canvas.jpg) **Canvas**: one frame per folder |\n| ![Reader](docs/screenshots/reader.jpg) **Reader** with contents and reading settings | ![Activity](docs/screenshots/activity.jpg) **Activity**: every agent call, live |\n| ![Agents](docs/screenshots/agents.jpg) **Agents & API keys**: one key per agent, scoped | ![Mnemo](docs/screenshots/mnemo.jpg) **Mnemo**: the notes agent, with its steps and the notes it used |\n\nScreenshots use a demo vault.\n\n## Features\n\n- **Markdown you own.** Every note is a `.md` file with optional frontmatter and\n `[[wikilinks]]`. Edit it with any tool; nothing is locked in a database.\n- **Git history.** Changes are committed, so any revision can be listed, diffed\n and restored (`get_history`, `diff`, `restore_memory`).\n- **MCP for agents.** 77 tools for notes, folders, search, tags, graph traversal,\n history, locks, activity, pins and import/export, plus admin tools, over the\n streamable HTTP transport.\n- **Mnemo, a built-in notes agent.** Chat with your notes in the browser or the\n console using your own OpenAI, Anthropic or OpenAI-compatible API key. Mnemo\n finds, writes, tags, links, moves and tidies notes with Memora's own tools,\n shows every step, and has no web, shell or delete-for-good access. It can\n answer with a chart or diagram: a file card that opens a sandboxed preview\n beside the chat.\n- **Images beside notes.** Paste or drop PNG, JPEG, WebP or GIF into a note; the\n file lives in the note's folder and moves, goes to the Trash and comes back\n with it. Folder galleries show which note and section uses each image.\n- **API keys or OAuth.** Give each agent its own key, or let MCP clients such as\n Claude or ChatGPT connect with OAuth after you approve them in the browser.\n- **Per-agent control.** Scopes (`mcp`, `read`, `write`, `admin`), per-key tool\n lists, server-wide tool switches, and privacy rules that hide notes or\n folders from chosen agents.\n- **Web UI.** Brain and graph views, a canvas, the vault editor with nine reading\n colours, fonts and sizes, tags, live agent activity, keys, tools, access\n rules and settings. Installable as a PWA.\n- **Safe first run.** An unclaimed instance cannot be taken over by whoever\n finds the port: the operator console opens a short setup window and you\n finish in the browser.\n- **One port, one process.** HTTP API, MCP, UI and WebSocket share port 8400.\n The database has no network port.\n\n## Quick start\n\nThree steps, about two minutes.\n\n**1. Install** (pick one, in this order of ease)\n\n```bash\n# npm (Linux x86_64 / arm64, Windows x64; Node.js 22 or newer): install, then keep it running\nnpm install -g @codrihub/memora && memora\n\n# Docker (any OS with Docker)\ndocker run -d --name memora --restart unless-stopped -p 8400:8400 \\\n -v memora-data:/data -v memora-state:/state ghcr.io/codrihub/memora:latest\n\n# Native installer (Linux server with systemd, x86_64 or aarch64)\ncurl -fsSL https://raw.githubusercontent.com/Codrihub/memora/main/scripts/install.sh | sudo sh\n```\n\nOn Windows, install Node.js 22 or newer and use npm (see [npm](#npm-linux-x86_64--arm64-windows-x64)).\n\n**2. Get a one-time setup code**\n\n```bash\nmemora-cli setup --minutes 15 # npm, in a second terminal\ndocker exec -it memora memora-cli setup --minutes 15 # Docker\nsudo memora-cli setup --minutes 15 # native\n```\n\n**3. Open the link it prints** (`http://<your-server>:8400/login`), enter the code\nand create your account. Memora then asks which folder to use as the vault and\nshows how to connect your first agent.\n\nThat is all. The sections below cover every other option.\n\n### npm (Linux x86_64 / arm64, Windows x64)\n\n```bash\nnpm install -g @codrihub/memora\nmkdir -p ~/memora && cd ~/memora\nMEMORA_VAULT=./vault MEMORA_STATE=./state memora\n# in a second terminal, same folder:\nMEMORA_STATE=./state memora-cli setup --minutes 15\n```\n\nOn Windows (PowerShell):\n\n```powershell\nnpm install -g @codrihub/memora\nmkdir ~\\memora; cd ~\\memora\n$env:MEMORA_VAULT = '.\\vault'; $env:MEMORA_STATE = '.\\state'; memora\n# in a second terminal, same folder:\n$env:MEMORA_STATE = '.\\state'; memora-cli setup --minutes 15\n```\n\nThe package carries the prebuilt release binaries and the web UI (no install\nscript, nothing downloaded at install time) and needs Node.js 22 or newer. It is\nhandy for trying Memora or running it under your own user; for a server, the\nnative installer adds the systemd service. On macOS use Docker or build from\nsource. Update with `npm install -g @codrihub/memora@latest`.\n\n### Docker (any OS)\n\nOne container, notes and state in named volumes (no clone, no folder\npermissions):\n\n```bash\ndocker run -d --name memora --restart unless-stopped -p 8400:8400 \\\n -v memora-data:/data -v memora-state:/state ghcr.io/codrihub/memora:latest\ndocker exec -it memora memora-cli setup --minutes 15\n```\n\nWith Docker Compose from the repository instead:\n\n```bash\ngit clone https://github.com/Codrihub/memora.git && cd memora\ncp .env.example .env # optional, every value has a default\nmkdir -p data state && sudo chown -R 1000:1000 data state\ndocker compose up -d\ndocker compose exec -it gateway memora-cli setup --minutes 15\n```\n\nThe image is `ghcr.io/codrihub/memora` (linux/amd64 and linux/arm64). See\n[docker/README.md](docker/README.md) for volumes, upgrades and local builds.\n\n### Native installer (Linux x86_64 / aarch64 with systemd)\n\nOne command:\n\n```bash\ncurl -fsSL https://raw.githubusercontent.com/Codrihub/memora/main/scripts/install.sh | sudo sh\n```\n\nOr download it and read it first:\n\n```bash\ncurl -fsSL https://raw.githubusercontent.com/Codrihub/memora/main/scripts/install.sh -o install.sh\nless install.sh # read it first\nsudo sh install.sh # add --behind-proxy for a local reverse proxy\nsudo memora-cli # then type /web\n```\n\nThe installer downloads the release for your CPU, verifies it against the\nrelease `SHA256SUMS`, creates a `memora` system user, and installs a hardened\n`memora.service` unit. Data lives in `/var/lib/memora`. Run\n`sh install.sh --help` for every option, and see\n[docs/INSTALL.md](docs/INSTALL.md) for details.\n\n### From source\n\n```bash\ngit clone https://github.com/Codrihub/memora.git && cd memora\ncargo build --release\nMEMORA_VAULT=./data MEMORA_STATE=./state ./target/release/memora\n# in a second terminal:\n./target/release/memora-cli # then type /web\n```\n\nThe server binds to `127.0.0.1:8400` by default. To install your build as a\nservice: `sudo ./scripts/install.sh --from-source`. The web UI is built from\n`web/` (see [CONTRIBUTING.md](CONTRIBUTING.md)).\n\n### First run\n\n1. Run `memora-cli setup` (or type `/web` in the `memora-cli` console). It\n prints a one-time setup code and the link to open.\n2. Open `http://<host>:8400/login`, enter the code and create the owner account.\n3. Choose the vault folder (`/var/lib/memora/vault` natively, `/data` in Docker).\n4. Add an agent: Agents, then New agent. Pick the app and paste the config it\n shows. One agent per app or device.\n\nIf a setup code expires unused, nothing breaks: run `memora-cli setup` again\nfor a new code.\n\n## Configuration\n\nSettings come from the environment (systemd unit, `.env` for Docker) and can be\noverridden in the state database with `memora-cli` -> `/config`; a stored value\nwins until you clear it. The most common ones:\n\n| Name | Default | Meaning |\n|---|---|---|\n| `MEMORA_PORT` | `8400` | HTTP port for API, MCP, UI and WebSocket |\n| `MEMORA_BIND` | `127.0.0.1` | Bind address (`0.0.0.0` in the container) |\n| `MEMORA_STATE` | `state` | Directory holding `memora.db` |\n| `MEMORA_VAULT` | empty | Suggested vault folder; the vault is confirmed in the browser |\n| `MEMORA_BASE_URL` | empty | Public URL behind a reverse proxy |\n| `MEMORA_DOMAIN` | empty (any) | Allowed hostnames; other hosts get 404 |\n| `MEMORA_TRUSTED_PROXIES` | empty | Remote proxies whose forwarding headers are trusted |\n| `MEMORA_ADMIN_PASSWORD[_FILE]`, `MEMORA_API_KEY[_FILE]` | unset | Provision an owner or an agent key at startup; only hashes are stored |\n| `RUST_LOG` | `info` | Log filter |\n\nThe full list, precedence rules and the Docker Compose variables are in\n[docs/CONFIGURATION.md](docs/CONFIGURATION.md). For TLS, reverse proxies and\nhardening, see [docs/DEPLOYMENT.md](docs/DEPLOYMENT.md).\n\n## Connecting agents over MCP\n\nThe MCP endpoint is `/mcp` on the same port. Authenticate with an API key in\n`Authorization: Bearer <key>` (or `X-API-Key`), or let the client use OAuth.\n\nClaude Code:\n\n```bash\nclaude mcp add --transport http memora https://memory.example.com/mcp \\\n --header \"Authorization: Bearer memora_live_REPLACE_WITH_YOUR_KEY\"\n```\n\nClients with an `mcpServers` JSON config:\n\n```json\n{\n \"mcpServers\": {\n \"memora\": {\n \"type\": \"http\",\n \"url\": \"http://localhost:8400/mcp\",\n \"headers\": {\n \"Authorization\": \"Bearer memora_live_REPLACE_WITH_YOUR_KEY\"\n }\n }\n }\n}\n```\n\nClients that support MCP authorization can connect with only the URL; you\napprove them in the browser and they appear as keys you can restrict or revoke.\nThe discovery card is at `/.well-known/mcp.json` and a readable tool catalog at\n`/tools`. [docs/MCP.md](docs/MCP.md) covers OAuth, other clients, every tool and\nthe error codes; [docs/API.md](docs/API.md) lists the HTTP API.\n\n## Operating\n\n```bash\nsudo systemctl status memora # native service\nsudo journalctl -u memora -f # logs\nsudo memora-cli # console: /status, /keys, /tools, /config, /backup ...\nsudo memora-cli db backup # consistent copy of memora.db, safe while running\nsudo /usr/local/share/memora/install.sh --upgrade\ndocker compose pull && docker compose up -d # Docker upgrade\n```\n\nBack up the vault folder and `memora.db` (with `memora-cli db backup`, never a\nplain `cp` of the live file). See [docs/INSTALL.md](docs/INSTALL.md#backups).\n\n### Start, stop and restart\n\n```bash\nmemora-cli start # or /start in the console\nmemora-cli stop # or /shutdown\nmemora-cli restart # or /restart\nmemora-cli uninstall # or /uninstall\n```\n\nThey work out how this install runs: a systemd service is driven with\n`systemctl`, an npm or source install runs in the background (pid and\nlog in the state folder), and inside Docker the console prints the host\ncommands (`docker start / stop / restart memora`). Uninstall asks, with a\nchecklist, whether to also delete your settings and your vault; both are kept\nunless you tick them. Details: [docs/INSTALL.md](docs/INSTALL.md#uninstall-with-memora-cli).\n\n### Update, uninstall, troubleshooting\n\n`memora-cli update` prints the right steps for your install (npm:\n`npm install -g @codrihub/memora@latest`, then `memora-cli restart`). Check\nyour version with `memora --version`. Per install method, and for older\nversions without `memora-cli uninstall` (before 1.3.2), see\n[Update](docs/INSTALL.md#update),\n[Uninstall by hand](docs/INSTALL.md#uninstall-by-hand-versions-before-132) and\n[Troubleshooting](docs/INSTALL.md#troubleshooting).\n\nThe owner can also **shut the server down from the browser**: Settings, Server,\nShut down. Every browser and agent is disconnected until it is started again on\nthe server. When a supervisor restarts it on its own (systemd `Restart=always`,\nDocker `--restart unless-stopped`), the confirmation says so and shows the stop\ncommand to use instead.\n\n## Security notes\n\n- The owner password is hashed with argon2id. API keys (`memora_live_...`) and\n session ids are stored only as SHA-256 hashes; a key is shown once.\n- Session cookies are `HttpOnly` and `SameSite=Lax`, cookie writes are checked\n against the request origin, and pages use a nonce-based Content-Security-Policy.\n- Login and setup are rate limited with per-IP cooldowns; many failures from\n many IPs only slow sign-ins down and never lock the owner out.\n- Forwarding headers are trusted only from loopback and `MEMORA_TRUSTED_PROXIES`.\n- Access rules can allow or block by IP, range, CIDR and domain; loopback always\n stays allowed so you cannot lock yourself out.\n- Terminate TLS at a reverse proxy before exposing Memora to the internet.\n\nReport vulnerabilities privately as described in [SECURITY.md](SECURITY.md).\n\n## Documentation\n\n| Document | Contents |\n|---|---|\n| [docs/INSTALL.md](docs/INSTALL.md) | Native installer, Docker, npm, updates, uninstall, troubleshooting, reverse proxy, backups |\n| [docs/CONFIGURATION.md](docs/CONFIGURATION.md) | Every setting and where it lives |\n| [docs/DEPLOYMENT.md](docs/DEPLOYMENT.md) | Production deployment and hardening |\n| [docs/MCP.md](docs/MCP.md) | Connecting agents, OAuth, tool reference |\n| [docs/API.md](docs/API.md) | HTTP API |\n| [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) | Crates, request flow, vault files |\n| [docs/DATABASE.md](docs/DATABASE.md) | State database schema |\n\n## Project layout\n\n```\ncrates/core vault: markdown, wikilinks, search, graph, git history\ncrates/state SQLite state database (memora.db)\ncrates/gateway password and key hashing, access checks, environment provisioning\ncrates/mcp MCP server: tool catalog, permissions, privacy\ncrates/http axum server: middleware, API, OAuth, UI assets (binary: memora)\ncrates/cli operator console (binary: memora-cli)\nweb/ web UI (TypeScript), built into crates/http/assets\ndocker/ container entrypoint and release Dockerfile\ndocs/ user and operator documentation\nscripts/ installer and maintenance scripts\n```\n\n## Versioning\n\nMemora follows [Semantic Versioning](https://semver.org/). Each release is a\n`vX.Y.Z` tag with a [GitHub Release](https://github.com/Codrihub/memora/releases)\n(static Linux binaries for x86_64 and aarch64 plus `SHA256SUMS`), npm\npackages for Linux and Windows, and a\nmulti-arch image `ghcr.io/codrihub/memora:X.Y.Z`. Changes are listed in\n[CHANGELOG.md](CHANGELOG.md).\n\n## Contributing\n\nContributions are welcome. Read [CONTRIBUTING.md](CONTRIBUTING.md) and the\n[Code of Conduct](CODE_OF_CONDUCT.md) before opening a pull request.\n\n## License\n\nMemora is free software under the [GNU Affero General Public License v3.0 or\nlater](LICENSE). You may use, modify and share it, including commercially. If\nyou distribute a modified version, or run one as a service for others, you must\npublish its source under the same license and keep the attribution in\n[NOTICE](NOTICE): \"Based on Memora by Codrihub Tech\". The name and logo are\ncovered by [TRADEMARK.md](TRADEMARK.md).\n\nVersions 1.3.8 and earlier were released under the MIT License.\n"},{"file":"docs/INSTALL.md","slug":"install","title":"Install","text":"# Installing Memora\n\nMemora ships as two binaries plus a folder of web UI assets:\n\n| Piece | Role |\n|---|---|\n| `memora` | The server: HTTP API, MCP, web UI, and WebSocket on **one TCP port** (default `8400`) |\n| `memora-cli` | The operator console. Run it with no arguments for slash commands (`/guide`, `/web`, `/config`, ...) |\n| `assets/` | Web UI files, found through `MEMORA_ASSETS` |\n\nIt runs on Linux (x86_64, aarch64) and Windows 10/11 (x64). Install it with\n**npm** (Linux and Windows, runs as you), **Docker**, the **native** installer\n(a systemd service on Linux) or from source. On Windows, use npm. All end the\nsame way: run `memora-cli setup`, open the link it prints and enter the code.\n\n**Fastest path** (pick one, in this order of ease), then open the link the\nsetup command prints and enter the code:\n\n```bash\n# npm (Linux x86_64 / arm64, Windows x64; Node.js 22 or newer)\nnpm install -g @codrihub/memora && memora\nmemora-cli setup --minutes 15 # in a second terminal\n\n# Docker: no clone or folder permissions needed (named volumes)\ndocker run -d --name memora --restart unless-stopped -p 8400:8400 \\\n -v memora-data:/data -v memora-state:/state ghcr.io/codrihub/memora:latest\ndocker exec -it memora memora-cli setup --minutes 15\n\n# Native installer (Linux server with systemd)\ncurl -fsSL https://raw.githubusercontent.com/Codrihub/memora/main/scripts/install.sh | sudo sh\nsudo memora-cli setup --minutes 15\n```\n\n- [Network exposure](#network-exposure)\n- [Native install](#native-install)\n- [Docker](#docker)\n- [npm](#npm)\n- [Start, stop and restart](#start-stop-and-restart)\n- [Update](#update)\n- [Uninstall with memora-cli](#uninstall-with-memora-cli)\n- [Uninstall by hand (versions before 1.3.2)](#uninstall-by-hand-versions-before-132)\n- [Troubleshooting](#troubleshooting)\n- [Reverse proxy](#reverse-proxy)\n- [Backups](#backups)\n- [Automation: `--check` and `--upgrade`](#automation---check-and---upgrade)\n\n## Network exposure\n\nMemora opens exactly **one TCP port**. The HTTP API, MCP (`/mcp`), the web UI,\nand the realtime WebSocket (`/ws`) all share it. The local event intake\n`/_bus` answers on the same port but only to loopback clients.\n\nThe state database is embedded SQLite (`<state>/memora.db`). The server creates\nand migrates it on first start; it opens no port and needs no separate\ndatabase server or install.\n\nNothing else listens. Allow only that one port through the firewall, or none at\nall when a reverse proxy on the same host is the entry point\n(`--behind-proxy`).\n\n## Native install\n\nRequirements: Linux on x86_64 or aarch64 with systemd, `curl` (or `wget`),\n`tar`, `sha256sum`, and `git` (vault history uses it).\n\n```sh\n# Inspect first: https://github.com/Codrihub/memora/blob/main/scripts/install.sh\ncurl -fsSL https://raw.githubusercontent.com/Codrihub/memora/main/scripts/install.sh | sudo sh\n```\n\nPass flags after `sh -s --`, for example:\n\n```sh\ncurl -fsSL https://raw.githubusercontent.com/Codrihub/memora/main/scripts/install.sh \\\n | sudo sh -s -- --version 1.0.0 --behind-proxy\n```\n\nor download the script and run it: `sudo sh install.sh --help`.\n\nThe script is idempotent: running it again reinstalls the same files and keeps\nthe port and bind address of the existing unit unless you pass new ones.\n\n### What it does\n\n1. Downloads `memora-<version>-<arch>-linux.tar.gz` for this CPU from GitHub\n Releases (the latest, or `--version`), downloads `SHA256SUMS` from the same\n release, and refuses to continue if the checksum does not match.\n2. Installs the binaries atomically (copy to a temp file, then `mv`).\n3. Creates the system user and group `memora` (no login shell, home\n `/var/lib/memora`).\n4. Creates `/var/lib/memora/state` (`0700`) and `/var/lib/memora/vault`\n (`0750`), owned by `memora`.\n5. Writes `/etc/systemd/system/memora.service`, enables and starts it, waits\n for `/healthz`, then verifies the state database with `memora-cli db check`.\n6. Prints the next step and, when listening on every interface, a firewall\n hint.\n\n### Paths\n\n| Path | Content |\n|---|---|\n| `/usr/local/bin/memora`, `/usr/local/bin/memora-cli` | Binaries |\n| `/usr/local/share/memora/assets/` | Web UI |\n| `/usr/local/share/memora/VERSION` | Installed version (read by `--check`) |\n| `/usr/local/share/memora/install.sh` | Copy of the installer, used for `--upgrade`, `--check`, `--uninstall`, and `memora-cli update` |\n| `/var/lib/memora/state/` | `memora.db` (owner, API key hashes, sessions, settings, activity log), `backups/` |\n| `/var/lib/memora/vault/` | Suggested vault folder (chosen in the browser after the first sign-in) |\n| `/etc/systemd/system/memora.service` | The unit |\n\n`--prefix` moves the first four (default `/usr/local`), `--data-dir` moves the\nlast two (default `/var/lib/memora`).\n\n### Flags\n\n| Flag | Meaning |\n|---|---|\n| *(none)* | Install or reinstall the latest release |\n| `--version X.Y.Z` | Install that release |\n| `--from-source` | Build with `cargo build --release --locked` in the checkout the script lives in (`sudo ./scripts/install.sh --from-source`); built as `$SUDO_USER` |\n| `--from-dir PATH` | Install `PATH/memora`, `PATH/memora-cli`, `PATH/assets/` (an unpacked release, or your own build). Version from `--version`, else `PATH/VERSION` |\n| `--port N` | Port (default `8400`) |\n| `--bind ADDR` | Bind address (default `0.0.0.0`) |\n| `--behind-proxy` | Bind `127.0.0.1`; a reverse proxy on this host is the only entry |\n| `--prefix DIR` | Install prefix (default `/usr/local`) |\n| `--data-dir DIR` | Data root (default `/var/lib/memora`) |\n| `--no-start` | Install and enable, but do not start |\n| `--no-systemd` | Skip the unit and the system user (containers, tests); prints the command to start the server by hand |\n| `--upgrade` | Replace binaries and assets, keep state, restart the service if it was running |\n| `--force` | With `--upgrade`: reinstall even when already up to date |\n| `--uninstall` | Stop and remove the unit, binaries, and assets; keep data |\n| `--purge` | With `--uninstall`: also delete the data dir and the `memora` user (asks first) |\n| `--check` | Print `MEMORA_LATEST=` and `MEMORA_INSTALLED=`; change nothing |\n| `--yes`, `-y` | Never ask (needed for `--purge` without a terminal) |\n| `--dry-run` | Print every action, change nothing |\n| `--repo OWNER/NAME` | Download from another GitHub repository (forks); also settable as `MEMORA_REPO` |\n\n`MEMORA_RELEASES_URL` points the installer at a mirror that serves the same\nlayout as GitHub (`<url>/latest`, `<url>/download/vX.Y.Z/<file>`).\n\nRoot is required except for `--check`, `--dry-run`, and `--no-systemd` into a\nprefix you can write to.\n\n### Exit codes\n\n| Code | Meaning |\n|---|---|\n| `0` | Success |\n| `1` | Error (see the message) |\n| `2` | Bad usage |\n| `3` | Already up to date (`--upgrade`) |\n| `4` | Network or download failure |\n| `5` | Checksum mismatch or missing from `SHA256SUMS` |\n| `6` | Not running as root |\n| `7` | Unsupported OS or CPU |\n\n### The systemd unit\n\nThe installer writes this unit (shown with the default paths and port):\n\n```ini\n[Unit]\nDescription=Memora - long-term memory for AI agents (HTTP API + MCP + web UI)\nDocumentation=https://github.com/Codrihub/memora\nAfter=network-online.target\nWants=network-online.target\n\n[Service]\nType=simple\nUser=memora\nGroup=memora\nWorkingDirectory=/var/lib/memora\nEnvironment=HOME=/var/lib/memora\nEnvironment=MEMORA_STATE=/var/lib/memora/state\nEnvironment=MEMORA_ASSETS=/usr/local/share/memora/assets\nEnvironment=MEMORA_PORT=8400\nEnvironment=MEMORA_BIND=0.0.0.0\nEnvironment=MEMORA_VAULT=/var/lib/memora/vault\nEnvironment=GIT_AUTHOR_NAME=Memora\nEnvironment=GIT_AUTHOR_EMAIL=memora@localhost\nEnvironment=GIT_COMMITTER_NAME=Memora\nEnvironment=GIT_COMMITTER_EMAIL=memora@localhost\nEnvironment=RUST_LOG=info\nExecStart=/usr/local/bin/memora\nRestart=on-failure\nRestartSec=3\nTimeoutStopSec=15\nLimitNOFILE=65536\nUMask=0027\n\n# Hardening\nNoNewPrivileges=yes\nAmbientCapabilities=\nCapabilityBoundingSet=\nProtectSystem=strict\nReadWritePaths=/var/lib/memora\nProtectHome=yes\nPrivateTmp=yes\nPrivateDevices=yes\nProtectKernelTunables=yes\nProtectKernelModules=yes\nProtectKernelLogs=yes\nProtectControlGroups=yes\nProtectClock=yes\nProtectHostname=yes\nRestrictAddressFamilies=AF_UNIX AF_INET AF_INET6\nRestrictNamespaces=yes\nRestrictRealtime=yes\nRestrictSUIDSGID=yes\nLockPersonality=yes\nMemoryDenyWriteExecute=yes\nSystemCallArchitectures=native\nSystemCallFilter=@system-service\nSystemCallFilter=~@privileged\n\n[Install]\nWantedBy=multi-user.target\n```\n\nA port below 1024 adds `CAP_NET_BIND_SERVICE` instead of the empty capability\nset. There are no IP restrictions (`IPAddressDeny=`) by default; use the\nfirewall, `MEMORA_DOMAIN`, or the access rules in the UI.\n\nThe installer rewrites the unit on every run. Put local changes in a drop-in:\n\n```sh\nsudo systemctl edit memora # for example, a vault outside /var/lib/memora:\n# [Service]\n# ReadWritePaths=/srv/notes\nsudo systemctl restart memora\n```\n\nBecause of `ProtectSystem=strict` and `ProtectHome=yes`, the server can only\nwrite under `/var/lib/memora`. A vault anywhere else (including `/home`) needs\nthe drop-in above (and `ProtectHome=read-only` or `no` for `/home`).\n\n### Settings\n\nThe unit sets the basics (`MEMORA_STATE`, `MEMORA_ASSETS`, `MEMORA_PORT`,\n`MEMORA_BIND`, `MEMORA_VAULT`, `RUST_LOG`) as `Environment=` lines. Everything\nelse (`MEMORA_BASE_URL`, `MEMORA_DOMAIN`, `MEMORA_TRUSTED_PROXIES`, ...) is\nstored in the state database (table `server_config`). Edit it with the\nconsole: `sudo memora-cli` → `/config`, then `/restart`.\n\nA value stored with `/config` wins over the unit's `Environment=` lines; a key\nwith no stored value uses the environment. If you stored `MEMORA_PORT` with\n`/config` and later reinstall with `--port`, change or clear it in `/config`\ntoo, otherwise the stored value keeps applying. The provisioning owner\npassword and API key are environment-only and never stored (see\n[CONFIGURATION.md](CONFIGURATION.md)).\n\nSee [CONFIGURATION.md](CONFIGURATION.md) for every variable.\n\n### First run\n\n```sh\nsudo memora-cli # opens the console; it finds the running server itself\n/guide # step-by-step, or:\n/web # prints a one-time code\n```\n\nOpen `http://<host>:8400/login`, enter the code, create the owner account, then\nchoose the vault folder (`/var/lib/memora/vault` is suggested).\n\n### Day to day\n\n```sh\nsudo systemctl status memora\nsudo systemctl restart memora\nsudo journalctl -u memora -f\nsudo memora-cli # /status, /keys, /config, /restart, /mcp ...\n```\n\n### Upgrading\n\n```sh\nsudo /usr/local/share/memora/install.sh --upgrade # latest release\nsudo /usr/local/share/memora/install.sh --upgrade --version 1.0.1\nsudo memora-cli update # same, from the console\n```\n\nBinaries and assets are swapped atomically, the state directory and vault are\nuntouched, and the service is restarted if it was running. The server migrates\n`memora.db` itself on start. Take a `memora-cli db backup` before upgrading,\nand read the [CHANGELOG](../CHANGELOG.md) before a major version bump.\n\n### Uninstall\n\n```sh\nsudo /usr/local/share/memora/install.sh --uninstall # keeps /var/lib/memora and the memora user\nsudo /usr/local/share/memora/install.sh --uninstall --purge # also deletes notes, account, keys, and the user\n```\n\nOr run `memora-cli uninstall`, which asks what to keep (see\n[Uninstall with memora-cli](#uninstall-with-memora-cli)).\n\n### Firewall\n\nOpen only the Memora port, and only when clients connect directly:\n\n```sh\nsudo ufw allow 8400/tcp\n# or\nsudo firewall-cmd --permanent --add-port=8400/tcp && sudo firewall-cmd --reload\n```\n\nBehind a reverse proxy on the same host, install with `--behind-proxy` and open\nonly the proxy's 80/443.\n\n## Docker\n\n```sh\ngit clone https://github.com/Codrihub/memora.git && cd memora\nmkdir -p data state && sudo chown -R 1000:1000 data state\ndocker compose up -d\ndocker compose exec -it gateway memora-cli # then /guide, or /web\n```\n\n`docker compose up` pulls `ghcr.io/codrihub/memora:<version>`; if the image is\nnot available (or you set `IMAGE=memora:local`) it builds from the\n`Dockerfile`. Image tags: `<version>` (for example `1.0.0`), `<major>.<minor>`\n(for example `1.0`), and `latest` (stable releases only), for `linux/amd64`\nand `linux/arm64`. The compose file pins the release it ships with; set\n`IMAGE` in `.env` to run another tag.\n\n### Volumes: `/data` and `/state`\n\nBoth must be persistent (the Compose file bind-mounts `./data` and `./state`):\n\n- `/data` is the vault: your notes, their git history, and the event\n log. Lose it and the notes are gone.\n- `/state` holds `memora.db` (owner account, password hash, API key hashes,\n sessions, settings, setup/lock state, activity log). Lose it and\n every agent key stops working, the instance falls back to first-run setup,\n and anyone who reaches the port during that window could claim it.\n\nThe container runs as uid 1000; set `MEMORA_UID`/`MEMORA_GID` in `.env` if the\nhost directories belong to another user. `MEMORA_DATA_DIR` and\n`MEMORA_STATE_DIR` move the host directories, and `MEMORA_HTTP_PORT` changes\nthe published host port. See [CONFIGURATION.md](CONFIGURATION.md#docker-compose-env).\n\n### Verify\n\n```sh\ncurl -s http://127.0.0.1:8400/healthz\ndocker compose exec gateway memora-cli db check\ndocker compose exec gateway memora-cli status\nls -l state/memora.db\n```\n\n### Upgrading\n\n```sh\ngit pull\ndocker compose pull && docker compose up -d # or: docker compose up -d --build\n```\n\nSettings: `docker compose exec -it gateway memora-cli` → `/config`, then\n`docker compose restart gateway` (`/restart` cannot restart a container from\ninside).\n\n## npm\n\nRequirements: Linux on x86_64 or arm64, or Windows 10/11 on x64; Node.js 22 or\nnewer; and `git` (vault history uses it).\n\n```sh\nnpm install -g @codrihub/memora\nmkdir -p ~/memora && cd ~/memora\nMEMORA_VAULT=./vault MEMORA_STATE=./state memora\n# in a second terminal, same folder:\nMEMORA_STATE=./state memora-cli # then /guide, or /web\n```\n\nOn Windows, in PowerShell:\n\n```powershell\nnpm install -g @codrihub/memora\nmkdir ~\\memora; cd ~\\memora\n$env:MEMORA_VAULT = '.\\vault'; $env:MEMORA_STATE = '.\\state'; memora\n# in a second terminal, same folder:\n$env:MEMORA_STATE = '.\\state'; memora-cli # then /guide, or /web\n```\n\n`npx @codrihub/memora --version` runs it without a global install.\n\n`@codrihub/memora` holds the `memora` and `memora-cli` commands and the web UI\n(used unless `MEMORA_ASSETS` is set). The binaries come from\n`@codrihub/memora-linux-x64`, `@codrihub/memora-linux-arm64` or\n`@codrihub/memora-win32-x64`, optional dependencies npm installs only on a\nmatching machine. The Linux ones are the static binaries of the GitHub\nrelease with the same version, so glibc and musl distributions both work; the\nWindows one is built with a static C runtime and needs nothing else. There is\nno install script and nothing is downloaded at install time, so it works with\n`--ignore-scripts` and from a registry mirror; it does not work with\n`--omit=optional`, which leaves the binaries out. On macOS the commands print\nwhere to go instead: use [Docker](#docker) or build from source.\n\nThe npm install sets up no service, user or data folder: the server runs as\nyou, with `MEMORA_STATE` and `MEMORA_VAULT` where you point them (`./state`\nby default). Keep the state folder private (`chmod 700 state`; on Windows,\nkeep it under your user profile), since it holds the owner account and key\nhashes. On Windows, `memora-cli` runs every command as you: there is no root\nor service account to switch to. For a long-running server, prefer the\n[native install](#native-install).\n\nUpgrade with `npm install -g @codrihub/memora@latest` (`memora-cli update`\nprints this too) and restart the server; the state database is migrated on\nstart.\n\n## Start, stop and restart\n\n`memora-cli start`, `stop` and `restart` (or `/start`, `/shutdown` and\n`/restart` in the console) work out how this install runs and do the right\nthing:\n\n| Install | What `memora-cli start / stop / restart` does | By hand |\n|---|---|---|\n| Native (systemd) | runs `systemctl start / stop / restart memora` (as root) | `sudo systemctl start memora` |\n| npm, source | runs the server in the background, with `memora.pid`, `memora.log` and `stop.token` in the state folder; `stop` asks it to end over a local, token-protected request and waits, `stop --force` kills it | run `memora` and keep it open; Ctrl+C stops it |\n| Docker | prints the host commands (a container cannot stop itself) | `docker start / stop / restart memora` |\n\nFrom the browser, the owner can shut the server down in Settings, Server, Shut\ndown: the server answers, then stops gracefully and exits with status 0, the\nsame as Ctrl+C or `systemctl stop`. A supervisor that restarts a cleanly exited\nprocess starts it again (systemd `Restart=always`, Docker\n`--restart unless-stopped`); the installer's unit uses `Restart=on-failure`, so\nit stays stopped. API keys cannot shut the server down.\n\n## Update\n\nCheck what you run first: `memora --version` and `memora-cli --version`.\n`memora-cli update` (or `/update` in the console) works out how this copy was\ninstalled and prints, or runs, the right steps. By install method:\n\n| Install | Update with | Then |\n|---|---|---|\n| npm (Windows, Linux) | `npm install -g @codrihub/memora@latest` | `memora-cli restart`, or Ctrl+C the running `memora` and start it again |\n| Docker Compose | `docker compose pull && docker compose up -d` | nothing: the container is re-created |\n| Docker run | `docker pull ghcr.io/codrihub/memora:latest`, then `docker rm -f memora` and the same `docker run` again (same volumes) | nothing |\n| Native (systemd) | `sudo memora-cli update` (runs `install.sh --upgrade`) | nothing: the service is restarted |\n| Source | `git pull && cargo build --release` | `memora-cli restart` |\n\nSettings, accounts and notes stay; the server migrates `memora.db` on start.\nTake a `memora-cli db backup` first if you are unsure.\n\n**Release zip (older Windows installs).** Windows now installs with npm. To\nswitch, stop the old server (Ctrl+C in its window), run\n`npm install -g @codrihub/memora`, and start `memora` with the same folders so\neverything carries over, for example in PowerShell:\n\n```powershell\n$env:MEMORA_STATE = 'C:\\Users\\you\\memora\\state'; $env:MEMORA_VAULT = 'C:\\Users\\you\\memora\\vault'; memora\n```\n\nThen delete the old program folder (only the `.exe` files and `assets`, not\nyour state or vault folders).\n\n## Uninstall with memora-cli\n\n```bash\nmemora-cli uninstall # or /uninstall in the console\n```\n\nIt explains what it removes for this install (the service and program\nfiles, or the npm package, or the container), then shows a checklist; press\nspace to select and Enter to continue:\n\n- **Settings and accounts** (the state folder: database, keys, sessions)\n- **Vault notes** (your vault folder)\n\nBoth are **unticked**, so by default your settings and notes are kept and a\nlater install picks them up again. Deleting the vault asks you to type its\nfolder name. Before the state folder is deleted, a final database backup is\noffered. System folders, your home folder and the program's own folder are\nnever deleted.\n\n| Install | What uninstall does |\n|---|---|\n| Native (systemd) | runs the installed `install.sh --uninstall` (adds `--purge` only when both folders are the installer's own) |\n| npm | stops the server, deletes what you ticked, then tells you to run `npm uninstall -g @codrihub/memora` |\n| Source | stops the server, deletes what you ticked; delete the program folder yourself |\n| Docker | prints `docker rm -f memora` and, for what you ticked, `docker volume rm memora-state` / `docker volume rm memora-data` |\n\nWithout a terminal it needs `--yes` and deletes only what the flags say:\n`memora-cli uninstall --yes [--delete-config] [--delete-vault]`.\n\nOn a version older than 1.3.2 there is no `uninstall` command: see\n[Uninstall by hand](#uninstall-by-hand-versions-before-132).\n\n## Uninstall by hand (versions before 1.3.2)\n\n`memora-cli uninstall` arrived in 1.3.2. On an older version it answers\n``unknown command `uninstall` ``. Either update first and then run\n`memora-cli uninstall` (npm: `npm install -g @codrihub/memora@latest`), or\nremove Memora by hand with the steps below. They only touch Memora: never use\nwildcards, and never delete a parent folder or your home folder.\n\n**1. Check the version.** `memora --version` and `memora-cli --version`.\n\n**2. Find the folders.** Memora keeps two folders:\n\n- the **state folder** (settings, accounts, keys): `MEMORA_STATE`, or by\n default `state` inside the folder where you started `memora` (for example\n `C:\\Users\\you\\state` or `~/memora/state`);\n- the **vault folder**: your notes, wherever you chose.\n\nThe server prints both when it starts:\n`Memora HTTP server starting vault=... state=...`. `memora-cli status`, run in\nthe same folder, shows the state folder too.\n\n**3. Stop Memora.** Press Ctrl+C in the window where `memora` runs (or close\nthat window). Then make sure it is gone:\n\n| Shell | Check | Stop if still running |\n|---|---|---|\n| PowerShell | `Get-Process memora -ErrorAction SilentlyContinue` | `Stop-Process -Name memora` |\n| cmd | `tasklist /FI \"IMAGENAME eq memora.exe\"` | `taskkill /IM memora.exe` |\n| Linux, macOS | `pgrep -ax memora` | `pkill -x memora` |\n\n**4. Remove the program.**\n\n| Install | Commands |\n|---|---|\n| npm (any OS) | `npm uninstall -g @codrihub/memora`, then `npm ls -g --depth=0`: if `@codrihub/memora-win32-x64` (or `-linux-x64`, `-linux-arm64`) is still listed, `npm uninstall -g` that exact name |\n| Docker run | `docker rm -f memora`, then `docker image rm ghcr.io/codrihub/memora:latest` |\n| Docker Compose | `docker compose down` in the folder of `docker-compose.yml` (no `-v`) |\n| Native (systemd) | `sudo /usr/local/share/memora/install.sh --uninstall` (keeps `/var/lib/memora`) |\n| Release zip | delete the folder that holds `memora.exe`, `memora-cli.exe` and `assets` (check its contents first, as below) |\n\n**5. Delete the state folder (optional).** Look inside first: it should hold\n`memora.db` (and maybe `memora.log`, `memora.pid`, `stop.token`, `backups`).\nThen delete that exact path:\n\n```powershell\n# Windows, PowerShell\nGet-ChildItem -LiteralPath 'C:\\Users\\you\\state'\nRemove-Item -LiteralPath 'C:\\Users\\you\\state' -Recurse -Confirm\n```\n\n```bat\n:: Windows, cmd\ndir \"C:\\Users\\you\\state\"\nrmdir /S \"C:\\Users\\you\\state\"\n```\n\n```sh\n# Linux, macOS\nls -la ~/memora/state\nrm -rI -- ~/memora/state\n```\n\nDocker: `docker volume ls`, then remove the exact names,\n`docker volume rm memora-state`. Compose: check and delete the `./state`\nfolder next to `docker-compose.yml`. Native: `/var/lib/memora/state`\n(or `install.sh --uninstall --purge`, which also deletes the notes, see below).\n\n**6. The vault folder: only if you are sure.** It holds your notes. It is\noptional to delete it; copy it somewhere safe first (it is plain Markdown).\nUse the same two steps on its exact path: look inside (`Get-ChildItem` /\n`ls`), then `Remove-Item -LiteralPath '<vault>' -Recurse -Confirm` or\n`rm -rI -- <vault>`. Docker: `docker volume rm memora-data`, or the `./data`\nfolder with Compose. Native: `sudo /usr/local/share/memora/install.sh\n--uninstall --purge` deletes `/var/lib/memora` with the notes, the account\nand the `memora` user.\n\n## Troubleshooting\n\n**``memora-cli: unknown command `uninstall` ``** (or `start`, `stop`,\n`restart`). You run a version older than 1.3.2. Update, then run the command\nagain: `npm install -g @codrihub/memora@latest`, then `memora-cli uninstall`.\nOr remove it by hand: [Uninstall by hand](#uninstall-by-hand-versions-before-132).\n\n**`/update` says \"not installed with install.sh (built from source)\" on an\nnpm install.** Older versions could miss an npm install. Update with npm,\n`npm install -g @codrihub/memora@latest`, and restart the server; newer\nversions detect npm reliably. Never run `cargo build` for an npm install.\n\n**`/restart` says \"systemctl restart\" on npm or Windows.** Same cause (older\nversion). Stop the server with Ctrl+C in its window and run `memora` again, or\nupdate and use `memora-cli restart`.\n\n**Which version do I have?** `memora --version` and `memora-cli --version`.\nThe latest release is on\n[GitHub Releases](https://github.com/Codrihub/memora/releases).\n\n## Reverse proxy\n\nRun Memora on loopback (`--behind-proxy` natively; in Docker set\n`MEMORA_HTTP_PORT=127.0.0.1:8400` in `.env`) and let the proxy terminate TLS.\nThen set, with `/config` or in `.env`:\n\n| Variable | Why |\n|---|---|\n| `MEMORA_BASE_URL=https://memory.example.com` | Public URL; links and MCP snippets use it, and its host becomes an allowed domain |\n| `MEMORA_DOMAIN=memory.example.com` | Only these hostnames are served; requests for the bare IP or other names get 404 |\n| `MEMORA_TRUSTED_PROXIES=203.0.113.10` | Proxies whose forwarding headers are believed. Loopback (same-host nginx, cloudflared) is always trusted; only list remote proxies |\n\nIn Docker, a proxy on the host reaches the container through the Docker\nnetwork, so the container sees the network's gateway address (for example\n`172.18.0.1`) instead of loopback. Add that address to\n`MEMORA_TRUSTED_PROXIES`, otherwise every request appears to come from it.\n\nThe proxy must forward `Host`, `X-Forwarded-For`, and `X-Forwarded-Proto`, and\nupgrade WebSockets on `/ws`. nginx and Caddy examples are in\n[DEPLOYMENT.md](DEPLOYMENT.md).\n\n## Backups\n\nBack up **both** the state database and the vault. The database is small but\ncritical.\n\nState, online (the server keeps running):\n\n```sh\nsudo memora-cli db backup # state/backups/memora-<UTC time>.db, keeps the newest 10\nsudo memora-cli db backup --to /var/backups/memora.db\nsudo memora-cli db check # integrity, permissions, sizes, last backup age\ndocker compose exec gateway memora-cli db backup # Docker: lands in ./state/backups/\n```\n\nThe copy is a consistent snapshot (`VACUUM INTO`), checked with\n`integrity_check`, mode 0600. Never `cp` a live `memora.db`: recent commits sit\nin `memora.db-wal`. Restore with the server stopped:\n\n```sh\nsudo systemctl stop memora\nsudo memora-cli db restore /var/backups/memora.db # verifies it; keeps the replaced DB in state/backups/\nsudo systemctl start memora\n```\n\nAlso keep a copy of `state/key-seal.bin`, which encrypts the sealed API key\ncopies. Vault and state together: archive both with the server stopped:\n\n```sh\nsudo systemctl stop memora\nsudo tar -C /var/lib/memora -czf memora-backup-$(date +%F).tar.gz state vault\nsudo systemctl start memora\n```\n\nKeep backups private: the database holds password and key hashes (never\nplaintext secrets).\n\n## Automation: `--check` and `--upgrade`\n\nThese are the contract for scripts and automation.\n\n```sh\n$ /usr/local/share/memora/install.sh --check\nMEMORA_LATEST=1.0.1\nMEMORA_INSTALLED=1.0.0\n```\n\n`MEMORA_INSTALLED` comes from `/usr/local/share/memora/VERSION` (written by\nthe installer), else from `memora --version`, else `unknown` (or `none` when\nnothing is installed). `MEMORA_LATEST` is `unknown` and the exit code `4` when\nGitHub cannot be reached. `--check` needs no root.\n\n```sh\n$ sudo /usr/local/share/memora/install.sh --upgrade --yes [--version X.Y.Z]\n...\nMEMORA_UPGRADE_RESULT=ok FROM=1.0.0 TO=1.0.1\n```\n\n`--upgrade --yes` never prompts. The last line of output is always\n`MEMORA_UPGRADE_RESULT=<ok|uptodate|error> FROM=<old> TO=<new>`, and the exit\ncode is `0` (ok), `3` (already up to date), `4` (network), `5` (checksum),\n`6` (not root), or `1`/`2` for other errors.\n"},{"file":"docs/CONFIGURATION.md","slug":"configuration","title":"Configuration","text":"# Configuration\n\nAll server state, settings included, lives in one SQLite database,\n`<MEMORA_STATE>/memora.db` (see [DATABASE.md](DATABASE.md)). Server settings are\nrows in the `server_config` table, edited with `memora-cli` (`/config` in the\nconsole). The process environment (systemd `Environment=`, Docker\n`environment:`) applies to every key that has no row.\n\n## Precedence\n\nFor each server setting:\n\n1. a row in `server_config` (set with `/config`), else\n2. the process environment (non-empty value), else\n3. the built-in default.\n\nThe server reads `server_config` once at startup, before anything else, so a\nchange made with `/config` applies after a restart (`/restart` for a native\ninstall, `docker compose restart gateway` in Docker). Clearing a value in\n`/config` deletes the row, and the environment or default applies again.\n\nA row wins over the environment. If you set `MEMORA_PORT` with `/config` and\nlater change the port in the systemd unit or `.env`, the row still applies\nuntil you clear it.\n\n## Server settings\n\n| Name | Default | Where it can live | What it does |\n|---|---|---|---|\n| `MEMORA_PORT` | `8400` | `server_config` or env | HTTP port (API, MCP, web UI, WebSocket). 1-65535. |\n| `MEMORA_BIND` | `127.0.0.1` | `server_config` or env | Bind address. `0.0.0.0` for every interface (the container image and the installer set it). |\n| `MEMORA_BASE_URL` | empty | `server_config` or env | Public URL, for example `https://memory.example.com`. Used for OAuth metadata and connection snippets; its host is also an allowed domain. |\n| `MEMORA_DOMAIN` | empty (any host) | `server_config` or env | Allowed hostnames, comma separated (`*.example.com` works). Requests for other hosts get 404. Loopback names are always allowed. |\n| `MEMORA_TRUSTED_PROXIES` | empty | `server_config` or env | IPs of remote reverse proxies whose forwarding headers are trusted. Loopback is always trusted. |\n| `MEMORA_ARM_TTL` | `300` | `server_config` or env | Accepted and validated (30-86400 seconds), but the server and `memora-cli` do not read it: the setup / reset window length comes from `memora-cli --minutes` (default 5 minutes). |\n| `MEMORA_VAULT` | empty (`data` as last resort) | `server_config` or env | Suggested vault folder. The vault in use is chosen in the browser (or with `memora-cli vault`) and stored in the `settings` table. |\n| `MEMORA_VAULT_AUTO` | `false` | `server_config` or env | `true` (also `1`, `yes`, `on`): use `MEMORA_VAULT` at startup instead of asking in the browser, only while no vault is configured and if the folder is writable. |\n| `MEMORA_ADMIN_USER` | `admin` | `server_config` or env | Name of the owner created at startup when no owner exists (needs `MEMORA_ADMIN_PASSWORD`). |\n| `RUST_LOG` | `info` | `server_config` or env | Log filter, for example `info` or `memora=debug`. |\n\n`server_config` accepts only these ten keys. Values are trimmed and validated\n(numbers in range, `true`/`false`, a valid user name, no control characters, at\nmost 2048 bytes).\n\n## Environment only\n\n| Name | Default | What it does |\n|---|---|---|\n| `MEMORA_ADMIN_PASSWORD`, `MEMORA_ADMIN_PASSWORD_FILE` | unset | Creates the owner at startup when none exists (at least 10 characters). Only the argon2id hash is stored; an existing owner is never replaced. |\n| `MEMORA_API_KEY`, `MEMORA_API_KEY_FILE` | unset | Installs an agent API key with id `k_env` and scopes `mcp`, `read`, `write` (at least 24 characters). Only its SHA-256 is stored; the key is replaced when the value changes. |\n| `MEMORA_STATE` | `state` (relative to the working directory) | State directory holding `memora.db`. Created with mode 0700 if missing. |\n| `MEMORA_ASSETS` | the `crates/http/assets` folder of the build tree | Directory of the web UI assets. |\n| `MEMORA_INSTALL` | set by the npm launcher (`npm`) and the Docker image (`docker`) | How this copy was installed: `npm`, `docker`, `native`, `zip` or `source`. `memora-cli update`, `start`, `stop`, `restart` and `uninstall` use it to pick the right steps; when unset they work it out from the program's path. |\n| `MEMORA_SETUP_HINT` | `memora-cli setup (run on the server)` | Hint returned by `GET /api/auth/state` and shown on the login screen. |\n| `MEMORA_UPDATE_CHECK` | `true` | Release check: shortly after start and then every 6 hours the server asks GitHub (`api.github.com/repos/Codrihub/memora/releases/latest`) for the newest release and the web UI shows when an update is available. The same check reads the repository's star count (`api.github.com/repos/Codrihub/memora`), shown in What's new. `false` (also `0`, `no`, `off`) turns both off; no network call is made. |\n\nThe two secrets can never be stored in `server_config` (the schema rejects\nthem). The `_FILE` variants read the value from a file, for example a Docker\nsecret; a non-empty file wins over the plain variable.\n\nIn `/config`, `MEMORA_API_KEY` offers to create an API key directly, and\n`MEMORA_ADMIN_PASSWORD` points to `/setup` or `/reset`.\n\n## Instance settings (web UI)\n\nThe `settings` table holds one row, edited from the Settings page of the web UI:\n\n| Key | Default | Range | What it does |\n|---|---|---|---|\n| `realm` | `Memora` | 1-64 characters | Instance name shown in the UI and reported by `/api/config` and `/api/auth/state`. |\n| `session_ttl` | `10800` (3 hours) | 300-2592000 seconds | Idle timeout of a browser session: any use renews it (requests, and an open tab in use). |\n| `session_max_age` | `0` | `0` or at least `session_ttl` | Absolute session lifetime in seconds. `0` means no cap. |\n| `min_password_len` | `10` | 10-256 | Minimum owner password length. |\n| `log_max_mb` | `8` | 1-512 | Size limit in MB of the vault event log (`.events.jsonl`). |\n| `log_max_days` | `0` | 0-3650 | Age limit in days of the vault event log. `0` means no age limit. |\n| `vault_path` | unset | absolute path | The vault folder. Set in the browser after the first sign-in, or with `memora-cli vault PATH`. |\n\nTwo more settings live in the `ui_layout` table and in a file beside the database:\n\n| Setting | Default | Where | What it does |\n|---|---|---|---|\n| Largest image | 5 MB | Settings, Images (`POST /api/settings/media`, admin); stored as the `srv-media` document | Uploads above this size are refused, from the app, the HTTP API and MCP `upload_image` alike. 0.1 to 50 MB. |\n| Mnemo | not set up | Settings, Mnemo, or `/mnemo setup` in the console; stored in `assistant.sqlite3` | Providers (OpenAI, Anthropic, one OpenAI-compatible server) with sealed API keys, models (pinned, hidden, default, context window and reply limit), temperature, reply and context limits, tool steps per reply, your instructions, and the floating button. |\n\n## memora-cli options\n\n| Option | Default | What it does |\n|---|---|---|\n| `--state <DIR>` | `$MEMORA_STATE`, else the state directory of the running `memora` server, else `./state` | State directory to work on. |\n| `--minutes <N>` | `5` | Window length for `setup` and `reset-password`, 1-60. |\n| `--ttl <SECONDS>` | | Window length in seconds (at most 3600). `--minutes` wins when both are given. |\n| `--create` | | With `vault PATH`: create the folder if it does not exist. |\n\nRun as root, `memora-cli` does all database work as the owner of the state\ndirectory, so no root-owned `memora.db*` files appear. See\n[INSTALL.md](INSTALL.md) and [DEPLOYMENT.md](DEPLOYMENT.md) for the commands.\n\n## Docker Compose (`.env`)\n\nThese variables are read by `docker-compose.yml`, not by Memora itself:\n\n| Name | Default | What it does |\n|---|---|---|\n| `COMPOSE_PROJECT_NAME` | `memora` | Compose project name, also the container name prefix. |\n| `IMAGE` | `ghcr.io/codrihub/memora:<version>` | Image to run or build. The compose file pins the release it ships with. |\n| `MEMORA_HTTP_PORT` | `8400` | Host port mapped to the container's port 8400. Use `127.0.0.1:8400` to publish on loopback only. |\n| `MEMORA_DATA_DIR` | `./data` | Host path mounted at `/data` (the vault). |\n| `MEMORA_STATE_DIR` | `./state` | Host path mounted at `/state` (the state directory). |\n| `MEMORA_UID`, `MEMORA_GID` | `1000` | uid:gid the container runs as. Must own both host directories. |\n| `MEMORA_ARM_TTL` | `300` | Passed to the container unchanged. |\n\nCompose also passes these through from `.env` to the container:\n`MEMORA_BASE_URL`, `MEMORA_DOMAIN`, `MEMORA_TRUSTED_PROXIES`,\n`MEMORA_VAULT_AUTO`, `MEMORA_ADMIN_USER`, `MEMORA_ADMIN_PASSWORD`,\n`MEMORA_ADMIN_PASSWORD_FILE`, `MEMORA_API_KEY`, `MEMORA_API_KEY_FILE`,\n`MEMORA_SETUP_HINT`, `MEMORA_UPDATE_CHECK`, and `RUST_LOG`.\n\nInside the container the image sets `MEMORA_VAULT=/data`,\n`MEMORA_STATE=/state`, `MEMORA_PORT=8400`, `MEMORA_BIND=0.0.0.0`,\n`MEMORA_ARM_TTL=300`, `MEMORA_ASSETS=/app/assets`, `MEMORA_INSTALL=docker`,\nand `RUST_LOG=info`.\n\n## State directory\n\n| Path | Content |\n|---|---|\n| `memora.db` (+ `-wal`, `-shm`) | The state database: owner, API keys (hashes), tool switches and per-key permissions, OAuth clients and grants, privacy rules, sessions (hashed ids), setup window and lock state, access rules, settings, `server_config`, activity log. Mode 0600, WAL mode, must be on a local filesystem. See [DATABASE.md](DATABASE.md). |\n| `key-seal.bin` | 32-byte master key (mode 0600) that encrypts the copies of dashboard-created API keys, so the owner can show a key again. Created on first use. Back it up together with `memora.db`. |\n| `assistant.sqlite3` (+ `-wal`, `-shm`) | Mnemo, the built-in agent: providers (API keys sealed with `key-seal.bin`), models, preferences, chats and messages. Mode 0600. Separate from `memora.db`, so the main schema is unchanged; delete it to forget every Mnemo chat and key. Back it up with `memora.db` if you want to keep chats. |\n| `backups/` | `memora-cli db backup` output (newest 10 kept by default). |\n| `exchange/` | Zips written by the `export_memory` MCP tool and read by `import_memory` (mode 0700, created on first use). Private to this instance; delete old zips when no longer needed. |\n| `legacy-json-<unix time>/` | JSON state files found at startup, moved here after their one-time import into `memora.db`. |\n| `internal.token` | Created by the Docker entrypoint. Not used by Memora. |\n\n## Vault files\n\nThe vault holds the markdown notes plus derived and metadata files. See\n[ARCHITECTURE.md](ARCHITECTURE.md#vault-markdown-portable) for the full list.\nThe important ones for operations are `.git/` (history), `.events.jsonl`\n(event log), and `.Trash/`\n(soft-deleted notes; `.Trash/.index.json` remembers where each one came from,\nso `restore_trash` puts it back there; `.Trash/.assets/<entry>/` keeps the images\nof a trashed note until it is restored or deleted for good). Images uploaded to a\nnote are ordinary files in the note's folder.\n\n## Version history\n\nVersion history (`get_history`, `get_note_at`, `diff`, `restore_memory`,\n`snapshot`) is on when the vault folder is a git repository of its own, that is\nwhen it has a `.git/` directory. Memora does not create one, so a new vault has\nno history and these tools answer \"version history is off\". To turn it on,\ninstall `git` and run, once:\n\n```sh\ngit -C /path/to/vault init\ngit -C /path/to/vault add -A\ngit -C /path/to/vault commit -m \"start history\"\n```\n\n(In Docker, the vault is the host directory mounted at `/data`.) From then on\nevery change made through Memora is committed automatically. Each commit's\nauthor is the agent or user whose call made the change; the committer is the\nvault's git identity (`git config user.name` / `user.email`), or `Memora\n<memora@localhost>` when none is set. Git never searches above the vault, so a\nvault inside another repository still needs its own `git init`.\n\nA snapshot (`snapshot` tool) commits pending changes and tags the last commit\nas `snap-<label>`; pass that tag as `rev` to `get_note_at`, `diff` or\n`restore_memory`.\n\nDeleting a note for good (Delete forever or Empty trash in the app,\n`/api/trash/delete`, `/api/trash/empty`, `delete_memory` with `permanent`)\nalso erases it from the history: Memora rewrites the vault's git history so\nno commit, snapshot tag or object keeps its text, any name it had, its trash\nrecord or its path in a commit message, then expires the reflog and runs\n`git gc --prune=now`. Other notes keep all their versions, but their revision\nids change, so old revision ids (and clones or pushes of the vault made\nbefore) no longer match. Moving a note to the Trash keeps its history.\n"},{"file":"docs/MCP.md","slug":"mcp","title":"MCP tools","text":"# MCP\n\nMemora exposes the vault to agents through the Model Context Protocol. The\nserver speaks JSON-RPC 2.0 over the Streamable HTTP transport at `/mcp`, on the\nsame port as the HTTP API and the web UI. There is one MCP endpoint and one tool\ncatalog.\n\n| | |\n|---|---|\n| Endpoint | `POST /mcp` |\n| Protocol versions | `2025-06-18` (preferred), `2025-03-26`, `2024-11-05` |\n| Auth | API key in `Authorization: Bearer <key>` or `X-API-Key: <key>`, or an OAuth 2.1 access token |\n| Discovery card | `GET /.well-known/mcp.json` (public) |\n| Readable catalog | `GET /tools` (HTML page, public) |\n| Catalog size | 77 tools, plus 5 admin tools for keys with the `admin` scope |\n\n`initialize` answers with the protocol version the client asks for when it is\none of the three above, and with `2025-06-18` otherwise.\n\n## Transport\n\n- Requests are JSON-RPC 2.0 objects sent with `POST /mcp`. Batches (JSON\n arrays) are not supported.\n- Responses are plain JSON (`application/json`), with one exception below.\n- `initialize` returns an `Mcp-Session-Id` header (`<catalog epoch>.<random>`).\n The epoch is a hash of the server version and the tools the caller may use, so\n it changes when the server is upgraded, a tool is switched on or off, or the\n key's scopes or tool grant change. No session id is ever refused: unknown or\n old ids work, and malformed ones count as no session.\n- When a request carries a session id whose catalog has changed since that\n session last heard, and its `Accept` header allows `text/event-stream`, the\n answer is an SSE stream with two events: the notification\n `notifications/tools/list_changed`, then the normal response. Each change is\n sent once per session (remembered in memory; a restart forgets, and the\n epoch in the id takes over). JSON-only clients always get plain JSON.\n- `GET /mcp` returns `405 Method Not Allowed` (there is no standalone server\n stream). `DELETE /mcp` with a session id returns `204 No Content`; without\n one it returns `405`.\n- A notification (a `notifications/*` method without an `id`) gets\n `202 Accepted` and no body.\n- `/mcp` needs a configured vault. Until one is chosen it returns\n `409 {\"error\":\"vault not configured\",\"needs_vault\":true}`.\n- A browser session (cookie) may also call `/mcp`. It then needs a same-origin\n request, like the rest of the JSON API.\n\nThe server speaks Streamable HTTP only. A client that can only launch local stdio\nservers can use a bridge such as `mcp-remote` (see below).\n\n## Connecting an agent\n\n### With an API key\n\nCreate a key in the web UI (Keys page), with `memora-cli` (`/keys`), or with\n`POST /api/keys`. The raw key (`memora_live_...`) is shown once. By default a key gets\nthe scopes `mcp`, `read` and `write` and may call every tool. See\n[Tool switches and per-key permissions](contracts/tools-permissions.md) to\nnarrow it.\n\nUse `http://localhost:8400/mcp` for a local install, or your public URL such as\n`https://memory.example.com/mcp` behind a reverse proxy. When the server sets\n`MEMORA_DOMAIN` or `MEMORA_BASE_URL`, requests for any other host get `404`, so\nuse that domain.\n\nClaude Code:\n\n```bash\nclaude mcp add --transport http memora https://memory.example.com/mcp \\\n --header \"Authorization: Bearer memora_live_REPLACE_WITH_YOUR_KEY\"\n```\n\nCursor, Windsurf and other clients with an `mcpServers` JSON config (VS Code\nuses the key `servers` in `.vscode/mcp.json`):\n\n```json\n{\n \"mcpServers\": {\n \"memora\": {\n \"type\": \"http\",\n \"url\": \"http://localhost:8400/mcp\",\n \"headers\": {\n \"Authorization\": \"Bearer memora_live_REPLACE_WITH_YOUR_KEY\"\n }\n }\n }\n}\n```\n\nCodex (`~/.codex/config.toml`), with the key in the `MEMORA_API_KEY`\nenvironment variable:\n\n```toml\n[mcp_servers.memora]\nurl = \"https://memory.example.com/mcp\"\nbearer_token_env_var = \"MEMORA_API_KEY\"\n```\n\nClients that only run local stdio servers, such as the Claude Desktop config\nfile, can bridge with `mcp-remote` (needs Node.js):\n\n```json\n{\n \"mcpServers\": {\n \"memora\": {\n \"command\": \"npx\",\n \"args\": [\n \"-y\", \"mcp-remote\", \"https://memory.example.com/mcp\",\n \"--header\", \"Authorization: Bearer memora_live_REPLACE_WITH_YOUR_KEY\"\n ]\n }\n }\n}\n```\n\nSome clients send the key as `X-API-Key: <key>` instead. Both headers are\naccepted.\n\n### With OAuth\n\nClients that support MCP authorization (for example Claude and ChatGPT custom\nconnectors, or Claude Code without a `--header`) can connect with only the URL:\n\n```bash\nclaude mcp add --transport http memora https://memory.example.com/mcp\n```\n\nThe flow:\n\n1. The client calls `/mcp` without credentials and gets `401` with\n `WWW-Authenticate: Bearer resource_metadata=\"https://memory.example.com/.well-known/oauth-protected-resource\"`.\n2. It reads the protected resource metadata (RFC 9728) and the authorization\n server metadata at `/.well-known/oauth-authorization-server` (RFC 8414; also\n served at `/.well-known/openid-configuration` and under a `/mcp` suffix).\n3. It registers itself with dynamic client registration at\n `POST /oauth/register` (RFC 7591), or uses an HTTPS client metadata document\n URL as its `client_id`. The owner can also register clients in the web UI.\n Redirect URIs must be HTTPS, or plain HTTP on `localhost`, `127.0.0.1` or\n `[::1]`.\n4. It opens `/oauth/authorize` (authorization code with PKCE `S256` only). The\n browser lands on the Memora sign-in page, and the signed-in owner approves or\n denies the connection on a consent card. Codes are valid for 10 minutes.\n5. It exchanges the code at `POST /oauth/token` and receives an access token and\n a refresh token. The only OAuth scope is `mcp`.\n\nThe access token is a regular Memora API key named after the client. It starts\nwith the default scopes (`mcp`, `read`, `write`) and every tool, and it shows up\non the Keys page like any other key, so you can restrict, disable or delete it\nthere. The access token has no expiry. A `refresh_token` grant replaces it with\na fresh one (the old token stops working at once) and rotates the refresh token.\nDisabling or deleting the key ends the connection.\n\nSet `MEMORA_BASE_URL` (for example `https://memory.example.com`) when the server\nruns behind a proxy, so the issuer and endpoint URLs in the metadata are the\npublic ones. Without it the server derives them from the request headers.\n\n### Test from a shell\n\n```bash\ncurl -s -X POST http://localhost:8400/mcp \\\n -H \"Authorization: Bearer memora_live_REPLACE_WITH_YOUR_KEY\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/list\"}'\n```\n\n## Discovery card\n\n`GET /.well-known/mcp.json` needs no auth and returns:\n\n| Field | Value |\n|---|---|\n| `name` | `memora` |\n| `version` | The server version |\n| `description` | One-line description of the server |\n| `mcp` | `{endpoint: \"/mcp\", transports: [\"streamable-http\"], protocolVersion: \"2025-06-18\"}` |\n| `auth` | `{type: \"api-key\", headers: [\"Authorization: Bearer <key>\", \"X-API-Key: <key>\"], oauth: \"/.well-known/oauth-authorization-server\"}` |\n| `capabilities` | `{tools: true, resources: true, prompts: false}` |\n| `tools` | Every catalog tool as `{name, category, description, enabled}`. `enabled` is `false` for tools switched off on this server. Admin tools are not listed. |\n| `resources` | `[{uri, name}]` for the three resources below |\n\nThe card is the same for every caller. To see what a given key may call, use\n`tools/list` with that key.\n\n## Methods\n\n| Method | Purpose |\n|---|---|\n| `initialize` | Handshake. Returns `protocolVersion`, `serverInfo` (`{name, version}`) and `capabilities` (`tools` with `listChanged: true`, `resources` with `listChanged: false`). |\n| `notifications/initialized` | Client notification. Without an `id` it gets `202 Accepted`. |\n| `tools/list` | The tools the caller may use, each with `name`, `description` (what it does and when to use it), `inputSchema`, and `_meta.category`. |\n| `tools/call` | Runs one tool. Params are `{name, arguments}`. |\n| `resources/list` | Lists the three resources below. |\n| `resources/read` | Reads one resource. Params are `{uri}`. |\n\nThere are no prompts and no pagination cursors. The only notification the server\nsends is `notifications/tools/list_changed` (see Transport).\n\n### Resources\n\n| URI | Content |\n|---|---|\n| `memory://catalog` | Every catalog tool with `name`, `category`, `description`, `when`, and `inputSchema` (JSON) |\n| `memory://schema` | Data shapes for a note, a folder, the graph, and activity (JSON) |\n| `memory://guide` | A short guide for agents using the vault (Markdown) |\n\n`resources/read` returns `{contents: [{uri, mimeType, text}]}`.\n\n## Results and errors\n\nA successful tool call returns the tool's JSON result as text:\n\n```json\n{\n \"jsonrpc\": \"2.0\",\n \"id\": 2,\n \"result\": {\n \"content\": [{ \"type\": \"text\", \"text\": \"{...}\" }],\n \"isError\": false\n }\n}\n```\n\nA tool that fails (bad arguments, note not found, unknown tool name) returns the\nsame envelope with `isError: true` and the error message as the text. The HTTP\nstatus stays `200`.\n\nJSON-RPC errors:\n\n| Code | When |\n|---|---|\n| `-32700` | The body is not valid JSON (HTTP `400`). |\n| `-32600` | The body is not a JSON-RPC request object (HTTP `400`). |\n| `-32601` | Unknown method: `unsupported method: <method>`. |\n| `-32602` | `resources/read` with an unknown URI: `unknown resource: <uri>`. |\n| `-32003` | The tool exists but the caller may not use it. Messages: `tool not allowed for this API key: <name>`, `tool disabled on this server: <name>`, `API key lacks the 'write' scope for tool: <name>`. |\n\nHTTP errors before JSON-RPC runs:\n\n| Status | When |\n|---|---|\n| `401` | No key, or a key that is unknown, disabled, deleted or replaced by a roll (`invalid API key`). Carries a `WWW-Authenticate` header that points OAuth clients at the protected resource metadata. |\n| `403` | The key lacks the `mcp` scope (`{\"error\":\"API key lacks the 'mcp' scope\",\"required_scope\":\"mcp\"}`), or a browser request failed the same-origin check. |\n| `405` | Any method other than `POST`. |\n| `409` | No vault is configured yet. |\n| `429` | Rate limit or cooldown after failed attempts. |\n\n## What each key sees\n\n`tools/list` is filtered per caller:\n\n- A tool switched off on the server is hidden for everyone.\n- A key whose tool list is not `\"*\"` only sees the tools in its list.\n- A key without the `write` scope only sees read-only tools.\n- Admin tools are added for keys with the `admin` scope (and for browser\n sessions).\n\n`tools/call` on a tool that `tools/list` would hide returns `-32003`. Details\nare in [Tool switches and per-key permissions](contracts/tools-permissions.md).\n\n### Privacy rules\n\nThe owner can hide notes and folders from specific agents (web UI,\n`/api/privacy`, or the `privacy_*` admin tools). For an API key covered by a\nrule, every tool works as if the hidden paths did not exist: they are left out\nof listings, search, the graph, tags, events, logs, locks and folder metadata; a\nhidden path named in an argument is answered as not found, for reads and writes\nalike; and folder operations that would carry hidden items along are refused.\nIf the rules cannot be read, the key sees nothing (fail closed). Browser\nsessions are never filtered.\n\n## Tools\n\nR = read-only (needs only the `mcp` scope). W = changes the vault or server\nstate (also needs the `write` scope). Unless marked required, arguments are\noptional. Paths are vault-relative, for example `Projects/Plan.md`. A path\ncopied in the web app (Copy path in a note or folder menu) works as is as the\n`path` argument of `read_memory` and the other tools.\n\n### Notes (`note`)\n\n| Tool | | Arguments | Purpose |\n|---|---|---|---|\n| `list_memory` | R | none | Every note grouped by its folder, the full parent path (`Projects/Atlas`; `Root` for the top level): `{folder: [{path, name, folder, mtime}]}`. |\n| `read_memory` | R | `path` (string, required) | Markdown body, frontmatter, tags and backlinks of one note. A `\\` in a path is read as `/`; replies echo the normalized path. |\n| `create_memory` | W | `title` (string, required), `folder` (string relative to the vault, default `Memory` when omitted or empty; `Root` for the top level), `content` (string; default is a stub with `created` frontmatter and a heading) | Creates `<folder>/<title>.md` and returns `{ok, path}`. A trailing `.md` in the title is dropped; `/` and `\\` in a title, an absolute folder and a folder that is a note are refused. Spaces are kept; `: * ? \" < > | # ^ [ ]` and a leading dot are removed and names are cut at 80 characters; the reply then adds `renamed_from` and a `note`. A note whose name differs only in case from an existing one is refused. |\n| `save_memory` | W | `path` (string, required), `content` (string, required) | Replaces the whole note. |\n| `patch_memory` | W | `path` (string, required), `ops` (array, required) | Partial edits. Each op is an object: `{op:\"append\", text}`, `{op:\"prepend\", text}`, `{op:\"replace\", find, with}`, `{op:\"set_field\", field, value}`, `{op:\"add_tag\", tag}`, `{op:\"remove_tag\", tag}`. |\n| `delete_memory` | W | `path` (string, required), `permanent` (boolean, default false) | Moves a note to the Trash (`.Trash`), remembering where it came from and who deleted it: `{ok, path, trashed, to}`. `list_trash` shows it and `restore_trash` brings it back. `permanent: true` deletes it for good instead (`{ok, path, permanent}`) and is refused for keys without the `admin` scope. With version history on, every earlier version is erased from the history as well (every name the note had, its trash record and the commit messages naming it; other notes keep their versions but their revision ids change), so no one, agents included, can read it again. |\n| `move_memory` | W | `path` (string, required), `folder` (string, required; relative to the vault, `Root` for the top level) | Moves a note into another folder. Wikilinks resolve by note name, so they keep working. |\n| `rename_memory` | W | `path` (string, required), `new_name` (string, required) | Renames a note in its folder. |\n| `upload_image` | W | `path` (string, required: the note the image belongs to), `name` (string, required, e.g. `diagram.png`), `data` (string, required: base64 or a `data:image/...;base64,` URL), `alt` (string), `append` (boolean, default false) | Stores a PNG, JPEG, WebP or GIF in the note's own folder (checked by content; the upload limit in Settings, Images applies, 5 MB by default). Identical bytes reuse the existing file; a taken name gets `-1`, `-2` ...: `{ok, path, name, bytes, url, markdown}`. Show it in the note with the returned `markdown` line, `![alt](path:name.png)`; `append: true` adds that line to the end of the note. The image then moves, goes to the Trash, is restored and is deleted with its note. |\n| `list_images` | R | `folder` (string; `Root` or empty for the top level) or `path` (a note) | The images of one folder (not its sub folders), each with `used_in` (the notes and sections that show it); with `path`, the images that note shows and every image of its folder. |\n\n### Search (`search`)\n\n| Tool | | Arguments | Purpose |\n|---|---|---|---|\n| `get_stats` | R | none | Counts of notes, links and folders. |\n| `search_memory` | R | `q` (string, required; `query` is accepted as an alias), `limit` (integer, default 12) | Search titles and bodies. Supports `tag:x` and `#x`. |\n\n### Query (`query`)\n\n| Tool | | Arguments | Purpose |\n|---|---|---|---|\n| `query_memory` | R | `folder`, `tags`, `author`, `type`, `status` (strings), `limit` (integer, default 50) | Filter notes by frontmatter. |\n| `find_similar` | R | `path` (string, required), `limit` (integer, default 8) | Notes most similar to one note (shared tags and words). |\n| `suggest_links` | R | `path` (string, required), `limit` (integer, default 8) | Similar notes not yet linked from this one. |\n| `list_tags` | R | none | Every tag with its usage count. |\n| `rename_tag` | W | `old` (string, required), `new` (string, required) | Renames a tag across the vault. |\n| `merge_tag` | W | `a` (string, required), `b` (string, required) | Merges tag `a` into tag `b` across every note. |\n\n### Tags (`tag`)\n\n| Tool | | Arguments | Purpose |\n|---|---|---|---|\n| `get_tags` | R | `path` (string; not in the advertised schema) | Every tag with its count, or the tags of one note when `path` is given. |\n| `search_by_tag` | R | `tag` (string, required), `limit` (integer, default 50; not in the advertised schema) | Every note carrying a tag. |\n| `add_tags` | W | `path` (string, required), `tags` (string, required, comma-separated) | Adds tags to a note. A leading `#` is stripped. |\n| `remove_tags` | W | `path` (string, required), `tags` (string, required, comma-separated) | Removes tags from a note. |\n| `set_tags` | W | `path` (string, required), `tags` (string, required, comma-separated) | Replaces a note's tag list. |\n\n### Folders (`folder`, `ops`)\n\n| Tool | | Arguments | Purpose |\n|---|---|---|---|\n| `list_folders` | R | none | `{count, folders: [{name, count, color}]}`. |\n| `create_folder` | W | `name` (string, required) | Creates a folder. |\n| `rename_folder` | W | `folder` (string, required), `name` (string, required, one segment) | Renames a folder in place. Notes, sub folders, color and icon move along. |\n| `move_folder` | W | `folder` (string, required), `into` (string; empty or `Root` = top level) | Moves a folder with everything in it. |\n| `move_folder_contents` | W | `folder` (string, required), `into` (string; empty = top level) | Moves everything inside a folder into another folder, then removes the empty folder. Name clashes get a `-N` suffix. |\n| `delete_folder` | W | `folder` (string, required), `into` (string), `mode` (`move` or `trash`) | Deletes a folder. By default its notes (at any depth) move to the folder's parent (Root for a top-level folder), keeping the sub folder structure below it; wikilinks to them are rewritten. `into` sends them to another existing folder instead (`Root` = top level). `mode: \"trash\"` moves every note to `.Trash` instead (`list_trash` / `restore_trash` bring them back) and cannot be combined with `into`. Other files in the folder are deleted. |\n| `folder_stats` | R | `folder` (string, required) | Note count and metadata for one folder. |\n| `get_folder_meta` | R | `folder` (string) | Color, icon and description of one folder, or of every folder. |\n| `set_folder_meta` | W | `folder` (string, required), `color`, `icon`, `desc` (strings) | Sets folder display metadata. A field sent as an empty string is cleared. |\n\n### Graph (`graph`)\n\n| Tool | | Arguments | Purpose |\n|---|---|---|---|\n| `get_graph` | R | none | Whole graph: `{nodes: [{id, path, folder, color, degree, tags, mtime}], links: [{source, target}]}`. |\n| `get_neighbors` | R | `path` (string, required), `depth` (integer, default 1) | Notes within N hops. |\n| `get_subgraph` | R | `path` (string, required), `depth` (integer, default 1), `max_nodes` (integer, default 60) | Subgraph around one note. |\n| `find_path` | R | `source` (string, required), `target` (string, required) | Shortest wikilink path between two notes. |\n| `get_hubs` | R | `limit` (integer, default 10) | Most connected notes. |\n| `get_isolated` | R | none | Notes with no links in or out. |\n| `link_stats` | R | `path` (string, required) | Outgoing, incoming and unresolved links of one note. |\n| `broken_links` | R | none | Wikilinks pointing at notes that do not exist. |\n\n### Versioning (`version`)\n\n| Tool | | Arguments | Purpose |\n|---|---|---|---|\n| `get_history` | R | `path` (string, required), `limit` (integer, default 20, at least 1) | Git history of a note, newest first, always an array of `{rev, date, author, message, version, total}` (plus `path` for commits under an earlier name: the history follows renames). `author` is the agent or user whose call made the change. `version` numbers the revisions from 1 (the oldest) to `total` (the current one), whatever `limit` is. |\n| `get_note_at` | R | `path` (string, required), `rev` (string, required) | `{ok, path, rev, content}` at a revision. `rev` is one revision: a `rev` from `get_history`, `snap-<label>`, `HEAD~1` or `HEAD@{<date>}`. Unknown revisions, dates before the history and empty `rev` are errors. |\n| `diff` | R | `path` (string, required), `rev_a` (string, required), `rev_b` (string) | `{path, from, to, changed, diff}` between two revisions, or `rev_a` against the current note. Ranges (`a..b`) and unknown revisions are errors. |\n| `restore_memory` | W | `path` (string, required), `rev` (string, required) | Restores a note to a revision (a new commit). Give the current path; content under an earlier name is found. Restoring the old path of a renamed note is refused and names the current one. |\n| `snapshot` | W | `label` (string, required) | Commits pending changes and tags the last commit `snap-<label>` (letters, digits, `.`, `_`, `-`; spaces become `-`; at most 40 characters; must be new). Use the tag as `rev`. |\n| `soft_delete` | W | `path` (string, required) | Moves a note to `.Trash` and remembers where it came from. |\n| `list_trash` | R | none | Notes in `.Trash`, newest first: `{name, path, original, deleted, by, title}` (`by` = `{id, name, kind}` of who deleted it, null when unknown). |\n| `restore_trash` | W | `name` (string, required; `.md` optional), `into` (string) | Restores a note from `.Trash` to the path it was deleted from, or into the folder `into` (`Root` = top level). |\n\nAll versioning tools except `soft_delete`, `list_trash` and `restore_trash`\nneed version history on (see [CONFIGURATION.md](CONFIGURATION.md#version-history));\notherwise they answer \"version history is off\".\n\n### Bulk writes (`write`)\n\n| Tool | | Arguments | Purpose |\n|---|---|---|---|\n| `batch_create` | W | `notes` (array, required) of `{title (required), folder (default `Memory`), content}` | Creates many notes in one call; titles and folders follow `create_memory`. Every item is checked first and nothing is created when one is malformed (missing title, wrong type, unknown key). The reply has one result per item: `{ok, path}` or `{ok: false, item, title, error}`. |\n| `duplicate_memory` | W | `path` (string, required) | Copies a note as `<name>-copy` in the same folder (a long name is shortened so the suffix fits in 80 characters). |\n| `merge_memory` | W | `paths` (array of strings, required: existing notes, each once, not `into`), `into` (string, required; `.md` optional) | Appends the body of each source, without its frontmatter, to `into` under `## from <name>`, and adds the sources' tags to the target's tags. `into` is created when missing. The sources are kept. Returns `{ok, into, created, merged, sources, tags_added}`. |\n| `template_create` | W | `template` (string, required; a note in `Templates/`, as `Meeting` or `Meeting.md`), `title` (string, required), `folder` (string, default `Root`), `variables` (object) | Creates a note from a template with `{{var}}` substitution. `{{title}}` (the note title) and `{{date}}` (today, `YYYY-MM-DD`) are built in unless given in `variables`. Only notes in `Templates/` can be templates. |\n| `bulk_replace` | W | `find` (string, required), `replace` (string, required), `folder` (string), `regex` (boolean, default false), `dry_run` (boolean, default false) | Find and replace across notes. `find` must not be empty or (with `regex`) match an empty string. `folder` includes its subfolders (`Root` = top level only); a missing folder is an error. With `regex`, `replace` expands `$1` / `${name}` (`$$` is a literal `$`); unknown groups are errors. Needs `write` even with `dry_run`. |\n| `bulk_delete` | W | `paths` (array of strings), `folder` (string) | Moves many notes to `.Trash` (recoverable with `restore_trash`), by list and / or folder (with subfolders). Any invalid path (missing, outside the vault, a folder, not a note) refuses the whole call and is listed. |\n\n### Collaboration (`collab`)\n\n| Tool | | Arguments | Purpose |\n|---|---|---|---|\n| `lock_node` | W | `path` (string, required), `owner` (string, default the caller), `ttl` (integer seconds, default 300) | Soft lock on a note. |\n| `release_lock` | W | `path` (string, required), `owner` (string, default the caller) | Releases a lock. |\n| `get_locks` | R | none | Active locks. |\n| `mention_agent` | W | `agent` (string, required), `path` (string, required), `message` (string) | Writes `> @agent: message` into a note. With agent `mnemo`, Memora's own agent answers it in the note (the request is struck through and the reply quoted under it). |\n| `get_assignments` | R | `agent` (string) | Notes with `assigned_to` in their frontmatter. |\n\n### Activity and health (`ops`)\n\n| Tool | | Arguments | Purpose |\n|---|---|---|---|\n| `get_events` | R | `since` (number, unix time), `folder`, `actor` (strings), `limit` (integer, default 50) | Recent note created, updated and deleted events. |\n| `presence` | R | `window` (integer seconds, default 300) | Agents active within the window. |\n| `get_logs` | R | `range` (string, default `1d`; also `7d`, `today`, `yesterday`), `actor` (string), `limit` (integer, default 100) | Activity log for a period. |\n| `search_logs` | R | `q` (string, required), `range` (string, default `7d`), `actor` (string), `limit` (integer, default 100) | Keyword search in the activity log. |\n| `digest` | R | `folder` (string), `since` (number) | Event counts per actor and per type. |\n| `healthcheck` | R | none | Note count, broken links, orphans and git status. |\n| `stale_detection` | R | `days` (integer, default 30) | Notes untouched for more than N days. |\n\n### Identity (`identity`)\n\n| Tool | | Arguments | Purpose |\n|---|---|---|---|\n| `set_my_name` | W | `name` (string, required) | Sets the display alias shown in the activity feed and log. |\n| `set_my_color` | W | `color` (string, required; `#rrggbb`, or `\"\"` to reset) | Sets the calling API key's display color. Fails for browser sessions. |\n| `list_actors` | R | none | `{me, aliases}`: the caller and every known alias. |\n\n### Import and export (`interop`)\n\n| Tool | | Arguments | Purpose |\n|---|---|---|---|\n| `export_memory` | W | `paths` (array of strings, required; notes or folders), `out_path` (string), `overwrite` (boolean, default false) | Writes a zip of the given paths to the server's exchange folder and returns `{ok, path, name, bytes, replaced}`, where `path` and `name` are the zip's file name. Every path must exist; missing ones are listed and nothing is written. `out_path` is a plain file name ending in `.zip` (letters, digits, `.`, `_`, `-`, at most 120 characters); the default is `memora-export-<unix seconds>.zip`. An existing zip of that name is only replaced with `overwrite: true`. |\n| `import_memory` | W | `zip_path` (string, required), `overwrite` (boolean, default false) | Imports the `.md` notes of a zip in the exchange folder, by the file name `export_memory` returned. Returns `{ok, added, overwritten, skipped, unsafe, failed}`: `skipped` are existing notes kept (no `overwrite`), `unsafe` are entries with an absolute or escaping path (`{entry, reason}`), `failed` are entries too large or unreadable. |\n\nThe exchange folder is `exchange` in the state directory (`<MEMORA_STATE>/exchange`),\none per Memora instance, created with mode 0700.\nTools never read or write anywhere else on the server's disk.\n\n### Checks, to-dos and pins (`ux`)\n\n| Tool | | Arguments | Purpose |\n|---|---|---|---|\n| `get_todos` | R | `path` (string) | Open checklist items (`- [ ]`) in one note or the whole vault. |\n| `follow_ups` | R | none | Notes whose status is still awaiting action. |\n| `validate_memory` | R | `path` (string, required) | Checks a note: frontmatter present and well formed, a valid `created` date, tags, and broken links (named in the issue and listed in `broken_links`). |\n| `list_pins` | R | none | The owner's pinned notes and folders in sidebar order: `{count, pins:[{kind, path, position, missing}]}`. `missing` is true when the path no longer exists (renamed or deleted outside Memora). |\n| `pin` | W | `path` (string, required), `kind` (`note` or `folder`; default: what the path is on disk), `position` (integer from 0; default: the end) | Pins an existing note or folder, or moves its pin. A note path may leave out `.md`. At most 200 pins. Returns the list. |\n| `unpin` | W | `path` (string, required), `kind` | Removes a pin; the note or folder is not touched. Returns the list with `removed`. |\n\nPins are shared by every browser of the owner (`/api/pins`). They follow their note or\nfolder through renames and moves done by Memora (over MCP or HTTP, including notes inside\na moved folder) and are removed when the item is deleted or moved to the trash; deleting a\nfolder removes every pin under it. A key whose privacy rules hide a path neither lists\nnor changes its pin, and `position` counts only the pins the key can see.\n\n### Admin tools (`admin`)\n\nListed and callable only for keys with the `admin` scope (and for browser\nsessions). They are not part of the switchable catalog: global tool switches and\na key's tool list do not apply to them, and they do not need `write`.\n\n| Tool | Arguments | Purpose |\n|---|---|---|\n| `admin_list_tools` | none | `{tools: [{name, category, description, enabled}]}` for every catalog tool. |\n| `admin_set_tool` | `name` (string, required), `enabled` (boolean, required) | Switches a catalog tool on or off for every key. Returns `{ok, name, enabled}`. |\n| `privacy_list` | `path` (string), `kind` (`node` or `folder`) | Without `path`: every privacy rule. With `path`: that note or folder's own rule, the folder rules it inherits, and which agents can see it. |\n| `privacy_set` | `path` (string, required), `agents` (array of key ids or names, required; a comma-separated string also works), `kind` (`node` or `folder`), `mode` (`deny` or `allow_only`, default `deny`) | Replaces the rule on a path. `deny` hides it from the listed agents; `allow_only` hides it from every other agent, including keys created later. `deny` with no agents removes the rule. A node rule follows its note through renames and moves. |\n| `privacy_clear` | `path` (string, required), `kind` (`node` or `folder`) | Removes the path's own rule. Rules on parent folders still apply. |\n\nWhen `kind` is omitted it is taken from the path on disk: a folder if a folder\nexists there, otherwise a note.\n\n## Identity and tracking\n\nEvery tool call is published to the web UI's realtime activity stream as an\n`ai_activity` start and end pair, named after the API key (or the signed-in\nuser), with the note paths involved. Calls are also counted per key: the Keys\npage and `GET /api/keys` show each key's `uses`, `last_ip`, and the tools it has\ncalled recently. `initialize` registers the connection under the key's name\n(`GET /api/aliases`). `set_my_name` changes the alias shown in the activity\nfeed and log, and `set_my_color` changes the key's color in the UI. See\n[API.md](API.md) for the HTTP endpoints.\n"},{"file":"docs/API.md","slug":"api","title":"HTTP API","text":"# HTTP API\n\nThe `memora` binary serves the HTTP API, the MCP endpoint, the OAuth endpoints,\nthe web UI, and the WebSocket on one port. This document lists the HTTP endpoints.\n\n## Authentication\n\nThe Auth column in the tables below uses these levels:\n\n- None: reachable without credentials.\n- Session: requires the `memora_sess` cookie set by a successful login.\n- Key (`scope`): an API key sent as `Authorization: Bearer <key>` or `X-API-Key: <key>`\n that carries the named scope.\n- Session or key (`scope`): either of the above.\n- Session only: an API key is not enough. API keys get `401` (or `403` where noted).\n- +CSRF: the same-origin check described below applies.\n\n### API key scopes\n\nA key carries any of the scopes `mcp`, `read`, `write`, and `admin`. New keys get\n`mcp`, `read`, and `write` unless other scopes are requested. The scope a route\nneeds is decided by its path and method:\n\n| Scope | Routes |\n|---|---|\n| `mcp` | `/mcp` |\n| `admin` | `/api/tools`, `/api/keys` and `/api/keys/*`, `/api/access` and `/api/access/*`, `/api/logs/settings`, `/api/settings/server`, `/api/oauth/clients` and `/api/oauth/clients/*`, `/api/privacy` and `/api/privacy/*`, `/api/trash/delete`, `/api/trash/empty`; deleting for good with `/api/delete` |\n| `read` | Every other `GET` or `HEAD` under `/api/` |\n| `write` | Every other method under `/api/` |\n\nA key without the needed scope gets `403 {error, required_scope}`. A missing key\ngets `401`; for `/mcp` the `401` carries a `WWW-Authenticate` header,\n`Bearer resource_metadata=\"<base>/.well-known/oauth-protected-resource\"`, so OAuth\ncapable clients can start sign-in. An invalid key gets `401` and is logged; an\nIP that keeps presenting invalid keys is put on a cooldown (`429`).\n\n`/api/auth/*` never accepts an API key: without a valid session it answers `401`.\n\nAPI keys see the vault through their privacy rules (see [Privacy](#privacy)):\nnotes and folders hidden from a key behave as if they do not exist. A browser\nsession sees everything.\n\n### CSRF\n\nWrite endpoints that accept a session check the request origin whenever a\nsession cookie is present: `Origin` (or, without it, `Referer`) must match the\nrequest `Host` (or an `X-Forwarded-Host` sent by a trusted proxy), and\n`Sec-Fetch-Site: cross-site` is refused. A failed check is\n`403 {\"error\":\"origin mismatch\"}`. Requests without a session cookie (API-key\nclients) pass, since a browser cannot attach an API key on its own.\n\nThe public auth forms (`/api/auth/login`, `/api/auth/verify`,\n`/api/auth/bootstrap`, `/api/auth/reset`) also refuse a foreign or `null`\n`Origin` when no cookie exists yet. A request with neither `Origin` nor\n`Referer` (curl, the CLI) passes.\n\n### Locked instance\n\nWhile the instance is LOCKED, `/api/*` and `/mcp` answer\n`423 {error, locked: true, hint}` except for `/api/auth/state`, `/api/auth/verify`,\n`/api/auth/login`, `/api/auth/logout`, `/api/auth/bootstrap`, and\n`/api/auth/reset`. Other pages redirect to `/login?locked=1`; static assets,\n`/login`, `/logout`, `/healthz`, and `/favicon.ico` are still served.\n`/api/auth/login` itself answers `423` while locked.\n\n### Vault not configured\n\nUntil a vault folder is configured, `/mcp` and every `/api/*` route except\n`/api/auth/*`, `/api/settings*`, `/api/config`, `/api/keys*`, `/api/tools`,\n`/api/access*`, and `/api/ui/*` answer\n`409 {\"error\":\"vault not configured\", \"needs_vault\":true}`.\n\n### Limits and other gates\n\n- Requests for a host outside the configured domain list get a bare `404`.\n- Access rules (see `/api/access`) can block a caller:\n `403 {\"error\":\"access denied by stack rule\", ip}`.\n- Per-IP rate limits answer `429` with a `Retry-After` header and\n `{error, limited, cooldown, retry_after}`. Login, code check, setup, reset, profile,\n password, and username changes have a stricter limit and a cooldown after\n repeated failed attempts. Requests from the machine itself and `/healthz` are\n not limited.\n- A request that takes longer than 30 seconds is answered with `408`.\n- A password hashing pool that is busy answers `503` with `Retry-After: 2`.\n- `GET` answers under `/api/` (except `/api/auth/*`) are gzip-compressed when the\n request sends `Accept-Encoding: gzip`. Pages, writes, sign-in, `/mcp` and\n server-sent events are never compressed.\n\nResponses are JSON unless stated otherwise. Errors are `{\"error\": \"...\"}`. Vault\nerrors map to `404` for not-found (including paths hidden from the caller) and\n`400` for bad input.\n\n## Health and discovery\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/healthz` | None | `{ok, server}` for unauthenticated callers from other machines. A signed-in browser or a caller on the same machine gets `{ok, server, version, vault_configured, vault, armed, locked, base_url, base_url_configured}`. |\n| GET | `/.well-known/mcp.json` | None | The MCP discovery card: `{name, version, description, mcp, auth, capabilities, tools, resources}`. `tools` lists the full catalog with `enabled` per tool. |\n| GET | `/tools` | None | An HTML rendering of the tool catalog. A signed-in browser gets the app shell instead. |\n| POST | `/mcp` | Key (`mcp`), or Session (+CSRF) | MCP over streamable HTTP (JSON-RPC in, JSON-RPC out). See [MCP.md](MCP.md). A session has full access; a key is limited by its tool grant. Notifications get `202` with no body. Malformed JSON is `400` with a JSON-RPC error. Other methods get `405` with `Allow: POST`. |\n\n## Auth\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/api/auth/state` | None | `{bootstrap, realm, min_password_len, gateway, armed, locked, setup_hint, ready, checks:{vault, state}, code_required, cooldown, vault_configured}`. Adds `signed_out` (`password_changed` or `signed_out_remotely`) when the browser's session was ended on purpose, and `mode`, `expires_in`, `ttl` while a setup or reset window is open. |\n| POST | `/api/auth/verify` | None (+CSRF) | Checks the setup code shown on the server before the setup or reset form is shown. Body: `{code}`. Returns `{ok, mode, expires_in, user}`. `403` when no window is open or the instance is not ready. A wrong code answers `403 {error, burned:false}` and counts against the caller IP's budget of 3 wrong codes (then `429`); after 50 wrong codes in one window the window closes and the code is void: `403 {error, burned:true}`. |\n| POST | `/api/auth/login` | None (+CSRF) | `{ok, user, expires_in, redirect}` and sets the session cookie. Body: `{username, password}`. `400` when a field is missing, `401` on bad credentials, `403` if the account is disabled, `423` if locked, `429` during a cooldown of the caller IP (there is no account-wide lockout; see DEPLOYMENT.md, Failed sign-ins). |\n| POST | `/api/auth/logout` | None (+CSRF) | `{ok:true}`. Ends the session named by the cookie, if any, and clears the cookie. |\n| POST | `/api/auth/bootstrap` | None (+CSRF) | Creates the owner account. Body: `{code, username, password}`. Returns `{ok, user, redirect, persisted}` and sets a session cookie. The username is stored lowercase. `400` for an invalid username or password length; `403` unless a window is open, the code is right, the instance is ready, and no account exists. |\n| POST | `/api/auth/reset` | None (+CSRF) | Sets a new password for the single account, and may rename it. Body: `{code, username, password}`. Returns `{ok, user, persisted}`. Signs out every session. `400` for invalid input; `403` unless a window is open, the code is right, and an account exists. |\n| POST | `/api/auth/profile` | Session only (+CSRF) | With `password` in the body, changes the password exactly like `POST /api/settings/password` (body `{current, password, confirm}`). Otherwise sets `display_name` (at most 48 characters) and returns `{ok, changed, persisted, user, password_changed:false}`; with no `display_name` it returns `{ok, changed:false}`. |\n| GET | `/api/auth/me` | Session only | `{authenticated, user, enabled, expires_in}`. `401` without a session. |\n| GET | `/api/auth/events` | Session only | Recent entries of the security activity log, newest first: `{events:[{at, event, ip, user, detail, actor, actor_kind, actor_id}], count}`. `user` is the stored actor (`key:<id>` for API-key calls); `actor` is the display name (the key's current name, falling back to its id; the username for the browser), `actor_kind` is `agent` or `user` (null when there is no actor). Query: `limit` (default 200, max 2000), `q`. |\n\n## Pages\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/login` | None | The sign-in page. A signed-in browser is redirected to `/` unless the instance is locked or the query has `oauth` (the OAuth consent card). |\n| POST | `/logout` | None (+CSRF) | Ends the session, clears the cookie, and redirects to `/login`. With a session cookie the request must be same-origin (`403` otherwise); other methods get `405`. The web UI uses `POST /api/auth/logout`. |\n| GET | `/`, `/index.html` | Session | The web app shell. Without a session: `302` to `/login`. `503` when the UI assets are not installed. |\n| GET | App routes (see below) | Session | The same app shell as `/`. Without a session: `302` to `/login?r=<path>`, so sign-in returns to the page. |\n\nApp routes are the web app's client-side pages: `/brain`, `/nodes`, `/graph`,\n`/canvas`, `/tags`, `/activity`, `/agents`, `/access`, `/settings`,\n`/overview`, `/welcome`, `/trash`, `/mnemo`, the older names `/home`, `/vault`, `/logs`, `/keys`,\nand `/node/` or `/node/<percent-encoded vault path>`. The path is never used to\nread a file; a path holding NUL or another control character (raw or\npercent-encoded) is `400`. `/tools` is an app route for a signed-in browser and\nthe public tool catalog otherwise.\n\nHTML pages are sent with `Cache-Control: no-cache, no-store, must-revalidate`\nand a per-response CSP nonce.\n\nAny other `GET` that asks for HTML (`Accept: text/html`), is outside `/api/`,\n`/mcp`, `/oauth`, and `/.well-known`, and has no file extension in its last\nsegment gets the app shell (which shows its \"page not found\" view). Every other\nunmatched request is `404 {\"error\":\"not found\"}`.\n\n## Static assets\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/assets/{name}` | None | Static UI assets (whitelisted filenames only, else `404`). |\n| GET | `/app.js`, `/app.css`, `/login.css` | None | The UI bundle and styles. Revalidated on every load (`Cache-Control: no-cache`, ETag). |\n| GET | `/favicon.svg` | None | The icon. |\n| GET | `/favicon.ico` | None | `204` with no body. |\n| GET | `/manifest.webmanifest`, `/sw.js`, `/robots.txt`, `/offline.html`, `/icon-192.png`, `/icon-512.png`, `/icon-maskable-512.png`, `/apple-touch-icon.png` | None | PWA files and `robots.txt`. Images and the manifest are cached for 5 minutes; code is revalidated on every load. |\n\n## Vault\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/api/tree` | Session or key (`read`) | Notes grouped by folder: `{folder: [{path, name, folder, mtime, title}]}`; `title` is what the app shows (front matter `title`, else the first `# heading`, else the file name with `_` as spaces). |\n| GET | `/api/folders` | Session or key (`read`) | Every folder the caller may see, empty and nested ones included (`{folders:[path]}`); dot folders such as `.Trash` are left out. |\n| GET | `/api/note` | Session or key (`read`) | `{path, name, content, html, tags, frontmatter, backlinks, size, mtime}`. Query: `path` (`400` when empty). |\n| GET | `/api/vault/file` | Session or key (`read`) | The raw bytes of one image file in the vault (PNG, JPEG, GIF, WebP, AVIF, BMP, ICO; never SVG). Query: `path` (vault-relative). The file content must match its type. At most 10 MiB (`413`). Sent with an `ETag` (`304` on `If-None-Match`), `Cache-Control: private, max-age=300`, and a sandbox CSP. `400` invalid path, `403` path not allowed, `404` not found, `415` not an image. |\n| GET | `/api/folder-meta` | Session or key (`read`) | Folder metadata keyed by folder name. Query: `folder` (optional). |\n| POST | `/api/save` | Session or key (`write`, +CSRF) | `{ok, path}`. Body: `{path, content}`. Overwrites the note. |\n| POST | `/api/create` | Session or key (`write`, +CSRF) | `{ok, path}`. Body: `{title, folder?, content?}`. |\n| POST | `/api/rename` | Session or key (`write`, +CSRF) | `{ok, path}` with the new path. Body: `{path, name}`. |\n| POST | `/api/move` | Session or key (`write`, +CSRF) | `{ok, path}` with the new path. Body: `{path, folder?}`. |\n| POST | `/api/delete` | Session or key (`write`; `admin` to delete for good, +CSRF) | `{ok:true}`. Body: `{path, mode?}`. Deletes the note for good (no trash); with version history on, its earlier versions are erased from the history too, so nothing can bring it back. Because that cannot be undone, an API key needs the `admin` scope for it (`403 {error, required_scope: \"admin\"}` otherwise, as MCP `delete_memory` with `permanent`); the owner's browser session may. `mode: \"trash\"` (what the web app sends) moves it to `.Trash` instead, remembering where it was and who deleted it: `{ok, trashed, to}`. |\n| GET | `/api/trash` | Session or key (`read`) | Notes in `.Trash` the caller may see, newest first: `{items: [{name, path, original, deleted, by, title}]}` (`by` = `{id, name, kind}`, null when unknown). Nothing is removed automatically. |\n| POST | `/api/trash/restore` | Session or key (`write`, +CSRF) | Body: `{name, into?}`. Back to where the note was deleted from (or into the folder `into`); a taken name gets `-1`, `-2` ...: `{ok, path, from, renamed?}`. 404 when the name is not in the trash. |\n| POST | `/api/trash/delete` | Session or key (`admin`, +CSRF) | Body: `{name}`. Deletes one trash entry for good: `{ok, deleted, name, history?}`. With version history on, the note is also erased from the history (every earlier version under every name it had, its trash record and its path in commit messages), and `history` is `{erased, ms, commits}`. Other notes keep their versions; their revision ids change. |\n| POST | `/api/trash/empty` | Session or key (`admin`, +CSRF) | Deletes every trash entry the caller may see, for good: `{ok, count, names, history?}`, erasing them from the version history in one rewrite (as `/api/trash/delete`). |\n| POST | `/api/folder` | Session or key (`write`, +CSRF) | `{ok, path}`. Body: `{name}`. |\n| POST | `/api/folder/rename` | Session or key (`write`, +CSRF) | `{ok, from, to, notes}`. Body: `{folder, name}`. |\n| POST | `/api/folder/move` | Session or key (`write`, +CSRF) | Moves a folder and everything in it. `{ok, from, to, notes}`. Body: `{folder, into}`; `into` empty or `Root` means the top level. |\n| POST | `/api/folder/move-contents` | Session or key (`write`, +CSRF) | Moves everything inside a folder into another one, then removes the emptied folder. Name clashes get a `-N` suffix. `{ok, from, to, moved}`. Body: `{folder, into}`; `into` empty or `Root` means the top level. |\n| POST | `/api/delete-folder` | Session or key (`write`, +CSRF) | Deletes a folder. Body: `{folder, into?, mode?}`. By default its notes move to the folder's parent (the top level for a top-level folder), keeping the sub folder structure below it, and wikilinks are rewritten: `{ok, deleted_folder, moved_to, moved, links_updated}` (`moved` lists the new paths; `moved_to_root` repeats it when they went to the top level). `into` names another existing folder for the notes (`Root` = top level). `mode: \"trash\"` moves every note to `.Trash` instead (restorable from the Trash on the Notes page, `/api/trash/restore`, or the MCP tools `list_trash` / `restore_trash`): `{ok, deleted_folder, mode, count, trashed}`. Other files in the folder are deleted. |\n| POST | `/api/folder-meta` | Session or key (`write`, +CSRF) | `{ok, folder}`. Body: `{folder, color?, icon?, desc?}`. |\n\nThe three folder operations also publish a `folder_changed` realtime event so\nopen browsers reload their tree.\n\n### Version history\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/api/history?path=&limit=` | Session or key (`read`) | A note's revisions, newest first (the vault's git history, following renames): `{path, total, versions: [{rev, date, author, message, version, total, path?, owner}]}`. `version` counts from 1 (the oldest) to `total` (the current one); `owner` is true when the signed-in owner made the change. `limit` defaults to 100 (at most 500). |\n| GET | `/api/note-at?path=&rev=` | Session or key (`read`) | The note as it was at one revision (a `rev` from `/api/history`, `snap-<label>`, `HEAD~1`, `HEAD@{<date>}`): `{path, rev, content, html}`, `html` rendered like `/api/note`. |\n| GET | `/api/diff?path=&a=&b=` | Session or key (`read`) | Unified diff of the note from revision `a` to `b`, or to the note as it is now when `b` is left out: `{path, from, to, changed, diff}`. |\n| POST | `/api/history/restore` | Session or key (`write`, +CSRF) | Body: `{path, rev}`. Gives the note its content from `rev` again as a new revision (restoring version 3 of 5 makes version 6; nothing is lost): `{ok, path, rev, changed, version, total}` (`changed` false when the note already had that content). |\n\nThe four history routes answer `409 {error, history: false}` while version history\nis off (the vault folder is not a git repository; see\n[CONFIGURATION.md](CONFIGURATION.md#version-history)) and `404` for a path that is\nnot in the vault or its history, or is hidden from the calling key. Web writes\n(save, create, rename, move, delete, restore) are committed with the caller as the\nauthor: the owner's username for the browser, the key's name for an API key.\n\n### Images\n\nImages live in the folder of the note that shows them, and a note shows one with\n`![alt](path:name.png)` (`path:` names a file in the note's own folder). Saving a\nnote that points with `path:Other/Folder/pic.png` to an image elsewhere copies that\nimage beside the note and rewrites the link, so notes never point across folders.\nImages follow their note: a move carries them, the Trash keeps them in\n`.Trash/.assets/<entry>/` until the note is restored (to the same or another\nfolder) or deleted for good, and a deleted folder takes its images along. An image\nthat another note of the same folder still shows is copied or kept instead.\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| POST | `/api/vault/image?note=<path>&name=<file>` | Session or key (`write`, +CSRF) | The raw image bytes as the body (PNG, JPEG, WebP or GIF, checked by content). Stored beside the note; identical bytes reuse the existing file, a taken name gets `-1`, `-2` ...: `{ok, path, name, bytes, url, markdown}` (`markdown` is the line to put in the note). `400` for another file type, a size above the upload limit, or a missing note. |\n| POST | `/api/vault/image/delete` | Session or key (`write`, +CSRF) | Body: `{path}`. Deletes one image file (the version history keeps it): `{ok, deleted}`. |\n| GET | `/api/vault/images?folder=<folder>` | Session or key (`read`) | The images of that one folder (not its sub folders or parents): `{folder, images: [{path, name, folder, bytes, mtime, url, used_in: [{note, title, heading}]}]}`. `heading` is the section that shows the image (`null` before the first heading). |\n| GET | `/api/vault/images?note=<path>` | Session or key (`read`) | `{note, folder, images, folder_images}`: the images the note shows, and every image of its folder. |\n| GET | `/api/vault/storage` | Session or key (`read`) | `{notes, note_bytes, images, image_bytes, total_bytes, max_image_bytes}`. |\n\n## Search and graph\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/api/search` | Session or key (`read`) | `{q, count, hits:[{path, name, folder, score, snippet}]}`, at most 20 hits. Query: `q`. Supports `tag:x` and `#x`. |\n| GET | `/api/stats` | Session or key (`read`) | `{notes, links, folders}`. |\n| GET | `/api/graph` | Session or key (`read`) | `{nodes:[{id, path, folder, color, degree, tags}], links:[{source, target}]}`. `tags` holds inline `#tags` plus frontmatter `tags` (as the note view reports them). Realtime `node_*` events' `node` payload carries `tags` too. |\n| GET | `/api/aliases` | Session or key (`read`) | `{aliases:[{alias, key_id, key_name, first_seen, last_seen, connections, actor, actor_kind}]}`: one record per API key that sent MCP `initialize`, kept in memory until the server restarts. `key_name` and `actor` are the key's current name (fallback: the id). |\n| GET | `/api/actors` | Session or key (`read`) | `{actors:[{actor, alias, display, events, tools, last_ip, last_ts, seen_minutes_ago}], count}`. `seen_minutes_ago` is `-1` when the actor has no events. |\n\n## Privacy\n\nPrivacy rules hide notes or folders from chosen agents (API keys). A rule has a\n`kind` (`node` or `folder`), a `path`, a `mode` (`deny`: hidden from the listed\nkeys; `allow_only`: hidden from every key except the listed ones), and a list\nof keys. Folder rules apply to everything inside the folder.\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/api/privacy` | Session or key (`admin`) | `{count, rules:[{id, kind, path, mode, keys:[{id, name, color}], created_at, updated_at}], agents:[{id, name, color, enabled}]}`. |\n| GET | `/api/privacy/path` | Session or key (`admin`) | The privacy state of one path: `{path, kind, own, own_rules, inherited, agents:[{id, name, color, enabled, can_see, hidden_by}], private}`. `own` is `{mode, keys}` or `null`. Query: `path`, `kind` (optional; defaults to `folder` when the path is a folder on disk, else `node`). |\n| PUT | `/api/privacy/path` | Session or key (`admin`, +CSRF) | Replaces the rule on a path. Body: `{path, kind?, mode, keys}`. `mode` defaults to `deny`; `keys` is a list of key ids (or unique key names). `deny` with no keys removes the rule. Returns the same shape as `GET`. |\n| DELETE | `/api/privacy/path` | Session or key (`admin`, +CSRF) | Removes the rule on a path. Query: `path`, `kind` (optional). Returns the same shape as `GET`. |\n\nChanges are written to the activity log and publish a `privacy_changed`\nrealtime event.\n\n## API keys, tools, and access\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/api/keys` | Session or key (`admin`) | `{count, keys:[{id, name, enabled, scopes, tools, prefix, created, color, revealable, uses, last_ip, used_tools}]}`. `tools` is `\"*\"` or a list of tool names; `revealable` says whether the secret can be shown again; `used_tools` lists recently used tools and routes. |\n| POST | `/api/keys` | Session or key (`admin`, +CSRF) | Creates a key. Body: `{name?, tools?, scopes?, color?}`. `tools` is `\"*\"` or a list of tool names; `scopes` a list of scope names (an empty list means the defaults). Returns `{ok, id, key, name, prefix, persisted, color, tools, scopes}`. The raw `key` is returned once. `400` for an unknown tool or scope. |\n| POST | `/api/keys/roll` | Session or key (`admin`, +CSRF) | New secret for an existing id. Body: `{id}`. Returns `{ok, id, key, prefix, persisted}`. `404` for an unknown id. |\n| POST | `/api/keys/reveal` | Session only (+CSRF) | Shows the secret of a key created or rolled from the dashboard again. Body: `{id, current}` where `current` is the owner's password. Returns `{ok, id, key}`. `403` for a wrong password; `429` after 5 wrong passwords (5 minute pause); `404 {error:\"not_stored\", message}` when the secret is not stored (for example keys created by the CLI or by OAuth). |\n| POST | `/api/keys/update` | Session or key (`admin`, +CSRF) | Body: `{id, name?, enabled?, tools?, scopes?, color?}`. `color` as `\"\"` or `null` clears it. Returns `{ok, id, name, enabled, color, tools, scopes, persisted}`. `400` for an unknown tool or scope, `404` for an unknown id. |\n| POST | `/api/keys/delete` | Session or key (`admin`, +CSRF) | `{ok, id, persisted}`. Moves the key to the trash. Body: `{id}`. |\n| POST | `/api/keys/restore` | Session or key (`admin`, +CSRF) | `{ok, id, persisted}`. Restores a deleted key. Body: `{id}`. `404` when no deleted key has that id. |\n| GET | `/api/tools` | Session or key (`admin`) | `{tools:[{name, category, description, enabled}]}`: the MCP tool catalog with the global on/off switch of each tool. |\n| POST | `/api/tools` | Session or key (`admin`, +CSRF) | Switches a tool on or off for every caller. Body: `{name, enabled}`. Returns `{ok, name, enabled}`. `400` for an unknown tool. |\n| GET | `/api/access` | Session or key (`admin`) | `{default_allow, rules, count}`. |\n| POST | `/api/access/test` | Session or key (`admin`) | `{action, would_lock_out_caller}` for the given address or domain. Body: `{ip?, domain?}`. |\n| POST | `/api/access/rules` | Session or key (`admin`, +CSRF) | `{ok, count, persisted}`. Body: `{op, kind, value, action}`. `op` is `add` (default) or `remove`. `kind` is `ip`, `range`, `cidr`, `domain`, or `all`; `value` is required unless `kind` is `all`. `action` is `allow` or `block` (default `block`). `remove` deletes every rule matching the given `kind` and `value`; `404` when none match. |\n| GET | `/api/config` | Session or key (`read`) | `{realm, min_password_len, session_ttl, vault, version, gateway, update}`. `update` is the cached release check: `{current, latest, available, url, checked_at, state, repo, stars}`, `state` one of `ok`, `none` (no release published), `error`, `disabled`, `pending`; `stars` is the repository's GitHub star count from the same check (`null` until known). |\n\n## Settings\n\nAll settings endpoints need a signed-in browser, except `/api/settings/server`, which also takes an API key with the `admin` scope.\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/api/settings` | Session only | `{user, vault_configured, vault, vault_suggested, vault_writable, stats, min_password_len, expires_in, session_ttl, session_max_age, state_dir}`. `stats` is `{notes, links, folders}` or `null` without a vault. |\n| POST | `/api/settings/password` | Session only (+CSRF) | Body: `{current, password, confirm}`. Returns `{ok, user, password_changed, revoked_sessions, persisted}`. Every other session is signed out. `400` for a short, mismatched, or unchanged password; `403` for a wrong current password (counts toward the login cooldown). |\n| POST | `/api/settings/username` | Session only (+CSRF) | Renames the account. Body: `{username, current}`. Returns `{ok, user, changed}` (plus `persisted` when changed). The username is stored lowercase. Sessions stay signed in. `400` for an invalid username, `403` for a wrong password. |\n| POST | `/api/settings/vault` | Session only (+CSRF) | Sets the vault folder and switches the running server to it. Body: `{path, create?}`. `path` must be absolute, without `..`, writable, not a system folder, and not overlap the state folder; with `create` a missing folder is created (its parent must exist). Returns `{ok, vault, created, stats}`. `400` with a message when the folder is refused. |\n| POST | `/api/settings/server` | Session or key (`admin`, +CSRF) | Body: `{realm?, session_ttl?, session_max_age?}` (at least one). Sets the server name (1-64 characters), how long a browser may stay idle before it must sign in again (300 to 2592000 seconds) and the longest sign-in (`0` for no limit, else at least `session_ttl`). Returns `{realm, session_ttl, session_max_age}`; open sessions follow the new limits at once. `400` for a value out of range. |\n| GET | `/api/settings/sessions` | Session only | `{sessions:[{id, current, source, alias, ip, user_agent, created_at, last_seen, expires_in}], count}`: live browser sessions. API keys are not sessions and never appear here. |\n| POST | `/api/settings/sessions/revoke` | Session only (+CSRF) | Signs other browsers out. Body: `{id}` or `{others:true}`. Returns `{ok, revoked}`. `400` for the current session (use logout), `404` when the session has already ended. |\n| POST | `/api/settings/sessions/rename` | Session only (+CSRF) | Names a device. Body: `{id, alias}`; an empty alias clears it. Returns `{ok, alias}`. |\n| GET | `/api/settings/sessions/activity` | Session only | `{events, count, ip, since}`: activity log entries from that session's IP address since it signed in, API-key entries left out, newest first, at most 200. Query: `id`. |\n\n| GET | `/api/settings/media` | Session or key | `{max_image_mb, max_image_bytes}`: the largest image upload (5 MB by default). |\n| POST | `/api/settings/media` | Session or key (`admin`, +CSRF) | Body: `{max_image_mb}` (0.1 to 50). Applies at once to the app, the HTTP API and MCP `upload_image`. |\n\nSession `id` values are the short ids returned by `GET /api/settings/sessions`\n(a unique prefix also works). An ambiguous or malformed id is `400`.\n\n## OAuth\n\nMemora is an OAuth 2.1 authorization server for remote MCP clients. Only the\nauthorization code flow with PKCE (`S256`) is supported. The access token is a\nnew API key named after the client, with the default scopes (`mcp`, `read`,\n`write`) and every tool; it appears on the Agents page like any other key and\nis revoked by deleting or disabling that key. URLs in the metadata use\n`MEMORA_BASE_URL` when it is set, else the scheme and host of the request.\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/.well-known/oauth-protected-resource`, `/.well-known/oauth-protected-resource/mcp` | None | Protected resource metadata (RFC 9728): `{resource, authorization_servers, bearer_methods_supported, scopes_supported, resource_name}`. |\n| GET | `/.well-known/oauth-authorization-server`, `/.well-known/oauth-authorization-server/mcp`, `/.well-known/openid-configuration` | None | Authorization server metadata (RFC 8414): `issuer`, the authorization, token, and registration endpoints, supported response types (`code`), grant types (`authorization_code`, `refresh_token`), PKCE methods (`S256`), token endpoint auth methods, `scopes_supported` (`mcp`), and `client_id_metadata_document_supported: true`. |\n| POST | `/oauth/register` | None | Dynamic client registration (RFC 7591). Body: `{redirect_uris, client_name?}`. `redirect_uris` holds 1 to 10 URIs, each HTTPS or plain HTTP on `localhost`, `127.0.0.1`, or `[::1]`, without a fragment. Returns `201 {client_id, client_name, redirect_uris, client_id_issued_at, token_endpoint_auth_method, grant_types, response_types}`. `400 {error, error_description}` for invalid metadata or when 500 clients are registered. `429` past 10 registrations from one IP (then one per minute). A client that has not completed an authorization within an hour is removed; it can register again. |\n| GET | `/oauth/authorize` | None | `302` to `/login?oauth=1&<query>`, where the sign-in page shows a consent card (after sign-in when needed). |\n| POST | `/oauth/token` | None | Form-encoded or JSON body. `grant_type=authorization_code` with `code`, `code_verifier`, `client_id` (or HTTP Basic), and optional `redirect_uri`; or `grant_type=refresh_token` with `refresh_token` and optional `client_id`. Returns `{access_token, token_type:\"Bearer\", refresh_token, scope:\"mcp\"}`. Codes are single use and expire after 10 minutes. A refresh gives the same key a new secret and a new refresh token. Errors are `400 {error, error_description}` (`invalid_request`, `invalid_grant`, `unsupported_grant_type`). |\n| GET | `/api/oauth/request` | None | What the consent card shows for an authorization request. Query: the `/oauth/authorize` query. Returns `{ok:true, client:{id, name, kind}, redirect_host, signed_in, user}` or `{ok:false, error, error_description, redirect}`. |\n| POST | `/api/oauth/approve` | Session only (+CSRF) | Body: `{query, allow}` where `query` is the authorization request query. Returns `{ok:true, redirect}`: the client's redirect URI with a `code` when `allow` is `true`, else with `error=access_denied`. An invalid request returns `{ok:false, error, error_description, redirect}`. `401` without a session. |\n| GET | `/api/oauth/clients` | Session or key (`admin`) | `{clients:[{client_id, name, redirect_uris, kind, created_at, fetched_at}], connections:[{key_id, client_id}]}`. `kind` is `dcr` (registered), `cimd` (metadata document), or `manual` (added by the owner). |\n| POST | `/api/oauth/clients` | Session or key (`admin`, +CSRF) | Registers a client by hand. Body: `{name?, redirect_uris}`. Returns `{ok, client}`. `400` for invalid redirect URIs. |\n| POST | `/api/oauth/clients/delete` | Session or key (`admin`, +CSRF) | Forgets a client and its refresh tokens. Body: `{client_id}`. Returns `{ok, deleted}`. Keys issued to the client stay until they are deleted. |\n\nA `client_id` may also be an HTTPS URL of a client metadata document. The\nserver fetches it (public addresses only, no redirects, at most 64 KiB), checks\nthat its `client_id` matches the URL, and caches it for 24 hours.\n\n## Logs and activity\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/api/logs` | Session or key (`read`) | `{range, count, events}`, newest first, each event with a local `time`. Query: `range` (for example `1d`, `7d`, `today`, `yesterday`, `all`; default `1d`), `days` (used when `range` is absent, at most 7), `since` and `until` (unix seconds; override `range`), `limit` (default 400, max 2000), `actor`, `q`. |\n| GET | `/api/logs/settings` | Session or key (`admin`) | `{max_mb, max_days, stats:{bytes, lines, oldest, newest, max_bytes, max_days}}` for the vault event log. |\n| POST | `/api/logs/settings` | Session or key (`admin`, +CSRF) | Body: `{max_mb?, max_days?}` (1 to 512 MB; 0 to 3650 days, 0 meaning no age limit). Returns the same shape as `GET`. The log is trimmed to the new limits at once. `400` for out-of-range values. |\n| GET | `/api/events` | Session or key (`read`) | `{events, count}`: the vault event log (`.events.jsonl`), oldest first, the newest `limit` entries. Query: `since` (unix seconds), `folder`, `actor` (the key name for agents), `limit` (default 100, max 2000). |\n\n### Realtime\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/ws` | Session only | WebSocket upgrade. The `Origin` must be same-origin (`403` otherwise). `503` when too many clients are connected. |\n| POST | `/_bus` | Loopback only | Publishes a JSON object (at most 64 KiB) into the event stream. Returns `{ok:true}`. `403` for callers that are not on the same machine, that come through a proxy (any forwarding header) or that are a web page (an `Origin` or `Sec-Fetch-*` header), `400` for a body that is not a JSON object, `413` for a body or event that is too large. |\n\nOn connect the server sends a `hello` event with the client count, replays the\nlast 40 stored events (each marked `replay: true`), then streams live events.\nWhen a client leaves, the others get a `presence` event with the new count.\nMessages from the client are ignored; the server pings every 30 seconds and\ncloses a connection that has been silent for 75 seconds.\n\n### Local stop\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| POST | `/_stop` | Loopback and stop token | Stops the server gracefully, like Ctrl+C (open requests finish, buffered usage is written). Returns `{ok:true}` and exits shortly after. `403` unless the caller is on the same machine, not behind a proxy (any forwarding header), and sends the `X-Memora-Stop-Token` header. Also accepted while the instance is locked. |\n\nAt startup, once the port is bound, the server writes a fresh random token to\n`<state>/stop.token` (readable by the server's user only on Linux and macOS)\nand removes it on exit. `memora-cli stop` reads that file and calls `/_stop`\nfirst on every OS; only if that fails does it fall back to SIGTERM (Linux,\nmacOS) or `taskkill` (Windows, where a server started without a console\nignores a polite `taskkill`). Anyone who can read the state folder can stop\nthe server; they can already read its database.\n\n### `ai_activity` events\n\nEvery MCP `tools/call` publishes a `start` and an `end` event sharing `call_id`:\n\n```json\n{\"type\":\"ai_activity\",\"phase\":\"start\",\"call_id\":\"c1a2b3c4d5e6-0\",\"actor\":\"research-bot\",\n \"actor_kind\":\"agent\",\"actor_id\":\"k_1a2b3c4d\",\"action\":\"read_memory\",\"label\":\"Plan/Index.md\",\n \"paths\":[\"Plan/Index.md\"],\"_ts\":1760600000.12}\n{\"type\":\"ai_activity\",\"phase\":\"end\",\"call_id\":\"c1a2b3c4d5e6-0\",\"actor\":\"research-bot\",\n \"actor_kind\":\"agent\",\"actor_id\":\"k_1a2b3c4d\",\"action\":\"read_memory\",\"label\":\"Plan/Index.md\",\n \"paths\":[\"Plan/Index.md\"],\"ok\":true,\"ms\":2,\"_ts\":1760600000.12}\n```\n\n- `actor`: the API key's name (fallback: key id) with `actor_kind: \"agent\"`; for a\n browser session the username with `actor_kind: \"user\"`. `actor_id` is the key id (or\n the username). Node events (`node_created`, ...) from the call carry the same `actor`.\n- `action`: the tool name.\n- `for` (optional): who the agent acted for and how it was asked. Mnemo, the built-in\n agent (`actor: \"Mnemo\"`, `actor_id: \"mnemo\"`), sets it: `owner · chat`,\n `owner · console`, `<who> · @mnemo in <note>`.\n- `paths`: vault-relative note paths from the arguments (`path`, `paths`, `from`, `to`,\n `old_path`, `new_path`, `into` of `merge_memory`, `source`/`target` of `find_path`)\n plus note paths found in the result (search hits, the created or moved note), at\n most 20, each at most 512 bytes (longer paths are dropped). Whole-vault overviews\n (`get_graph`, `list_memory`, logs, ...) add no result paths.\n- Read-only tools publish `start` after running (so it carries the result paths),\n immediately followed by `end`; mutating tools publish `start` before running and `end`\n after, with the result paths added.\n- `end` adds `ok`, `ms`, and on failure `error` (at most 200 characters). `label` is at\n most 160 characters. `_ts` is the publish time in unix seconds. `end` events are\n realtime only: they are not written to `.events.jsonl` or the replay buffer.\n\n## UI layout\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/api/ui/layout/{name}` | Session only | `{name, data, updated_at}`; `data` and `updated_at` are `null` if never saved. |\n| PUT | `/api/ui/layout/{name}` | Session only (+CSRF) | `{ok:true, updated_at}`. Body: `{data: <any JSON>}`. |\n\n`name` is `[a-z0-9_-]{1,40}` (else `400`). API keys get `403`. `data` is stored as\nserialized JSON of at most 512 KiB (`413` above); the request body limit is 600 KiB.\nNames starting with `srv-` are reserved for server settings (`403`).\nLayouts are stored in the `ui_layout` table of `memora.db`. The web UI uses them for\n`canvas` (card positions and frames) and `graph` (pinned positions).\n\n## Pins\n\nThe owner's pinned notes and folders (the sidebar's Pinned list), shared by every\nbrowser and device of the instance.\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/api/pins` | Session only | `{count, pins:[{kind, path, position, missing}]}` in display order. |\n| PUT | `/api/pins` | Session only (+CSRF) | Same as GET. Body: `{pins:[{kind, path}]}`, the whole ordered list (reorder, remove). |\n| POST | `/api/pins/pin` | Session only (+CSRF) | Same as GET. Body: `{kind, path, position?}`. Pins an existing note or folder at `position` (default: the end), or moves its pin there; `404` if it does not exist. |\n| POST | `/api/pins/unpin` | Session only (+CSRF) | Same as GET plus `removed`. Body: `{kind, path}`. |\n\n`kind` is `note` or `folder`. `path` is vault-relative as the tree shows it (notes end in\n`.md`): absolute paths, `..`, empty or hidden segments, `\\`, control characters and paths\nover 1024 characters get `400`, as do more than 200 pins. API keys get `403` (agents use\nthe MCP tools `list_pins`, `pin` and `unpin`). Bodies are limited to 256 KiB for `PUT`\nand 8 KiB for `pin`/`unpin` (`413`). `missing` is true when the path no longer exists,\nfor example after a rename outside Memora; such a pin is kept until it is removed.\n\nRenames, moves and deletes done by Memora (HTTP or MCP) rewrite or drop pins in the same\ndatabase transaction, including pins on notes and folders inside a moved folder;\nmoving an item to the trash or deleting it removes its pin, and deleting a folder\nremoves every pin under it. Every change publishes a `pins_changed` realtime event with\nno other data; open browsers reload the list. Pins are stored in the `pin` table of\n`memora.db`.\n\n## Mnemo (built-in agent)\n\nMnemo is the notes agent built into Memora. Every route needs the signed-in\nbrowser session (API keys get `403`, writes need CSRF); the console's `/mnemo`\nuses a short local session. Mnemo's data lives in `assistant.sqlite3` beside\n`memora.db` (file mode 0600): providers with their API keys sealed\n(ChaCha20-Poly1305, the same key as the server's other secrets), models,\npreferences, chats and messages. A key is never returned; providers carry a\nfour-character `key_hint`.\n\n| Method | Path | Returns |\n|---|---|---|\n| GET | `/api/assistant/state` | `{name, ready, providers, models, prefs, tools, defaults}`. `ready` is true when a model can answer. `tools` is the fixed list Mnemo may use. Each model has `thinks`: it can think, so the chat offers a thinking level (Claude 3.7 and later, OpenAI reasoning models, open reasoning models known by name). |\n| POST | `/api/assistant/providers` | Adds or changes a provider. Body: `{id?, kind?, label?, api_style?, base_url?, api_key?, enabled?}`. Up to 20 providers, several of the same type allowed. `id` is the owner's own (1-32 characters of `a-z`, `0-9`, `-`; made from `label` when left out; it cannot change, since models are keyed `id/model`). `kind` is `openai`, `anthropic` or `custom` (any OpenAI-compatible server, which needs `base_url`, its `/v1` address); `api_style` is `chat` or `responses` (OpenAI and compatible) or `messages` (Anthropic). For an existing `id`, fields left out keep their value, so `{id, enabled: false}` switches a provider off (its models leave the model pickers). Leaving `api_key` out keeps the saved key; `\"\"` removes it. Returns the state plus `saved` (the id). |\n| POST | `/api/assistant/providers/test` | Body: `{id}`. Lists the provider's models as a connection check: `{ok, models, ms}` or `{ok: false, error}`. |\n| POST | `/api/assistant/providers/delete` | Body: `{id}`. Removes the provider, its key and its models. |\n| POST | `/api/assistant/models/fetch` | Body: `{provider}`. Reads the provider's model list (`GET <base>/models`, every page for Anthropic) with the limits it reports: the context window from `max_input_tokens`, `context_length`, `context_window`, `max_context_length` or `max_model_len`, and the reply limit from `max_tokens` or `max_completion_tokens`. Pinned models stay; unpinned ones the provider no longer lists go. Returns the state plus `fetched`. `502` when the provider refuses. |\n| POST | `/api/assistant/models` | Body: `{provider, model, label?, context_window?, max_output?, pinned?, hidden?}`. Adds a model by hand or changes it; `null` clears a limit. The app sets only pinned, hidden and new models; limits normally come from the provider. |\n| POST | `/api/assistant/models/delete` | Body: `{provider, model}`. |\n| POST | `/api/assistant/prefs` | Any of `default_model` (`provider/model`), `system_prompt` (up to 4000 characters), `temperature` (0-2), `max_output_tokens` (64-200000), `context_tokens` (2000-2000000, for models without a window), `max_steps` (1-30 tool rounds per reply), `launcher` (the floating button), `thinking` (`auto`, `off`, `low`, `medium` or `high`: how hard models that can think do so; `auto` leaves it to the model), `fallback_models` (up to 5 `provider/model` keys: when a reply's model fails after its retries, Mnemo carries on with the next one, streamed as `fallback {from, model, reason}`; with none left the error stands and the owner tries again); `null` resets one. |\n| GET | `/api/assistant/sessions` | `{sessions: [{id, title, scope, model, pinned, created_at, updated_at, messages, running, seen}]}`. `messages` counts the owner's and Mnemo's messages (not tool results); `?about=<path>` lists only the chats about that note or folder (kept for it, with it attached, or naming it in a tool call). `seen` is how many of them the owner has read on any device (the unread count is `messages - seen`). The first list after 2.1.5 counts every existing chat as read. |\n| POST | `/api/assistant/sessions` | Body: `{scope?, model?, title?, fleeting?}`. A fleeting chat is left out of lists, search and Mnemo's look-back tools and is deleted (with the pictures sent in it) by `.../delete` when the owner leaves, or after 30 minutes idle. `scope` is `global`, `note:<path>` or `folder:<path>`. Returns `{session}`. |\n| GET | `/api/assistant/sessions/{id}` | `{session, messages: [{id, role, content, tool_calls, tool_call_id, tool_name, meta, created_at}], context}`. `context` is `{used, window, reserved_output, compact_at, compactions, model}` for the model the chat would use now (approximate tokens), or `null` without a usable model. A message with `meta.compact: true` is a summary that stands in for every message before `meta.keep_from`. |\n| GET | `/api/assistant/search` | Query `q` (every word must appear, any case), `limit` (default 60, at most 200). `{query, hits: [{chat, title, scope, message_id, role, snippet, at}]}`, newest first: the owner's messages and Mnemo's replies whose text or chat title holds the words; `message_id` is `null` for a chat matched by its title alone. |\n| POST | `/api/assistant/sessions/{id}/rerun` | Body: `{message_id?, model?}` (default: the last of the owner's messages). Runs that message's turn again: every message after it is removed, then the reply streams as for `/chat`. `400` when `message_id` is not one of the owner's messages in the chat, `409` while it answers. |\n| POST | `/api/assistant/sessions/{id}/steer` | Body: as for `/chat`. Send this message now: the reply running is cut where it is (what it wrote so far is kept, `meta.stopped`) and Mnemo answers this message as a new turn; with no reply running it goes at once. `{ok, queue}`. (Older chats may hold `meta.steer` messages from before 2.1.9.) |\n| GET | `/api/assistant/sessions/{id}/queue` | `{items: [{id, text, attach, at}], held}`: messages waiting for the reply running. They go out one by one, on the server, as each reply ends (finished, stopped or cut), whichever device queued them. A failed reply pauses the queue (`held`) until a message is sent now or the queue resumes. Kept in memory: a restart empties it. |\n| POST | `/api/assistant/sessions/{id}/queue` | Body: as for `/chat`. Queue a message (it goes at once when no reply runs). `{id, queue}`. |\n| POST | `/api/assistant/sessions/{id}/queue/{qid}` | Body: `{op: del \\| up \\| down \\| move \\| send, to?}` (`to` the new place for `move`). `send` puts it first and sends it now, cutting the reply running. `{qid}` may also be `clear` (drop every queued message) or `resume` (let a paused queue go on). Answers with the queue. |\n| GET | `/api/assistant/sessions/{id}/watch` | What happens in the chat from now on, as server-sent events, so every device with it open stays in step: `hello {running}`, `user {message, via, client}` (a message stored from any device or out of the queue; `client` is the id the sender put in its request), `running`, `idle {outcome}` (`done`, `stopped`, `failed`), `queue {items, held}`, `queue_error {message}`, `compacted`, `reload` (turns were replaced: read the chat again). |\n| GET | `/api/assistant/sessions/{id}/live` | The reply running in the chat as server-sent events: every event since it began, then live, until it ends. `204` when none is running. |\n| GET | `/api/assistant/sessions/{id}/export` | The chat as a Markdown file (`text/markdown`, a download): each message with its time, Mnemo's steps, what it showed, compaction summaries. |\n| GET | `/api/assistant/skills` | `{folder: \"Skills\", skills: [{name, path, description}]}`: the owner's skills (notes in `Skills/`). A message starting `/name` sends that skill's steps with it (`meta.skill`). |\n| GET | `/api/assistant/suggestions` | `{own, ai}`: the owner's suggestions and Mnemo's (from recent notes; written again in the background when older than 12 hours). |\n| POST | `/api/assistant/suggestions` | Body `{own: [text]}` (up to 30): the owner's own suggestions. |\n| POST | `/api/assistant/suggestions/refresh` | Mnemo writes its suggestions again now. `{own, ai, fresh}`. |\n| POST | `/api/assistant/sessions/prune` | Delete many chats: body `{ids}`, `{older_than_days}` (1 to 3650; not active for that long) or `{all: true}`, with `keep_pinned` (default `true`, used with age or all). Chats answering right now are skipped. `{deleted, skipped}`. |\n| POST | `/api/assistant/sessions/{id}/seen` | Body: `{messages}`. The owner has read the chat up to `messages` (capped at what it holds; never goes back). `{ok, seen}`. |\n| POST | `/api/assistant/sessions/{id}/stop` | End the reply running in the chat; what it wrote so far is kept (`meta.stopped`) and the next queued message goes out. `{stopped}`. |\n| POST | `/api/assistant/sessions/{id}/compact` | Fold the older turns into a summary now (the chat's model writes it; the last turn stays as it is). `{ok: true, messages, tokens, summary, context}`, or `{ok: false, reason, context}` when there is nothing older yet. `409` while the chat is answering. |\n| POST | `/api/assistant/sessions/{id}` | Body: `{title?, model?, pinned?}`. |\n| POST | `/api/assistant/sessions/{id}/delete` | Deletes the chat and its messages (notes are not touched). |\n| POST | `/api/assistant/sessions/{id}/chat` | Body: `{text, model?, attach?, tz?, tz_offset?, answer?}` (`answer` `{to, approve?, other?}` answers one of Mnemo's questions by its call id; `approve` is set when the tapped option approves a change) (`tz` an IANA zone name and `tz_offset` minutes east of UTC, from the browser, for Mnemo's `current_time`). `attach` lists up to 8 items `{kind, path}`: `note` (its text, up to 8000 characters), `folder` (the notes in it, up to 200) or `image` (`path` is an id from `/api/assistant/uploads`). A snapshot of them is stored with the message (`meta.attach`, `meta.context`) and stays in the chat's context. Replies as server-sent events, one JSON object per `data:` line: `start {model, context}`, `ask {id, question, options: [{label, description, approve}], allow_other}` (Mnemo's `ask_owner`: the reply ends and waits for the answer), `steered {text}`, `compacting` and `compacted {messages, tokens}` (the chat was near full and its older messages were folded into a summary first), `thinking {delta}` (the model's thinking, where the provider shows it), `text {delta}`, `tool_start {id, name, args}`, `tool_end {id, name, ok, summary, ms}`, `notice {text}`, `error {message}`, `done {input_tokens, output_tokens, title, context}`. `409` while the chat is already answering (queue it instead). Also `compact_text {delta}` (the summary as it is written, before `compacted {messages, tokens, summary}`) and `fallback {from, model, reason}` (the model failed; the next fallback model answers). A body may carry `client` (any short id) so the sender can tell its own message in `/watch`. The reply runs on the server: closing the stream does not stop it (watch it again with `/live`, end it with `/stop`); `GET /api/assistant/sessions` and `GET /api/assistant/sessions/{id}` say `running` meanwhile. |\n| POST | `/api/assistant/uploads?name=<file>` | The raw bytes of a PNG, JPEG, WebP or GIF (the Images upload limit applies): `{id, name, bytes, url}`. The image waits in `assistant-uploads/` in the state folder for a week. Attached to a chat message, it goes to the model as an image (OpenAI `image_url`, Responses `input_image`, Anthropic `image` blocks; the newest 6 images of the chat, each up to 4.5 MB; a model that refuses images gets their names instead), and Mnemo's `place_image` tool can put it beside a note through MCP `upload_image`. |\n| GET | `/api/assistant/uploads/{id}` | The staged image, for the chat's thumbnails. |\n\nMnemo runs its tools through the MCP server under the name **Mnemo** (actor id\n`mnemo`), so every call shows in Activity and respects tools switched off on the\nTools page. It has one tool of its own, `place_image {upload, note, name?, alt?,\nappend?}`, which hands a staged chat image to `upload_image` (and is off when\nthat tool is off).\n\nThinking: Anthropic models are asked for adaptive thinking with summaries\n(models that refuse the field are asked without it from then on), OpenAI GPT-5\nand o-series models on the Responses API for reasoning summaries, and\nOpenAI-compatible servers stream `reasoning_content` or `reasoning` on their\nown. A Claude reply that carried thinking is stored block for block\n(`meta.raw`) and sent back verbatim, and each chat keeps the system prompt it\nstarted with (`meta.system` on its first message), so the model's earlier\nthinking stays valid. Thinking from before a compaction is not replayed, and\nwhen the API refuses a replayed thinking block the request is sent again\nwithout it. Permission (`POST /api/assistant/prefs` `{permission: \"ask\" | \"auto\"}`, default `ask`): in Ask first mode a tool call that would change notes is refused until the owner's latest message approves (an `answer` with `approve: true`, or an `@mnemo:` request from a note); Auto lets changes through and runs up to 40 steps a reply (25 otherwise; `max_steps` overrides, up to 60). Besides `place_image` it has `ask_owner` (a question with 2 to 5 options and Other), `current_time` (date, time, weekday and the owner's time zone), `search_docs` and `read_docs` (Memora's own documentation, from `mnemo-docs.json` the web build writes next to the assets; answers link `/docs/<page>#<heading>`), `show_items` (cards in the reply for notes, folders,\nimages or the vault; `tool_end` carries the checked items as `shown`) and tools of its own over its chats: `list_chats` (newest first, optionally by\ntitle), `search_chats` (every word, newest first) and `read_chat` (one chat's\nmessages, 60 at a time with `page`), for when the owner refers to an earlier\nconversation; and over the pages it wrote (```` ```html ```` / ```` ```svg ```` blocks\nin its replies, named by their `<title>`; the same title again is a newer version):\n`list_artifacts` (across chats or in one) and `read_artifact` (a page's source, the\nlatest version unless `version` is given), so it reworks a page instead of starting\nover and can reuse one from another chat. Pages live in their chat's messages and\nare deleted with it. It may use 54 tools for reading and looking after notes, folders,\ntags, links, pins, history and the Trash; it never gets `delete_memory`,\n`bulk_delete`, `delete_folder`, export or import, admin or web tools. A line with `@mnemo: <request>` in a note (outside code; a struck\n`~~@mnemo: …~~` is done) is a request to Mnemo: a few seconds after the owner\nsaves the note (`POST /api/save` or `/api/create`), or after an agent's tool\ncall changes it (Mnemo's own changes from a chat or the console too; not those\nit makes while answering a request), Mnemo runs it in the note's chat (one per\nnote, titled `@mnemo · <note>`, scope `note:<path>`; every later request in the\nnote joins it, unless it is answering right now; each request's message holds it\nas written, `meta.mention` says `{path, line, by}` and `meta.attach` names\nthe note), then saves the note with\nthe request struck through and its reply quoted under it. Activity events of\nMnemo's tool calls carry `for` (\"owner · chat\", \"owner · console\",\n\"<who> · @mnemo in <note>\"). A chat keeps\nits whole conversation for its model: when its history fills all the tokens it\nmay use (the model's context minus the room kept for the reply), the chat's model folds the older turns into a summary (stored as a\nmessage with `meta.compact`, sent in front of the kept turns) before the next\nreply, keeping the last one or two turns as they are. Only if that fails are the\noldest turns left out (a reply and its tool results always stay together).\n\n## Status codes\n\n| Code | Meaning |\n|---|---|\n| 200 | Success. |\n| 201 | OAuth client registered. |\n| 202 | MCP notification accepted. |\n| 204 | `/favicon.ico`. |\n| 302 | Redirect (pages to `/login` without a session, `/login` to `/` when signed in, logout to `/login`, locked instance to `/login?locked=1`, `/oauth/authorize` to the consent page). |\n| 304 | Not modified (`/api/vault/file`, static assets). |\n| 400 | Bad request, for example a missing required field or an invalid value. |\n| 401 | Missing or invalid credentials, or a session-only endpoint called without a session. |\n| 403 | Blocked by an access rule, a CSRF origin mismatch, a missing key scope, a wrong password or setup code, or an endpoint that needs an open setup or reset window. |\n| 404 | Note, key, session, rule, or route not found; also any request for a host outside the domain list. |\n| 405 | `/mcp` called with a method other than `POST`. |\n| 408 | The request took longer than 30 seconds. |\n| 409 | No vault configured (`needs_vault: true`), or a state conflict. |\n| 413 | Body, layout, image, or event too large. |\n| 415 | `/api/vault/file` path is not an image. |\n| 423 | Instance is LOCKED. |\n| 429 | Rate limit or failed-attempt cooldown (`Retry-After` header). |\n| 500 | Internal error, for example the state database failed. |\n| 503 | UI assets are not installed, the password hashing pool is busy, or too many realtime clients. |\n"},{"file":"docs/DEPLOYMENT.md","slug":"deployment","title":"Deployment","text":"# Deployment\n\nThis guide covers health checks, running Memora behind a reverse proxy, in a\ncontainer, and under systemd, first-run and recovery, backups, and upgrades.\nFor the installer and the Compose quick start, see [INSTALL.md](INSTALL.md);\nfor every setting, see [CONFIGURATION.md](CONFIGURATION.md).\n\n## Health check\n\n`GET /healthz` is public, never rate limited, and reachable even while the\ninstance is LOCKED. An outside caller gets only:\n\n```json\n{ \"ok\": true, \"server\": \"memora\" }\n```\n\nA caller on the same machine (loopback) or a signed-in browser gets more\ndetail:\n\n```json\n{\n \"ok\": true,\n \"server\": \"memora\",\n \"version\": \"1.0.0\",\n \"vault_configured\": true,\n \"vault\": \"/var/lib/memora/vault\",\n \"armed\": false,\n \"locked\": false,\n \"base_url\": \"https://memory.example.com\",\n \"base_url_configured\": true\n}\n```\n\nUse it for container health checks and load balancer probes. Run locally, it\nalso tells you whether a setup window is open or the instance is locked.\n\n## Reverse proxy\n\nThe `memora` binary binds `127.0.0.1` by default, which is the intended setup\nbehind a proxy on the same host (`install.sh --behind-proxy` does the same).\nBind `0.0.0.0` only when clients connect directly.\n\nOn the proxy:\n\n- Forward `Host`, and append the client IP to `X-Forwarded-For`.\n Memora reads the right-most `X-Forwarded-For` entry that is not itself a\n trusted proxy; only when there is none does it fall back to\n `CF-Connecting-IP`, then `X-Real-IP`. Forwarding headers count only when the\n connection comes from a trusted proxy. Loopback is always trusted; list any\n other proxy address in `MEMORA_TRUSTED_PROXIES`. A loopback address in a\n header is ignored, so no outside caller can pass as local.\n- Forward `X-Forwarded-Proto: https`. From a trusted proxy, it makes Memora mark\n the session cookie `Secure` and send HSTS.\n- Upgrade WebSockets on `/ws` and allow long-lived connections there.\n\nSet `MEMORA_BASE_URL` to the public URL (OAuth clients and connection snippets\nuse it) and, optionally, `MEMORA_DOMAIN` to refuse requests for other\nhostnames.\n\n### nginx\n\n```nginx\nserver {\n listen 443 ssl;\n server_name memory.example.com;\n\n location / {\n proxy_pass http://127.0.0.1:8400;\n proxy_set_header Host $host;\n proxy_set_header X-Real-IP $remote_addr;\n proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n proxy_set_header X-Forwarded-Proto $scheme;\n }\n\n location /ws {\n proxy_pass http://127.0.0.1:8400;\n proxy_http_version 1.1;\n proxy_set_header Upgrade $http_upgrade;\n proxy_set_header Connection \"upgrade\";\n proxy_set_header Host $host;\n proxy_set_header X-Real-IP $remote_addr;\n proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n proxy_set_header X-Forwarded-Proto $scheme;\n proxy_read_timeout 3600s;\n }\n}\n```\n\n### Caddy\n\n```\nmemory.example.com {\n reverse_proxy 127.0.0.1:8400\n}\n```\n\nCaddy handles WebSocket upgrades and the `X-Forwarded-*` headers itself.\n\n## Running in a container\n\nThe repository ships a `Dockerfile` and a `docker-compose.yml`;\n[docker/README.md](../docker/README.md) is the short practical guide. The\nessentials:\n\n```sh\nmkdir -p data state && sudo chown -R 1000:1000 data state\ndocker compose up -d\ncurl -s http://127.0.0.1:8400/healthz\ndocker compose exec -it gateway memora-cli # then /guide, or /web\n```\n\nThe container runs as uid:gid 1000:1000 by default. Set `MEMORA_UID` and\n`MEMORA_GID` in `.env` to match the owner of the host vault and state\ndirectories. If the container cannot write to them, the entrypoint stops and\nprints the container uid and the directory owner. A root-owned bind mount is\nthe most common startup failure.\n\nInside the container, the vault is `/data` and the state directory is\n`/state`, bind-mounted from `MEMORA_DATA_DIR` and `MEMORA_STATE_DIR` (default\n`./data` and `./state`). Port `8400` is the only port: the HTTP API, MCP, the\nUI, and the WebSocket share it. `MEMORA_HTTP_PORT` sets the host side of the\nmapping.\n\nBehind a proxy on the host, publish on loopback only\n(`MEMORA_HTTP_PORT=127.0.0.1:8400`). The container then sees the proxy as the\nDocker network's gateway address, so add that address to\n`MEMORA_TRUSTED_PROXIES`.\n\nThe entrypoint also accepts `setup`, `reset-password`, `status`, `unlock`,\n`list`, and `cli <args>` as the container command, for one-off runs such as\n`docker compose run --rm gateway cli db check`.\n\n### Restricted container runtimes\n\nSome hosts run containers inside another sandbox that does not grant full\nkernel privileges. The container runtime can then fail before Memora starts,\nwith errors such as:\n\n```\napparmor_parser: Access denied. You need policy admin privileges.\n```\n\nor:\n\n```\nrunc create failed: unable to start container process: error during container init:\nopen sysctl net.ipv4.ip_unprivileged_port_start file: reopen fd 8: permission denied\n```\n\nThese come from the runtime loading an AppArmor profile and writing network\nsysctls, not from anything Memora needs. If you control the runtime, run the\ncontainer with AppArmor unconfined (when the outer sandbox already confines\nit) and without the optional network sysctls, or use a wrapper runtime that\nremoves those fields from the OCI spec. Do not use `--privileged`: it is not\nrequired and does not fix either cause.\n\n## systemd\n\n`install.sh` writes a hardened unit to `/etc/systemd/system/memora.service`;\nits full contents are in [INSTALL.md](INSTALL.md#the-systemd-unit). Put local\nchanges in a drop-in (`sudo systemctl edit memora`), because the installer\nrewrites the unit on every run.\n\nFor a manual install, a minimal unit looks like this:\n\n```ini\n[Unit]\nDescription=Memora memory vault\nAfter=network-online.target\nWants=network-online.target\n\n[Service]\nType=simple\nUser=memora\nGroup=memora\nWorkingDirectory=/var/lib/memora\nEnvironment=HOME=/var/lib/memora\nEnvironment=MEMORA_STATE=/var/lib/memora/state\nEnvironment=MEMORA_VAULT=/var/lib/memora/vault\nEnvironment=MEMORA_ASSETS=/usr/local/share/memora/assets\nEnvironment=MEMORA_BIND=127.0.0.1\nEnvironment=MEMORA_PORT=8400\nEnvironment=RUST_LOG=info\nExecStart=/usr/local/bin/memora\nRestart=on-failure\nRestartSec=3\nTimeoutStopSec=15\nNoNewPrivileges=yes\nPrivateTmp=yes\nProtectSystem=strict\nProtectHome=yes\nReadWritePaths=/var/lib/memora\n\n[Install]\nWantedBy=multi-user.target\n```\n\nMemora needs write access to the vault and the state directory, and `git` on\nthe `PATH` for vault history. Then:\n\n```sh\nsudo systemctl daemon-reload\nsudo systemctl enable --now memora\nsudo memora-cli setup\n```\n\nRun as root, `memora-cli` finds the running server's state directory and does\nits database work as the owner of that directory.\n\n## First-run and recovery\n\nThe CLI opens a short window and the browser completes it:\n\n```sh\nmemora-cli setup # first-run window, prints a one-time code\nmemora-cli reset-password # password reset window, prints a one-time code\nmemora-cli setup --minutes 10 # longer window (1-60 minutes, default 5)\nmemora-cli status # state dir, vault, owner, window, and lock\nmemora-cli disarm # close an open window without locking\nmemora-cli unlock # lift the lock; the owner account stays as it is\nmemora-cli list # the owner and the API keys\nmemora-cli clear-cooldowns # clear login cooldowns in the running server\n```\n\nIn the console (`memora-cli` with no arguments), `/web` does the same as\n`setup` or `reset-password`, and `/guide` walks through the first run.\n\nThen open `/login`, enter the code, and fill in the form before the window\ncloses. A wrong code counts against that IP's budget of 3 (then it waits 5\nminutes); the code stays valid and single-use until the window ends. Only 50\nwrong codes in one window, from any IPs, close it early; open a new one then. If a window expires\nunfinished, the instance locks: API and MCP return `423` and pages go to the lock screen until\n`setup`, `reset-password`, or `unlock` runs. This keeps an unclaimed instance\nfrom being taken over by whoever reaches the port first.\n\n### Failed sign-ins\n\nMemora limits guessing without letting anyone lock you out:\n\n- Per IP: 5 failed sign-ins (or 3 wrong setup codes) within 15 minutes put\n that IP on a cooldown of 5, then 10, then 15 minutes (`429`). A successful\n sign-in from the IP clears it.\n- Across all IPs: 20 failures within 15 minutes switch on slow mode for 15\n minutes after the latest failure. Every sign-in then waits about a second,\n and one failure is enough to put an IP on its cooldown. There is no\n account-wide lockout: a correct password from an IP without recent failures\n still signs in, and that ends slow mode.\n- `memora-cli clear-cooldowns` clears every cooldown in the running server.\n\nBehind a proxy, these limits only work per client when Memora sees the real\nclient IP (see [Reverse proxy](#reverse-proxy)).\n\n## Backups\n\nBack up both the state directory and the vault.\n\nState: one SQLite database, `memora.db`, holding the owner, API keys,\nsessions, settings, access and privacy rules, OAuth grants, and the activity\nlog, plus `key-seal.bin`. It is small but critical: losing it means losing the\naccount and every API key. Back it up online with the CLI; never `cp` a live\ndatabase, because recent commits sit in `memora.db-wal`:\n\n```sh\nsudo memora-cli db backup --to /var/backups/memora-state-$(date +%F).db\nsudo memora-cli db check # exit status 1 on any problem\n```\n\nWithout `--to`, backups go to `state/backups/` and the newest 10 are kept\n(`--keep N`). A daily systemd timer or cron job running `memora-cli db backup`\nis enough; encrypt copies that leave the host. See\n[DATABASE.md](DATABASE.md#operations) for details.\n\nVault: the markdown notes and their git history. Copy the directory, or use\ngit:\n\n```sh\ngit -C /var/lib/memora/vault bundle create /var/backups/memora-vault-$(date +%F).bundle --all\n```\n\n`.events.jsonl` is the event log. (`.fts.db`, the search index of older\nversions, is no longer used and is removed automatically.)\n\nWith Docker Compose, both live in the host directories, so an archive taken\nwith the container stopped covers everything:\n\n```sh\ndocker compose stop gateway\ntar -czf memora-$(date +%F).tar.gz data state\ndocker compose start gateway\n```\n\n### Restore\n\nStop the service, restore the database with `memora-cli db restore FILE` (it\nverifies the file and keeps the replaced database in `state/backups/`), put\nback `key-seal.bin` and the vault, then start the service again.\n\nIf you restore only the vault and start with an empty state directory, Memora\nhas no account and expects a new first-run setup; the notes are intact.\n\n## Upgrades\n\nNative: `sudo /usr/local/share/memora/install.sh --upgrade` or\n`sudo memora-cli update` (see [INSTALL.md](INSTALL.md#upgrading)).\n\nDocker: pull the new image and recreate the container:\n\n```sh\ndocker compose pull && docker compose up -d\n```\n\nThe server migrates `memora.db` on start. Take a `memora-cli db backup` first:\na database migrated by a newer release cannot be opened by an older one.\n"},{"file":"docs/ARCHITECTURE.md","slug":"architecture","title":"Architecture","text":"# Architecture\n\nThis document describes how Memora is put together: the crates, what each one\nowns, the request path from a browser or an agent to the vault, the realtime\nWebSocket fan-out, the auth model, and the storage model. Every claim here maps\nto code under `crates/`.\n\n## Crate layout\n\nMemora is a Cargo workspace with six crates. The web UI is a TypeScript app in\n`web/src`, built with Vite into `crates/http/assets`.\n\n| Crate | Binary | Owns |\n|---|---|---|\n| `memora-core` | (library) | The vault: walking notes, parsing wikilinks and frontmatter, the in-memory note index, search, the graph, git versioning, per-caller path visibility, and the `*_impl` methods that every interface calls. Also the realtime event hub. |\n| `memora-gateway` | (library) | Auth primitives: argon2id password hashing, API key generation and hashing, OAuth token and PKCE helpers, setup codes, the access stack evaluator, host and lock allow lists, scopes and per-key tool permissions, and reading the provisioning environment. No state of its own. |\n| `memora-state` | (library) | The state database `memora.db` (SQLite, WAL): opening, migrations, change detection, and one typed repository per table group (owner, settings, `server_config`, keys, tools, usage, sessions, arm window, access rules, activity, control requests, OAuth, privacy rules, UI layouts, retention), plus the one-time import of JSON state files. No SQL lives outside this crate. |\n| `memora-mcp` | (library) | The MCP server: the tool catalog, JSON-RPC 2.0 handling, the discovery card, client detection, `ai_activity` events, and the privacy view applied to agent callers. |\n| `memora-http` | `memora` | The axum server: routing, middleware, the REST API, OAuth 2.1 endpoints, the privacy API, the WebSocket and intake bus, sealed key copies, and serving the UI assets. |\n| `memora-cli` | `memora-cli` | The operator console (slash commands such as `/guide`, `/web`, `/keys`, `/tools`, `/sessions`, `/config`, `/backup`, `/db`, `/update`) and one-shot commands (`setup`, `reset-password`, `status`, `disarm`, `unlock`, `list`, `clear-cooldowns`, `vault`, `db ...`, `update`, `version`). It opens `memora.db` directly; run as root, it does database work as the state directory's owner. |\n\nDependencies point one way: `http` depends on `core`, `mcp`, `gateway`, and\n`state`; `mcp` depends on `core`, `gateway`, and `state`; `cli` depends on\n`gateway`, `mcp`, and `state`. `core`, `gateway`, and `state` depend on no\nother Memora crate.\n\n## What each crate owns\n\n### memora-core\n\n`MemoryStore` is the single point through which the vault is read and written.\nBoth the HTTP API and the MCP tools call its `*_impl` methods, so a change made\nthrough the UI and one made through an agent take the same code path.\n\n- `walk()` enumerates `.md` files under the vault root, skipping dot\n directories. Walk order is stable, so tools that depend on first-hit order\n behave deterministically.\n- Parsing: wikilinks, inline tags, frontmatter tags, and frontmatter fields.\n- The note index: parsed facts per note (links, tags, frontmatter, text,\n checklist items) kept in memory and checked against each file's mtime and\n size on every call, so notes changed outside Memora are seen at once. Nothing\n is stored on disk.\n- `search()` blends word matching over name and body with `tag:` and `#tag`\n filters, scored by hits, name hits, phrase, and position.\n- The graph: nodes are notes, links are resolved wikilinks.\n- Versioning: when the vault is a git repository, vault changes are committed\n to it (`create:`, `edit:`,\n `rename:`, `move:`, `delete:`, `folder:`); history, diff, restore, and\n snapshot read from that history.\n- Privacy views: while a caller's `PathView` is set, listings skip hidden\n notes, hidden paths resolve as \"not found\", and folder operations that would\n carry hidden items along are refused. A path hook reports renames, moves, and\n deletes so privacy rules follow the notes they protect.\n- The event hub (see below).\n\n### memora-gateway\n\n- `hash_password` and `verify_password` use argon2id.\n- `generate_key` produces `memora_live_` plus 128 random bits as hex.\n `hash_api_key` stores the SHA-256 hex of the key. `verify_key` compares in\n constant time.\n- `AccessStack` evaluates ordered IP, range, CIDR, domain, and catch-all rules.\n Loopback is always allowed.\n- `host_allowed` checks the `Host` against `MEMORA_DOMAIN` and the host of\n `MEMORA_BASE_URL`.\n- `tool_access` combines a key's scopes (`mcp`, `read`, `write`, `admin`), its\n tool list, and the global tool switches.\n\n### memora-state\n\n- `Db::open` creates or opens `memora.db` (0600 in a 0700 directory), refuses\n foreign or newer-schema files, and runs migrations.\n- Every write is one `BEGIN IMMEDIATE` transaction (`Db::write`), so the server\n and `memora-cli` can write concurrently without losing updates.\n- Sessions are looked up per request by the SHA-256 of the cookie value;\n `last_seen` and key usage are buffered and flushed in the background.\n- The arm window, the LOCKED state, and the last burned window live in one\n `arm_state` row.\n- Triggers bump a per-domain revision counter. The server checks\n `PRAGMA data_version` about once a second and reloads only the caches whose\n domain changed, so CLI edits apply without a restart (except\n `server_config`, which is read at startup).\n- Old rows (activity, key events, sessions, trashed keys, control requests) are\n pruned hourly.\n- See [DATABASE.md](DATABASE.md) for the schema and operations.\n\n### memora-mcp\n\n- `catalog()` returns the full tool list. Each tool carries a name, a category,\n a description, a \"when to use\" note, and a JSON input schema. See\n [MCP.md](MCP.md).\n- `handle()` dispatches JSON-RPC methods: `initialize`,\n `notifications/initialized`, `tools/list`, `tools/call`, `resources/list`,\n and `resources/read`. Unknown methods return JSON-RPC error `-32601`.\n- `call_tool()` dispatches to `MemoryStore` under the caller's privacy view.\n- Every tool call publishes `ai_activity` start and end events.\n- `discovery_card()` builds the `/.well-known/mcp.json` document.\n- `detect_client()` classifies a request as MCP, web, or API from the path, the\n `mcp-session-id` header, the JSON-RPC body shape, and the user agent.\n\n### memora-http\n\n- `build_router()` wires every route and stacks the middleware layers listed\n below.\n- `AppState` holds the shared store, the MCP server, the database handle, the\n in-memory caches (owner, keys, tools, access stack, settings, arm window),\n the rate-limit guard, the allowed domains, the asset directory, and the vault\n path.\n- `oauth.rs` is an OAuth 2.1 authorization server for remote MCP clients;\n `privacy.rs` serves `/api/privacy`; `secrets.rs` seals API key copies.\n\n### memora-cli\n\nThe CLI never asks for the owner password. It opens setup and reset windows and\nprints one-time codes; credentials are always typed into the browser form.\n\n## Request path\n\nA request enters through `axum::serve` on the single bound address. Layers run\nin this order, outermost first:\n\n1. Security headers (`mw_security_headers`): CSP, `X-Frame-Options: DENY`,\n `X-Content-Type-Options`, `Referrer-Policy`, COOP/CORP,\n `Permissions-Policy`, `Cache-Control: no-store` for API and auth responses,\n and HSTS when HTTPS is reported by a trusted proxy. Applied to every\n response, including errors produced by inner layers.\n2. `X-Robots-Tag: noindex` (`mw_noindex`).\n3. A global concurrency limit of 1024 requests.\n4. A 30 second request timeout (`408`).\n5. Guard (`mw_guard`): requests for a host outside the domain allow list get a\n bare `404`. Forwarding headers from untrusted peers are dropped. The caller\n IP is resolved, only when the peer is a trusted proxy, from the right-most\n `X-Forwarded-For` entry that is not a trusted proxy, else `CF-Connecting-IP`,\n else `X-Real-IP`; a loopback address in a header is ignored. Per-IP\n token buckets apply to auth endpoints and to all traffic, and callers in a\n cooldown after failed logins or bad API keys get `429`. `/healthz` and\n direct loopback callers (no forwarding headers) are not rate limited.\n6. Access stack (`mw_access`): picks up changes from `memora-cli`, then\n evaluates the caller IP and the `Host` domain against the access rules. A\n block returns `403`. `/healthz` bypasses it.\n7. Auth and lock gate (`mw_auth`):\n - If the instance is LOCKED and the path is neither in the lock allow list\n nor a static asset: `/api/*` and `/mcp` return `423`; other paths redirect\n to `/login`.\n - Public paths pass: `/healthz`, `/.well-known/mcp.json`, `/tools`,\n `/login`, `/logout`, `/_bus`, `/`, `/index.html`, static assets, the OAuth\n discovery and flow endpoints, and the auth endpoints\n `/api/auth/{state,login,logout,bootstrap,reset,verify}`.\n - `/ws` needs a valid session and a same-origin request.\n - A valid session cookie (`memora_sess`) passes and is touched (sliding\n TTL); the response renews the cookie's `Max-Age` too, at most every five\n minutes per session, so an active browser keeps it. The web app pings\n `/api/auth/me` every few minutes while its tab is visible and in use.\n - Remaining `/api/*` and `/mcp` requests need an API key, read from\n `Authorization: Bearer <key>` or `X-API-Key: <key>`. The key must carry\n the scope the route needs (`mcp` for `/mcp`, `admin` for keys, tools,\n access, OAuth clients, privacy, and log settings, otherwise `read` for\n GET and `write` for changes). Usage is recorded; an unknown key is logged\n (`key_fail`) and counts toward the IP's cooldown. `/mcp` answers `401`\n with a `WWW-Authenticate` header so OAuth clients can start sign-in.\n8. Vault gate (`mw_vault`): until a vault folder is configured, every route\n that needs the vault (notes, graph, logs, `/mcp`) answers\n `409 {\"needs_vault\": true}`.\n\nThen the matched handler runs. Unmatched browser navigations get the app shell;\nother unmatched paths get a JSON `404`.\n\nFor a browser: `GET /` without a session redirects to `/login`. After login,\nthe UI calls the `/api/*` endpoints. Reads go to `MemoryStore`. Writes from a\ncookie session pass a same-origin check, then call `MemoryStore` `*_impl`\nmethods, which write the note, update the index, and commit to git.\n\nFor an agent: `POST /mcp` carries a JSON-RPC body. The handler parses it,\ndetects the client kind, and calls the MCP server under the key's privacy view.\nA tool call dispatches to the same `MemoryStore` methods the UI uses. REST\ncalls with an API key run under the same privacy view. See [API.md](API.md)\nand [MCP.md](MCP.md).\n\n## Realtime WebSocket fan-out\n\nThe event hub lives in `memora-core::events` as a process-wide singleton.\n\n- `publish()` stamps `_ts`. Persistable event types (`ai_activity` start\n events, `node_created`, `node_updated`, `node_deleted`, `node_renamed`,\n `folder_meta`, `folder_changed`, `actor_alias`, `key_color`) go into a\n 40-entry replay ring and are appended to `<vault>/.events.jsonl`, which is\n trimmed by the `log_max_mb` and `log_max_days` settings.\n- Events are broadcast on a Tokio broadcast channel (capacity 256); a lagging\n subscriber skips missed events instead of stalling the server.\n- `GET /ws` (signed-in browser, same origin, at most 512 clients) sends a\n `hello` event with the client count, replays the ring (each event marked\n `replay: true`), then streams live events. When a client disconnects, a\n `presence` event announces the new count.\n- `POST /_bus` is the local intake: it publishes a JSON object, but only from a\n loopback peer with no forwarding headers and no browser headers (`Origin`,\n `Sec-Fetch-*`), so a web page cannot post to it. Everyone else gets `403`.\n\nThe WebSocket and the intake bus share the single port. There is no second port\nto open or proxy.\n\n## Auth model\n\nOwner login (browser): the owner posts a username and password to\n`/api/auth/login`. The argon2id hash is verified, a session is created, and the\n`memora_sess` cookie is set (`HttpOnly`, `SameSite=Lax`, `Secure` when HTTPS is\nreported by a trusted proxy). The session slides on activity up to\n`session_ttl`, with an optional absolute cap (`session_max_age`).\n\nAPI keys (agents and scripts): created from the dashboard, the API, or\n`memora-cli` (`/keys`); the raw key is shown once. Only the SHA-256 hex is\nstored, plus an optional encrypted copy (see [Storage model](#storage-model))\nso the owner can show a dashboard-created key again after re-entering the\npassword. Keys carry scopes and an optional tool list.\n\nOAuth 2.1 (remote MCP clients): discovery at\n`/.well-known/oauth-protected-resource` and\n`/.well-known/oauth-authorization-server`; clients register dynamically\n(`/oauth/register`), by a client metadata document URL, or manually by the\nowner. The flow is authorization code with PKCE S256 only. The signed-in owner\napproves the request in the browser, and `/oauth/token` issues an access token\nthat is an ordinary API key, plus a rotating refresh token. Revoking the key\nends the connection.\n\nPrivacy rules: the owner can hide a folder or a note from chosen agents\n(`deny`) or from every agent except chosen ones (`allow_only`). Rules add up;\nthe signed-in owner always sees everything. Rules are managed through\n`/api/privacy` and the admin MCP tools.\n\nFirst-run and recovery (the arm window):\n\n- `GET /api/auth/state` is public and reports `bootstrap` (true when no owner\n exists), `armed`, `locked`, the setup hint, and readiness checks.\n- `memora-cli setup` (or `/web` in the console) arms a `bootstrap` window in\n the `arm_state` row, clearing any lock, and prints a one-time code. The\n browser submits the code and creates the owner through\n `/api/auth/bootstrap`, which works only while armed and only when no owner\n exists.\n- `memora-cli reset-password` arms a `reset` window; `/api/auth/reset`\n replaces the password.\n- A wrong code spends that IP's small budget (3, then a cooldown); 50 wrong\n codes in one window void it. A window that expires unfinished just closes\n (back to idle; agents and signed-in browsers keep working). LOCKED is only\n entered on purpose. While locked, only the lock allow list and static assets\n are reachable. `memora-cli unlock`, `setup`, or `reset-password` clears the lock.\n\nLock allow list (`LOCK_ALLOWED`): `/login`, `/logout`, `/api/auth/state`,\n`/api/auth/verify`, `/api/auth/login`, `/api/auth/logout`,\n`/api/auth/bootstrap`, `/api/auth/reset`, `/healthz`, `/favicon.ico`.\n\n## Storage model\n\nMemora keeps two directories apart on purpose.\n\n### Vault (markdown, portable)\n\nChosen in the browser after the first sign-in (`MEMORA_VAULT` is the\nsuggestion) and stored in the `settings` table.\n\n- One `.md` file per note. Frontmatter and inline `#tags` are both supported.\n- Wikilinks use `[[Note Name]]` and resolve by name, so moving or renaming a\n note does not break links.\n- `.git/` is the vault history. Changes commit automatically.\n- `.events.jsonl` is the append-only event log.\n- `.folders.json` stores folder color, icon, and description.\n- `.locks.json` stores soft locks used for collaboration.\n- `.actors.json` stores actor aliases.\n- `.Trash/` holds soft-deleted notes, recoverable with `restore_trash`.\n\n### State (credentials, operational)\n\nSet by `MEMORA_STATE` (default `state`).\n\n- `memora.db` is the single SQLite database for all server state: the owner\n (argon2id hash), API keys (SHA-256 hex, with a trash for restore), scopes\n and tool lists, global tool switches, OAuth clients and grants, privacy\n rules, sessions (hashed ids), the arm window and lock, access rules, instance\n settings, `server_config`, UI layouts, and the activity log. It is created\n and migrated on first start; WAL mode, mode 0600.\n- `key-seal.bin` is the 32-byte master key (0600) for the sealed API key copies\n (ChaCha20-Poly1305). The database holds only ciphertext, so a copy of\n `memora.db` alone reveals no key.\n- `backups/` holds `memora-cli db backup` copies.\n- `legacy-json-<unix time>/` holds JSON state files found at startup, moved\n there after their one-time import.\n- `internal.token` is created by the container entrypoint. Memora does not use\n it.\n\nState changes are transactional: a crash leaves either the old or the new\nstate, never a mix.\n"},{"file":"docs/DATABASE.md","slug":"database","title":"Database","text":"# State database\n\nMemora keeps all server state in one embedded SQLite file,\n`<MEMORA_STATE>/memora.db`, managed by the `memora-state` crate. The vault\n(markdown notes plus git) is separate and stays plain files.\n\nNo SQL lives outside `crates/state`. The server (`memora`) and the operator\nconsole (`memora-cli`) both open the file directly; there is no database\nserver, port, or password.\n\n## Files and permissions\n\n| Path | Mode | Content |\n|---|---|---|\n| `<state>/` | 0700 | The state directory. Created if missing; its mode is tightened on open. |\n| `memora.db` | 0600 | The database. |\n| `memora.db-wal`, `memora.db-shm` | 0600 | WAL journal and shared memory. Part of the live database; never copy `memora.db` without them while the server runs. |\n| `key-seal.bin` | 0600 | Master key for the sealed API key copies (`api_key_secret`). Not inside the database. |\n| `assistant.sqlite3` (+ `-wal`, `-shm`) | 0600 | Mnemo's own small database (`memora_state::assistant`): `providers` (API keys sealed with `key-seal.bin`, a four-character hint), `models`, `prefs`, `sessions` and `messages`. Kept apart from `memora.db`, so the main schema and its migrations are unchanged and an older binary simply ignores it. |\n| `backups/` | 0700 | Output of `memora-cli db backup` and the pre-restore snapshot. |\n| `legacy-json-<unix time>/` | 0700 | JSON state files found at startup, moved here after their one-time import. |\n\nThe state directory must be on a local filesystem. WAL needs shared memory\nand does not work on NFS or SMB; the server refuses to start when WAL cannot be\nenabled.\n\nRun as root, `memora-cli` does every database operation as the owner of the\nstate directory (in a child process that drops privileges), so no root-owned\n`memora.db*` files appear and the server can always open them.\n\n## Connection settings\n\nEvery connection, server and CLI, uses: `journal_mode=WAL`,\n`synchronous=FULL`, `foreign_keys=ON`, `busy_timeout`, `secure_delete=ON`\n(deleted rows are zeroed), `trusted_schema=OFF`, SQLite defensive mode, and a\n4 MiB `journal_size_limit`.\n\nThe file is marked with `PRAGMA application_id = 0x4D454D4F` (`MEMO`). Memora\nrefuses to open a file with another application id, or one whose\n`user_version` is newer than the binary supports.\n\n## Schema\n\nConventions: times are `INTEGER` unix seconds UTC; booleans are\n`INTEGER CHECK (x IN (0,1))`; every table is `STRICT`. Constraints (CHECK,\nUNIQUE, foreign keys, triggers) reject invalid data at the database level; the\nRust repositories validate first to return readable errors. The DDL is in\n`crates/state/migrations/*.sql`.\n\n### Auth and settings\n\n| Table | Content |\n|---|---|\n| `meta` | Key/value markers (for example the legacy import marker). |\n| `owner` | The single owner account: `id` is always 1, so a second account is impossible. Lowercase username (1-32 chars of `a-z0-9._-`), argon2id password hash, display name, timestamps. |\n| `settings` | One row (`id = 1`): `realm`, `session_ttl`, `session_max_age`, `min_password_len`, `log_max_mb`, `log_max_days`, `vault_path` (absolute or NULL). Ranges are listed in [CONFIGURATION.md](CONFIGURATION.md#instance-settings-web-ui). |\n| `server_config` | Server settings that override the environment. Only the ten known keys are accepted, with range checks for `MEMORA_PORT`, `MEMORA_ARM_TTL`, and `MEMORA_VAULT_AUTO`. `MEMORA_ADMIN_PASSWORD` and `MEMORA_API_KEY` cannot be stored. |\n| `arm_state` | One row: `idle`, `armed`, or `locked`, the window mode (`bootstrap` or `reset`), start time, length (30-86400 s), the SHA-256 of the one-time code, lock time, and the last burned window. Checks make an armed row without a code, or a code outside an armed window, impossible. |\n| `session` | Browser sessions keyed by `sid_hash`, the SHA-256 of the cookie value (the cookie itself is never stored). Source, alias, IP, user agent, `created_at`, `last_seen`. The CLI addresses sessions by a prefix of at least 8 characters of `sid_hash`. |\n\n### API keys and tools\n\n| Table | Content |\n|---|---|\n| `api_key` | `id` (`k_...`), name, SHA-256 hex `hash` (unique), display `prefix`, `enabled`, `tools_all`, `color` (`#rrggbb` or NULL), `created_at`, `deleted_at` (trash). `grace_until` is unused and always NULL. |\n| `api_key_scope` | Scopes per key: `mcp`, `read`, `write`, `admin`. |\n| `api_key_tool` | Allowed tools per key, only when `tools_all = 0` (a trigger enforces this and clears the list when `tools_all` is set back to 1). |\n| `api_key_secret` | Optional sealed copy of a dashboard-created key: `base64url(nonce || ChaCha20-Poly1305 ciphertext)` under `key-seal.bin`. |\n| `api_key_usage` | Last use, last IP, and use count per key. Separate from `api_key` so usage flushes do not trigger a key reload. |\n| `api_key_event` | Per-request key events (time, IP, tool or route, path). Used for activity views and new-IP detection. |\n| `tool` | Mirror of the MCP tool catalog, synced at server start. Tools missing from the catalog are marked `retired`. |\n| `tool_disabled` | Globally disabled tools (foreign key to `tool`). |\n\n### OAuth\n\n| Table | Content |\n|---|---|\n| `oauth_client` | Registered clients: `client_id`, name, redirect URIs (JSON array), kind (`dcr`, `cimd`, or `manual`). |\n| `oauth_code` | One-time authorization codes (SHA-256), PKCE S256 challenge, redirect URI, resource, expiry. |\n| `oauth_grant` | Refresh tokens (SHA-256), one per connection, rotated on every use. Each grant points at the API key that serves as its access token and is deleted with it. |\n\n### Access, privacy, and logs\n\n| Table | Content |\n|---|---|\n| `access_policy` | One row: the default action when no rule matches. |\n| `access_rule` | Ordered rules (`position`): kind (`ip`, `range`, `cidr`, `domain`, `all`), value, `allow` or `block`, enabled flag, note. |\n| `privacy_rule` | Hides a vault path from agents: kind `folder` (the folder and everything below it) or `node` (one note), mode `deny` (hidden from the listed keys) or `allow_only` (hidden from every key not listed). Paths are vault-relative and matched case-insensitively. |\n| `privacy_rule_key` | Keys a privacy rule lists. |\n| `privacy_trail` | Earlier paths of a rule after renames and moves (at most 64 per rule), used only to keep log and event lines that name the item away from hidden agents. |\n| `activity` | Audit log: time, event name, IP, actor (username, key id, or `cli`), detail. |\n| `control_request` | Requests from `memora-cli` to the running server for state that lives in server memory (`limiter_reset`, `reload_all`), with an acknowledgement (`done_at`, `result`). |\n| `ui_layout` | One JSON document per web UI layout name (canvas positions, pinned graph positions), at most 512 KiB each. |\n| `pin` | The owner's pinned notes and folders in sidebar order (`position`): kind `note` or `folder`, vault-relative path. At most 200. Renames, moves and deletes done by Memora rewrite or drop them in the same transaction. |\n| `revision` | One counter per cache domain (`auth`, `keys`, `tools`, `access`, `settings`, `arm`), bumped by triggers. |\n\nRevision triggers (one per insert, update, and delete) map tables to domains:\n`owner` to `auth`; `api_key`, `api_key_scope`, `api_key_tool` to `keys`;\n`tool_disabled` to `tools`; `access_policy`, `access_rule` to `access`;\n`settings`, `server_config` to `settings`; `arm_state` to `arm`. Sessions,\nusage, events, activity, OAuth, privacy rules, pins, and UI layouts have no revision\nand are read from the database when needed.\n\n## Concurrency and change detection\n\n- Every write is one transaction started with `BEGIN IMMEDIATE`, so the server\n and `memora-cli` can write at the same time without losing updates.\n `busy_timeout` makes a concurrent writer wait instead of failing.\n Multi-step changes are atomic, for example a password change also deletes the\n other sessions and writes the activity row in the same transaction.\n- The server keeps caches of the owner, keys, tools, access stack, settings,\n and arm window. It checks `PRAGMA data_version` on requests and at least once\n a second; when another connection committed, it reads `revision` and reloads\n only the changed domains. Changes made with `memora-cli` therefore apply on\n the next request, without a restart. `server_config` is the exception: it is\n read at startup.\n- Sessions are not cached: each request looks up `session.sid_hash`, so a\n sign-out from the CLI applies on the next request.\n- Hot-path writes are buffered: session `last_seen` is flushed every 5 seconds\n and key usage every 30 seconds. Pending control requests are served every 2\n seconds. Buffers are flushed on shutdown.\n- Window expiry is a conditional update (`armed` to `idle`, never `locked`), and a setup code\n is checked and consumed in the same transaction, so a code works at most\n once.\n\nKept in memory on purpose: rate-limit token buckets and login cooldowns (a\nrestart resets them; cooldown starts are still written to `activity`), the\ntrusted proxy list, and the caches above.\n\n## Retention\n\nThe server prunes in small batches every hour, and `memora-cli db vacuum` runs\nthe same pruning:\n\n| Data | Kept |\n|---|---|\n| `activity` | 365 days, at most 200,000 rows |\n| `api_key_event` | 30 days, at most 100,000 rows |\n| `session` | Until idle longer than `session_ttl` or older than `session_max_age` |\n| Trashed `api_key` rows | 90 days after `deleted_at` (scopes, tools, usage, and events cascade) |\n| `control_request` | 1 day after `done_at`; unanswered requests expire after 1 hour |\n\n## Migrations\n\nMigrations are SQL files embedded in the binary\n(`crates/state/migrations/0001_init.sql` and onward) and tracked with\n`PRAGMA user_version`. Each one runs in its own `BEGIN IMMEDIATE` transaction\ntogether with the version bump, so a crash leaves either the old or the new\nschema, and two processes opening a fresh file apply it exactly once. The\nserver and `memora-cli` migrate the database when they open it. A binary\nrefuses a database with a newer schema; to go back to an older release,\nrestore the backup taken before upgrading.\n\n| Version | File | Adds |\n|---|---|---|\n| 1 | `0001_init.sql` | Base schema and revision triggers |\n| 2 | `0002_ui_layout.sql` | `ui_layout` |\n| 3 | `0003_colors_logs.sql` | `api_key.color`, `settings.log_max_mb`, `settings.log_max_days` |\n| 4 | `0004_oauth.sql` | `oauth_client`, `oauth_code`, `oauth_grant` |\n| 5 | `0005_key_secret.sql` | `api_key_secret` |\n| 6 | `0006_privacy.sql` | `privacy_rule`, `privacy_rule_key`, `privacy_trail` |\n| 7 | `0007_pins.sql` | `pin` |\n| 8 | `0008_windows_vault_path.sql` | `settings.vault_path` accepts Windows absolute paths (table rebuilt) |\n\n### JSON state import\n\nWhen the server starts on a state directory that holds JSON state files\n(`gateway.json`, `config.json`, `memora.env`, `tools.json`,\n`access_stack.json`, `sessions.json`, `arm.json`, `lock.json`,\n`key-usage.json`, `activity.jsonl`, and related files), it imports them once,\nin one transaction, then moves them to `legacy-json-<unix time>/`. Auth data\nmust be valid or nothing is imported; bad log lines are skipped and counted.\nPlaintext `MEMORA_ADMIN_PASSWORD` and `MEMORA_API_KEY` values are dropped. A\nsummary is written to the log and the `activity` table. On a fresh state\ndirectory the import is a no-op.\n\n## Operations\n\n| Task | Command | Notes |\n|---|---|---|\n| Backup (server running) | `memora-cli db backup [--to PATH] [--keep N]` | `VACUUM INTO` a consistent copy, checked with `integrity_check`, mode 0600. Default target `state/backups/memora-<UTC time>.db`; the newest 10 there are kept (`--keep N`). `--to` takes a file or a directory. |\n| Backup without memora-cli | `sqlite3 memora.db \".backup '/var/backups/memora.db'\"` | Never `cp` a live WAL database: recent commits sit in `memora.db-wal`. |\n| Restore | `memora-cli db restore FILE [--force]` | The server must be stopped (the CLI checks for it and for any process holding `memora.db*`; `--force` skips the check). Verifies `application_id`, schema version, `integrity_check`, and foreign keys, saves the current database to `state/backups/memora-<time>-pre-restore.db`, then replaces it and removes stale `-wal`/`-shm` files. |\n| Health | `memora-cli db check` | Directory and file permissions, application id, schema version, `integrity_check`, `foreign_key_check`, file sizes, last backup age. Exit status 1 on any problem, for timers and health checks. |\n| Maintenance | `memora-cli db vacuum` | Prune by retention, `PRAGMA optimize`, `VACUUM`, `wal_checkpoint(TRUNCATE)`. |\n| Inspect | `memora-cli db shell [--write]` | Runs `sqlite3` (must be installed), read-only unless `--write`. Writes through the shell bypass Memora's checks and the activity log. |\n| Export | `memora-cli db export-json [DIR]` | Writes the database out as JSON state files (default: the state directory). |\n\nIn the console: `/backup`, and `/db` with `check`, `vacuum`, or `backup`.\n\nIn Docker, run the same commands through the container:\n\n```sh\ndocker compose exec gateway memora-cli db backup # lands in ./state/backups/\ndocker compose exec gateway memora-cli db check\n```\n\nFor a restore, stop the service first and run the CLI in a one-off container:\n\n```sh\ndocker compose stop gateway\ndocker compose run --rm gateway cli db restore /state/backups/memora-<time>.db\ndocker compose start gateway\n```\n\nA daily systemd timer or cron job running `memora-cli db backup` is enough for\nmost installs. Back up `key-seal.bin` with the database; without it, sealed key\ncopies cannot be shown again (the keys themselves keep working).\n\n## Encryption at rest\n\nThe database is not encrypted. Every credential in it is a one-way hash\n(argon2id for the owner password, SHA-256 for API keys, OAuth codes and refresh\ntokens, setup codes, and session ids), and sealed key copies are encrypted\nunder a key stored outside the database. What remains (IPs, user agents,\nactivity) is low sensitivity. Use a 0700 state directory, host disk\nencryption, and encrypt backups that leave the host (for example with `age` or\n`gpg`).\n"},{"file":"docs/contracts/tools-permissions.md","slug":"tool-reference","title":"Tool reference","text":"# Tool switches and per-key permissions\n\nThis page describes how Memora decides which MCP tools an agent may see and\ncall. Two controls combine:\n\n- **Global tool switches** turn a tool off for every API key on the server.\n- **Per-key permissions** (scopes and a tool list) limit what one key may do.\n\nThey are managed in the web UI, with `memora-cli` (`/tools` and `/keys`), over\nthe HTTP API, and with the MCP admin tools. All of them write the same state\ndatabase (`state/memora.db`, see [../DATABASE.md](../DATABASE.md)). Tool\nswitches and per-key tool lists from older installs (`state/tools.json` and the\n`tools` field of keys in `gateway.json`) are imported into the database once.\n\n## Tool catalog\n\nThe switchable catalog is `memora_mcp::catalog()`: every tool with its `name`,\n`category`, `description`, when to use it, and input schema (74 tools; see\n[../MCP.md](../MCP.md#tools)). At startup the server mirrors the catalog into\nthe `tool` table, so switches and per-key grants can refer to tools by name.\nA tool that leaves the catalog is marked retired, not deleted: its switch and\ngrants are kept but have no effect, and they apply again if the tool returns.\n\nThe admin tools (`admin_list_tools`, `admin_set_tool`, `privacy_list`,\n`privacy_set`, `privacy_clear`) are not part of the catalog. They cannot be\nswitched off or granted through a tool list; only the `admin` scope controls\nthem.\n\n## Global tool switches\n\nTable `tool_disabled` holds one row per switched-off tool. No row means the tool\nis on. A switched-off tool is hidden from `tools/list` and refused by\n`tools/call` for every caller, browser sessions included. It is still listed in\nthe discovery card and on the `/tools` page, marked as disabled.\n\nSwitching a tool that is already in the requested position changes nothing.\nA change made by another process (for example `memora-cli` while the server\nruns) reaches the server within about a second, without a restart.\n\n## Scopes\n\nEach key has a set of scopes (table `api_key_scope`):\n\n| Scope | Allows |\n|---|---|\n| `mcp` | Calling `/mcp` at all, and every read-only MCP tool. |\n| `read` | `GET` and `HEAD` on the `/api/*` vault routes. |\n| `write` | Mutating `/api/*` vault routes, and every MCP tool that is not read-only. |\n| `admin` | Managing tools, keys, access rules, log settings, OAuth clients and privacy rules (`/api/tools`, `/api/keys`, `/api/access`, `/api/logs/settings`, `/api/oauth/clients`, `/api/privacy` and everything below them), and the MCP admin tools. |\n\nA key created without explicit scopes gets `mcp`, `read` and `write` and every\ntool. Keys that MCP clients obtain through OAuth start with the same defaults.\n`admin` is never granted by default. An empty scope list on create also means\nthe defaults.\n\n## Per-key tool list\n\nEach key either may use every catalog tool (`\"tools\": \"*\"`, stored as\n`api_key.tools_all = 1`, the default) or only the tools listed for it\n(`\"tools\": [\"search_memory\", \"read_memory\"]`, stored as `tools_all = 0` plus one\n`api_key_tool` row per tool). An empty list allows no catalog tools. Tool names\nmust be catalog tools; unknown names are refused with `unknown tool: <name>`.\n\nThe tool list does not replace scopes: a tool that changes the vault still\nneeds `write`, even when the list names it.\n\n## Effective access\n\nA key may call catalog tool T over MCP when all of these hold:\n\n1. The key is enabled.\n2. The key has the `mcp` scope.\n3. T is not switched off globally.\n4. The key's tool list is `\"*\"` or contains T.\n5. T is read-only, or the key has the `write` scope.\n\nRead-only tools are the ones listed as read-only in `crates/mcp/src/activity.rs`\n(the R tools in [../MCP.md](../MCP.md#tools)). Every other catalog tool needs\n`write`, including tools added later until they are marked read-only.\n\nAn admin tool may be called when the key is enabled and has both `mcp` and\n`admin`. Browser sessions have full access, including the admin tools, but\nglobal switches still apply to them.\n\nDisabled keys are rejected before MCP runs (HTTP `401`, `invalid API key`), and\na key without `mcp` gets HTTP `403` with\n`{\"error\":\"API key lacks the 'mcp' scope\",\"required_scope\":\"mcp\"}`.\n\n## How refusals look\n\n`tools/list` returns only the tools the caller may use (plus the admin tools for\nadmin keys).\n\n`tools/call` on a tool the caller may not use returns JSON-RPC error `-32003`\nwith one of these messages:\n\n| Message | Cause |\n|---|---|\n| `tool not allowed for this API key: <name>` | The key's tool list does not include the tool, or the caller lacks `admin` for an admin tool. |\n| `tool disabled on this server: <name>` | The tool is switched off globally. |\n| `API key lacks the 'write' scope for tool: <name>` | The tool is not read-only and the key has no `write` scope. |\n\nA name that is neither a catalog tool nor an admin tool is not refused with\n`-32003`; the call returns a tool result with `isError: true` and\n`unknown tool: <name>`.\n\n## HTTP API\n\nThese routes need a signed-in browser session or an API key with the `admin`\nscope. For browser sessions, `POST` requests must be same-origin.\n\n| Route | Body | Response |\n|---|---|---|\n| `GET /api/tools` | | `{tools: [{name, category, description, enabled}]}` |\n| `POST /api/tools` | `{name, enabled}` | `{ok, name, enabled}`. Unknown tool or missing `enabled`: `400`. |\n| `GET /api/keys` | | `{count, keys}`. Each key includes `tools` (`\"*\"` or a list) and `scopes`. |\n| `POST /api/keys` | `{name, tools?, scopes?, color?}` | `{ok, id, key, name, prefix, persisted, color, tools, scopes}`. The raw `key` is returned once. |\n| `POST /api/keys/update` | `{id, name?, enabled?, color?, tools?, scopes?}` | `{ok, id, name, enabled, color, tools, scopes, persisted}` |\n\n`tools` is `\"*\"` or an array of catalog tool names. `scopes` is an array of\n`mcp`, `read`, `write` and `admin`. Fields left out stay unchanged. Unknown tool\nor scope names return `400` (`unknown tool: <name>`, `unknown scope: <name>`).\n\n## MCP admin tools\n\nListed only for keys with the `admin` scope:\n\n- `admin_list_tools`: no arguments. Same shape as `GET /api/tools`.\n- `admin_set_tool`: `{name, enabled}`. Same effect as `POST /api/tools`.\n\nThe privacy admin tools (`privacy_list`, `privacy_set`, `privacy_clear`) are\ndescribed in [../MCP.md](../MCP.md#admin-tools-admin).\n\n## Activity log\n\nEvery change is written to the `activity` table in the same transaction:\n\n| Event | When | Detail |\n|---|---|---|\n| `tool_enabled` | A tool is switched on | The tool name |\n| `tool_disabled` | A tool is switched off | The tool name |\n| `key_permissions` | A key's scopes or tool list are set on create or changed on update | `<id> tools=[...] scopes=[...]` |\n\nCreating and updating a key also logs `key_created` and `key_updated`. The actor\nis the signed-in user, or `key:<id>` when an API key made the change.\n"},{"file":"SECURITY.md","slug":"security","title":"Security","text":"# Security Policy\n\n## Supported versions\n\nSecurity fixes are applied to the latest release. Run the newest published\nversion to receive them.\n\n| Version | Supported |\n|---|---|\n| Latest release | Yes |\n| Older releases | No |\n\n## Reporting a vulnerability\n\nDo not open a public issue for a security problem. Report it privately:\n\n- Use GitHub's private vulnerability reporting on the repository\n (Security tab, \"Report a vulnerability\"), or\n- Email the maintainers at the address listed in the repository profile.\n\nInclude as much as you can:\n\n- A description of the issue and its impact.\n- Steps to reproduce, or a proof of concept.\n- Affected version and deployment method (binary or container).\n- Any suggested fix or mitigation.\n\nWe aim to acknowledge reports within a few business days and to provide a\ntimeline for a fix. We will credit reporters who wish to be named once a fix is\nreleased.\n\n## Security model\n\nMemora is designed to run as a single-owner service, usually behind a reverse\nproxy. Relevant properties:\n\n- User passwords are stored as argon2id hashes and verified in constant time.\n- API keys are random, shown once, and stored only as SHA-256 hex. Verification\n is constant time. Unknown hash formats are rejected.\n- Browser sessions use an `HttpOnly`, `SameSite=Lax` cookie with a sliding TTL.\n Only a hash of the session id is stored. The `Secure` attribute is set when\n the request arrives over HTTPS through a trusted proxy.\n- Cookie-based writes are protected by an origin check (`Origin`/`Referer`\n against `Host`). Pages are served with a nonce-based Content-Security-Policy.\n- API keys carry scopes (`mcp`, `read`, `write`, `admin`) and an optional tool\n list; tools can be switched off for every key, and privacy rules hide notes or\n folders from chosen agents.\n- MCP clients that use OAuth get an ordinary API key after the owner approves\n them in the browser (authorization code with PKCE S256), so the same scopes,\n revocation and activity log apply.\n- An unclaimed instance is protected by the setup window: the CLI opens a\n short-lived session and the browser completes it. If the window expires\n unfinished, the instance locks and only recovery paths stay reachable.\n- The access stack can restrict access by IP, range, CIDR, and domain, with\n loopback always allowed to prevent lockout.\n- The local event intake (`POST /_bus`) accepts loopback only, and refuses\n requests a browser marks as its own (`Origin`, `Sec-Fetch-*`).\n- Failed sign-ins are limited per IP: after 5 failures in 15 minutes that IP\n waits 5, then 10, then 15 minutes. Failures from many IPs never lock the\n owner out: 20 failures in 15 minutes across all IPs switch on a slow mode in\n which every sign-in waits about a second and a single failure puts that IP on\n its cooldown. A correct password from an IP without recent failures is still\n accepted, and a successful sign-in ends slow mode.\n- A wrong setup code counts against that IP's budget of 3 wrong codes (then a\n cooldown). The code stays single-use and the window time-limited; only 50\n wrong codes in one window (from any IPs) close it early.\n- Dynamic OAuth client registration is limited per IP, and registered clients\n that never complete an authorization are removed after an hour.\n\n## Deployment guidance\n\n- Terminate TLS at the reverse proxy and forward `X-Forwarded-Proto: https`.\n- Keep the state directory private. Its database, `memora.db`, holds credential\n hashes and the activity log.\n- Back up `memora.db` with `memora-cli db backup`; losing it loses the owner\n account, API keys and settings.\n- Do not expose the service directly on a public interface without a proxy and\n without the access stack configured.\n- Rotate API keys periodically (web UI, `memora-cli` -> `/keys`, or\n `POST /api/keys/roll`).\n\n## Dependencies\n\nCI checks the dependency trees for published advisories on every push and pull\nrequest:\n\n- `cargo audit` checks `Cargo.lock` against the RustSec advisory database. A\n vulnerability advisory fails the build; unmaintained, unsound and yanked\n notices are shown as warnings. Advisories reviewed and found not to apply\n are listed with their reason in `.cargo/audit.toml`.\n- `npm audit --omit=dev` checks the web UI packages that end up in the built\n assets.\n\nDependabot proposes updates for Cargo, npm, GitHub Actions and the Docker base\nimages. GitHub Actions are pinned to full commit SHAs. These checks only cover\nadvisories that have been published; they do not replace a review of the code.\n\n## Out of scope\n\n- Misconfiguration of a reverse proxy or TLS termination.\n- Issues that require an already-compromised host or root access.\n- Denial of service from an attacker with unlimited network access, absent a\n specific, novel amplification vector.\n"},{"file":"CHANGELOG.md","slug":"changelog","title":"Changelog","text":"# Changelog\n\nAll notable changes to this project are documented in this file.\n\nThe format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),\nand this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).\n\n## [Unreleased]\n\n## [2.1.9] - 2026-11-18\n\nChats stay in step on every device, and the queue never gets stuck.\n\n### Added\n\n- Live chats on every device: a message sent from one device shows on every\n other device that has the chat open, and Mnemo's reply streams on all of\n them (`GET /api/assistant/sessions/{id}/watch`).\n- Fallback models (Settings, Mnemo): up to five models, in order. When a\n reply's model fails after its retries, the next one carries on by itself;\n with none left the error stands and the owner tries again by hand\n (`@mnemo` requests keep their own retries).\n- Thinking level next to the model, for models that can think: Auto, Off,\n Low, Medium or High (Anthropic `output_config.effort`, OpenAI\n `reasoning.effort` / `reasoning_effort`, OpenRouter-style `reasoning.effort`).\n- Switching the model of a chat that has begun asks first.\n\n### Changed\n\n- The queue lives on the server, shared by every device: queued messages go\n out one by one as each reply ends, whether it finished, was stopped or was\n cut. A failed reply pauses the queue until a message is sent now or the\n queue resumes. Send now, Clear and Resume are always available\n (`/api/assistant/sessions/{id}/queue`).\n- Send now (a queued message, or Ctrl/Cmd+Enter) no longer slips the message\n into the running reply: the reply is cut where it is and the message is\n answered as a new turn of its own (`/steer`).\n- Stop keeps what the reply wrote so far in the chat (`meta.stopped`).\n- A long queue shows three rows with a fade and scrolls; Show all opens it.\n\n### Fixed\n\n- The compaction summary shows as it is written and can always be opened,\n instead of an empty divider until the chat was opened again.\n- After Stop, queued messages could lose their buttons and never go out.\n\n## [2.1.8] - 2026-11-17\n\n`@mnemo` requests are never dropped.\n\n### Fixed\n\n- An `@mnemo:` request Mnemo could not answer (the AI provider or the\n network down, or no model yet) is no longer struck through with \"Could\n not answer\": it stays open in the note and is tried again after 1, 3, 10\n and 30 minutes, then hourly (up to about a day; any change to the note\n starts over). A retry runs the same message in the note's chat instead of\n asking twice, and only the answer to that request is written back.\n- What's new: the release row starts flush left and fades only on a side\n with more to scroll to; an arrow shows only where there is somewhere to go.\n- Opening Mnemo at `/mnemo/<id>` shows that chat's title right away instead\n of \"New chat\" while it loads.\n- Fresh ideas shows a shimmer on the button and placeholder cards while\n Mnemo writes, instead of a spinning icon.\n\n## [2.1.7] - 2026-11-17\n\nSkills, fleeting chats, suggestions that change, and a note's chats that\nfollow the note.\n\n### Added\n\n- Skills: notes in the vault's `Skills` folder (file name = skill name, a\n `description:` line, then the steps). Typing `/` in Mnemo's message box\n lists them; `/name ...` sends the skill's steps with the message\n (`meta.skill`). Mnemo makes, changes and removes skills with its note\n tools. New endpoint `GET /api/assistant/skills`.\n- Fleeting chats (the eye in Mnemo's header): not kept, left out of the chat\n list, search and Mnemo's look-back tools, and deleted with the pictures\n sent in them when the owner leaves (or after 30 minutes idle). Changes to\n notes stay. `POST /api/assistant/sessions` takes `fleeting: true`.\n- Suggestions on a new chat change each time: the owner's own (Your\n suggestions, kept), ones Mnemo writes from recent notes (refreshed at most\n every 12 hours, or now with Fresh ideas) and built-in ones; skills show as\n chips. Endpoints `GET/POST /api/assistant/suggestions` and\n `POST /api/assistant/suggestions/refresh`.\n- Mnemo tool `view_image`: look at a picture in the vault (a note's\n picture by its path); a web address is refused with a note to send or add\n the picture instead.\n- Ask Mnemo from a note's page offers that note's earlier chats\n (`GET /api/assistant/sessions?about=<path>`).\n\n### Changed\n\n- All `@mnemo:` requests in one note go to that note's one chat (titled\n `@mnemo · <note>`), and a note's chats follow it when it is renamed,\n moved, sent to the Trash or restored.\n- An `@mnemo:` request Mnemo writes into a note from a chat or the console\n is answered like the owner's; what it writes while answering a request\n never asks again.\n- Deleting chats also deletes the pictures sent in them (pictures placed in\n notes stay in the vault).\n- What's new: arrows show only where there is more, and a new footer with\n the GitHub star count.\n- A page open beside the chat folds the chat list and \"In this chat\" away\n so the chat keeps its room; the list comes back when the divider leaves\n room for it, and everything returns when the page closes. When the chat\n and the page cannot both fit, the page opens full screen.\n\n### Fixed\n\n- Pictures in notes are capped at about 60% of the screen height (480 px).\n- Leaving a chat while Mnemo answers no longer shows a network error; the\n chat reconnects to the running reply.\n- Chats left with their question's first words as the title (the model\n could not name them) get a proper title on the next reply; titles have\n room for models that think first.\n\n## [2.1.6] - 2026-11-17\n\nMnemo's pages become versions of one file, chats can be cleaned up in bulk,\nand a chat is compacted only once it is full.\n\n### Added\n\n- Page versions: an HTML or SVG page Mnemo rewrites under the same title is\n the next version of the same file. Cards show v1, v2 and latest (older\n ones dimmed), the preview panel steps between versions, and the newest\n opens beside the chat by itself on a wide screen (or replaces what an open\n panel shows). Mnemo is told to rework its latest version when asked to\n change or tidy a page, and to start a new page only when asked.\n- A draggable divider between the chat and an open page (keyboard arrows\n too; double-click resets). The page keeps at least 360 px, the chat at\n least 420 px, and the page at most 75% of the width; the width is\n remembered per device.\n- Deleting many chats: Select chats (pick several, then Delete), Clean up\n chats (untouched for 7, 30 or 90 days) and Delete all chats, from the ⋯\n beside New chat and the chat menu. Pinned chats are kept unless asked; a\n chat answering right now is left alone. New endpoint\n `POST /api/assistant/sessions/prune` (`ids`, `older_than_days` or `all`,\n with `keep_pinned`).\n- Mnemo tool `list_chats` (the owner's chats, newest first, optionally by\n title) and paging for `read_chat`, so Mnemo can connect a chat with\n earlier ones.\n- Mnemo tools `list_artifacts` and `read_artifact`: the pages Mnemo wrote,\n across chats, and a page's full source by version, so a page can be\n reworked or reused from another chat. Pages live in their chat's messages\n and are deleted with it; the \"In this chat\" panel lists them under Pages.\n\n### Changed\n\n- Auto-compaction starts only when a chat's history fills all the tokens it\n may use (the model's context minus the room kept for the reply), instead\n of at 80%. While it runs, a working divider with a clock shows in the\n chat; it turns into Compacted (with how long it took) and the reply goes\n on. Compact now shows the same divider.\n- Page cards are as wide as the reply, tinted with an accent edge and an\n accent Open button, and long titles end in an ellipsis.\n- Mnemo's chat list foot: Appearance is one wide button (showing the theme\n and background in use) above Activity, Settings and Memora.\n- Thin rounded scrollbars in the chat, the message box and the chat list\n that show only while scrolling; the track keeps its width, so nothing\n shifts.\n- What's new: releases slide in one row with arrows (newest first) and the\n footer stacks neatly on phones.\n\n### Fixed\n\n- The New chat button in Mnemo's chat list header on phones no longer takes\n the unread badge's look.\n\n## [2.1.5] - 2026-11-17\n\nUnread chats agree on every device, Mnemo's chat list ends in one tidy row,\nand phones no longer send a message on Enter.\n\n### Changed\n\n- Unread chats are remembered on the server instead of per browser: a chat\n read on one device is read on all of them. New endpoint\n `POST /api/assistant/sessions/{id}/seen`; the chat list carries each\n chat's `seen` count. The first list after updating counts everything\n there as read.\n- The scroll-down button in Mnemo's chat is a plain scroll to the bottom;\n the \"New messages\" label is gone (it also showed for older messages).\n- On touch keyboards Enter adds a new line in Mnemo's message box and the\n send button sends; on physical keyboards Enter still sends and\n Shift+Enter adds a line.\n- Mnemo's chat list: theme, chat background and text size moved into an\n Appearance panel (a bottom sheet on phones), and the foot of the list is\n one row of four tiles: Appearance, Activity, Settings and Memora.\n\n## [2.1.4] - 2026-11-17\n\nMnemo's pages open like files, a button takes you back to the latest\nmessage, and chats with news are marked.\n\n### Added\n\n- A scroll-down button in Mnemo's chat: it appears in the middle above the\n message box when the latest message is out of sight, and turns into \"New\n messages\" when a reply arrives while you are reading further up.\n- Unread chats: the sidebar's Mnemo item (and its menu entry) shows how many\n chats have news you have not seen, and the Mnemo chat list marks each one\n with its number of new messages, in bold. Kept per device; a chat counts\n as read once it is open on screen.\n\n### Changed\n\n- An HTML or SVG answer now shows in the chat as a file card (title, kind\n and length, Open and Download). Opening it shows the page in a panel\n beside the chat on a wide screen, with the chat making room, and full\n screen on tablets and phones; the panel has Preview and Code, Copy,\n Download and a clear Close (Esc). A page Mnemo has just written opens\n beside the chat by itself when there is room.\n\n### Fixed\n\n- The \"Compacted\" divider sits in the middle of the chat column again (its\n own margin overrode the column's centring).\n\n## [2.1.3] - 2026-11-17\n\nMnemo can answer with a picture: charts, diagrams and small pages show as a\nlive preview right in the chat.\n\n### Added\n\n- HTML and SVG answers: when a chart, graph, diagram, timeline or mock-up\n explains better than text, Mnemo writes one self-contained page and, once\n the reply is done, the chat shows it as a live preview (the eye) with Code,\n Copy, Download and Full screen. The page runs in a sandboxed frame with no\n access to your notes, your session or the network beyond scripts and\n styles from https, so it costs the server nothing. Older chats learn it\n too.\n\n### Changed\n\n- The divider where a chat's memory was compacted now just says\n \"Compacted\", centred between its lines on every screen size; open it to\n read the summary.\n\n## [2.1.2] - 2026-11-16\n\nMnemo fits your screen and rides out a provider that is down for a moment:\nfull width on phones, a text size you choose, and plain errors with Try again.\n\n### Added\n\n- Text size for Mnemo's chat: Auto, Small, Medium or Large, from Appearance\n in the chat list or Settings, Mnemo (kept per device). Auto is small on\n phones, so more fits on the screen, and medium elsewhere. Replies, your\n messages, questions, steps and thinking all follow it.\n\n### Changed\n\n- On phones Mnemo's replies drop the avatar beside them and use the full\n width, with equal margins on both sides; the timeline narrows into the\n right margin.\n- When a reply fails (the provider answers 503, 404, 401, 429, times out…)\n Mnemo says what went wrong in plain words with Try again (and Open\n settings when the key or model needs a look); the provider's full error\n shows only when you open it. In the console `/details` prints it.\n- A provider that is briefly down or busy (502, 503, 504, 429, a dropped\n connection) is asked again up to three times over about half a minute,\n with a note in the reply, before Mnemo shows an error; never once text has\n started to stream. An HTML error page from a proxy is cut down to its\n title in the error.\n\n## [2.1.1] - 2026-11-16\n\nMnemo asks before it guesses, works on its own when you let it, and takes\nmessages while it works.\n\n### Added\n\n- Mnemo can ask you a question with options listed one under another, and\n Other, which opens a box in the card for your own answer; its reply ends\n there and your answer goes on. Sending something else instead marks the\n question skipped. In the console the options are a pick list.\n- Permission: **Ask first** (the default: Mnemo reads freely, but a change to\n your notes waits until you approve it through one of its questions) or\n **Auto** (changes go ahead without asking and long jobs keep going, up to 40\n steps a reply). Switch it from the chip in the composer, Settings, Mnemo,\n or `/auto` and `/ask` in the console. Requests written with `@mnemo:` in a\n note count as approved.\n- A queue: what you send while Mnemo is answering waits above the prompt,\n can be reordered (arrows or drag) or removed, and goes out by itself when\n the reply ends (not after Stop). Ctrl/Cmd+Enter, or the Enter button on a\n queued message, steers the running reply instead: Mnemo reads it before its next\n step, and it shows inside the reply. While a reply runs the button is Stop,\n and turns back into Send (to the queue) as soon as you type.\n\n### Changed\n\n- On the Mnemo page notices appear at the top right, clear of Send and Stop.\n- The composer reads left to right: attach, the permission chip, then the\n model (with its pin) beside the memory ring and Send.\n- Mnemo's replies sit on a frosted card that stays readable over any chat\n background; the chat scrolls without a scrollbar (the timeline and the\n edge fades show where you are).\n- Thinking, steps and every other detail start closed; an open section keeps\n its header in view while you scroll through it, so it closes from anywhere.\n- A reply without approval runs up to 25 steps before it pauses (was 10).\n\n### Fixed\n\n- Mnemo no longer shows as \"key removed\" in Your AIs, nor greyed out in Live\n activity: it is built in. Your AIs lists five agents, with Show all for\n the rest.\n- The note panel's Contents and Details tabs, and Outline, Links, Mentions\n and Images, follow the reading theme, so they stay readable in every\n theme; the four tabs always fit, each count above its name.\n- A long note path no longer runs over the step's title and result.\n- The ⋯ on each chat in the list works on touch screens (iOS spent the first\n tap on a hover), and All chats opens a folded chat list.\n\n## [2.1.0] - 2026-11-16\n\nMnemo, a notes agent built into Memora, and images that live beside their\nnotes. The state database needs no migration: Mnemo keeps its chats, models\nand sealed API keys in a separate `assistant.sqlite3` beside it, so 2.0 can\nstill roll back by swapping the binary.\n\n### Added\n\n- **Mnemo**, the notes agent built into Memora. Add as many providers as\n you like, each with its own name and ID: OpenAI (Chat Completions or the\n Responses API), Anthropic (Messages) or any OpenAI-compatible server\n (OpenRouter, Groq, Ollama, LM Studio, vLLM…), with your own API key; the\n key is sealed on the server and never sent back. Each provider can be\n tested, switched off (its models leave the pickers) or deleted.\n Mnemo finds, reads, writes, tags, links, moves and tidies notes with\n Memora's own tools, under its own name in Activity. It has no web, shell,\n admin or delete-for-good tools.\n - A full-screen chat page at `/mnemo` (no app header or tab bar; close it\n with the X or Esc, or go back to Memora from the chat list) with a chat\n list (search, pin, rename, delete). Opening Mnemo (the menu, the floating\n button on every page, Ctrl/Cmd+J or \"Ask Mnemo\" on notes and folders)\n always starts a new chat, with the open note or folder ready to attach;\n earlier chats are in the list. Drag the button to either side; drop it on the X (or\n use its × on hover) to hide it on that device, and bring it back from\n More, Show the Mnemo button.\n - Thinking as the model writes it: Claude's and OpenAI's reasoning\n summaries, the raw reasoning that OpenAI-compatible servers send\n (`reasoning_content`, `reasoning`, `reasoning_details`; Mnemo asks for it\n and stops asking a server that refuses), and the `<think>` blocks open\n models such as DeepSeek-R1, Qwen and Hermes write into their answers.\n - Mnemo knows the time where you are (its `current_time` tool uses your\n device's time zone) and Memora's own documentation (`search_docs`,\n `read_docs`): it answers questions about Memora and links the Docs page\n it used.\n - Streaming replies with live thinking (where the provider shows it) and an\n Activity block per reply: each step as it happens, then what Mnemo did,\n how long it took and the notes it read or changed (tap to open).\n Wikilinks open notes. The composer rests as a one-line capsule and opens\n on focus with +, the model picker (pinned first, hidden left out), a pin\n that makes the model the default for new chats (browser and console) and\n the memory ring. A timeline rail at the right edge, in thumb reach, has a\n bar per question: tap one to jump, hover it, or press and slide along the\n rail to scrub through the chat (the bars swell under the finger, a label\n names the question, phones tick). The transcript fades under its edges\n while you scroll.\n - Each chat keeps its whole conversation for its model. Near full, Mnemo\n folds the older messages into a summary written by the same model and\n carries on (a marker in the chat opens the summary); the memory ring\n shows how full the chat is, where compaction starts, and compacts on\n request.\n - Attach notes, folders and images to a message with + (or paste and drop\n images): they show as chips above the prompt, each with an ×, in one row\n that slides left and right (arrows on wide screens, no scrollbar). Up to\n four images per message; tap one to preview it. Images go to the model\n as real image input (OpenAI, Responses and Anthropic formats), so it can\n see them; a model without vision gets their names and a notice. Mnemo\n can also put an attached image beside the note it belongs to with its\n `place_image` tool. A big folder or the whole vault goes along as a list\n that Mnemo reads one note at a time, in batches, saying how far it got.\n - In the chat, the pictures that came with a message are tiles (tap for\n the full view, with the others of that message) next to its note chips,\n in the order they were attached, in a sliding row. Under every reply a\n Related row lists what it changed, showed and read.\n - Models: fetch them from the provider, with the context window and\n reply limit it reports in its standard model list, or add them by name;\n pin, hide and pick a default (with no default, new chats take the first\n pinned model, the same one everywhere).\n - Settings, Mnemo: providers, models, your own instructions in plain\n words and the floating button. Temperature, limits and tool steps keep\n sensible defaults (and stay adjustable over `POST /api/assistant/prefs`).\n - Ask Mnemo inside a note: a line with `@mnemo: <request>` (the editor\n offers it as you type `@` or `/mn`; also in a quote or a list item, never\n in code) runs a few seconds after the note is saved. Each request gets a\n chat of its own, titled `@mnemo · <note>: <request>` and shown with an\n \"@ note\" tag, where its steps and thinking stay; then Mnemo strikes the\n request through\n (`~~@mnemo: …~~`) and quotes its reply right under it; a struck request\n never runs again. Agents can ask the same way with\n `mention_agent` and agent `mnemo`.\n - Every chat has its own address (`/mnemo/<id>`): a reload, a link or Back\n opens the same chat. A new chat is called \"New chat\" until Mnemo's first\n reply, then the model names it in a few words in your language (a chat\n you renamed keeps your name).\n - The Mnemo sidebar has an Appearance card: the theme switch (light, dark,\n system) and the chat background, picked from preview tiles: Glow (the\n default), Aurora, Mesh, Dusk, Dawn, Deep, Dots, Grid, Lines, Waves, Grain\n or Plain. Quiet and theme-aware (a touch stronger on dark), remembered\n per device.\n - \"In this chat\", a panel on the right (a drawer on smaller screens):\n every note, folder, image and the vault the chat attached, read, changed\n or showed, grouped, each opening on a tap. The chat list folds away on\n wide screens too; both are remembered.\n - Phones: the Mnemo page follows the part of the screen the keyboard\n leaves, so the composer stays right above it (iOS, Android and the\n installed app).\n - Replies keep going on the server when you leave: open another chat,\n leave the page or lose the network, and the reply goes on; its chat\n spins in the list, and opening it shows the reply still streaming (or\n done). Only Stop ends a reply early.\n - Regenerate under every reply, and Try again on every message of yours\n and on errors: the turn runs again with the chat's model (later turns\n are replaced, after you confirm).\n - Mnemo hands things over: with its `show_items` tool, notes, folders,\n images or the whole vault appear as cards in its reply that open on a\n tap. The model picker links straight to Settings (Manage models and\n providers).\n - Export a chat: Download as Markdown, or Save as a note (in \"Mnemo\n chats\"), from the chat's menu; `/export` in the console.\n - Search every chat: the chat list's search box finds words in what you\n and Mnemo said (and in titles), marks them, and opens the chat at the\n message. Mnemo can look back too, with its own `search_chats` and\n `read_chat` tools, when you refer to an earlier conversation.\n - Mnemo has its own activity (Mnemo page, Activity; or its row on the\n Activity page): every tool call, each marked with who it was for and how\n it was asked (\"owner · chat\", \"owner · console\",\n `research-bot · @mnemo in Inbox`). Activity events carry this as `for`.\n - The console has it too: `/mnemo` chats with the same Mnemo (same chats,\n models and keys), shows its thinking and a summary of each reply, and\n takes `/attach` (a note or folder) and `/image` (a picture file),\n `/pin` (this model for new chats), `/memory`, `/compact`, `/activity`,\n `/search` and `/retry`, and opening a chat with a reply still running\n streams it;\n `/mnemo setup` adds, tests, switches and deletes providers and manages\n models.\n - Routes under `/api/assistant/` (signed-in browser only; API keys are\n refused). See docs/API.md.\n- **Images beside notes.** Upload PNG, JPEG, WebP or GIF from the editor\n (button, paste or drop). An image is stored in the note's own folder and\n shown with `![alt](path:name.png)`; a `path:` to an image in another\n folder is copied beside the note on save, so a note never points across\n folders. URLs still work.\n - Images follow their note: moved with it, soft-deleted to the Trash with\n it, restored with it (to the same or another folder) and deleted for\n good with it. An image another note in the folder still shows is kept.\n - A gallery view of a folder's images (that folder only), and an Images\n tab beside a note (this note or its folder). The viewer shows which\n notes and sections show an image and opens the note at that spot.\n - Settings, Images: the largest upload (0.1 to 50 MB, 5 MB by default)\n and how much notes and images take.\n - MCP tools `upload_image` and `list_images` (77 tools in all), and\n `POST /api/vault/image`, `POST /api/vault/image/delete`,\n `GET /api/vault/images`, `GET /api/vault/storage`,\n `GET|POST /api/settings/media`.\n- Reading settings offer nine colours (from paper and sepia to night and\n high contrast), nine fonts (including Literata, Atkinson Hyperlegible,\n Nunito, IBM Plex and OpenDyslexic, served by Memora itself) and nine text\n sizes.\n- The sidebar can be dragged wider (up to 440 px) while it is open;\n double-click the edge to reset. Collapsing works as before.\n- Version history shows a calm loading animation while it reads.\n\n### Fixed\n\n- Staying signed in while you work: the browser's session cookie used to keep\n the lifetime it got at sign-in, so it was dropped after the idle timeout (3\n hours by default) however active you were, although the server kept the\n session alive. Every request now renews the cookie too (at most every five\n minutes), and an open, visible tab you are using renews it while you read\n or scroll. An idle or hidden tab still signs out after the timeout.\n- The Brain, Graph and Canvas toolbar no longer lets the search box, its\n shortcut and the badges overlap or spill out on medium widths. On phones\n the search is a plain \"Search\" pill, and touch screens no longer show the\n \"/\" keyboard hint.\n\n### Security\n\n- SQLite updated (bundled with `rusqlite` 0.41 / `libsqlite3-sys` 0.39) for\n RUSTSEC-2026-0459.\n\n## [2.0.1] - 2026-10-24\n\nA calmer reader. Notes read like a clean page whatever the reading settings.\n\n### Changed\n\n- Note text has a new type scale: clearer headings, even list spacing,\n quieter code, quotes and tables, and real check boxes for tasks.\n- The side panel beside a note has two tabs, Contents and Details. Contents\n has its own tabs for the outline, links and mentions.\n- Reading settings keep the choices that look right on every system: Sans,\n Serif and Mono; Default, Sepia and High contrast. Justified text, the\n Rounded and Legible fonts and the Night, Paper and Mint colours are gone;\n a saved choice moves to the nearest one left.\n\n## [2.0.0] - 2026-10-24\n\nA redesign of every page around one calm look, with new tools where people\nspend their time: version history for notes, tag patterns, an Activity summary\nand a cleaner way to read. The license changes to the GNU AGPL. The state\ndatabase needs no migration: a 1.3 install updates in place and can roll back\nby swapping the binary.\n\n### Added\n\n- Version history for every note: browse versions with who made them, preview\n one, compare it with the current text and restore it. Restoring adds a new\n version, so nothing is lost. Over HTTP: `GET /api/history`,\n `GET /api/note-at`, `GET /api/diff` and `POST /api/history/restore`; the MCP\n tool `get_history` now also returns `version` and `total`.\n- A Trash page at `/trash`: restoring asks where the note goes (its folder,\n another folder or the top level), and deleting for good asks you to type\n DELETE (DELETE ALL to empty the Trash).\n- Tags: pick or tick tags to see their notes at once, preview a note in the\n map's card, merge, rename or remove tags in bulk, and find notes by a\n pattern of tags joined with and, or and not.\n- Activity is a summary page (numbers, actions over time, what agents do most,\n problems, most touched notes, agents) with every action on its own\n Timeline tab at `/activity/timeline`. An agent's activity lives on its own\n page at `/agents/<id>/activity`.\n- Reading: Contents (outline, links, mentions and details) beside the note,\n and a fold-away toolbar (F) for a clean page.\n- Maps: a clean view that hides every control (C), a dot grid switch, note\n titles on the maps, and a first-setup guide while the vault is empty.\n- Settings: edit the server name and how long browsers stay signed in\n (`POST /api/settings/server`, admin); the folder switch says what moves\n with each notes folder.\n- What's new: the notes of each release, shown once after an update and from\n the profile menu or Settings, Version, with a quiet link to star the project.\n- New notes keep their title as the file name, spaces included, and the web\n app shows display titles (front matter title or first heading).\n- Refused MCP calls are logged, so Activity and the Overview can show what an\n agent tried and was not allowed to do.\n\n### Changed\n\n- **License: GNU AGPL v3.0 or later** (was MIT). You may use, modify and share\n Memora, including commercially; a modified version that you distribute or\n run as a service must publish its source and keep the attribution in\n `NOTICE` (\"Based on Memora by Codrihub Tech\"). The name and logo are covered\n by `TRADEMARK.md`. Versions 1.3.8 and earlier stay MIT.\n- Every page is redesigned: Overview, Brain, Graph and Canvas, Notes and the\n reader, Tags, Activity, Agents, Trash, Settings, Docs, sign-in, welcome and\n setup, with layouts for tablets and phones and the Geist typeface.\n- Deleting a note for good also erases it from the vault's version history,\n so no one, agents included, can read it again. Other notes keep their\n versions; their revision ids change.\n- Deleting a note for good over HTTP (`POST /api/delete` without\n `mode: \"trash\"`) needs an admin key, like MCP `delete_memory` with\n `permanent`. Moving to the Trash is unchanged.\n- Notes saved from the web app are committed with the signed-in user as the\n author, so version history can tell people from agents.\n- The theme follows the device by default, sign-in and setup included.\n- The release check also reads the repository's star count (off with\n `MEMORA_UPDATE_CHECK`, like the release check itself).\n\n### Fixed\n\n- An unused setup or reset code that ran out locked the instance; it now goes\n back to idle, and locks older versions took on expiry are lifted.\n- Activity summarised only the newest 800 events whatever range was chosen.\n- The update offer appeared when nothing had changed; it now follows a\n content hash of the built app.\n- Pins are checked again right after the notes folder is switched.\n\n### Performance\n\n- Signed-in `GET` answers under `/api/` are gzip-compressed (pages, writes,\n sign-in and `/mcp` are not), about a twelfth of the size for activity pages.\n- Activity shows the newest page at once, fills the range behind it and\n remembers each range.\n- The boot splash is plain HTML that paints at once and leaves as soon as the\n app is ready.\n\n\n## [1.3.8] - 2026-10-21\n\nA security and reliability pass: dependencies checked against published\nadvisories, Memora's own code reviewed for common vulnerability classes, and a\nlong load test for leaks. This covers what was found; it is not a guarantee\nthat nothing else is there.\n\n### Security\n\n- Dependencies: updated rustls-webpki (RUSTSEC-2026-0382) and webpki-roots\n (RUSTSEC-2026-0381), used by the release check and OAuth metadata fetch, and\n zip (RUSTSEC-2026-0367, -0368, -0369; Memora never extracted archives, so it\n was not exposed). `cargo audit` and `npm audit` now run in CI, Dependabot is\n on, GitHub Actions are pinned to commits, and the Docker image is based on\n Debian 13.\n- A note containing a crafted embed could crash the server every time it was\n viewed. Fixed.\n- Behind a reverse proxy, a client-sent `CF-Connecting-IP` or `X-Real-IP` could\n choose the caller's address, including `127.0.0.1`, and skip sign-in rate\n limits. Memora now uses the right-most `X-Forwarded-For` entry that is not a\n trusted proxy and ignores loopback addresses in headers.\n- Many failed sign-ins no longer lock the owner out: the server slows down\n instead, and a correct password from a device without recent failures still\n works. A wrong setup code no longer closes the setup window on the first try.\n- OAuth client registration is rate-limited per address and unused clients are\n removed after an hour. The public client metadata fetch also refuses IPv4\n addresses wrapped in IPv6 (such as NAT64).\n- Paths that pointed at `.git` or other store files through a symlink or a\n Windows short name (`GIT~1`), and respelled paths that slipped past soft\n locks, are refused. Windows device names, `:` streams and trailing dots or\n spaces are refused too.\n- Privacy rules now also cover the trash, the activity log of `create_memory`,\n the history of a hidden note's former path, and `import_memory` replies.\n- Text replacements (`bulk_replace`, patch `replace`, templates) are capped so\n they cannot exhaust memory.\n- `/logout` accepts POST only, with the same-origin check. `/_bus` refuses\n requests made by a browser.\n- Folder colours and icons read from `.folders.json` are validated.\n- The state folder is tightened to owner-only, and Memora's own files in the\n vault (`.events.jsonl`, `.locks.json` and others) are created owner-only.\n\n### Fixed\n\n- `memora.log` grew without limit (one line per MCP request); it is now\n bounded. The server raises its open-file limit so connection spikes do not\n run out of file handles.\n- Memora's own files (`.events.jsonl`, `.locks.json`) were committed to the\n vault's git history on every write.\n- The activity log endpoint kept every parsed event of its window in memory.\n- Leaving the Brain view kept its node card and controller in memory, and a\n paused Activity page queued events without limit.\n\n### Changed\n\n- The npm package needs Node.js 22 or newer (18 and 20 no longer get security\n updates).\n\n## [1.3.7] - 2026-10-21\n\n### Added\n\n- Drag and drop in the sidebar tree, with the mouse, a pen or touch (hold for a\n moment, then drag): drop on a folder to move into it, on a note to move into\n that note's folder, or on \"All nodes\" to move to the top level. A hint says\n where the item will go, places it cannot go are marked, the list scrolls when\n you drag near its top or bottom edge, and a closed folder opens when you hold\n over it. Every drop asks \"Move \"X\" to \"Y\"?\" first; Escape cancels a drag.\n- A folder picker shaped like the sidebar tree in New node, Move to, Move\n contents to and the folder delete dialog: expand and collapse, keyboard\n navigation, and a search that finds folders by name or path at any depth.\n- `GET /api/folders` lists every folder you can see, empty ones included.\n\n### Changed\n\n- Very deep folder trees stay readable: indentation stops growing after six\n levels and deeper rows show their level; long names end with an ellipsis and\n show the full path on hover.\n\n### Fixed\n\n- A new subfolder could not be chosen in New node (it only listed top-level\n folders), and empty folders were missing from the sidebar, Move to and the\n folder delete dialog.\n- A word made only of digits after `#` (for example \"PR #2\") was read as a tag.\n- The sidebar kept jumping back to the top when the tree redrew.\n\n## [1.3.6] - 2026-10-21\n\n### Added\n\n- Rows in the sidebar have a \"⋯\" button that opens the same menu as a right\n click. It shows on hover and keyboard focus, and always on touch screens.\n- Copy path and Copy wikilink in every note and folder menu (sidebar, Nodes list,\n node cards and the reader), so you can point an agent at an exact note. Copy\n wikilink now copies the full path, e.g. `[[Projects/Launch plan]]`.\n- Deleting a folder that holds notes now asks what to do with them: move them to\n the parent folder, the top-level folder, Root or any other folder, or send\n everything to `.Trash`. The MCP tool `delete_folder` and `/api/delete-folder`\n take the same choice as optional arguments (`into`, `mode: \"trash\"`); without\n them nothing changes.\n- An \"Update & uninstall\" guide in the documentation (web, console and\n `docs/INSTALL.md`), including how to remove versions before 1.3.2 by hand,\n safely: it stops Memora, removes only Memora's program and state folder by\n exact path, asks before deleting, and keeps the vault unless you choose\n otherwise.\n- A real \"Page not found\" / \"Node not found\" view instead of a silent redirect\n to Overview.\n\n### Changed\n\n- Windows is installed with npm (`npm install -g @codrihub/memora`); releases no\n longer carry a separate Windows zip. The npm package for Windows x64 is built\n and tested as before. Zips of 1.3.0 to 1.3.5 stay on their release pages.\n- The note delete dialog says plainly that a note is deleted for good (there is\n no trash for single notes) and when an agent can still restore it.\n- `memora-cli update`, `/update` and `/restart` detect how Memora was installed\n (npm, Docker, the installer, a release folder or a source build) and give the\n matching steps. The npm launcher and the Docker image set `MEMORA_INSTALL`.\n- `memora-cli help` lists start, stop, restart, update and uninstall, and an\n unknown command prints the version and points to `memora-cli update`.\n\n### Fixed\n\n- An npm install was reported as \"built from source\" by `/update`, and\n `/restart` suggested systemctl on Windows.\n- `memora-cli start`, `stop`, `restart` and `uninstall` without `--state` could\n act on another install's running server (for example a systemd service). They\n now name the state folder and service first, and refuse to drive a service\n that belongs to a different kind of install.\n- `#tags` inside inline code, code blocks, URLs (`…#install`) and link targets\n were read as tags, and a tag written twice was listed twice. Tag rename and\n merge no longer rewrite text in code or URLs either.\n- Activity: rows of read-only calls (including `pin`/`unpin`) no longer stay\n \"running\"; the Live popover only says \"now\" for agents that are active; agent\n colours match everywhere; counts that may be cut off by the log limit show\n \"2,000+\".\n- The sidebar footer lines no longer overlap when they switch.\n- Nodes list excerpts load as rows come into view instead of queueing; folder\n paths and tags end with an ellipsis on phones.\n- Agent labels in the brain no longer cover the map controls on phones, and the\n Overview Agents card no longer shows 0 while loading.\n\n## [1.3.5] - 2026-10-20\n\n### Fixed\n\n- Memora slowed to a crawl under steady agent traffic: with a few hundred notes\n and a few MCP calls per second, the web UI (tree, notes, agents) took tens of\n seconds to answer. Tag lookups (`search_by_tag`, `list_tags`) re-rendered every\n note while holding the vault lock, MCP calls and vault reads blocked the\n server's async workers, and the note view walked the vault once per link. Tag\n lookups now read the note cache, reads run off the async workers on a snapshot\n of the vault, and a write refreshes only the note it changed. Under the same\n traffic the tree and note requests answer in about 20 ms instead of 20-35 s.\n- The node card in Brain, Graph and Canvas no longer flashes its loading state\n and refetches the note on every realtime update; it refreshes only when that\n note changes.\n- The Tags page builds its index in one request instead of one per note.\n\n## [1.3.4] - 2026-10-20\n\nEvery MCP tool was tested against bad, missing, hidden and extreme input. This\nrelease fixes what that found. Some calls that used to be accepted, and did\nsomething other than what was asked, are now refused with a clear message.\n\n### Added\n\n- Agent instructions come in five styles: Balanced (recommended), Remember\n everything, Private, Session journal and Read only, each in a full and a\n short version, on the docs page, in the connect guide and in the console.\n Remember everything warns that secrets end up as plain Markdown and how to\n hide them with privacy rules. Where to paste covers more clients.\n- The live panel in the header opens an agent's page; in Activity, an agent's\n name on any row, the event drawer and an agent's activity page do too.\n- `list_trash` (MCP): the notes in the trash, with where they came from.\n- Version history can be turned on with a plain `git init` in the vault;\n `docs/CONFIGURATION.md` explains how.\n\n### Changed\n\n- `tools/call` checks arguments against the tool's schema: unknown names,\n missing required arguments, wrong types, values outside an enum and numbers\n below the minimum are refused. Every tool error starts with the tool name.\n- Search no longer keeps a `.fts.db` index. Search and the graph, query and\n digest tools read one in-memory cache that follows the files on disk, so\n results are right at startup and include notes changed outside Memora.\n Old `.fts.db` files are removed.\n- `bulk_delete` moves notes to the trash, and refuses the whole call when any\n path is wrong. `restore_trash` puts a note back where it was.\n- Moving or renaming a note or folder rewrites the wikilinks that pointed to\n it, in MCP and in the web UI; results report `links_updated`.\n- `delete_folder` moves notes to the parent folder and keeps their subfolders.\n- Soft locks are enforced: an agent cannot write to a note another agent has\n locked, and only the holder (or the owner) can release a lock.\n- Tags may contain letters, digits and `- _ / .`; tag tools ignore case.\n Frontmatter fields refuse line breaks.\n- `follow_ups` returns `{notes, count, truncated}` and takes `limit`; it also\n counts `waiting` and `blocked`. `digest` reports all events and takes `limit`.\n- Export and import use an exchange folder inside the state folder (0700),\n not a folder shared by every instance in `/tmp`.\n- `template_create` only reads templates from `Templates/`.\n\n### Fixed\n\n- `move_memory` without `folder` moved the note to the top level, and\n `create_memory` with an unknown argument created the note somewhere else.\n- `bulk_replace` with an empty `find` inserted text between every character.\n- Tags or fields with line breaks or YAML characters could break a note's\n frontmatter; `mention_agent` could add fake mention lines.\n- `privacy_set` with an empty agent list removed the rule, exposing a hidden\n folder; an agent could take another agent's display name or \"owner\".\n- An agent could release or create locks in another agent's name.\n- `template_create` could read any note, including hidden ones.\n- Search snippets mixed highlight tags with raw note HTML.\n- `get_subgraph` reversed edges, dropped one side of two-way links and\n returned one node too many; nested folders were ignored by `query_memory`,\n `digest`, `bulk_replace` and `bulk_delete`; `list_memory` showed nested\n notes under their top-level folder.\n- `merge_memory` skipped missing sources silently, merged a note into itself\n and pasted frontmatter into the body; `batch_create` ignored typos.\n- `create_folder` accepted `Root`; `move_folder` into a note created a folder.\n- History tools returned empty results when the vault has no git repository;\n they now say version history is off. `snapshot` explains its refusals.\n- Many tools returned an empty success for paths that do not exist; they now\n say what is missing.\n- Parallel calls of one tool could close each other's rows in Activity.\n- `batch_create` did not tell open browsers about the notes it created.\n\n## [1.3.3] - 2026-10-20\n\n### Added\n\n- Agents see new tools without reconnecting. The MCP session id now carries\n the tool catalog it was issued for; when tools are added or switched off\n (after an update, or in Settings), the next request on an older session is\n answered as a short SSE stream that first sends\n `notifications/tools/list_changed`, once, and then the normal response.\n `initialize` advertises `tools.listChanged: true`. Old sessions are never\n refused, so clients that do not re-initialize keep working. This is what\n made `list_pins`, `pin` and `unpin` missing for agents connected before\n 1.2.2.\n- Pins animate when they are added, moved or removed, in every open browser,\n and a toast names the agent or person who pinned or unpinned (following the\n activity toast setting).\n- `memora-cli stop` stops a background server gracefully on every OS through\n `POST /_stop`, a loopback-only request that needs the token the server\n writes to `<state>/stop.token`. It falls back to SIGTERM or `taskkill`.\n\n### Fixed\n\n- Windows: `memora-cli stop` without `--force` could not stop a server it\n started, because Windows refuses a polite `taskkill` for a process without\n a console.\n- Windows: `memora-cli start` handed its console pipes to the server, so a\n script or CI step reading its output waited until the server exited.\n- Windows: the vault chooser in the browser (first run and Settings) refused\n paths such as `C:\\Users\\you\\memora`; it accepts drive and UNC paths.\n- Windows: `memora-cli db backup` always failed with \"Access is denied\",\n which also stopped the final backup during uninstall (nothing was\n deleted). `db restore` finds a server started by `memora-cli start` and\n says clearly when the database is in use.\n- Windows: paths are stored and printed without the `\\\\?\\` prefix\n (`memora-cli vault`, uninstall output, the npm assets path in the log).\n- Windows: Ctrl+C in the console restores the console input mode, so the\n shell never stays without echo after a password prompt.\n\n## [1.3.2] - 2026-10-20\n\n### Added\n\n- `memora-cli start`, `stop` (`--force`), `restart` and `uninstall`, and\n `/start`, `/shutdown` (alias `/stop`), `/restart` and `/uninstall` in the\n console. They detect how the install runs: a systemd service is driven\n with `systemctl`; an npm, release zip or source install runs the server in\n the background with `memora.pid` and `memora.log` in the state folder;\n inside Docker the console prints the host commands.\n- Uninstall explains what it removes, then offers a checklist (space to\n select) to also delete the settings and accounts and the vault. Both are\n kept by default; deleting the vault needs its folder name typed, a final\n database backup is offered before the state goes, and system folders, the\n home folder and the program folder are never deleted. Without a terminal\n it needs `--yes` and only deletes what `--delete-config` and\n `--delete-vault` say.\n- `/guide` gains a \"Run and manage the server\" step; `memora-cli docs manage`\n covers it per install.\n\n### Changed\n\n- The install guide's introduction names Windows and the npm and zip\n installs and leads with `memora-cli setup`.\n\n## [1.3.1] - 2026-10-20\n\n### Added\n\n- Shut the server down from the browser: Settings, Server, Shut down (owner\n only, after a confirmation). The server stops gracefully and exits with\n status 0. When systemd (`Restart=always`) or Docker starts it again, the\n confirmation says so and shows the stop command to use instead.\n `POST /api/server/shutdown` refuses API keys and cross-site requests.\n- One floating back-to-top button on every scrolling page, at the bottom\n right and above the tab bar on phones.\n\n### Changed\n\n- The welcome screen of a new instance is a wider two-column card, and its\n steps use `memora-cli setup` (it prints the code and the link) with the\n install's own command prefix.\n- At tablet widths the profile menu opens as a popover next to the sidebar\n instead of a bottom sheet.\n- README and the install guide list start, stop and restart per install.\n\n### Fixed\n\n- Code in reading themes: inline code and code blocks take the theme's\n colours (Paper on the dark app was 1.3:1, now about 12:1).\n- The `web/node_modules` symlink of a work tree slipped into 1.2.3; it is no\n longer tracked and the ignore rules now match a folder or a link.\n\n## [1.3.0] - 2026-10-19\n\n### Added\n\n- Native Windows support: `memora` and `memora-cli` build and run on Windows\n 10/11 (x64), and `npm install -g @codrihub/memora` installs the new\n `@codrihub/memora-win32-x64` package there. The release workflow builds it\n with a static C runtime.\n- A Windows zip on every GitHub release\n (`memora-<version>-x86_64-windows.zip`, listed in `SHA256SUMS`) with\n `memora.exe`, `memora-cli.exe` and the web UI: unzip and run, no installer\n or Node needed.\n\n### Changed\n\n- On Windows, `memora-cli` runs database work in-process (there is no root\n privilege drop), reports state files as private, and finds `sqlite3.exe`\n on `PATH` for `db shell`.\n- The vault folder may be a Windows absolute path (`C:\\...` or\n `\\\\server\\share`). Migration 8 rebuilds the `settings` table so the\n database accepts it; Unix paths are unchanged. On Windows, system folders\n (`%SystemRoot%`, `%ProgramFiles%`, `%ProgramData%`) are refused as vaults.\n- `memora` finds its web UI in an `assets` folder next to the executable\n (an unpacked release zip or tarball) when `MEMORA_ASSETS` is not set.\n\n### Fixed\n\n- The Windows system-folder check compares paths without regard to case, so\n `C:\\Windows` is refused even when `%SystemRoot%` reads `C:\\WINDOWS`.\n\n## [1.2.3] - 2026-10-19\n\n### Added\n\n- Pins are saved on the server instead of in each browser. They follow a\n note or folder when it is renamed, moved, trashed or deleted (including\n everything inside a moved folder), show on every device, and update live\n in open browsers. A pin whose item disappeared outside Memora stays\n visible as \"Not found\" with a remove button. Existing browser pins are\n uploaded once. Migration 7 adds the `pin` table.\n- Pins over HTTP (`GET`/`PUT /api/pins`, `POST /api/pins/pin`,\n `POST /api/pins/unpin`, signed-in owner only) and over MCP: `list_pins`\n (read), `pin` and `unpin` (write), under the usual key scopes, tool grants\n and privacy rules.\n\n### Changed\n\n- Install in three steps: one command (the installer, a single\n `docker run` with named volumes, or npm), `memora-cli setup` for a\n one-time code, then the link it prints. README, the install guide and the\n in-app Get started page lead with it.\n- The desktop sidebar is a little wider (288 px) and the profile menu fits\n its width. While dragging onto Pinned, only the drop box is highlighted.\n\n### Fixed\n\n- `patch_memory`: an op missing a required field is an error instead of an\n empty value. A `replace` without its replacement used to delete the\n matched text; an empty `find` or one that matches nothing now fails too.\n `replace` accepts `replace` as an alias of `with`, and the tool\n description lists every op and its fields.\n- Wikilinks written as `[[target\\|alias]]` (the escape used inside tables)\n no longer count the backslash as part of the target, so the graph,\n backlinks and broken-link checks see the right note.\n- `docker-compose.yml` pointed at an old image; it now follows the release.\n\n## [1.2.2] - 2026-10-19\n\n### Added\n\n- npm install for Linux x86_64 and arm64: `npm install -g @codrihub/memora`\n provides the `memora` and `memora-cli` commands. npm picks the matching\n `@codrihub/memora-linux-x64` or `-linux-arm64` package with the prebuilt\n release binaries; nothing is downloaded by an install script. The web UI\n ships in the package. Other platforms get a clear message pointing to\n Docker or a source build. The release workflow builds, smoke tests and\n publishes the packages at the release version when the `NPM_TOKEN` secret\n is set.\n- `memora-cli update` recognises an npm install and prints the npm command\n to update it.\n\n## [1.2.1] - 2026-10-19\n\n### Changed\n\n- Each agent has its own page at `/agents/<id>` with tabs for Overview,\n Setup, Activity, Access and Settings, each with its own address, instead\n of a long sheet. Overview shows its stats, recent calls, app, access and\n key; Activity groups calls by day with search, status and range filters.\n- An agent's app is locked once it is known. Setup shows only that app's\n guide; there is no switching an agent to another app any more. A guessed\n app is confirmed once, and an agent without an app picks it once. For\n another app or device, create a new agent.\n- New agents are made on a page at `/agents/new` with a stepper that stays\n in view, a summary panel, and a recommendation of one agent per app or\n device so Activity shows who did what. Old `/agents#connect` links still\n work.\n\n### Fixed\n\n- Tables: an aliased wikilink such as `[[Folder/Note|name]]` in a cell no\n longer splits the cell and adds a column. Escaped pipes (`\\|`) work, and\n rows with too few or too many cells fit the header.\n\n## [1.2.0] - 2026-10-18\n\n### Added\n\n- Settings, Notifications: turn agent activity toasts off for every agent,\n or for single API keys. The main switch always wins: when it is off, no\n activity toast appears, even for keys that are turned on.\n- Node editor: Save and Cancel buttons. On phones they sit in a large bar\n pinned to the bottom of the screen while editing. Cancel asks before\n discarding changes, Esc cancels, and Ctrl+S saves without closing.\n\n### Changed\n\n- The node editor no longer saves while you type; changes are saved with\n Save or Ctrl+S, and closing the tab with unsaved changes asks first.\n Leaving the node still keeps your changes.\n\n## [1.1.5] - 2026-10-18\n\n### Fixed\n\n- Folder icons given by name (for example `credit-card`, `cpu` or `key`, as\n agents often set them) showed the name as text. More icons are built in,\n common names and aliases map to them, and an unknown name falls back to\n the folder icon. The `set_folder_meta` MCP tool lists the icon names.\n\n## [1.1.4] - 2026-10-18\n\n### Fixed\n\n- \"On this page\" in the node reader and the documentation: the last\n sections are now marked when scrolled to the bottom, a clicked entry is\n marked right away and stays marked while the page scrolls to it, and the\n current section is picked earlier while scrolling.\n\n### Changed\n\n- README: a centered header with the logo, badges and links, and screenshots\n as JPEG so they display everywhere.\n\n## [1.1.3] - 2026-10-18\n\n### Fixed\n\n- After an update, a normal reload or a hard reload could show the offline\n page. The service worker now only serves the offline page when the server\n really cannot be reached (after a retry); pages, scripts and styles always\n come from the network, the app script URL carries a content hash, and the\n service worker itself is never served from the HTTP cache.\n- The offline page retries on its own and returns as soon as the server is\n back.\n\n## [1.1.2] - 2026-10-18\n\n### Changed\n\n- Agents & API keys page redesigned: a stats strip (agents, active now, calls\n in 24 hours, MCP endpoint), and an agents list that is a table on wide\n screens, condensed rows on tablets and cards on phones, with the app each\n agent uses, its status, access summary, a 24-hour sparkline and last call.\n- Clicking an agent opens a detail sheet with its stats, the app it is used\n with, access, key details, activity and every action (rename and color,\n show key, new key, turn off or on, delete, edit permissions, set up again).\n- Connecting an app: pick the app, name the agent and choose Read & write,\n Read only or Custom access, then follow the setup with the new key filled\n in and a live \"Connected\" check. Setting up an existing agent goes straight\n to its app, with an inline unlock for a sealed key.\n- Permissions editor: a live summary, capability toggles with plain\n descriptions, and a searchable tool picker grouped by category.\n- Every dropdown in the web UI is a custom, keyboard-accessible select that\n works inside sheets and opens as a bottom sheet on phones.\n\n## [1.1.1] - 2026-10-18\n\n### Added\n\n- Documentation in the web UI at `/docs`: getting started, agent\n instructions, connecting agents, install, configuration, MCP, a live tool\n reference, API, security, deployment, architecture, database, changelog and\n keyboard shortcuts, with search, an on-page table of contents and copy\n buttons. Reachable from the profile menu, the help dialog, the search\n palette and Settings.\n- `/docs` in the setup console and `memora-cli docs [topic]`: the same topics\n in the terminal, including the recommended agent instructions.\n- Recommended agent instructions (a full and a short prompt) that tell an\n agent to recall from Memora before answering and to save what is worth\n keeping, with where to paste them for each client.\n\n### Changed\n\n- Connecting an app is a four-step wizard (app, key, set up, instructions)\n instead of a sideways carousel: searchable app grid, inline key creation,\n filled-in config with a copy button, a live \"Connected\" check and the\n agent instructions. `/agents#connect` opens it directly.\n\n## [1.1.0] - 2026-10-18\n\n### Changed\n\n- Search engines and AI crawlers are kept out of every page: `robots.txt`\n now disallows the whole instance (with explicit rules for common AI\n crawlers), and every response and page carries\n `noindex, nofollow, noarchive, nosnippet, noimageindex`.\n- README: one-command install and screenshots of the web UI.\n\n## [1.0.0] - 2026-10-18\n\nFirst public release.\n\n### Added\n\n- Vault of plain Markdown files with folders, wikilinks, tags, backlinks,\n pins, trash and history.\n- MCP server over Streamable HTTP with 71 tools (read, search, write, organize,\n graph, interop) and admin tools for keys and tool switches.\n- API keys per agent with scopes (`mcp`, `read`, `write`, `admin`), per-key tool\n lists, global tool switches, key rolling and revocation. MCP tools that change\n the vault require the `write` scope.\n- OAuth 2.1 sign-in for MCP clients (authorization code with PKCE, dynamic\n client registration, client metadata documents).\n- Per-agent privacy for folders and notes; rules follow renames and moves.\n- Access rules by IP, network, range or domain, first match wins.\n- Web UI: Overview, Brain (3D), Graph, Canvas, Nodes with reader and editor,\n Tags, Activity with per-agent pages, Agents and API keys, Tools, Access rules\n and Settings; light, dark and system themes; installable PWA.\n- Activity log of every agent call with filters, export and retention settings.\n- State in one SQLite database (`<state>/memora.db`) with migrations, backup,\n restore and integrity check.\n- `memora-cli` with an interactive setup console (`/welcome`, `/setup`, `/web`,\n `/keys`, `/tools`, `/mcp`, `/status`, ...), one-time setup codes and updates.\n- Release check: the server looks up the newest GitHub release every 6 hours\n and the web UI shows when an update is available (`MEMORA_UPDATE_CHECK=false`\n turns it off).\n- Docker image, Docker Compose file and an installer script with checksum\n verification.\n\n[2.0.1]: https://github.com/Codrihub/memora/releases/tag/v2.0.1\n[2.0.0]: https://github.com/Codrihub/memora/releases/tag/v2.0.0\n[1.3.8]: https://github.com/Codrihub/memora/releases/tag/v1.3.8\n[1.3.7]: https://github.com/Codrihub/memora/releases/tag/v1.3.7\n[1.3.6]: https://github.com/Codrihub/memora/releases/tag/v1.3.6\n[1.3.5]: https://github.com/Codrihub/memora/releases/tag/v1.3.5\n[1.3.4]: https://github.com/Codrihub/memora/releases/tag/v1.3.4\n[1.3.3]: https://github.com/Codrihub/memora/releases/tag/v1.3.3\n[1.3.2]: https://github.com/Codrihub/memora/releases/tag/v1.3.2\n[1.3.1]: https://github.com/Codrihub/memora/releases/tag/v1.3.1\n[1.3.0]: https://github.com/Codrihub/memora/releases/tag/v1.3.0\n[1.2.3]: https://github.com/Codrihub/memora/releases/tag/v1.2.3\n[1.2.2]: https://github.com/Codrihub/memora/releases/tag/v1.2.2\n[1.2.1]: https://github.com/Codrihub/memora/releases/tag/v1.2.1\n[1.2.0]: https://github.com/Codrihub/memora/releases/tag/v1.2.0\n[1.1.5]: https://github.com/Codrihub/memora/releases/tag/v1.1.5\n[1.1.4]: https://github.com/Codrihub/memora/releases/tag/v1.1.4\n[1.1.3]: https://github.com/Codrihub/memora/releases/tag/v1.1.3\n[1.1.2]: https://github.com/Codrihub/memora/releases/tag/v1.1.2\n[1.1.1]: https://github.com/Codrihub/memora/releases/tag/v1.1.1\n[1.1.0]: https://github.com/Codrihub/memora/releases/tag/v1.1.0\n[1.0.0]: https://github.com/Codrihub/memora/releases/tag/v1.0.0\n"}]
1
+ [{"file":"README.md","slug":"get-started","title":"Get started","text":"<p align=\"center\">\n <img src=\"docs/assets/memora-logo.png\" alt=\"Memora\" width=\"96\" height=\"96\">\n</p>\n\n<h1 align=\"center\">Memora</h1>\n\n<p align=\"center\"><b>Second brain for your AI.</b><br>Long-term memory for AI agents, on your own server.</p>\n\n<p align=\"center\">\n <a href=\"https://github.com/Codrihub/memora/releases/latest\"><img src=\"https://img.shields.io/github/v/release/Codrihub/memora?sort=semver\" alt=\"Latest release\"></a>\n <a href=\"https://www.npmjs.com/package/@codrihub/memora\"><img src=\"https://img.shields.io/npm/v/@codrihub/memora?logo=npm&label=npm\" alt=\"npm: @codrihub/memora\"></a>\n <a href=\"https://github.com/Codrihub/memora/actions/workflows/ci.yml\"><img src=\"https://github.com/Codrihub/memora/actions/workflows/ci.yml/badge.svg\" alt=\"CI\"></a>\n <a href=\"LICENSE\"><img src=\"https://img.shields.io/github/license/Codrihub/memora\" alt=\"License: AGPL-3.0\"></a>\n <a href=\"https://github.com/Codrihub/memora/pkgs/container/memora\"><img src=\"https://img.shields.io/badge/ghcr.io-codrihub%2Fmemora-blue?logo=docker\" alt=\"Docker image\"></a>\n</p>\n\n<p align=\"center\">\n <a href=\"https://memora.codrihub.tech\">Website</a> ·\n <a href=\"https://memora.codrihub.tech/docs\">Documentation</a> ·\n <a href=\"#quick-start\">Quick start</a> ·\n <a href=\"https://www.npmjs.com/package/@codrihub/memora\">npm</a> ·\n <a href=\"https://github.com/Codrihub/memora/releases\">Releases</a>\n</p>\n\n<p align=\"center\"><code>npm install -g @codrihub/memora</code></p>\n\nMemora is a self-hosted memory vault for AI agents. Notes are plain markdown\nfiles in a git-backed folder. Agents read and write them over the Model Context\nProtocol (MCP); you browse, edit and govern them in a web UI. One Rust binary\nserves the HTTP API, the MCP endpoint, the web UI and realtime updates on a\nsingle port, with all server state in one embedded SQLite database.\n\n## Screenshots\n\n![Overview](docs/screenshots/overview.jpg)\n\n| | |\n|---|---|\n| ![Brain](docs/screenshots/brain.jpg) **Brain**: every folder is a region, every note a node | ![Node card](docs/screenshots/brain-node.jpg) **Node card**: links, backlinks and a preview |\n| ![Graph](docs/screenshots/graph.jpg) **Graph**: force, radial or cluster layouts | ![Canvas](docs/screenshots/canvas.jpg) **Canvas**: one frame per folder |\n| ![Reader](docs/screenshots/reader.jpg) **Reader** with contents and reading settings | ![Activity](docs/screenshots/activity.jpg) **Activity**: every agent call, live |\n| ![Agents](docs/screenshots/agents.jpg) **Agents & API keys**: one key per agent, scoped | ![Mnemo](docs/screenshots/mnemo.jpg) **Mnemo**: the notes agent, with its steps and the notes it used |\n\nScreenshots use a demo vault.\n\n## Features\n\n- **Markdown you own.** Every note is a `.md` file with optional frontmatter and\n `[[wikilinks]]`. Edit it with any tool; nothing is locked in a database.\n- **Git history.** Changes are committed, so any revision can be listed, diffed\n and restored (`get_history`, `diff`, `restore_memory`).\n- **MCP for agents.** 77 tools for notes, folders, search, tags, graph traversal,\n history, locks, activity, pins and import/export, plus admin tools, over the\n streamable HTTP transport.\n- **Mnemo, a built-in notes agent.** Chat with your notes in the browser or the\n console using your own OpenAI, Anthropic or OpenAI-compatible API key. Mnemo\n finds, writes, tags, links, moves and tidies notes with Memora's own tools,\n shows every step, and has no web, shell or delete-for-good access. It can\n answer with a chart or diagram: a file card that opens a sandboxed preview\n beside the chat.\n- **Images beside notes.** Paste or drop PNG, JPEG, WebP or GIF into a note; the\n file lives in the note's folder and moves, goes to the Trash and comes back\n with it. Folder galleries show which note and section uses each image.\n- **API keys or OAuth.** Give each agent its own key, or let MCP clients such as\n Claude or ChatGPT connect with OAuth after you approve them in the browser.\n- **Per-agent control.** Scopes (`mcp`, `read`, `write`, `admin`), per-key tool\n lists, server-wide tool switches, and privacy rules that hide notes or\n folders from chosen agents.\n- **Web UI.** Brain and graph views, a canvas, the vault editor with nine reading\n colours, fonts and sizes, tags, live agent activity, keys, tools, access\n rules and settings. Installable as a PWA.\n- **Safe first run.** An unclaimed instance cannot be taken over by whoever\n finds the port: the operator console opens a short setup window and you\n finish in the browser.\n- **One port, one process.** HTTP API, MCP, UI and WebSocket share port 8400.\n The database has no network port.\n\n## Quick start\n\nThree steps, about two minutes.\n\n**1. Install** (pick one, in this order of ease)\n\n```bash\n# npm (Linux x86_64 / arm64, Windows x64; Node.js 22 or newer): install, then keep it running\nnpm install -g @codrihub/memora && memora\n\n# Docker (any OS with Docker)\ndocker run -d --name memora --restart unless-stopped -p 8400:8400 \\\n -v memora-data:/data -v memora-state:/state ghcr.io/codrihub/memora:latest\n\n# Native installer (Linux server with systemd, x86_64 or aarch64)\ncurl -fsSL https://raw.githubusercontent.com/Codrihub/memora/main/scripts/install.sh | sudo sh\n```\n\nOn Windows, install Node.js 22 or newer and use npm (see [npm](#npm-linux-x86_64--arm64-windows-x64)).\n\n**2. Get a one-time setup code**\n\n```bash\nmemora-cli setup --minutes 15 # npm, in a second terminal\ndocker exec -it memora memora-cli setup --minutes 15 # Docker\nsudo memora-cli setup --minutes 15 # native\n```\n\n**3. Open the link it prints** (`http://<your-server>:8400/login`), enter the code\nand create your account. Memora then asks which folder to use as the vault and\nshows how to connect your first agent.\n\nThat is all. The sections below cover every other option.\n\n### npm (Linux x86_64 / arm64, Windows x64)\n\n```bash\nnpm install -g @codrihub/memora\nmkdir -p ~/memora && cd ~/memora\nMEMORA_VAULT=./vault MEMORA_STATE=./state memora\n# in a second terminal, same folder:\nMEMORA_STATE=./state memora-cli setup --minutes 15\n```\n\nOn Windows (PowerShell):\n\n```powershell\nnpm install -g @codrihub/memora\nmkdir ~\\memora; cd ~\\memora\n$env:MEMORA_VAULT = '.\\vault'; $env:MEMORA_STATE = '.\\state'; memora\n# in a second terminal, same folder:\n$env:MEMORA_STATE = '.\\state'; memora-cli setup --minutes 15\n```\n\nThe package carries the prebuilt release binaries and the web UI (no install\nscript, nothing downloaded at install time) and needs Node.js 22 or newer. It is\nhandy for trying Memora or running it under your own user; for a server, the\nnative installer adds the systemd service. On macOS use Docker or build from\nsource. Update with `npm install -g @codrihub/memora@latest`.\n\n### Docker (any OS)\n\nOne container, notes and state in named volumes (no clone, no folder\npermissions):\n\n```bash\ndocker run -d --name memora --restart unless-stopped -p 8400:8400 \\\n -v memora-data:/data -v memora-state:/state ghcr.io/codrihub/memora:latest\ndocker exec -it memora memora-cli setup --minutes 15\n```\n\nWith Docker Compose from the repository instead:\n\n```bash\ngit clone https://github.com/Codrihub/memora.git && cd memora\ncp .env.example .env # optional, every value has a default\nmkdir -p data state && sudo chown -R 1000:1000 data state\ndocker compose up -d\ndocker compose exec -it gateway memora-cli setup --minutes 15\n```\n\nThe image is `ghcr.io/codrihub/memora` (linux/amd64 and linux/arm64). See\n[docker/README.md](docker/README.md) for volumes, upgrades and local builds.\n\n### Native installer (Linux x86_64 / aarch64 with systemd)\n\nOne command:\n\n```bash\ncurl -fsSL https://raw.githubusercontent.com/Codrihub/memora/main/scripts/install.sh | sudo sh\n```\n\nOr download it and read it first:\n\n```bash\ncurl -fsSL https://raw.githubusercontent.com/Codrihub/memora/main/scripts/install.sh -o install.sh\nless install.sh # read it first\nsudo sh install.sh # add --behind-proxy for a local reverse proxy\nsudo memora-cli # then type /web\n```\n\nThe installer downloads the release for your CPU, verifies it against the\nrelease `SHA256SUMS`, creates a `memora` system user, and installs a hardened\n`memora.service` unit. Data lives in `/var/lib/memora`. Run\n`sh install.sh --help` for every option, and see\n[docs/INSTALL.md](docs/INSTALL.md) for details.\n\n### From source\n\n```bash\ngit clone https://github.com/Codrihub/memora.git && cd memora\ncargo build --release\nMEMORA_VAULT=./data MEMORA_STATE=./state ./target/release/memora\n# in a second terminal:\n./target/release/memora-cli # then type /web\n```\n\nThe server binds to `127.0.0.1:8400` by default. To install your build as a\nservice: `sudo ./scripts/install.sh --from-source`. The web UI is built from\n`web/` (see [CONTRIBUTING.md](CONTRIBUTING.md)).\n\n### First run\n\n1. Run `memora-cli setup` (or type `/web` in the `memora-cli` console). It\n prints a one-time setup code and the link to open.\n2. Open `http://<host>:8400/login`, enter the code and create the owner account.\n3. Choose the vault folder (`/var/lib/memora/vault` natively, `/data` in Docker).\n4. Add an agent: Agents, then New agent. Pick the app and paste the config it\n shows. One agent per app or device.\n\nIf a setup code expires unused, nothing breaks: run `memora-cli setup` again\nfor a new code.\n\n## Configuration\n\nSettings come from the environment (systemd unit, `.env` for Docker) and can be\noverridden in the state database with `memora-cli` -> `/config`; a stored value\nwins until you clear it. The most common ones:\n\n| Name | Default | Meaning |\n|---|---|---|\n| `MEMORA_PORT` | `8400` | HTTP port for API, MCP, UI and WebSocket |\n| `MEMORA_BIND` | `127.0.0.1` | Bind address (`0.0.0.0` in the container) |\n| `MEMORA_STATE` | `state` | Directory holding `memora.db` |\n| `MEMORA_VAULT` | empty | Suggested vault folder; the vault is confirmed in the browser |\n| `MEMORA_BASE_URL` | empty | Public URL behind a reverse proxy |\n| `MEMORA_DOMAIN` | empty (any) | Allowed hostnames; other hosts get 404 |\n| `MEMORA_TRUSTED_PROXIES` | empty | Remote proxies whose forwarding headers are trusted |\n| `MEMORA_ADMIN_PASSWORD[_FILE]`, `MEMORA_API_KEY[_FILE]` | unset | Provision an owner or an agent key at startup; only hashes are stored |\n| `RUST_LOG` | `info` | Log filter |\n\nThe full list, precedence rules and the Docker Compose variables are in\n[docs/CONFIGURATION.md](docs/CONFIGURATION.md). For TLS, reverse proxies and\nhardening, see [docs/DEPLOYMENT.md](docs/DEPLOYMENT.md).\n\n## Connecting agents over MCP\n\nThe MCP endpoint is `/mcp` on the same port. Authenticate with an API key in\n`Authorization: Bearer <key>` (or `X-API-Key`), or let the client use OAuth.\n\nClaude Code:\n\n```bash\nclaude mcp add --transport http memora https://memory.example.com/mcp \\\n --header \"Authorization: Bearer memora_live_REPLACE_WITH_YOUR_KEY\"\n```\n\nClients with an `mcpServers` JSON config:\n\n```json\n{\n \"mcpServers\": {\n \"memora\": {\n \"type\": \"http\",\n \"url\": \"http://localhost:8400/mcp\",\n \"headers\": {\n \"Authorization\": \"Bearer memora_live_REPLACE_WITH_YOUR_KEY\"\n }\n }\n }\n}\n```\n\nClients that support MCP authorization can connect with only the URL; you\napprove them in the browser and they appear as keys you can restrict or revoke.\nThe discovery card is at `/.well-known/mcp.json` and a readable tool catalog at\n`/tools`. [docs/MCP.md](docs/MCP.md) covers OAuth, other clients, every tool and\nthe error codes; [docs/API.md](docs/API.md) lists the HTTP API.\n\n## Operating\n\n```bash\nsudo systemctl status memora # native service\nsudo journalctl -u memora -f # logs\nsudo memora-cli # console: /status, /keys, /tools, /config, /backup ...\nsudo memora-cli db backup # consistent copy of memora.db, safe while running\nsudo /usr/local/share/memora/install.sh --upgrade\ndocker compose pull && docker compose up -d # Docker upgrade\n```\n\nBack up the vault folder and `memora.db` (with `memora-cli db backup`, never a\nplain `cp` of the live file). See [docs/INSTALL.md](docs/INSTALL.md#backups).\n\n### Start, stop and restart\n\n```bash\nmemora-cli start # or /start in the console\nmemora-cli stop # or /shutdown\nmemora-cli restart # or /restart\nmemora-cli uninstall # or /uninstall\n```\n\nThey work out how this install runs: a systemd service is driven with\n`systemctl`, an npm or source install runs in the background (pid and\nlog in the state folder), and inside Docker the console prints the host\ncommands (`docker start / stop / restart memora`). Uninstall asks, with a\nchecklist, whether to also delete your settings and your vault; both are kept\nunless you tick them. Details: [docs/INSTALL.md](docs/INSTALL.md#uninstall-with-memora-cli).\n\n### Update, uninstall, troubleshooting\n\n`memora-cli update` prints the right steps for your install (npm:\n`npm install -g @codrihub/memora@latest`, then `memora-cli restart`). Check\nyour version with `memora --version`. Per install method, and for older\nversions without `memora-cli uninstall` (before 1.3.2), see\n[Update](docs/INSTALL.md#update),\n[Uninstall by hand](docs/INSTALL.md#uninstall-by-hand-versions-before-132) and\n[Troubleshooting](docs/INSTALL.md#troubleshooting).\n\nThe owner can also **shut the server down from the browser**: Settings, Server,\nShut down. Every browser and agent is disconnected until it is started again on\nthe server. When a supervisor restarts it on its own (systemd `Restart=always`,\nDocker `--restart unless-stopped`), the confirmation says so and shows the stop\ncommand to use instead.\n\n## Security notes\n\n- The owner password is hashed with argon2id. API keys (`memora_live_...`) and\n session ids are stored only as SHA-256 hashes; a key is shown once.\n- Session cookies are `HttpOnly` and `SameSite=Lax`, cookie writes are checked\n against the request origin, and pages use a nonce-based Content-Security-Policy.\n- Login and setup are rate limited with per-IP cooldowns; many failures from\n many IPs only slow sign-ins down and never lock the owner out.\n- Forwarding headers are trusted only from loopback and `MEMORA_TRUSTED_PROXIES`.\n- Access rules can allow or block by IP, range, CIDR and domain; loopback always\n stays allowed so you cannot lock yourself out.\n- Terminate TLS at a reverse proxy before exposing Memora to the internet.\n\nReport vulnerabilities privately as described in [SECURITY.md](SECURITY.md).\n\n## Documentation\n\n| Document | Contents |\n|---|---|\n| [docs/INSTALL.md](docs/INSTALL.md) | Native installer, Docker, npm, updates, uninstall, troubleshooting, reverse proxy, backups |\n| [docs/CONFIGURATION.md](docs/CONFIGURATION.md) | Every setting and where it lives |\n| [docs/DEPLOYMENT.md](docs/DEPLOYMENT.md) | Production deployment and hardening |\n| [docs/MCP.md](docs/MCP.md) | Connecting agents, OAuth, tool reference |\n| [docs/API.md](docs/API.md) | HTTP API |\n| [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) | Crates, request flow, vault files |\n| [docs/DATABASE.md](docs/DATABASE.md) | State database schema |\n\n## Project layout\n\n```\ncrates/core vault: markdown, wikilinks, search, graph, git history\ncrates/state SQLite state database (memora.db)\ncrates/gateway password and key hashing, access checks, environment provisioning\ncrates/mcp MCP server: tool catalog, permissions, privacy\ncrates/http axum server: middleware, API, OAuth, UI assets (binary: memora)\ncrates/cli operator console (binary: memora-cli)\nweb/ web UI (TypeScript), built into crates/http/assets\ndocker/ container entrypoint and release Dockerfile\ndocs/ user and operator documentation\nscripts/ installer and maintenance scripts\n```\n\n## Versioning\n\nMemora follows [Semantic Versioning](https://semver.org/). Each release is a\n`vX.Y.Z` tag with a [GitHub Release](https://github.com/Codrihub/memora/releases)\n(static Linux binaries for x86_64 and aarch64 plus `SHA256SUMS`), npm\npackages for Linux and Windows, and a\nmulti-arch image `ghcr.io/codrihub/memora:X.Y.Z`. Changes are listed in\n[CHANGELOG.md](CHANGELOG.md).\n\n## Contributing\n\nContributions are welcome. Read [CONTRIBUTING.md](CONTRIBUTING.md) and the\n[Code of Conduct](CODE_OF_CONDUCT.md) before opening a pull request.\n\n## License\n\nMemora is free software under the [GNU Affero General Public License v3.0 or\nlater](LICENSE). You may use, modify and share it, including commercially. If\nyou distribute a modified version, or run one as a service for others, you must\npublish its source under the same license and keep the attribution in\n[NOTICE](NOTICE): \"Based on Memora by Codrihub Tech\". The name and logo are\ncovered by [TRADEMARK.md](TRADEMARK.md).\n\nVersions 1.3.8 and earlier were released under the MIT License.\n"},{"file":"docs/INSTALL.md","slug":"install","title":"Install","text":"# Installing Memora\n\nMemora ships as two binaries plus a folder of web UI assets:\n\n| Piece | Role |\n|---|---|\n| `memora` | The server: HTTP API, MCP, web UI, and WebSocket on **one TCP port** (default `8400`) |\n| `memora-cli` | The operator console. Run it with no arguments for slash commands (`/guide`, `/web`, `/config`, ...) |\n| `assets/` | Web UI files, found through `MEMORA_ASSETS` |\n\nIt runs on Linux (x86_64, aarch64) and Windows 10/11 (x64). Install it with\n**npm** (Linux and Windows, runs as you), **Docker**, the **native** installer\n(a systemd service on Linux) or from source. On Windows, use npm. All end the\nsame way: run `memora-cli setup`, open the link it prints and enter the code.\n\n**Fastest path** (pick one, in this order of ease), then open the link the\nsetup command prints and enter the code:\n\n```bash\n# npm (Linux x86_64 / arm64, Windows x64; Node.js 22 or newer)\nnpm install -g @codrihub/memora && memora\nmemora-cli setup --minutes 15 # in a second terminal\n\n# Docker: no clone or folder permissions needed (named volumes)\ndocker run -d --name memora --restart unless-stopped -p 8400:8400 \\\n -v memora-data:/data -v memora-state:/state ghcr.io/codrihub/memora:latest\ndocker exec -it memora memora-cli setup --minutes 15\n\n# Native installer (Linux server with systemd)\ncurl -fsSL https://raw.githubusercontent.com/Codrihub/memora/main/scripts/install.sh | sudo sh\nsudo memora-cli setup --minutes 15\n```\n\n- [Network exposure](#network-exposure)\n- [Native install](#native-install)\n- [Docker](#docker)\n- [npm](#npm)\n- [Start, stop and restart](#start-stop-and-restart)\n- [Update](#update)\n- [Uninstall with memora-cli](#uninstall-with-memora-cli)\n- [Uninstall by hand (versions before 1.3.2)](#uninstall-by-hand-versions-before-132)\n- [Troubleshooting](#troubleshooting)\n- [Reverse proxy](#reverse-proxy)\n- [Backups](#backups)\n- [Automation: `--check` and `--upgrade`](#automation---check-and---upgrade)\n\n## Network exposure\n\nMemora opens exactly **one TCP port**. The HTTP API, MCP (`/mcp`), the web UI,\nand the realtime WebSocket (`/ws`) all share it. The local event intake\n`/_bus` answers on the same port but only to loopback clients.\n\nThe state database is embedded SQLite (`<state>/memora.db`). The server creates\nand migrates it on first start; it opens no port and needs no separate\ndatabase server or install.\n\nNothing else listens. Allow only that one port through the firewall, or none at\nall when a reverse proxy on the same host is the entry point\n(`--behind-proxy`).\n\n## Native install\n\nRequirements: Linux on x86_64 or aarch64 with systemd, `curl` (or `wget`),\n`tar`, `sha256sum`, and `git` (vault history uses it).\n\n```sh\n# Inspect first: https://github.com/Codrihub/memora/blob/main/scripts/install.sh\ncurl -fsSL https://raw.githubusercontent.com/Codrihub/memora/main/scripts/install.sh | sudo sh\n```\n\nPass flags after `sh -s --`, for example:\n\n```sh\ncurl -fsSL https://raw.githubusercontent.com/Codrihub/memora/main/scripts/install.sh \\\n | sudo sh -s -- --version 1.0.0 --behind-proxy\n```\n\nor download the script and run it: `sudo sh install.sh --help`.\n\nThe script is idempotent: running it again reinstalls the same files and keeps\nthe port and bind address of the existing unit unless you pass new ones.\n\n### What it does\n\n1. Downloads `memora-<version>-<arch>-linux.tar.gz` for this CPU from GitHub\n Releases (the latest, or `--version`), downloads `SHA256SUMS` from the same\n release, and refuses to continue if the checksum does not match.\n2. Installs the binaries atomically (copy to a temp file, then `mv`).\n3. Creates the system user and group `memora` (no login shell, home\n `/var/lib/memora`).\n4. Creates `/var/lib/memora/state` (`0700`) and `/var/lib/memora/vault`\n (`0750`), owned by `memora`.\n5. Writes `/etc/systemd/system/memora.service`, enables and starts it, waits\n for `/healthz`, then verifies the state database with `memora-cli db check`.\n6. Prints the next step and, when listening on every interface, a firewall\n hint.\n\n### Paths\n\n| Path | Content |\n|---|---|\n| `/usr/local/bin/memora`, `/usr/local/bin/memora-cli` | Binaries |\n| `/usr/local/share/memora/assets/` | Web UI |\n| `/usr/local/share/memora/VERSION` | Installed version (read by `--check`) |\n| `/usr/local/share/memora/install.sh` | Copy of the installer, used for `--upgrade`, `--check`, `--uninstall`, and `memora-cli update` |\n| `/var/lib/memora/state/` | `memora.db` (owner, API key hashes, sessions, settings, activity log), `backups/` |\n| `/var/lib/memora/vault/` | Suggested vault folder (chosen in the browser after the first sign-in) |\n| `/etc/systemd/system/memora.service` | The unit |\n\n`--prefix` moves the first four (default `/usr/local`), `--data-dir` moves the\nlast two (default `/var/lib/memora`).\n\n### Flags\n\n| Flag | Meaning |\n|---|---|\n| *(none)* | Install or reinstall the latest release |\n| `--version X.Y.Z` | Install that release |\n| `--from-source` | Build with `cargo build --release --locked` in the checkout the script lives in (`sudo ./scripts/install.sh --from-source`); built as `$SUDO_USER` |\n| `--from-dir PATH` | Install `PATH/memora`, `PATH/memora-cli`, `PATH/assets/` (an unpacked release, or your own build). Version from `--version`, else `PATH/VERSION` |\n| `--port N` | Port (default `8400`) |\n| `--bind ADDR` | Bind address (default `0.0.0.0`) |\n| `--behind-proxy` | Bind `127.0.0.1`; a reverse proxy on this host is the only entry |\n| `--prefix DIR` | Install prefix (default `/usr/local`) |\n| `--data-dir DIR` | Data root (default `/var/lib/memora`) |\n| `--no-start` | Install and enable, but do not start |\n| `--no-systemd` | Skip the unit and the system user (containers, tests); prints the command to start the server by hand |\n| `--upgrade` | Replace binaries and assets, keep state, restart the service if it was running |\n| `--force` | With `--upgrade`: reinstall even when already up to date |\n| `--uninstall` | Stop and remove the unit, binaries, and assets; keep data |\n| `--purge` | With `--uninstall`: also delete the data dir and the `memora` user (asks first) |\n| `--check` | Print `MEMORA_LATEST=` and `MEMORA_INSTALLED=`; change nothing |\n| `--yes`, `-y` | Never ask (needed for `--purge` without a terminal) |\n| `--dry-run` | Print every action, change nothing |\n| `--repo OWNER/NAME` | Download from another GitHub repository (forks); also settable as `MEMORA_REPO` |\n\n`MEMORA_RELEASES_URL` points the installer at a mirror that serves the same\nlayout as GitHub (`<url>/latest`, `<url>/download/vX.Y.Z/<file>`).\n\nRoot is required except for `--check`, `--dry-run`, and `--no-systemd` into a\nprefix you can write to.\n\n### Exit codes\n\n| Code | Meaning |\n|---|---|\n| `0` | Success |\n| `1` | Error (see the message) |\n| `2` | Bad usage |\n| `3` | Already up to date (`--upgrade`) |\n| `4` | Network or download failure |\n| `5` | Checksum mismatch or missing from `SHA256SUMS` |\n| `6` | Not running as root |\n| `7` | Unsupported OS or CPU |\n\n### The systemd unit\n\nThe installer writes this unit (shown with the default paths and port):\n\n```ini\n[Unit]\nDescription=Memora - long-term memory for AI agents (HTTP API + MCP + web UI)\nDocumentation=https://github.com/Codrihub/memora\nAfter=network-online.target\nWants=network-online.target\n\n[Service]\nType=simple\nUser=memora\nGroup=memora\nWorkingDirectory=/var/lib/memora\nEnvironment=HOME=/var/lib/memora\nEnvironment=MEMORA_STATE=/var/lib/memora/state\nEnvironment=MEMORA_ASSETS=/usr/local/share/memora/assets\nEnvironment=MEMORA_PORT=8400\nEnvironment=MEMORA_BIND=0.0.0.0\nEnvironment=MEMORA_VAULT=/var/lib/memora/vault\nEnvironment=GIT_AUTHOR_NAME=Memora\nEnvironment=GIT_AUTHOR_EMAIL=memora@localhost\nEnvironment=GIT_COMMITTER_NAME=Memora\nEnvironment=GIT_COMMITTER_EMAIL=memora@localhost\nEnvironment=RUST_LOG=info\nExecStart=/usr/local/bin/memora\nRestart=on-failure\nRestartSec=3\nTimeoutStopSec=15\nLimitNOFILE=65536\nUMask=0027\n\n# Hardening\nNoNewPrivileges=yes\nAmbientCapabilities=\nCapabilityBoundingSet=\nProtectSystem=strict\nReadWritePaths=/var/lib/memora\nProtectHome=yes\nPrivateTmp=yes\nPrivateDevices=yes\nProtectKernelTunables=yes\nProtectKernelModules=yes\nProtectKernelLogs=yes\nProtectControlGroups=yes\nProtectClock=yes\nProtectHostname=yes\nRestrictAddressFamilies=AF_UNIX AF_INET AF_INET6\nRestrictNamespaces=yes\nRestrictRealtime=yes\nRestrictSUIDSGID=yes\nLockPersonality=yes\nMemoryDenyWriteExecute=yes\nSystemCallArchitectures=native\nSystemCallFilter=@system-service\nSystemCallFilter=~@privileged\n\n[Install]\nWantedBy=multi-user.target\n```\n\nA port below 1024 adds `CAP_NET_BIND_SERVICE` instead of the empty capability\nset. There are no IP restrictions (`IPAddressDeny=`) by default; use the\nfirewall, `MEMORA_DOMAIN`, or the access rules in the UI.\n\nThe installer rewrites the unit on every run. Put local changes in a drop-in:\n\n```sh\nsudo systemctl edit memora # for example, a vault outside /var/lib/memora:\n# [Service]\n# ReadWritePaths=/srv/notes\nsudo systemctl restart memora\n```\n\nBecause of `ProtectSystem=strict` and `ProtectHome=yes`, the server can only\nwrite under `/var/lib/memora`. A vault anywhere else (including `/home`) needs\nthe drop-in above (and `ProtectHome=read-only` or `no` for `/home`).\n\n### Settings\n\nThe unit sets the basics (`MEMORA_STATE`, `MEMORA_ASSETS`, `MEMORA_PORT`,\n`MEMORA_BIND`, `MEMORA_VAULT`, `RUST_LOG`) as `Environment=` lines. Everything\nelse (`MEMORA_BASE_URL`, `MEMORA_DOMAIN`, `MEMORA_TRUSTED_PROXIES`, ...) is\nstored in the state database (table `server_config`). Edit it with the\nconsole: `sudo memora-cli` → `/config`, then `/restart`.\n\nA value stored with `/config` wins over the unit's `Environment=` lines; a key\nwith no stored value uses the environment. If you stored `MEMORA_PORT` with\n`/config` and later reinstall with `--port`, change or clear it in `/config`\ntoo, otherwise the stored value keeps applying. The provisioning owner\npassword and API key are environment-only and never stored (see\n[CONFIGURATION.md](CONFIGURATION.md)).\n\nSee [CONFIGURATION.md](CONFIGURATION.md) for every variable.\n\n### First run\n\n```sh\nsudo memora-cli # opens the console; it finds the running server itself\n/guide # step-by-step, or:\n/web # prints a one-time code\n```\n\nOpen `http://<host>:8400/login`, enter the code, create the owner account, then\nchoose the vault folder (`/var/lib/memora/vault` is suggested).\n\n### Day to day\n\n```sh\nsudo systemctl status memora\nsudo systemctl restart memora\nsudo journalctl -u memora -f\nsudo memora-cli # /status, /keys, /config, /restart, /mcp ...\n```\n\n### Upgrading\n\n```sh\nsudo /usr/local/share/memora/install.sh --upgrade # latest release\nsudo /usr/local/share/memora/install.sh --upgrade --version 1.0.1\nsudo memora-cli update # same, from the console\n```\n\nBinaries and assets are swapped atomically, the state directory and vault are\nuntouched, and the service is restarted if it was running. The server migrates\n`memora.db` itself on start. Take a `memora-cli db backup` before upgrading,\nand read the [CHANGELOG](../CHANGELOG.md) before a major version bump.\n\n### Uninstall\n\n```sh\nsudo /usr/local/share/memora/install.sh --uninstall # keeps /var/lib/memora and the memora user\nsudo /usr/local/share/memora/install.sh --uninstall --purge # also deletes notes, account, keys, and the user\n```\n\nOr run `memora-cli uninstall`, which asks what to keep (see\n[Uninstall with memora-cli](#uninstall-with-memora-cli)).\n\n### Firewall\n\nOpen only the Memora port, and only when clients connect directly:\n\n```sh\nsudo ufw allow 8400/tcp\n# or\nsudo firewall-cmd --permanent --add-port=8400/tcp && sudo firewall-cmd --reload\n```\n\nBehind a reverse proxy on the same host, install with `--behind-proxy` and open\nonly the proxy's 80/443.\n\n## Docker\n\n```sh\ngit clone https://github.com/Codrihub/memora.git && cd memora\nmkdir -p data state && sudo chown -R 1000:1000 data state\ndocker compose up -d\ndocker compose exec -it gateway memora-cli # then /guide, or /web\n```\n\n`docker compose up` pulls `ghcr.io/codrihub/memora:<version>`; if the image is\nnot available (or you set `IMAGE=memora:local`) it builds from the\n`Dockerfile`. Image tags: `<version>` (for example `1.0.0`), `<major>.<minor>`\n(for example `1.0`), and `latest` (stable releases only), for `linux/amd64`\nand `linux/arm64`. The compose file pins the release it ships with; set\n`IMAGE` in `.env` to run another tag.\n\n### Volumes: `/data` and `/state`\n\nBoth must be persistent (the Compose file bind-mounts `./data` and `./state`):\n\n- `/data` is the vault: your notes, their git history, and the event\n log. Lose it and the notes are gone.\n- `/state` holds `memora.db` (owner account, password hash, API key hashes,\n sessions, settings, setup/lock state, activity log). Lose it and\n every agent key stops working, the instance falls back to first-run setup,\n and anyone who reaches the port during that window could claim it.\n\nThe container runs as uid 1000; set `MEMORA_UID`/`MEMORA_GID` in `.env` if the\nhost directories belong to another user. `MEMORA_DATA_DIR` and\n`MEMORA_STATE_DIR` move the host directories, and `MEMORA_HTTP_PORT` changes\nthe published host port. See [CONFIGURATION.md](CONFIGURATION.md#docker-compose-env).\n\n### Verify\n\n```sh\ncurl -s http://127.0.0.1:8400/healthz\ndocker compose exec gateway memora-cli db check\ndocker compose exec gateway memora-cli status\nls -l state/memora.db\n```\n\n### Upgrading\n\n```sh\ngit pull\ndocker compose pull && docker compose up -d # or: docker compose up -d --build\n```\n\nSettings: `docker compose exec -it gateway memora-cli` → `/config`, then\n`docker compose restart gateway` (`/restart` cannot restart a container from\ninside).\n\n## npm\n\nRequirements: Linux on x86_64 or arm64, or Windows 10/11 on x64; Node.js 22 or\nnewer; and `git` (vault history uses it).\n\n```sh\nnpm install -g @codrihub/memora\nmkdir -p ~/memora && cd ~/memora\nMEMORA_VAULT=./vault MEMORA_STATE=./state memora\n# in a second terminal, same folder:\nMEMORA_STATE=./state memora-cli # then /guide, or /web\n```\n\nOn Windows, in PowerShell:\n\n```powershell\nnpm install -g @codrihub/memora\nmkdir ~\\memora; cd ~\\memora\n$env:MEMORA_VAULT = '.\\vault'; $env:MEMORA_STATE = '.\\state'; memora\n# in a second terminal, same folder:\n$env:MEMORA_STATE = '.\\state'; memora-cli # then /guide, or /web\n```\n\n`npx @codrihub/memora --version` runs it without a global install.\n\n`@codrihub/memora` holds the `memora` and `memora-cli` commands and the web UI\n(used unless `MEMORA_ASSETS` is set). The binaries come from\n`@codrihub/memora-linux-x64`, `@codrihub/memora-linux-arm64` or\n`@codrihub/memora-win32-x64`, optional dependencies npm installs only on a\nmatching machine. The Linux ones are the static binaries of the GitHub\nrelease with the same version, so glibc and musl distributions both work; the\nWindows one is built with a static C runtime and needs nothing else. There is\nno install script and nothing is downloaded at install time, so it works with\n`--ignore-scripts` and from a registry mirror; it does not work with\n`--omit=optional`, which leaves the binaries out. On macOS the commands print\nwhere to go instead: use [Docker](#docker) or build from source.\n\nThe npm install sets up no service, user or data folder: the server runs as\nyou, with `MEMORA_STATE` and `MEMORA_VAULT` where you point them (`./state`\nby default). Keep the state folder private (`chmod 700 state`; on Windows,\nkeep it under your user profile), since it holds the owner account and key\nhashes. On Windows, `memora-cli` runs every command as you: there is no root\nor service account to switch to. For a long-running server, prefer the\n[native install](#native-install).\n\nUpgrade with `npm install -g @codrihub/memora@latest` (`memora-cli update`\nprints this too) and restart the server; the state database is migrated on\nstart.\n\n## Start, stop and restart\n\n`memora-cli start`, `stop` and `restart` (or `/start`, `/shutdown` and\n`/restart` in the console) work out how this install runs and do the right\nthing:\n\n| Install | What `memora-cli start / stop / restart` does | By hand |\n|---|---|---|\n| Native (systemd) | runs `systemctl start / stop / restart memora` (as root) | `sudo systemctl start memora` |\n| npm, source | runs the server in the background, with `memora.pid`, `memora.log` and `stop.token` in the state folder; `stop` asks it to end over a local, token-protected request and waits, `stop --force` kills it | run `memora` and keep it open; Ctrl+C stops it |\n| Docker | prints the host commands (a container cannot stop itself) | `docker start / stop / restart memora` |\n\nFrom the browser, the owner can shut the server down in Settings, Server, Shut\ndown: the server answers, then stops gracefully and exits with status 0, the\nsame as Ctrl+C or `systemctl stop`. A supervisor that restarts a cleanly exited\nprocess starts it again (systemd `Restart=always`, Docker\n`--restart unless-stopped`); the installer's unit uses `Restart=on-failure`, so\nit stays stopped. API keys cannot shut the server down.\n\n## Update\n\nCheck what you run first: `memora --version` and `memora-cli --version`.\n`memora-cli update` (or `/update` in the console) works out how this copy was\ninstalled and prints, or runs, the right steps. By install method:\n\n| Install | Update with | Then |\n|---|---|---|\n| npm (Windows, Linux) | `npm install -g @codrihub/memora@latest` | `memora-cli restart`, or Ctrl+C the running `memora` and start it again |\n| Docker Compose | `docker compose pull && docker compose up -d` | nothing: the container is re-created |\n| Docker run | `docker pull ghcr.io/codrihub/memora:latest`, then `docker rm -f memora` and the same `docker run` again (same volumes) | nothing |\n| Native (systemd) | `sudo memora-cli update` (runs `install.sh --upgrade`) | nothing: the service is restarted |\n| Source | `git pull && cargo build --release` | `memora-cli restart` |\n\nSettings, accounts and notes stay; the server migrates `memora.db` on start.\nTake a `memora-cli db backup` first if you are unsure.\n\n**Release zip (older Windows installs).** Windows now installs with npm. To\nswitch, stop the old server (Ctrl+C in its window), run\n`npm install -g @codrihub/memora`, and start `memora` with the same folders so\neverything carries over, for example in PowerShell:\n\n```powershell\n$env:MEMORA_STATE = 'C:\\Users\\you\\memora\\state'; $env:MEMORA_VAULT = 'C:\\Users\\you\\memora\\vault'; memora\n```\n\nThen delete the old program folder (only the `.exe` files and `assets`, not\nyour state or vault folders).\n\n## Uninstall with memora-cli\n\n```bash\nmemora-cli uninstall # or /uninstall in the console\n```\n\nIt explains what it removes for this install (the service and program\nfiles, or the npm package, or the container), then shows a checklist; press\nspace to select and Enter to continue:\n\n- **Settings and accounts** (the state folder: database, keys, sessions)\n- **Vault notes** (your vault folder)\n\nBoth are **unticked**, so by default your settings and notes are kept and a\nlater install picks them up again. Deleting the vault asks you to type its\nfolder name. Before the state folder is deleted, a final database backup is\noffered. System folders, your home folder and the program's own folder are\nnever deleted.\n\n| Install | What uninstall does |\n|---|---|\n| Native (systemd) | runs the installed `install.sh --uninstall` (adds `--purge` only when both folders are the installer's own) |\n| npm | stops the server, deletes what you ticked, then tells you to run `npm uninstall -g @codrihub/memora` |\n| Source | stops the server, deletes what you ticked; delete the program folder yourself |\n| Docker | prints `docker rm -f memora` and, for what you ticked, `docker volume rm memora-state` / `docker volume rm memora-data` |\n\nWithout a terminal it needs `--yes` and deletes only what the flags say:\n`memora-cli uninstall --yes [--delete-config] [--delete-vault]`.\n\nOn a version older than 1.3.2 there is no `uninstall` command: see\n[Uninstall by hand](#uninstall-by-hand-versions-before-132).\n\n## Uninstall by hand (versions before 1.3.2)\n\n`memora-cli uninstall` arrived in 1.3.2. On an older version it answers\n``unknown command `uninstall` ``. Either update first and then run\n`memora-cli uninstall` (npm: `npm install -g @codrihub/memora@latest`), or\nremove Memora by hand with the steps below. They only touch Memora: never use\nwildcards, and never delete a parent folder or your home folder.\n\n**1. Check the version.** `memora --version` and `memora-cli --version`.\n\n**2. Find the folders.** Memora keeps two folders:\n\n- the **state folder** (settings, accounts, keys): `MEMORA_STATE`, or by\n default `state` inside the folder where you started `memora` (for example\n `C:\\Users\\you\\state` or `~/memora/state`);\n- the **vault folder**: your notes, wherever you chose.\n\nThe server prints both when it starts:\n`Memora HTTP server starting vault=... state=...`. `memora-cli status`, run in\nthe same folder, shows the state folder too.\n\n**3. Stop Memora.** Press Ctrl+C in the window where `memora` runs (or close\nthat window). Then make sure it is gone:\n\n| Shell | Check | Stop if still running |\n|---|---|---|\n| PowerShell | `Get-Process memora -ErrorAction SilentlyContinue` | `Stop-Process -Name memora` |\n| cmd | `tasklist /FI \"IMAGENAME eq memora.exe\"` | `taskkill /IM memora.exe` |\n| Linux, macOS | `pgrep -ax memora` | `pkill -x memora` |\n\n**4. Remove the program.**\n\n| Install | Commands |\n|---|---|\n| npm (any OS) | `npm uninstall -g @codrihub/memora`, then `npm ls -g --depth=0`: if `@codrihub/memora-win32-x64` (or `-linux-x64`, `-linux-arm64`) is still listed, `npm uninstall -g` that exact name |\n| Docker run | `docker rm -f memora`, then `docker image rm ghcr.io/codrihub/memora:latest` |\n| Docker Compose | `docker compose down` in the folder of `docker-compose.yml` (no `-v`) |\n| Native (systemd) | `sudo /usr/local/share/memora/install.sh --uninstall` (keeps `/var/lib/memora`) |\n| Release zip | delete the folder that holds `memora.exe`, `memora-cli.exe` and `assets` (check its contents first, as below) |\n\n**5. Delete the state folder (optional).** Look inside first: it should hold\n`memora.db` (and maybe `memora.log`, `memora.pid`, `stop.token`, `backups`).\nThen delete that exact path:\n\n```powershell\n# Windows, PowerShell\nGet-ChildItem -LiteralPath 'C:\\Users\\you\\state'\nRemove-Item -LiteralPath 'C:\\Users\\you\\state' -Recurse -Confirm\n```\n\n```bat\n:: Windows, cmd\ndir \"C:\\Users\\you\\state\"\nrmdir /S \"C:\\Users\\you\\state\"\n```\n\n```sh\n# Linux, macOS\nls -la ~/memora/state\nrm -rI -- ~/memora/state\n```\n\nDocker: `docker volume ls`, then remove the exact names,\n`docker volume rm memora-state`. Compose: check and delete the `./state`\nfolder next to `docker-compose.yml`. Native: `/var/lib/memora/state`\n(or `install.sh --uninstall --purge`, which also deletes the notes, see below).\n\n**6. The vault folder: only if you are sure.** It holds your notes. It is\noptional to delete it; copy it somewhere safe first (it is plain Markdown).\nUse the same two steps on its exact path: look inside (`Get-ChildItem` /\n`ls`), then `Remove-Item -LiteralPath '<vault>' -Recurse -Confirm` or\n`rm -rI -- <vault>`. Docker: `docker volume rm memora-data`, or the `./data`\nfolder with Compose. Native: `sudo /usr/local/share/memora/install.sh\n--uninstall --purge` deletes `/var/lib/memora` with the notes, the account\nand the `memora` user.\n\n## Troubleshooting\n\n**``memora-cli: unknown command `uninstall` ``** (or `start`, `stop`,\n`restart`). You run a version older than 1.3.2. Update, then run the command\nagain: `npm install -g @codrihub/memora@latest`, then `memora-cli uninstall`.\nOr remove it by hand: [Uninstall by hand](#uninstall-by-hand-versions-before-132).\n\n**`/update` says \"not installed with install.sh (built from source)\" on an\nnpm install.** Older versions could miss an npm install. Update with npm,\n`npm install -g @codrihub/memora@latest`, and restart the server; newer\nversions detect npm reliably. Never run `cargo build` for an npm install.\n\n**`/restart` says \"systemctl restart\" on npm or Windows.** Same cause (older\nversion). Stop the server with Ctrl+C in its window and run `memora` again, or\nupdate and use `memora-cli restart`.\n\n**Which version do I have?** `memora --version` and `memora-cli --version`.\nThe latest release is on\n[GitHub Releases](https://github.com/Codrihub/memora/releases).\n\n## Reverse proxy\n\nRun Memora on loopback (`--behind-proxy` natively; in Docker set\n`MEMORA_HTTP_PORT=127.0.0.1:8400` in `.env`) and let the proxy terminate TLS.\nThen set, with `/config` or in `.env`:\n\n| Variable | Why |\n|---|---|\n| `MEMORA_BASE_URL=https://memory.example.com` | Public URL; links and MCP snippets use it, and its host becomes an allowed domain |\n| `MEMORA_DOMAIN=memory.example.com` | Only these hostnames are served; requests for the bare IP or other names get 404 |\n| `MEMORA_TRUSTED_PROXIES=203.0.113.10` | Proxies whose forwarding headers are believed. Loopback (same-host nginx, cloudflared) is always trusted; only list remote proxies |\n\nIn Docker, a proxy on the host reaches the container through the Docker\nnetwork, so the container sees the network's gateway address (for example\n`172.18.0.1`) instead of loopback. Add that address to\n`MEMORA_TRUSTED_PROXIES`, otherwise every request appears to come from it.\n\nThe proxy must forward `Host`, `X-Forwarded-For`, and `X-Forwarded-Proto`, and\nupgrade WebSockets on `/ws`. nginx and Caddy examples are in\n[DEPLOYMENT.md](DEPLOYMENT.md).\n\n## Backups\n\nBack up **both** the state database and the vault. The database is small but\ncritical.\n\nState, online (the server keeps running):\n\n```sh\nsudo memora-cli db backup # state/backups/memora-<UTC time>.db, keeps the newest 10\nsudo memora-cli db backup --to /var/backups/memora.db\nsudo memora-cli db check # integrity, permissions, sizes, last backup age\ndocker compose exec gateway memora-cli db backup # Docker: lands in ./state/backups/\n```\n\nThe copy is a consistent snapshot (`VACUUM INTO`), checked with\n`integrity_check`, mode 0600. Never `cp` a live `memora.db`: recent commits sit\nin `memora.db-wal`. Restore with the server stopped:\n\n```sh\nsudo systemctl stop memora\nsudo memora-cli db restore /var/backups/memora.db # verifies it; keeps the replaced DB in state/backups/\nsudo systemctl start memora\n```\n\nAlso keep a copy of `state/key-seal.bin`, which encrypts the sealed API key\ncopies. Vault and state together: archive both with the server stopped:\n\n```sh\nsudo systemctl stop memora\nsudo tar -C /var/lib/memora -czf memora-backup-$(date +%F).tar.gz state vault\nsudo systemctl start memora\n```\n\nKeep backups private: the database holds password and key hashes (never\nplaintext secrets).\n\n## Automation: `--check` and `--upgrade`\n\nThese are the contract for scripts and automation.\n\n```sh\n$ /usr/local/share/memora/install.sh --check\nMEMORA_LATEST=1.0.1\nMEMORA_INSTALLED=1.0.0\n```\n\n`MEMORA_INSTALLED` comes from `/usr/local/share/memora/VERSION` (written by\nthe installer), else from `memora --version`, else `unknown` (or `none` when\nnothing is installed). `MEMORA_LATEST` is `unknown` and the exit code `4` when\nGitHub cannot be reached. `--check` needs no root.\n\n```sh\n$ sudo /usr/local/share/memora/install.sh --upgrade --yes [--version X.Y.Z]\n...\nMEMORA_UPGRADE_RESULT=ok FROM=1.0.0 TO=1.0.1\n```\n\n`--upgrade --yes` never prompts. The last line of output is always\n`MEMORA_UPGRADE_RESULT=<ok|uptodate|error> FROM=<old> TO=<new>`, and the exit\ncode is `0` (ok), `3` (already up to date), `4` (network), `5` (checksum),\n`6` (not root), or `1`/`2` for other errors.\n"},{"file":"docs/CONFIGURATION.md","slug":"configuration","title":"Configuration","text":"# Configuration\n\nAll server state, settings included, lives in one SQLite database,\n`<MEMORA_STATE>/memora.db` (see [DATABASE.md](DATABASE.md)). Server settings are\nrows in the `server_config` table, edited with `memora-cli` (`/config` in the\nconsole). The process environment (systemd `Environment=`, Docker\n`environment:`) applies to every key that has no row.\n\n## Precedence\n\nFor each server setting:\n\n1. a row in `server_config` (set with `/config`), else\n2. the process environment (non-empty value), else\n3. the built-in default.\n\nThe server reads `server_config` once at startup, before anything else, so a\nchange made with `/config` applies after a restart (`/restart` for a native\ninstall, `docker compose restart gateway` in Docker). Clearing a value in\n`/config` deletes the row, and the environment or default applies again.\n\nA row wins over the environment. If you set `MEMORA_PORT` with `/config` and\nlater change the port in the systemd unit or `.env`, the row still applies\nuntil you clear it.\n\n## Server settings\n\n| Name | Default | Where it can live | What it does |\n|---|---|---|---|\n| `MEMORA_PORT` | `8400` | `server_config` or env | HTTP port (API, MCP, web UI, WebSocket). 1-65535. |\n| `MEMORA_BIND` | `127.0.0.1` | `server_config` or env | Bind address. `0.0.0.0` for every interface (the container image and the installer set it). |\n| `MEMORA_BASE_URL` | empty | `server_config` or env | Public URL, for example `https://memory.example.com`. Used for OAuth metadata and connection snippets; its host is also an allowed domain. |\n| `MEMORA_DOMAIN` | empty (any host) | `server_config` or env | Allowed hostnames, comma separated (`*.example.com` works). Requests for other hosts get 404. Loopback names are always allowed. |\n| `MEMORA_TRUSTED_PROXIES` | empty | `server_config` or env | IPs of remote reverse proxies whose forwarding headers are trusted. Loopback is always trusted. |\n| `MEMORA_ARM_TTL` | `300` | `server_config` or env | Accepted and validated (30-86400 seconds), but the server and `memora-cli` do not read it: the setup / reset window length comes from `memora-cli --minutes` (default 5 minutes). |\n| `MEMORA_VAULT` | empty (`data` as last resort) | `server_config` or env | Suggested vault folder. The vault in use is chosen in the browser (or with `memora-cli vault`) and stored in the `settings` table. |\n| `MEMORA_VAULT_AUTO` | `false` | `server_config` or env | `true` (also `1`, `yes`, `on`): use `MEMORA_VAULT` at startup instead of asking in the browser, only while no vault is configured and if the folder is writable. |\n| `MEMORA_ADMIN_USER` | `admin` | `server_config` or env | Name of the owner created at startup when no owner exists (needs `MEMORA_ADMIN_PASSWORD`). |\n| `RUST_LOG` | `info` | `server_config` or env | Log filter, for example `info` or `memora=debug`. |\n\n`server_config` accepts only these ten keys. Values are trimmed and validated\n(numbers in range, `true`/`false`, a valid user name, no control characters, at\nmost 2048 bytes).\n\n## Environment only\n\n| Name | Default | What it does |\n|---|---|---|\n| `MEMORA_ADMIN_PASSWORD`, `MEMORA_ADMIN_PASSWORD_FILE` | unset | Creates the owner at startup when none exists (at least 10 characters). Only the argon2id hash is stored; an existing owner is never replaced. |\n| `MEMORA_API_KEY`, `MEMORA_API_KEY_FILE` | unset | Installs an agent API key with id `k_env` and scopes `mcp`, `read`, `write` (at least 24 characters). Only its SHA-256 is stored; the key is replaced when the value changes. |\n| `MEMORA_STATE` | `state` (relative to the working directory) | State directory holding `memora.db`. Created with mode 0700 if missing. |\n| `MEMORA_ASSETS` | the `crates/http/assets` folder of the build tree | Directory of the web UI assets. |\n| `MEMORA_INSTALL` | set by the npm launcher (`npm`) and the Docker image (`docker`) | How this copy was installed: `npm`, `docker`, `native`, `zip` or `source`. `memora-cli update`, `start`, `stop`, `restart` and `uninstall` use it to pick the right steps; when unset they work it out from the program's path. |\n| `MEMORA_SETUP_HINT` | `memora-cli setup (run on the server)` | Hint returned by `GET /api/auth/state` and shown on the login screen. |\n| `MEMORA_UPDATE_CHECK` | `true` | Release check: shortly after start and then every 6 hours the server asks GitHub (`api.github.com/repos/Codrihub/memora/releases/latest`) for the newest release and the web UI shows when an update is available. The same check reads the repository's star count (`api.github.com/repos/Codrihub/memora`), shown in What's new. `false` (also `0`, `no`, `off`) turns both off; no network call is made. |\n\nThe two secrets can never be stored in `server_config` (the schema rejects\nthem). The `_FILE` variants read the value from a file, for example a Docker\nsecret; a non-empty file wins over the plain variable.\n\nIn `/config`, `MEMORA_API_KEY` offers to create an API key directly, and\n`MEMORA_ADMIN_PASSWORD` points to `/setup` or `/reset`.\n\n## Instance settings (web UI)\n\nThe `settings` table holds one row, edited from the Settings page of the web UI:\n\n| Key | Default | Range | What it does |\n|---|---|---|---|\n| `realm` | `Memora` | 1-64 characters | Instance name shown in the UI and reported by `/api/config` and `/api/auth/state`. |\n| `session_ttl` | `10800` (3 hours) | 300-2592000 seconds | Idle timeout of a browser session: any use renews it (requests, and an open tab in use). |\n| `session_max_age` | `0` | `0` or at least `session_ttl` | Absolute session lifetime in seconds. `0` means no cap. |\n| `min_password_len` | `10` | 10-256 | Minimum owner password length. |\n| `log_max_mb` | `8` | 1-512 | Size limit in MB of the vault event log (`.events.jsonl`). |\n| `log_max_days` | `0` | 0-3650 | Age limit in days of the vault event log. `0` means no age limit. |\n| `vault_path` | unset | absolute path | The vault folder. Set in the browser after the first sign-in, or with `memora-cli vault PATH`. |\n\nTwo more settings live in the `ui_layout` table and in a file beside the database:\n\n| Setting | Default | Where | What it does |\n|---|---|---|---|\n| Largest image | 5 MB | Settings, Images (`POST /api/settings/media`, admin); stored as the `srv-media` document | Uploads above this size are refused, from the app, the HTTP API and MCP `upload_image` alike. 0.1 to 50 MB. |\n| Mnemo | not set up | Settings, Mnemo, or `/mnemo setup` in the console; stored in `assistant.sqlite3` | Providers (OpenAI, Anthropic, one OpenAI-compatible server) with sealed API keys, models (pinned, hidden, default, context window and reply limit), temperature, reply and context limits, tool steps per reply, your instructions, and the floating button. |\n\n## memora-cli options\n\n| Option | Default | What it does |\n|---|---|---|\n| `--state <DIR>` | `$MEMORA_STATE`, else the state directory of the running `memora` server, else `./state` | State directory to work on. |\n| `--minutes <N>` | `5` | Window length for `setup` and `reset-password`, 1-60. |\n| `--ttl <SECONDS>` | | Window length in seconds (at most 3600). `--minutes` wins when both are given. |\n| `--create` | | With `vault PATH`: create the folder if it does not exist. |\n\nRun as root, `memora-cli` does all database work as the owner of the state\ndirectory, so no root-owned `memora.db*` files appear. See\n[INSTALL.md](INSTALL.md) and [DEPLOYMENT.md](DEPLOYMENT.md) for the commands.\n\n## Docker Compose (`.env`)\n\nThese variables are read by `docker-compose.yml`, not by Memora itself:\n\n| Name | Default | What it does |\n|---|---|---|\n| `COMPOSE_PROJECT_NAME` | `memora` | Compose project name, also the container name prefix. |\n| `IMAGE` | `ghcr.io/codrihub/memora:<version>` | Image to run or build. The compose file pins the release it ships with. |\n| `MEMORA_HTTP_PORT` | `8400` | Host port mapped to the container's port 8400. Use `127.0.0.1:8400` to publish on loopback only. |\n| `MEMORA_DATA_DIR` | `./data` | Host path mounted at `/data` (the vault). |\n| `MEMORA_STATE_DIR` | `./state` | Host path mounted at `/state` (the state directory). |\n| `MEMORA_UID`, `MEMORA_GID` | `1000` | uid:gid the container runs as. Must own both host directories. |\n| `MEMORA_ARM_TTL` | `300` | Passed to the container unchanged. |\n\nCompose also passes these through from `.env` to the container:\n`MEMORA_BASE_URL`, `MEMORA_DOMAIN`, `MEMORA_TRUSTED_PROXIES`,\n`MEMORA_VAULT_AUTO`, `MEMORA_ADMIN_USER`, `MEMORA_ADMIN_PASSWORD`,\n`MEMORA_ADMIN_PASSWORD_FILE`, `MEMORA_API_KEY`, `MEMORA_API_KEY_FILE`,\n`MEMORA_SETUP_HINT`, `MEMORA_UPDATE_CHECK`, and `RUST_LOG`.\n\nInside the container the image sets `MEMORA_VAULT=/data`,\n`MEMORA_STATE=/state`, `MEMORA_PORT=8400`, `MEMORA_BIND=0.0.0.0`,\n`MEMORA_ARM_TTL=300`, `MEMORA_ASSETS=/app/assets`, `MEMORA_INSTALL=docker`,\nand `RUST_LOG=info`.\n\n## State directory\n\n| Path | Content |\n|---|---|\n| `memora.db` (+ `-wal`, `-shm`) | The state database: owner, API keys (hashes), tool switches and per-key permissions, OAuth clients and grants, privacy rules, sessions (hashed ids), setup window and lock state, access rules, settings, `server_config`, activity log. Mode 0600, WAL mode, must be on a local filesystem. See [DATABASE.md](DATABASE.md). |\n| `key-seal.bin` | 32-byte master key (mode 0600) that encrypts the copies of dashboard-created API keys, so the owner can show a key again. Created on first use. Back it up together with `memora.db`. |\n| `assistant.sqlite3` (+ `-wal`, `-shm`) | Mnemo, the built-in agent: providers (API keys sealed with `key-seal.bin`), models, preferences, chats and messages. Mode 0600. Separate from `memora.db`, so the main schema is unchanged; delete it to forget every Mnemo chat and key. Back it up with `memora.db` if you want to keep chats. |\n| `backups/` | `memora-cli db backup` output (newest 10 kept by default). |\n| `exchange/` | Zips written by the `export_memory` MCP tool and read by `import_memory` (mode 0700, created on first use). Private to this instance; delete old zips when no longer needed. |\n| `legacy-json-<unix time>/` | JSON state files found at startup, moved here after their one-time import into `memora.db`. |\n| `internal.token` | Created by the Docker entrypoint. Not used by Memora. |\n\n## Vault files\n\nThe vault holds the markdown notes plus derived and metadata files. See\n[ARCHITECTURE.md](ARCHITECTURE.md#vault-markdown-portable) for the full list.\nThe important ones for operations are `.git/` (history), `.events.jsonl`\n(event log), and `.Trash/`\n(soft-deleted notes; `.Trash/.index.json` remembers where each one came from,\nso `restore_trash` puts it back there; `.Trash/.assets/<entry>/` keeps the images\nof a trashed note until it is restored or deleted for good). Images uploaded to a\nnote are ordinary files in the note's folder.\n\n## Version history\n\nVersion history (`get_history`, `get_note_at`, `diff`, `restore_memory`,\n`snapshot`) is on when the vault folder is a git repository of its own, that is\nwhen it has a `.git/` directory. Memora does not create one, so a new vault has\nno history and these tools answer \"version history is off\". To turn it on,\ninstall `git` and run, once:\n\n```sh\ngit -C /path/to/vault init\ngit -C /path/to/vault add -A\ngit -C /path/to/vault commit -m \"start history\"\n```\n\n(In Docker, the vault is the host directory mounted at `/data`.) From then on\nevery change made through Memora is committed automatically. Each commit's\nauthor is the agent or user whose call made the change; the committer is the\nvault's git identity (`git config user.name` / `user.email`), or `Memora\n<memora@localhost>` when none is set. Git never searches above the vault, so a\nvault inside another repository still needs its own `git init`.\n\nA snapshot (`snapshot` tool) commits pending changes and tags the last commit\nas `snap-<label>`; pass that tag as `rev` to `get_note_at`, `diff` or\n`restore_memory`.\n\nDeleting a note for good (Delete forever or Empty trash in the app,\n`/api/trash/delete`, `/api/trash/empty`, `delete_memory` with `permanent`)\nalso erases it from the history: Memora rewrites the vault's git history so\nno commit, snapshot tag or object keeps its text, any name it had, its trash\nrecord or its path in a commit message, then expires the reflog and runs\n`git gc --prune=now`. Other notes keep all their versions, but their revision\nids change, so old revision ids (and clones or pushes of the vault made\nbefore) no longer match. Moving a note to the Trash keeps its history.\n"},{"file":"docs/MCP.md","slug":"mcp","title":"MCP tools","text":"# MCP\n\nMemora exposes the vault to agents through the Model Context Protocol. The\nserver speaks JSON-RPC 2.0 over the Streamable HTTP transport at `/mcp`, on the\nsame port as the HTTP API and the web UI. There is one MCP endpoint and one tool\ncatalog.\n\n| | |\n|---|---|\n| Endpoint | `POST /mcp` |\n| Protocol versions | `2025-06-18` (preferred), `2025-03-26`, `2024-11-05` |\n| Auth | API key in `Authorization: Bearer <key>` or `X-API-Key: <key>`, or an OAuth 2.1 access token |\n| Discovery card | `GET /.well-known/mcp.json` (public) |\n| Readable catalog | `GET /tools` (HTML page, public) |\n| Catalog size | 77 tools, plus 5 admin tools for keys with the `admin` scope |\n\n`initialize` answers with the protocol version the client asks for when it is\none of the three above, and with `2025-06-18` otherwise.\n\n## Transport\n\n- Requests are JSON-RPC 2.0 objects sent with `POST /mcp`. Batches (JSON\n arrays) are not supported.\n- Responses are plain JSON (`application/json`), with one exception below.\n- `initialize` returns an `Mcp-Session-Id` header (`<catalog epoch>.<random>`).\n The epoch is a hash of the server version and the tools the caller may use, so\n it changes when the server is upgraded, a tool is switched on or off, or the\n key's scopes or tool grant change. No session id is ever refused: unknown or\n old ids work, and malformed ones count as no session.\n- When a request carries a session id whose catalog has changed since that\n session last heard, and its `Accept` header allows `text/event-stream`, the\n answer is an SSE stream with two events: the notification\n `notifications/tools/list_changed`, then the normal response. Each change is\n sent once per session (remembered in memory; a restart forgets, and the\n epoch in the id takes over). JSON-only clients always get plain JSON.\n- `GET /mcp` returns `405 Method Not Allowed` (there is no standalone server\n stream). `DELETE /mcp` with a session id returns `204 No Content`; without\n one it returns `405`.\n- A notification (a `notifications/*` method without an `id`) gets\n `202 Accepted` and no body.\n- `/mcp` needs a configured vault. Until one is chosen it returns\n `409 {\"error\":\"vault not configured\",\"needs_vault\":true}`.\n- A browser session (cookie) may also call `/mcp`. It then needs a same-origin\n request, like the rest of the JSON API.\n\nThe server speaks Streamable HTTP only. A client that can only launch local stdio\nservers can use a bridge such as `mcp-remote` (see below).\n\n## Connecting an agent\n\n### With an API key\n\nCreate a key in the web UI (Keys page), with `memora-cli` (`/keys`), or with\n`POST /api/keys`. The raw key (`memora_live_...`) is shown once. By default a key gets\nthe scopes `mcp`, `read` and `write` and may call every tool. See\n[Tool switches and per-key permissions](contracts/tools-permissions.md) to\nnarrow it.\n\nUse `http://localhost:8400/mcp` for a local install, or your public URL such as\n`https://memory.example.com/mcp` behind a reverse proxy. When the server sets\n`MEMORA_DOMAIN` or `MEMORA_BASE_URL`, requests for any other host get `404`, so\nuse that domain.\n\nClaude Code:\n\n```bash\nclaude mcp add --transport http memora https://memory.example.com/mcp \\\n --header \"Authorization: Bearer memora_live_REPLACE_WITH_YOUR_KEY\"\n```\n\nCursor, Windsurf and other clients with an `mcpServers` JSON config (VS Code\nuses the key `servers` in `.vscode/mcp.json`):\n\n```json\n{\n \"mcpServers\": {\n \"memora\": {\n \"type\": \"http\",\n \"url\": \"http://localhost:8400/mcp\",\n \"headers\": {\n \"Authorization\": \"Bearer memora_live_REPLACE_WITH_YOUR_KEY\"\n }\n }\n }\n}\n```\n\nCodex (`~/.codex/config.toml`), with the key in the `MEMORA_API_KEY`\nenvironment variable:\n\n```toml\n[mcp_servers.memora]\nurl = \"https://memory.example.com/mcp\"\nbearer_token_env_var = \"MEMORA_API_KEY\"\n```\n\nClients that only run local stdio servers, such as the Claude Desktop config\nfile, can bridge with `mcp-remote` (needs Node.js):\n\n```json\n{\n \"mcpServers\": {\n \"memora\": {\n \"command\": \"npx\",\n \"args\": [\n \"-y\", \"mcp-remote\", \"https://memory.example.com/mcp\",\n \"--header\", \"Authorization: Bearer memora_live_REPLACE_WITH_YOUR_KEY\"\n ]\n }\n }\n}\n```\n\nSome clients send the key as `X-API-Key: <key>` instead. Both headers are\naccepted.\n\n### With OAuth\n\nClients that support MCP authorization (for example Claude and ChatGPT custom\nconnectors, or Claude Code without a `--header`) can connect with only the URL:\n\n```bash\nclaude mcp add --transport http memora https://memory.example.com/mcp\n```\n\nThe flow:\n\n1. The client calls `/mcp` without credentials and gets `401` with\n `WWW-Authenticate: Bearer resource_metadata=\"https://memory.example.com/.well-known/oauth-protected-resource\"`.\n2. It reads the protected resource metadata (RFC 9728) and the authorization\n server metadata at `/.well-known/oauth-authorization-server` (RFC 8414; also\n served at `/.well-known/openid-configuration` and under a `/mcp` suffix).\n3. It registers itself with dynamic client registration at\n `POST /oauth/register` (RFC 7591), or uses an HTTPS client metadata document\n URL as its `client_id`. The owner can also register clients in the web UI.\n Redirect URIs must be HTTPS, or plain HTTP on `localhost`, `127.0.0.1` or\n `[::1]`.\n4. It opens `/oauth/authorize` (authorization code with PKCE `S256` only). The\n browser lands on the Memora sign-in page, and the signed-in owner approves or\n denies the connection on a consent card. Codes are valid for 10 minutes.\n5. It exchanges the code at `POST /oauth/token` and receives an access token and\n a refresh token. The only OAuth scope is `mcp`.\n\nThe access token is a regular Memora API key named after the client. It starts\nwith the default scopes (`mcp`, `read`, `write`) and every tool, and it shows up\non the Keys page like any other key, so you can restrict, disable or delete it\nthere. The access token has no expiry. A `refresh_token` grant replaces it with\na fresh one (the old token stops working at once) and rotates the refresh token.\nDisabling or deleting the key ends the connection.\n\nSet `MEMORA_BASE_URL` (for example `https://memory.example.com`) when the server\nruns behind a proxy, so the issuer and endpoint URLs in the metadata are the\npublic ones. Without it the server derives them from the request headers.\n\n### Test from a shell\n\n```bash\ncurl -s -X POST http://localhost:8400/mcp \\\n -H \"Authorization: Bearer memora_live_REPLACE_WITH_YOUR_KEY\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/list\"}'\n```\n\n## Discovery card\n\n`GET /.well-known/mcp.json` needs no auth and returns:\n\n| Field | Value |\n|---|---|\n| `name` | `memora` |\n| `version` | The server version |\n| `description` | One-line description of the server |\n| `mcp` | `{endpoint: \"/mcp\", transports: [\"streamable-http\"], protocolVersion: \"2025-06-18\"}` |\n| `auth` | `{type: \"api-key\", headers: [\"Authorization: Bearer <key>\", \"X-API-Key: <key>\"], oauth: \"/.well-known/oauth-authorization-server\"}` |\n| `capabilities` | `{tools: true, resources: true, prompts: false}` |\n| `tools` | Every catalog tool as `{name, category, description, enabled}`. `enabled` is `false` for tools switched off on this server. Admin tools are not listed. |\n| `resources` | `[{uri, name}]` for the three resources below |\n\nThe card is the same for every caller. To see what a given key may call, use\n`tools/list` with that key.\n\n## Methods\n\n| Method | Purpose |\n|---|---|\n| `initialize` | Handshake. Returns `protocolVersion`, `serverInfo` (`{name, version}`) and `capabilities` (`tools` with `listChanged: true`, `resources` with `listChanged: false`). |\n| `notifications/initialized` | Client notification. Without an `id` it gets `202 Accepted`. |\n| `tools/list` | The tools the caller may use, each with `name`, `description` (what it does and when to use it), `inputSchema`, and `_meta.category`. |\n| `tools/call` | Runs one tool. Params are `{name, arguments}`. |\n| `resources/list` | Lists the three resources below. |\n| `resources/read` | Reads one resource. Params are `{uri}`. |\n\nThere are no prompts and no pagination cursors. The only notification the server\nsends is `notifications/tools/list_changed` (see Transport).\n\n### Resources\n\n| URI | Content |\n|---|---|\n| `memory://catalog` | Every catalog tool with `name`, `category`, `description`, `when`, and `inputSchema` (JSON) |\n| `memory://schema` | Data shapes for a note, a folder, the graph, and activity (JSON) |\n| `memory://guide` | A short guide for agents using the vault (Markdown) |\n\n`resources/read` returns `{contents: [{uri, mimeType, text}]}`.\n\n## Results and errors\n\nA successful tool call returns the tool's JSON result as text:\n\n```json\n{\n \"jsonrpc\": \"2.0\",\n \"id\": 2,\n \"result\": {\n \"content\": [{ \"type\": \"text\", \"text\": \"{...}\" }],\n \"isError\": false\n }\n}\n```\n\nA tool that fails (bad arguments, note not found, unknown tool name) returns the\nsame envelope with `isError: true` and the error message as the text. The HTTP\nstatus stays `200`.\n\nJSON-RPC errors:\n\n| Code | When |\n|---|---|\n| `-32700` | The body is not valid JSON (HTTP `400`). |\n| `-32600` | The body is not a JSON-RPC request object (HTTP `400`). |\n| `-32601` | Unknown method: `unsupported method: <method>`. |\n| `-32602` | `resources/read` with an unknown URI: `unknown resource: <uri>`. |\n| `-32003` | The tool exists but the caller may not use it. Messages: `tool not allowed for this API key: <name>`, `tool disabled on this server: <name>`, `API key lacks the 'write' scope for tool: <name>`. |\n\nHTTP errors before JSON-RPC runs:\n\n| Status | When |\n|---|---|\n| `401` | No key, or a key that is unknown, disabled, deleted or replaced by a roll (`invalid API key`). Carries a `WWW-Authenticate` header that points OAuth clients at the protected resource metadata. |\n| `403` | The key lacks the `mcp` scope (`{\"error\":\"API key lacks the 'mcp' scope\",\"required_scope\":\"mcp\"}`), or a browser request failed the same-origin check. |\n| `405` | Any method other than `POST`. |\n| `409` | No vault is configured yet. |\n| `429` | Rate limit or cooldown after failed attempts. |\n\n## What each key sees\n\n`tools/list` is filtered per caller:\n\n- A tool switched off on the server is hidden for everyone.\n- A key whose tool list is not `\"*\"` only sees the tools in its list.\n- A key without the `write` scope only sees read-only tools.\n- Admin tools are added for keys with the `admin` scope (and for browser\n sessions).\n\n`tools/call` on a tool that `tools/list` would hide returns `-32003`. Details\nare in [Tool switches and per-key permissions](contracts/tools-permissions.md).\n\n### Privacy rules\n\nThe owner can hide notes and folders from specific agents (web UI,\n`/api/privacy`, or the `privacy_*` admin tools). For an API key covered by a\nrule, every tool works as if the hidden paths did not exist: they are left out\nof listings, search, the graph, tags, events, logs, locks and folder metadata; a\nhidden path named in an argument is answered as not found, for reads and writes\nalike; and folder operations that would carry hidden items along are refused.\nIf the rules cannot be read, the key sees nothing (fail closed). Browser\nsessions are never filtered.\n\n## Tools\n\nR = read-only (needs only the `mcp` scope). W = changes the vault or server\nstate (also needs the `write` scope). Unless marked required, arguments are\noptional. Paths are vault-relative, for example `Projects/Plan.md`. A path\ncopied in the web app (Copy path in a note or folder menu) works as is as the\n`path` argument of `read_memory` and the other tools.\n\n### Notes (`note`)\n\n| Tool | | Arguments | Purpose |\n|---|---|---|---|\n| `list_memory` | R | none | Every note grouped by its folder, the full parent path (`Projects/Atlas`; `Root` for the top level): `{folder: [{path, name, folder, mtime}]}`. |\n| `read_memory` | R | `path` (string, required) | Markdown body, frontmatter, tags and backlinks of one note. A `\\` in a path is read as `/`; replies echo the normalized path. |\n| `create_memory` | W | `title` (string, required), `folder` (string relative to the vault, default `Memory` when omitted or empty; `Root` for the top level), `content` (string; default is a stub with `created` frontmatter and a heading) | Creates `<folder>/<title>.md` and returns `{ok, path}`. A trailing `.md` in the title is dropped; `/` and `\\` in a title, an absolute folder and a folder that is a note are refused. Spaces are kept; `: * ? \" < > | # ^ [ ]` and a leading dot are removed and names are cut at 80 characters; the reply then adds `renamed_from` and a `note`. A note whose name differs only in case from an existing one is refused. |\n| `save_memory` | W | `path` (string, required), `content` (string, required) | Replaces the whole note. |\n| `patch_memory` | W | `path` (string, required), `ops` (array, required) | Partial edits. Each op is an object: `{op:\"append\", text}`, `{op:\"prepend\", text}`, `{op:\"replace\", find, with}`, `{op:\"set_field\", field, value}`, `{op:\"add_tag\", tag}`, `{op:\"remove_tag\", tag}`. |\n| `delete_memory` | W | `path` (string, required), `permanent` (boolean, default false) | Moves a note to the Trash (`.Trash`), remembering where it came from and who deleted it: `{ok, path, trashed, to}`. `list_trash` shows it and `restore_trash` brings it back. `permanent: true` deletes it for good instead (`{ok, path, permanent}`) and is refused for keys without the `admin` scope. With version history on, every earlier version is erased from the history as well (every name the note had, its trash record and the commit messages naming it; other notes keep their versions but their revision ids change), so no one, agents included, can read it again. |\n| `move_memory` | W | `path` (string, required), `folder` (string, required; relative to the vault, `Root` for the top level) | Moves a note into another folder. Wikilinks resolve by note name, so they keep working. |\n| `rename_memory` | W | `path` (string, required), `new_name` (string, required) | Renames a note in its folder. |\n| `upload_image` | W | `path` (string, required: the note the image belongs to), `name` (string, required, e.g. `diagram.png`), `data` (string, required: base64 or a `data:image/...;base64,` URL), `alt` (string), `append` (boolean, default false) | Stores a PNG, JPEG, WebP or GIF in the note's own folder (checked by content; the upload limit in Settings, Images applies, 5 MB by default). Identical bytes reuse the existing file; a taken name gets `-1`, `-2` ...: `{ok, path, name, bytes, url, markdown}`. Show it in the note with the returned `markdown` line, `![alt](path:name.png)`; `append: true` adds that line to the end of the note. The image then moves, goes to the Trash, is restored and is deleted with its note. |\n| `list_images` | R | `folder` (string; `Root` or empty for the top level) or `path` (a note) | The images of one folder (not its sub folders), each with `used_in` (the notes and sections that show it); with `path`, the images that note shows and every image of its folder. |\n\n### Search (`search`)\n\n| Tool | | Arguments | Purpose |\n|---|---|---|---|\n| `get_stats` | R | none | Counts of notes, links and folders. |\n| `search_memory` | R | `q` (string, required; `query` is accepted as an alias), `limit` (integer, default 12) | Search titles and bodies. Supports `tag:x` and `#x`. |\n\n### Query (`query`)\n\n| Tool | | Arguments | Purpose |\n|---|---|---|---|\n| `query_memory` | R | `folder`, `tags`, `author`, `type`, `status` (strings), `limit` (integer, default 50) | Filter notes by frontmatter. |\n| `find_similar` | R | `path` (string, required), `limit` (integer, default 8) | Notes most similar to one note (shared tags and words). |\n| `suggest_links` | R | `path` (string, required), `limit` (integer, default 8) | Similar notes not yet linked from this one. |\n| `list_tags` | R | none | Every tag with its usage count. |\n| `rename_tag` | W | `old` (string, required), `new` (string, required) | Renames a tag across the vault. |\n| `merge_tag` | W | `a` (string, required), `b` (string, required) | Merges tag `a` into tag `b` across every note. |\n\n### Tags (`tag`)\n\n| Tool | | Arguments | Purpose |\n|---|---|---|---|\n| `get_tags` | R | `path` (string; not in the advertised schema) | Every tag with its count, or the tags of one note when `path` is given. |\n| `search_by_tag` | R | `tag` (string, required), `limit` (integer, default 50; not in the advertised schema) | Every note carrying a tag. |\n| `add_tags` | W | `path` (string, required), `tags` (string, required, comma-separated) | Adds tags to a note. A leading `#` is stripped. |\n| `remove_tags` | W | `path` (string, required), `tags` (string, required, comma-separated) | Removes tags from a note. |\n| `set_tags` | W | `path` (string, required), `tags` (string, required, comma-separated) | Replaces a note's tag list. |\n\n### Folders (`folder`, `ops`)\n\n| Tool | | Arguments | Purpose |\n|---|---|---|---|\n| `list_folders` | R | none | `{count, folders: [{name, count, color}]}`. |\n| `create_folder` | W | `name` (string, required) | Creates a folder. |\n| `rename_folder` | W | `folder` (string, required), `name` (string, required, one segment) | Renames a folder in place. Notes, sub folders, color and icon move along. |\n| `move_folder` | W | `folder` (string, required), `into` (string; empty or `Root` = top level) | Moves a folder with everything in it. |\n| `move_folder_contents` | W | `folder` (string, required), `into` (string; empty = top level) | Moves everything inside a folder into another folder, then removes the empty folder. Name clashes get a `-N` suffix. |\n| `delete_folder` | W | `folder` (string, required), `into` (string), `mode` (`move` or `trash`) | Deletes a folder. By default its notes (at any depth) move to the folder's parent (Root for a top-level folder), keeping the sub folder structure below it; wikilinks to them are rewritten. `into` sends them to another existing folder instead (`Root` = top level). `mode: \"trash\"` moves every note to `.Trash` instead (`list_trash` / `restore_trash` bring them back) and cannot be combined with `into`. Other files in the folder are deleted. |\n| `folder_stats` | R | `folder` (string, required) | Note count and metadata for one folder. |\n| `get_folder_meta` | R | `folder` (string) | Color, icon and description of one folder, or of every folder. |\n| `set_folder_meta` | W | `folder` (string, required), `color`, `icon`, `desc` (strings) | Sets folder display metadata. A field sent as an empty string is cleared. |\n\n### Graph (`graph`)\n\n| Tool | | Arguments | Purpose |\n|---|---|---|---|\n| `get_graph` | R | none | Whole graph: `{nodes: [{id, path, folder, color, degree, tags, mtime}], links: [{source, target}]}`. |\n| `get_neighbors` | R | `path` (string, required), `depth` (integer, default 1) | Notes within N hops. |\n| `get_subgraph` | R | `path` (string, required), `depth` (integer, default 1), `max_nodes` (integer, default 60) | Subgraph around one note. |\n| `find_path` | R | `source` (string, required), `target` (string, required) | Shortest wikilink path between two notes. |\n| `get_hubs` | R | `limit` (integer, default 10) | Most connected notes. |\n| `get_isolated` | R | none | Notes with no links in or out. |\n| `link_stats` | R | `path` (string, required) | Outgoing, incoming and unresolved links of one note. |\n| `broken_links` | R | none | Wikilinks pointing at notes that do not exist. |\n\n### Versioning (`version`)\n\n| Tool | | Arguments | Purpose |\n|---|---|---|---|\n| `get_history` | R | `path` (string, required), `limit` (integer, default 20, at least 1) | Git history of a note, newest first, always an array of `{rev, date, author, message, version, total}` (plus `path` for commits under an earlier name: the history follows renames). `author` is the agent or user whose call made the change. `version` numbers the revisions from 1 (the oldest) to `total` (the current one), whatever `limit` is. |\n| `get_note_at` | R | `path` (string, required), `rev` (string, required) | `{ok, path, rev, content}` at a revision. `rev` is one revision: a `rev` from `get_history`, `snap-<label>`, `HEAD~1` or `HEAD@{<date>}`. Unknown revisions, dates before the history and empty `rev` are errors. |\n| `diff` | R | `path` (string, required), `rev_a` (string, required), `rev_b` (string) | `{path, from, to, changed, diff}` between two revisions, or `rev_a` against the current note. Ranges (`a..b`) and unknown revisions are errors. |\n| `restore_memory` | W | `path` (string, required), `rev` (string, required) | Restores a note to a revision (a new commit). Give the current path; content under an earlier name is found. Restoring the old path of a renamed note is refused and names the current one. |\n| `snapshot` | W | `label` (string, required) | Commits pending changes and tags the last commit `snap-<label>` (letters, digits, `.`, `_`, `-`; spaces become `-`; at most 40 characters; must be new). Use the tag as `rev`. |\n| `soft_delete` | W | `path` (string, required) | Moves a note to `.Trash` and remembers where it came from. |\n| `list_trash` | R | none | Notes in `.Trash`, newest first: `{name, path, original, deleted, by, title}` (`by` = `{id, name, kind}` of who deleted it, null when unknown). |\n| `restore_trash` | W | `name` (string, required; `.md` optional), `into` (string) | Restores a note from `.Trash` to the path it was deleted from, or into the folder `into` (`Root` = top level). |\n\nAll versioning tools except `soft_delete`, `list_trash` and `restore_trash`\nneed version history on (see [CONFIGURATION.md](CONFIGURATION.md#version-history));\notherwise they answer \"version history is off\".\n\n### Bulk writes (`write`)\n\n| Tool | | Arguments | Purpose |\n|---|---|---|---|\n| `batch_create` | W | `notes` (array, required) of `{title (required), folder (default `Memory`), content}` | Creates many notes in one call; titles and folders follow `create_memory`. Every item is checked first and nothing is created when one is malformed (missing title, wrong type, unknown key). The reply has one result per item: `{ok, path}` or `{ok: false, item, title, error}`. |\n| `duplicate_memory` | W | `path` (string, required) | Copies a note as `<name>-copy` in the same folder (a long name is shortened so the suffix fits in 80 characters). |\n| `merge_memory` | W | `paths` (array of strings, required: existing notes, each once, not `into`), `into` (string, required; `.md` optional) | Appends the body of each source, without its frontmatter, to `into` under `## from <name>`, and adds the sources' tags to the target's tags. `into` is created when missing. The sources are kept. Returns `{ok, into, created, merged, sources, tags_added}`. |\n| `template_create` | W | `template` (string, required; a note in `Templates/`, as `Meeting` or `Meeting.md`), `title` (string, required), `folder` (string, default `Root`), `variables` (object) | Creates a note from a template with `{{var}}` substitution. `{{title}}` (the note title) and `{{date}}` (today, `YYYY-MM-DD`) are built in unless given in `variables`. Only notes in `Templates/` can be templates. |\n| `bulk_replace` | W | `find` (string, required), `replace` (string, required), `folder` (string), `regex` (boolean, default false), `dry_run` (boolean, default false) | Find and replace across notes. `find` must not be empty or (with `regex`) match an empty string. `folder` includes its subfolders (`Root` = top level only); a missing folder is an error. With `regex`, `replace` expands `$1` / `${name}` (`$$` is a literal `$`); unknown groups are errors. Needs `write` even with `dry_run`. |\n| `bulk_delete` | W | `paths` (array of strings), `folder` (string) | Moves many notes to `.Trash` (recoverable with `restore_trash`), by list and / or folder (with subfolders). Any invalid path (missing, outside the vault, a folder, not a note) refuses the whole call and is listed. |\n\n### Collaboration (`collab`)\n\n| Tool | | Arguments | Purpose |\n|---|---|---|---|\n| `lock_node` | W | `path` (string, required), `owner` (string, default the caller), `ttl` (integer seconds, default 300) | Soft lock on a note. |\n| `release_lock` | W | `path` (string, required), `owner` (string, default the caller) | Releases a lock. |\n| `get_locks` | R | none | Active locks. |\n| `mention_agent` | W | `agent` (string, required), `path` (string, required), `message` (string) | Writes `> @agent: message` into a note. With agent `mnemo`, Memora's own agent answers it in the note (the request is struck through and the reply quoted under it). |\n| `get_assignments` | R | `agent` (string) | Notes with `assigned_to` in their frontmatter. |\n\n### Activity and health (`ops`)\n\n| Tool | | Arguments | Purpose |\n|---|---|---|---|\n| `get_events` | R | `since` (number, unix time), `folder`, `actor` (strings), `limit` (integer, default 50) | Recent note created, updated and deleted events. |\n| `presence` | R | `window` (integer seconds, default 300) | Agents active within the window. |\n| `get_logs` | R | `range` (string, default `1d`; also `7d`, `today`, `yesterday`), `actor` (string), `limit` (integer, default 100) | Activity log for a period. |\n| `search_logs` | R | `q` (string, required), `range` (string, default `7d`), `actor` (string), `limit` (integer, default 100) | Keyword search in the activity log. |\n| `digest` | R | `folder` (string), `since` (number) | Event counts per actor and per type. |\n| `healthcheck` | R | none | Note count, broken links, orphans and git status. |\n| `stale_detection` | R | `days` (integer, default 30) | Notes untouched for more than N days. |\n\n### Identity (`identity`)\n\n| Tool | | Arguments | Purpose |\n|---|---|---|---|\n| `set_my_name` | W | `name` (string, required) | Sets the display alias shown in the activity feed and log. |\n| `set_my_color` | W | `color` (string, required; `#rrggbb`, or `\"\"` to reset) | Sets the calling API key's display color. Fails for browser sessions. |\n| `list_actors` | R | none | `{me, aliases}`: the caller and every known alias. |\n\n### Import and export (`interop`)\n\n| Tool | | Arguments | Purpose |\n|---|---|---|---|\n| `export_memory` | W | `paths` (array of strings, required; notes or folders), `out_path` (string), `overwrite` (boolean, default false) | Writes a zip of the given paths to the server's exchange folder and returns `{ok, path, name, bytes, replaced}`, where `path` and `name` are the zip's file name. Every path must exist; missing ones are listed and nothing is written. `out_path` is a plain file name ending in `.zip` (letters, digits, `.`, `_`, `-`, at most 120 characters); the default is `memora-export-<unix seconds>.zip`. An existing zip of that name is only replaced with `overwrite: true`. |\n| `import_memory` | W | `zip_path` (string, required), `overwrite` (boolean, default false) | Imports the `.md` notes of a zip in the exchange folder, by the file name `export_memory` returned. Returns `{ok, added, overwritten, skipped, unsafe, failed}`: `skipped` are existing notes kept (no `overwrite`), `unsafe` are entries with an absolute or escaping path (`{entry, reason}`), `failed` are entries too large or unreadable. |\n\nThe exchange folder is `exchange` in the state directory (`<MEMORA_STATE>/exchange`),\none per Memora instance, created with mode 0700.\nTools never read or write anywhere else on the server's disk.\n\n### Checks, to-dos and pins (`ux`)\n\n| Tool | | Arguments | Purpose |\n|---|---|---|---|\n| `get_todos` | R | `path` (string) | Open checklist items (`- [ ]`) in one note or the whole vault. |\n| `follow_ups` | R | none | Notes whose status is still awaiting action. |\n| `validate_memory` | R | `path` (string, required) | Checks a note: frontmatter present and well formed, a valid `created` date, tags, and broken links (named in the issue and listed in `broken_links`). |\n| `list_pins` | R | none | The owner's pinned notes and folders in sidebar order: `{count, pins:[{kind, path, position, missing}]}`. `missing` is true when the path no longer exists (renamed or deleted outside Memora). |\n| `pin` | W | `path` (string, required), `kind` (`note` or `folder`; default: what the path is on disk), `position` (integer from 0; default: the end) | Pins an existing note or folder, or moves its pin. A note path may leave out `.md`. At most 200 pins. Returns the list. |\n| `unpin` | W | `path` (string, required), `kind` | Removes a pin; the note or folder is not touched. Returns the list with `removed`. |\n\nPins are shared by every browser of the owner (`/api/pins`). They follow their note or\nfolder through renames and moves done by Memora (over MCP or HTTP, including notes inside\na moved folder) and are removed when the item is deleted or moved to the trash; deleting a\nfolder removes every pin under it. A key whose privacy rules hide a path neither lists\nnor changes its pin, and `position` counts only the pins the key can see.\n\n### Admin tools (`admin`)\n\nListed and callable only for keys with the `admin` scope (and for browser\nsessions). They are not part of the switchable catalog: global tool switches and\na key's tool list do not apply to them, and they do not need `write`.\n\n| Tool | Arguments | Purpose |\n|---|---|---|\n| `admin_list_tools` | none | `{tools: [{name, category, description, enabled}]}` for every catalog tool. |\n| `admin_set_tool` | `name` (string, required), `enabled` (boolean, required) | Switches a catalog tool on or off for every key. Returns `{ok, name, enabled}`. |\n| `privacy_list` | `path` (string), `kind` (`node` or `folder`) | Without `path`: every privacy rule. With `path`: that note or folder's own rule, the folder rules it inherits, and which agents can see it. |\n| `privacy_set` | `path` (string, required), `agents` (array of key ids or names, required; a comma-separated string also works), `kind` (`node` or `folder`), `mode` (`deny` or `allow_only`, default `deny`) | Replaces the rule on a path. `deny` hides it from the listed agents; `allow_only` hides it from every other agent, including keys created later. `deny` with no agents removes the rule. A node rule follows its note through renames and moves. |\n| `privacy_clear` | `path` (string, required), `kind` (`node` or `folder`) | Removes the path's own rule. Rules on parent folders still apply. |\n\nWhen `kind` is omitted it is taken from the path on disk: a folder if a folder\nexists there, otherwise a note.\n\n## Identity and tracking\n\nEvery tool call is published to the web UI's realtime activity stream as an\n`ai_activity` start and end pair, named after the API key (or the signed-in\nuser), with the note paths involved. Calls are also counted per key: the Keys\npage and `GET /api/keys` show each key's `uses`, `last_ip`, and the tools it has\ncalled recently. `initialize` registers the connection under the key's name\n(`GET /api/aliases`). `set_my_name` changes the alias shown in the activity\nfeed and log, and `set_my_color` changes the key's color in the UI. See\n[API.md](API.md) for the HTTP endpoints.\n"},{"file":"docs/API.md","slug":"api","title":"HTTP API","text":"# HTTP API\n\nThe `memora` binary serves the HTTP API, the MCP endpoint, the OAuth endpoints,\nthe web UI, and the WebSocket on one port. This document lists the HTTP endpoints.\n\n## Authentication\n\nThe Auth column in the tables below uses these levels:\n\n- None: reachable without credentials.\n- Session: requires the `memora_sess` cookie set by a successful login.\n- Key (`scope`): an API key sent as `Authorization: Bearer <key>` or `X-API-Key: <key>`\n that carries the named scope.\n- Session or key (`scope`): either of the above.\n- Session only: an API key is not enough. API keys get `401` (or `403` where noted).\n- +CSRF: the same-origin check described below applies.\n\n### API key scopes\n\nA key carries any of the scopes `mcp`, `read`, `write`, and `admin`. New keys get\n`mcp`, `read`, and `write` unless other scopes are requested. The scope a route\nneeds is decided by its path and method:\n\n| Scope | Routes |\n|---|---|\n| `mcp` | `/mcp` |\n| `admin` | `/api/tools`, `/api/keys` and `/api/keys/*`, `/api/access` and `/api/access/*`, `/api/logs/settings`, `/api/settings/server`, `/api/oauth/clients` and `/api/oauth/clients/*`, `/api/privacy` and `/api/privacy/*`, `/api/trash/delete`, `/api/trash/empty`; deleting for good with `/api/delete` |\n| `read` | Every other `GET` or `HEAD` under `/api/` |\n| `write` | Every other method under `/api/` |\n\nA key without the needed scope gets `403 {error, required_scope}`. A missing key\ngets `401`; for `/mcp` the `401` carries a `WWW-Authenticate` header,\n`Bearer resource_metadata=\"<base>/.well-known/oauth-protected-resource\"`, so OAuth\ncapable clients can start sign-in. An invalid key gets `401` and is logged; an\nIP that keeps presenting invalid keys is put on a cooldown (`429`).\n\n`/api/auth/*` never accepts an API key: without a valid session it answers `401`.\n\nAPI keys see the vault through their privacy rules (see [Privacy](#privacy)):\nnotes and folders hidden from a key behave as if they do not exist. A browser\nsession sees everything.\n\n### CSRF\n\nWrite endpoints that accept a session check the request origin whenever a\nsession cookie is present: `Origin` (or, without it, `Referer`) must match the\nrequest `Host` (or an `X-Forwarded-Host` sent by a trusted proxy), and\n`Sec-Fetch-Site: cross-site` is refused. A failed check is\n`403 {\"error\":\"origin mismatch\"}`. Requests without a session cookie (API-key\nclients) pass, since a browser cannot attach an API key on its own.\n\nThe public auth forms (`/api/auth/login`, `/api/auth/verify`,\n`/api/auth/bootstrap`, `/api/auth/reset`) also refuse a foreign or `null`\n`Origin` when no cookie exists yet. A request with neither `Origin` nor\n`Referer` (curl, the CLI) passes.\n\n### Locked instance\n\nWhile the instance is LOCKED, `/api/*` and `/mcp` answer\n`423 {error, locked: true, hint}` except for `/api/auth/state`, `/api/auth/verify`,\n`/api/auth/login`, `/api/auth/logout`, `/api/auth/bootstrap`, and\n`/api/auth/reset`. Other pages redirect to `/login?locked=1`; static assets,\n`/login`, `/logout`, `/healthz`, and `/favicon.ico` are still served.\n`/api/auth/login` itself answers `423` while locked.\n\n### Vault not configured\n\nUntil a vault folder is configured, `/mcp` and every `/api/*` route except\n`/api/auth/*`, `/api/settings*`, `/api/config`, `/api/keys*`, `/api/tools`,\n`/api/access*`, and `/api/ui/*` answer\n`409 {\"error\":\"vault not configured\", \"needs_vault\":true}`.\n\n### Limits and other gates\n\n- Requests for a host outside the configured domain list get a bare `404`.\n- Access rules (see `/api/access`) can block a caller:\n `403 {\"error\":\"access denied by stack rule\", ip}`.\n- Per-IP rate limits answer `429` with a `Retry-After` header and\n `{error, limited, cooldown, retry_after}`. Login, code check, setup, reset, profile,\n password, and username changes have a stricter limit and a cooldown after\n repeated failed attempts. Requests from the machine itself and `/healthz` are\n not limited.\n- A request that takes longer than 30 seconds is answered with `408`.\n- A password hashing pool that is busy answers `503` with `Retry-After: 2`.\n- `GET` answers under `/api/` (except `/api/auth/*`) are gzip-compressed when the\n request sends `Accept-Encoding: gzip`. Pages, writes, sign-in, `/mcp` and\n server-sent events are never compressed.\n\nResponses are JSON unless stated otherwise. Errors are `{\"error\": \"...\"}`. Vault\nerrors map to `404` for not-found (including paths hidden from the caller) and\n`400` for bad input.\n\n## Health and discovery\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/healthz` | None | `{ok, server}` for unauthenticated callers from other machines. A signed-in browser or a caller on the same machine gets `{ok, server, version, vault_configured, vault, armed, locked, base_url, base_url_configured}`. |\n| GET | `/.well-known/mcp.json` | None | The MCP discovery card: `{name, version, description, mcp, auth, capabilities, tools, resources}`. `tools` lists the full catalog with `enabled` per tool. |\n| GET | `/tools` | None | An HTML rendering of the tool catalog. A signed-in browser gets the app shell instead. |\n| POST | `/mcp` | Key (`mcp`), or Session (+CSRF) | MCP over streamable HTTP (JSON-RPC in, JSON-RPC out). See [MCP.md](MCP.md). A session has full access; a key is limited by its tool grant. Notifications get `202` with no body. Malformed JSON is `400` with a JSON-RPC error. Other methods get `405` with `Allow: POST`. |\n\n## Auth\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/api/auth/state` | None | `{bootstrap, realm, min_password_len, gateway, armed, locked, setup_hint, ready, checks:{vault, state}, code_required, cooldown, vault_configured}`. Adds `signed_out` (`password_changed` or `signed_out_remotely`) when the browser's session was ended on purpose, and `mode`, `expires_in`, `ttl` while a setup or reset window is open. |\n| POST | `/api/auth/verify` | None (+CSRF) | Checks the setup code shown on the server before the setup or reset form is shown. Body: `{code}`. Returns `{ok, mode, expires_in, user}`. `403` when no window is open or the instance is not ready. A wrong code answers `403 {error, burned:false}` and counts against the caller IP's budget of 3 wrong codes (then `429`); after 50 wrong codes in one window the window closes and the code is void: `403 {error, burned:true}`. |\n| POST | `/api/auth/login` | None (+CSRF) | `{ok, user, expires_in, redirect}` and sets the session cookie. Body: `{username, password}`. `400` when a field is missing, `401` on bad credentials, `403` if the account is disabled, `423` if locked, `429` during a cooldown of the caller IP (there is no account-wide lockout; see DEPLOYMENT.md, Failed sign-ins). |\n| POST | `/api/auth/logout` | None (+CSRF) | `{ok:true}`. Ends the session named by the cookie, if any, and clears the cookie. |\n| POST | `/api/auth/bootstrap` | None (+CSRF) | Creates the owner account. Body: `{code, username, password}`. Returns `{ok, user, redirect, persisted}` and sets a session cookie. The username is stored lowercase. `400` for an invalid username or password length; `403` unless a window is open, the code is right, the instance is ready, and no account exists. |\n| POST | `/api/auth/reset` | None (+CSRF) | Sets a new password for the single account, and may rename it. Body: `{code, username, password}`. Returns `{ok, user, persisted}`. Signs out every session. `400` for invalid input; `403` unless a window is open, the code is right, and an account exists. |\n| POST | `/api/auth/profile` | Session only (+CSRF) | With `password` in the body, changes the password exactly like `POST /api/settings/password` (body `{current, password, confirm}`). Otherwise sets `display_name` (at most 48 characters) and returns `{ok, changed, persisted, user, password_changed:false}`; with no `display_name` it returns `{ok, changed:false}`. |\n| GET | `/api/auth/me` | Session only | `{authenticated, user, enabled, expires_in}`. `401` without a session. |\n| GET | `/api/auth/events` | Session only | Recent entries of the security activity log, newest first: `{events:[{at, event, ip, user, detail, actor, actor_kind, actor_id}], count}`. `user` is the stored actor (`key:<id>` for API-key calls); `actor` is the display name (the key's current name, falling back to its id; the username for the browser), `actor_kind` is `agent` or `user` (null when there is no actor). Query: `limit` (default 200, max 2000), `q`. |\n\n## Pages\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/login` | None | The sign-in page. A signed-in browser is redirected to `/` unless the instance is locked or the query has `oauth` (the OAuth consent card). |\n| POST | `/logout` | None (+CSRF) | Ends the session, clears the cookie, and redirects to `/login`. With a session cookie the request must be same-origin (`403` otherwise); other methods get `405`. The web UI uses `POST /api/auth/logout`. |\n| GET | `/`, `/index.html` | Session | The web app shell. Without a session: `302` to `/login`. `503` when the UI assets are not installed. |\n| GET | App routes (see below) | Session | The same app shell as `/`. Without a session: `302` to `/login?r=<path>`, so sign-in returns to the page. |\n\nApp routes are the web app's client-side pages: `/brain`, `/nodes`, `/graph`,\n`/canvas`, `/tags`, `/activity`, `/agents`, `/access`, `/settings`,\n`/overview`, `/welcome`, `/trash`, `/mnemo`, the older names `/home`, `/vault`, `/logs`, `/keys`,\nand `/node/` or `/node/<percent-encoded vault path>`. The path is never used to\nread a file; a path holding NUL or another control character (raw or\npercent-encoded) is `400`. `/tools` is an app route for a signed-in browser and\nthe public tool catalog otherwise.\n\nHTML pages are sent with `Cache-Control: no-cache, no-store, must-revalidate`\nand a per-response CSP nonce.\n\nAny other `GET` that asks for HTML (`Accept: text/html`), is outside `/api/`,\n`/mcp`, `/oauth`, and `/.well-known`, and has no file extension in its last\nsegment gets the app shell (which shows its \"page not found\" view). Every other\nunmatched request is `404 {\"error\":\"not found\"}`.\n\n## Static assets\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/assets/{name}` | None | Static UI assets (whitelisted filenames only, else `404`). |\n| GET | `/app.js`, `/app.css`, `/login.css` | None | The UI bundle and styles. Revalidated on every load (`Cache-Control: no-cache`, ETag). |\n| GET | `/favicon.svg` | None | The icon. |\n| GET | `/favicon.ico` | None | `204` with no body. |\n| GET | `/manifest.webmanifest`, `/sw.js`, `/robots.txt`, `/offline.html`, `/icon-192.png`, `/icon-512.png`, `/icon-maskable-512.png`, `/apple-touch-icon.png` | None | PWA files and `robots.txt`. Images and the manifest are cached for 5 minutes; code is revalidated on every load. |\n\n## Vault\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/api/tree` | Session or key (`read`) | Notes grouped by folder: `{folder: [{path, name, folder, mtime, title}]}`; `title` is what the app shows (front matter `title`, else the first `# heading`, else the file name with `_` as spaces). |\n| GET | `/api/folders` | Session or key (`read`) | Every folder the caller may see, empty and nested ones included (`{folders:[path]}`); dot folders such as `.Trash` are left out. |\n| GET | `/api/note` | Session or key (`read`) | `{path, name, content, html, tags, frontmatter, backlinks, size, mtime}`. Query: `path` (`400` when empty). |\n| GET | `/api/vault/file` | Session or key (`read`) | The raw bytes of one image file in the vault (PNG, JPEG, GIF, WebP, AVIF, BMP, ICO; never SVG). Query: `path` (vault-relative). The file content must match its type. At most 10 MiB (`413`). Sent with an `ETag` (`304` on `If-None-Match`), `Cache-Control: private, max-age=300`, and a sandbox CSP. `400` invalid path, `403` path not allowed, `404` not found, `415` not an image. |\n| GET | `/api/folder-meta` | Session or key (`read`) | Folder metadata keyed by folder name. Query: `folder` (optional). |\n| POST | `/api/save` | Session or key (`write`, +CSRF) | `{ok, path}`. Body: `{path, content}`. Overwrites the note. |\n| POST | `/api/create` | Session or key (`write`, +CSRF) | `{ok, path}`. Body: `{title, folder?, content?}`. |\n| POST | `/api/rename` | Session or key (`write`, +CSRF) | `{ok, path}` with the new path. Body: `{path, name}`. |\n| POST | `/api/move` | Session or key (`write`, +CSRF) | `{ok, path}` with the new path. Body: `{path, folder?}`. |\n| POST | `/api/delete` | Session or key (`write`; `admin` to delete for good, +CSRF) | `{ok:true}`. Body: `{path, mode?}`. Deletes the note for good (no trash); with version history on, its earlier versions are erased from the history too, so nothing can bring it back. Because that cannot be undone, an API key needs the `admin` scope for it (`403 {error, required_scope: \"admin\"}` otherwise, as MCP `delete_memory` with `permanent`); the owner's browser session may. `mode: \"trash\"` (what the web app sends) moves it to `.Trash` instead, remembering where it was and who deleted it: `{ok, trashed, to}`. |\n| GET | `/api/trash` | Session or key (`read`) | Notes in `.Trash` the caller may see, newest first: `{items: [{name, path, original, deleted, by, title}]}` (`by` = `{id, name, kind}`, null when unknown). Nothing is removed automatically. |\n| POST | `/api/trash/restore` | Session or key (`write`, +CSRF) | Body: `{name, into?}`. Back to where the note was deleted from (or into the folder `into`); a taken name gets `-1`, `-2` ...: `{ok, path, from, renamed?}`. 404 when the name is not in the trash. |\n| POST | `/api/trash/delete` | Session or key (`admin`, +CSRF) | Body: `{name}`. Deletes one trash entry for good: `{ok, deleted, name, history?}`. With version history on, the note is also erased from the history (every earlier version under every name it had, its trash record and its path in commit messages), and `history` is `{erased, ms, commits}`. Other notes keep their versions; their revision ids change. |\n| POST | `/api/trash/empty` | Session or key (`admin`, +CSRF) | Deletes every trash entry the caller may see, for good: `{ok, count, names, history?}`, erasing them from the version history in one rewrite (as `/api/trash/delete`). |\n| POST | `/api/folder` | Session or key (`write`, +CSRF) | `{ok, path}`. Body: `{name}`. |\n| POST | `/api/folder/rename` | Session or key (`write`, +CSRF) | `{ok, from, to, notes}`. Body: `{folder, name}`. |\n| POST | `/api/folder/move` | Session or key (`write`, +CSRF) | Moves a folder and everything in it. `{ok, from, to, notes}`. Body: `{folder, into}`; `into` empty or `Root` means the top level. |\n| POST | `/api/folder/move-contents` | Session or key (`write`, +CSRF) | Moves everything inside a folder into another one, then removes the emptied folder. Name clashes get a `-N` suffix. `{ok, from, to, moved}`. Body: `{folder, into}`; `into` empty or `Root` means the top level. |\n| POST | `/api/delete-folder` | Session or key (`write`, +CSRF) | Deletes a folder. Body: `{folder, into?, mode?}`. By default its notes move to the folder's parent (the top level for a top-level folder), keeping the sub folder structure below it, and wikilinks are rewritten: `{ok, deleted_folder, moved_to, moved, links_updated}` (`moved` lists the new paths; `moved_to_root` repeats it when they went to the top level). `into` names another existing folder for the notes (`Root` = top level). `mode: \"trash\"` moves every note to `.Trash` instead (restorable from the Trash on the Notes page, `/api/trash/restore`, or the MCP tools `list_trash` / `restore_trash`): `{ok, deleted_folder, mode, count, trashed}`. Other files in the folder are deleted. |\n| POST | `/api/folder-meta` | Session or key (`write`, +CSRF) | `{ok, folder}`. Body: `{folder, color?, icon?, desc?}`. |\n\nThe three folder operations also publish a `folder_changed` realtime event so\nopen browsers reload their tree.\n\n### Version history\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/api/history?path=&limit=` | Session or key (`read`) | A note's revisions, newest first (the vault's git history, following renames): `{path, total, versions: [{rev, date, author, message, version, total, path?, owner}]}`. `version` counts from 1 (the oldest) to `total` (the current one); `owner` is true when the signed-in owner made the change. `limit` defaults to 100 (at most 500). |\n| GET | `/api/note-at?path=&rev=` | Session or key (`read`) | The note as it was at one revision (a `rev` from `/api/history`, `snap-<label>`, `HEAD~1`, `HEAD@{<date>}`): `{path, rev, content, html}`, `html` rendered like `/api/note`. |\n| GET | `/api/diff?path=&a=&b=` | Session or key (`read`) | Unified diff of the note from revision `a` to `b`, or to the note as it is now when `b` is left out: `{path, from, to, changed, diff}`. |\n| POST | `/api/history/restore` | Session or key (`write`, +CSRF) | Body: `{path, rev}`. Gives the note its content from `rev` again as a new revision (restoring version 3 of 5 makes version 6; nothing is lost): `{ok, path, rev, changed, version, total}` (`changed` false when the note already had that content). |\n\nThe four history routes answer `409 {error, history: false}` while version history\nis off (the vault folder is not a git repository; see\n[CONFIGURATION.md](CONFIGURATION.md#version-history)) and `404` for a path that is\nnot in the vault or its history, or is hidden from the calling key. Web writes\n(save, create, rename, move, delete, restore) are committed with the caller as the\nauthor: the owner's username for the browser, the key's name for an API key.\n\n### Images\n\nImages live in the folder of the note that shows them, and a note shows one with\n`![alt](path:name.png)` (`path:` names a file in the note's own folder). Saving a\nnote that points with `path:Other/Folder/pic.png` to an image elsewhere copies that\nimage beside the note and rewrites the link, so notes never point across folders.\nImages follow their note: a move carries them, the Trash keeps them in\n`.Trash/.assets/<entry>/` until the note is restored (to the same or another\nfolder) or deleted for good, and a deleted folder takes its images along. An image\nthat another note of the same folder still shows is copied or kept instead.\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| POST | `/api/vault/image?note=<path>&name=<file>` | Session or key (`write`, +CSRF) | The raw image bytes as the body (PNG, JPEG, WebP or GIF, checked by content). Stored beside the note; identical bytes reuse the existing file, a taken name gets `-1`, `-2` ...: `{ok, path, name, bytes, url, markdown}` (`markdown` is the line to put in the note). `400` for another file type, a size above the upload limit, or a missing note. |\n| POST | `/api/vault/image/delete` | Session or key (`write`, +CSRF) | Body: `{path}`. Deletes one image file (the version history keeps it): `{ok, deleted}`. |\n| GET | `/api/vault/images?folder=<folder>` | Session or key (`read`) | The images of that one folder (not its sub folders or parents): `{folder, images: [{path, name, folder, bytes, mtime, url, used_in: [{note, title, heading}]}]}`. `heading` is the section that shows the image (`null` before the first heading). |\n| GET | `/api/vault/images?note=<path>` | Session or key (`read`) | `{note, folder, images, folder_images}`: the images the note shows, and every image of its folder. |\n| GET | `/api/vault/storage` | Session or key (`read`) | `{notes, note_bytes, images, image_bytes, total_bytes, max_image_bytes}`. |\n\n## Search and graph\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/api/search` | Session or key (`read`) | `{q, count, hits:[{path, name, folder, score, snippet}]}`, at most 20 hits. Query: `q`. Supports `tag:x` and `#x`. |\n| GET | `/api/stats` | Session or key (`read`) | `{notes, links, folders}`. |\n| GET | `/api/graph` | Session or key (`read`) | `{nodes:[{id, path, folder, color, degree, tags}], links:[{source, target}]}`. `tags` holds inline `#tags` plus frontmatter `tags` (as the note view reports them). Realtime `node_*` events' `node` payload carries `tags` too. |\n| GET | `/api/aliases` | Session or key (`read`) | `{aliases:[{alias, key_id, key_name, first_seen, last_seen, connections, actor, actor_kind}]}`: one record per API key that sent MCP `initialize`, kept in memory until the server restarts. `key_name` and `actor` are the key's current name (fallback: the id). |\n| GET | `/api/actors` | Session or key (`read`) | `{actors:[{actor, alias, display, events, tools, last_ip, last_ts, seen_minutes_ago}], count}`. `seen_minutes_ago` is `-1` when the actor has no events. |\n\n## Privacy\n\nPrivacy rules hide notes or folders from chosen agents (API keys). A rule has a\n`kind` (`node` or `folder`), a `path`, a `mode` (`deny`: hidden from the listed\nkeys; `allow_only`: hidden from every key except the listed ones), and a list\nof keys. Folder rules apply to everything inside the folder.\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/api/privacy` | Session or key (`admin`) | `{count, rules:[{id, kind, path, mode, keys:[{id, name, color}], created_at, updated_at}], agents:[{id, name, color, enabled}]}`. |\n| GET | `/api/privacy/path` | Session or key (`admin`) | The privacy state of one path: `{path, kind, own, own_rules, inherited, agents:[{id, name, color, enabled, can_see, hidden_by}], private}`. `own` is `{mode, keys}` or `null`. Query: `path`, `kind` (optional; defaults to `folder` when the path is a folder on disk, else `node`). |\n| PUT | `/api/privacy/path` | Session or key (`admin`, +CSRF) | Replaces the rule on a path. Body: `{path, kind?, mode, keys}`. `mode` defaults to `deny`; `keys` is a list of key ids (or unique key names). `deny` with no keys removes the rule. Returns the same shape as `GET`. |\n| DELETE | `/api/privacy/path` | Session or key (`admin`, +CSRF) | Removes the rule on a path. Query: `path`, `kind` (optional). Returns the same shape as `GET`. |\n\nChanges are written to the activity log and publish a `privacy_changed`\nrealtime event.\n\n## API keys, tools, and access\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/api/keys` | Session or key (`admin`) | `{count, keys:[{id, name, enabled, scopes, tools, prefix, created, color, revealable, uses, last_ip, used_tools}]}`. `tools` is `\"*\"` or a list of tool names; `revealable` says whether the secret can be shown again; `used_tools` lists recently used tools and routes. |\n| POST | `/api/keys` | Session or key (`admin`, +CSRF) | Creates a key. Body: `{name?, tools?, scopes?, color?}`. `tools` is `\"*\"` or a list of tool names; `scopes` a list of scope names (an empty list means the defaults). Returns `{ok, id, key, name, prefix, persisted, color, tools, scopes}`. The raw `key` is returned once. `400` for an unknown tool or scope. |\n| POST | `/api/keys/roll` | Session or key (`admin`, +CSRF) | New secret for an existing id. Body: `{id}`. Returns `{ok, id, key, prefix, persisted}`. `404` for an unknown id. |\n| POST | `/api/keys/reveal` | Session only (+CSRF) | Shows the secret of a key created or rolled from the dashboard again. Body: `{id, current}` where `current` is the owner's password. Returns `{ok, id, key}`. `403` for a wrong password; `429` after 5 wrong passwords (5 minute pause); `404 {error:\"not_stored\", message}` when the secret is not stored (for example keys created by the CLI or by OAuth). |\n| POST | `/api/keys/update` | Session or key (`admin`, +CSRF) | Body: `{id, name?, enabled?, tools?, scopes?, color?}`. `color` as `\"\"` or `null` clears it. Returns `{ok, id, name, enabled, color, tools, scopes, persisted}`. `400` for an unknown tool or scope, `404` for an unknown id. |\n| POST | `/api/keys/delete` | Session or key (`admin`, +CSRF) | `{ok, id, persisted}`. Moves the key to the trash. Body: `{id}`. |\n| POST | `/api/keys/restore` | Session or key (`admin`, +CSRF) | `{ok, id, persisted}`. Restores a deleted key. Body: `{id}`. `404` when no deleted key has that id. |\n| GET | `/api/tools` | Session or key (`admin`) | `{tools:[{name, category, description, enabled}]}`: the MCP tool catalog with the global on/off switch of each tool. |\n| POST | `/api/tools` | Session or key (`admin`, +CSRF) | Switches a tool on or off for every caller. Body: `{name, enabled}`. Returns `{ok, name, enabled}`. `400` for an unknown tool. |\n| GET | `/api/access` | Session or key (`admin`) | `{default_allow, rules, count}`. |\n| POST | `/api/access/test` | Session or key (`admin`) | `{action, would_lock_out_caller}` for the given address or domain. Body: `{ip?, domain?}`. |\n| POST | `/api/access/rules` | Session or key (`admin`, +CSRF) | `{ok, count, persisted}`. Body: `{op, kind, value, action}`. `op` is `add` (default) or `remove`. `kind` is `ip`, `range`, `cidr`, `domain`, or `all`; `value` is required unless `kind` is `all`. `action` is `allow` or `block` (default `block`). `remove` deletes every rule matching the given `kind` and `value`; `404` when none match. |\n| GET | `/api/config` | Session or key (`read`) | `{realm, min_password_len, session_ttl, vault, version, gateway, update}`. `update` is the cached release check: `{current, latest, available, url, checked_at, state, repo, stars}`, `state` one of `ok`, `none` (no release published), `error`, `disabled`, `pending`; `stars` is the repository's GitHub star count from the same check (`null` until known). |\n\n## Settings\n\nAll settings endpoints need a signed-in browser, except `/api/settings/server`, which also takes an API key with the `admin` scope.\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/api/settings` | Session only | `{user, vault_configured, vault, vault_suggested, vault_writable, stats, min_password_len, expires_in, session_ttl, session_max_age, state_dir}`. `stats` is `{notes, links, folders}` or `null` without a vault. |\n| POST | `/api/settings/password` | Session only (+CSRF) | Body: `{current, password, confirm}`. Returns `{ok, user, password_changed, revoked_sessions, persisted}`. Every other session is signed out. `400` for a short, mismatched, or unchanged password; `403` for a wrong current password (counts toward the login cooldown). |\n| POST | `/api/settings/username` | Session only (+CSRF) | Renames the account. Body: `{username, current}`. Returns `{ok, user, changed}` (plus `persisted` when changed). The username is stored lowercase. Sessions stay signed in. `400` for an invalid username, `403` for a wrong password. |\n| POST | `/api/settings/vault` | Session only (+CSRF) | Sets the vault folder and switches the running server to it. Body: `{path, create?}`. `path` must be absolute, without `..`, writable, not a system folder, and not overlap the state folder; with `create` a missing folder is created (its parent must exist). Returns `{ok, vault, created, stats}`. `400` with a message when the folder is refused. |\n| POST | `/api/settings/server` | Session or key (`admin`, +CSRF) | Body: `{realm?, session_ttl?, session_max_age?}` (at least one). Sets the server name (1-64 characters), how long a browser may stay idle before it must sign in again (300 to 2592000 seconds) and the longest sign-in (`0` for no limit, else at least `session_ttl`). Returns `{realm, session_ttl, session_max_age}`; open sessions follow the new limits at once. `400` for a value out of range. |\n| GET | `/api/settings/sessions` | Session only | `{sessions:[{id, current, source, alias, ip, user_agent, created_at, last_seen, expires_in}], count}`: live browser sessions. API keys are not sessions and never appear here. |\n| POST | `/api/settings/sessions/revoke` | Session only (+CSRF) | Signs other browsers out. Body: `{id}` or `{others:true}`. Returns `{ok, revoked}`. `400` for the current session (use logout), `404` when the session has already ended. |\n| POST | `/api/settings/sessions/rename` | Session only (+CSRF) | Names a device. Body: `{id, alias}`; an empty alias clears it. Returns `{ok, alias}`. |\n| GET | `/api/settings/sessions/activity` | Session only | `{events, count, ip, since}`: activity log entries from that session's IP address since it signed in, API-key entries left out, newest first, at most 200. Query: `id`. |\n\n| GET | `/api/settings/media` | Session or key | `{max_image_mb, max_image_bytes}`: the largest image upload (5 MB by default). |\n| POST | `/api/settings/media` | Session or key (`admin`, +CSRF) | Body: `{max_image_mb}` (0.1 to 50). Applies at once to the app, the HTTP API and MCP `upload_image`. |\n\nSession `id` values are the short ids returned by `GET /api/settings/sessions`\n(a unique prefix also works). An ambiguous or malformed id is `400`.\n\n## OAuth\n\nMemora is an OAuth 2.1 authorization server for remote MCP clients. Only the\nauthorization code flow with PKCE (`S256`) is supported. The access token is a\nnew API key named after the client, with the default scopes (`mcp`, `read`,\n`write`) and every tool; it appears on the Agents page like any other key and\nis revoked by deleting or disabling that key. URLs in the metadata use\n`MEMORA_BASE_URL` when it is set, else the scheme and host of the request.\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/.well-known/oauth-protected-resource`, `/.well-known/oauth-protected-resource/mcp` | None | Protected resource metadata (RFC 9728): `{resource, authorization_servers, bearer_methods_supported, scopes_supported, resource_name}`. |\n| GET | `/.well-known/oauth-authorization-server`, `/.well-known/oauth-authorization-server/mcp`, `/.well-known/openid-configuration` | None | Authorization server metadata (RFC 8414): `issuer`, the authorization, token, and registration endpoints, supported response types (`code`), grant types (`authorization_code`, `refresh_token`), PKCE methods (`S256`), token endpoint auth methods, `scopes_supported` (`mcp`), and `client_id_metadata_document_supported: true`. |\n| POST | `/oauth/register` | None | Dynamic client registration (RFC 7591). Body: `{redirect_uris, client_name?}`. `redirect_uris` holds 1 to 10 URIs, each HTTPS or plain HTTP on `localhost`, `127.0.0.1`, or `[::1]`, without a fragment. Returns `201 {client_id, client_name, redirect_uris, client_id_issued_at, token_endpoint_auth_method, grant_types, response_types}`. `400 {error, error_description}` for invalid metadata or when 500 clients are registered. `429` past 10 registrations from one IP (then one per minute). A client that has not completed an authorization within an hour is removed; it can register again. |\n| GET | `/oauth/authorize` | None | `302` to `/login?oauth=1&<query>`, where the sign-in page shows a consent card (after sign-in when needed). |\n| POST | `/oauth/token` | None | Form-encoded or JSON body. `grant_type=authorization_code` with `code`, `code_verifier`, `client_id` (or HTTP Basic), and optional `redirect_uri`; or `grant_type=refresh_token` with `refresh_token` and optional `client_id`. Returns `{access_token, token_type:\"Bearer\", refresh_token, scope:\"mcp\"}`. Codes are single use and expire after 10 minutes. A refresh gives the same key a new secret and a new refresh token. Errors are `400 {error, error_description}` (`invalid_request`, `invalid_grant`, `unsupported_grant_type`). |\n| GET | `/api/oauth/request` | None | What the consent card shows for an authorization request. Query: the `/oauth/authorize` query. Returns `{ok:true, client:{id, name, kind}, redirect_host, signed_in, user}` or `{ok:false, error, error_description, redirect}`. |\n| POST | `/api/oauth/approve` | Session only (+CSRF) | Body: `{query, allow}` where `query` is the authorization request query. Returns `{ok:true, redirect}`: the client's redirect URI with a `code` when `allow` is `true`, else with `error=access_denied`. An invalid request returns `{ok:false, error, error_description, redirect}`. `401` without a session. |\n| GET | `/api/oauth/clients` | Session or key (`admin`) | `{clients:[{client_id, name, redirect_uris, kind, created_at, fetched_at}], connections:[{key_id, client_id}]}`. `kind` is `dcr` (registered), `cimd` (metadata document), or `manual` (added by the owner). |\n| POST | `/api/oauth/clients` | Session or key (`admin`, +CSRF) | Registers a client by hand. Body: `{name?, redirect_uris}`. Returns `{ok, client}`. `400` for invalid redirect URIs. |\n| POST | `/api/oauth/clients/delete` | Session or key (`admin`, +CSRF) | Forgets a client and its refresh tokens. Body: `{client_id}`. Returns `{ok, deleted}`. Keys issued to the client stay until they are deleted. |\n\nA `client_id` may also be an HTTPS URL of a client metadata document. The\nserver fetches it (public addresses only, no redirects, at most 64 KiB), checks\nthat its `client_id` matches the URL, and caches it for 24 hours.\n\n## Logs and activity\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/api/logs` | Session or key (`read`) | `{range, count, events}`, newest first, each event with a local `time`. Query: `range` (for example `1d`, `7d`, `today`, `yesterday`, `all`; default `1d`), `days` (used when `range` is absent, at most 7), `since` and `until` (unix seconds; override `range`), `limit` (default 400, max 2000), `actor`, `q`. |\n| GET | `/api/logs/settings` | Session or key (`admin`) | `{max_mb, max_days, stats:{bytes, lines, oldest, newest, max_bytes, max_days}}` for the vault event log. |\n| POST | `/api/logs/settings` | Session or key (`admin`, +CSRF) | Body: `{max_mb?, max_days?}` (1 to 512 MB; 0 to 3650 days, 0 meaning no age limit). Returns the same shape as `GET`. The log is trimmed to the new limits at once. `400` for out-of-range values. |\n| GET | `/api/events` | Session or key (`read`) | `{events, count}`: the vault event log (`.events.jsonl`), oldest first, the newest `limit` entries. Query: `since` (unix seconds), `folder`, `actor` (the key name for agents), `limit` (default 100, max 2000). |\n\n### Realtime\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/ws` | Session only | WebSocket upgrade. The `Origin` must be same-origin (`403` otherwise). `503` when too many clients are connected. |\n| POST | `/_bus` | Loopback only | Publishes a JSON object (at most 64 KiB) into the event stream. Returns `{ok:true}`. `403` for callers that are not on the same machine, that come through a proxy (any forwarding header) or that are a web page (an `Origin` or `Sec-Fetch-*` header), `400` for a body that is not a JSON object, `413` for a body or event that is too large. |\n\nOn connect the server sends a `hello` event with the client count, replays the\nlast 40 stored events (each marked `replay: true`), then streams live events.\nWhen a client leaves, the others get a `presence` event with the new count.\nMessages from the client are ignored; the server pings every 30 seconds and\ncloses a connection that has been silent for 75 seconds.\n\n### Local stop\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| POST | `/_stop` | Loopback and stop token | Stops the server gracefully, like Ctrl+C (open requests finish, buffered usage is written). Returns `{ok:true}` and exits shortly after. `403` unless the caller is on the same machine, not behind a proxy (any forwarding header), and sends the `X-Memora-Stop-Token` header. Also accepted while the instance is locked. |\n\nAt startup, once the port is bound, the server writes a fresh random token to\n`<state>/stop.token` (readable by the server's user only on Linux and macOS)\nand removes it on exit. `memora-cli stop` reads that file and calls `/_stop`\nfirst on every OS; only if that fails does it fall back to SIGTERM (Linux,\nmacOS) or `taskkill` (Windows, where a server started without a console\nignores a polite `taskkill`). Anyone who can read the state folder can stop\nthe server; they can already read its database.\n\n### `ai_activity` events\n\nEvery MCP `tools/call` publishes a `start` and an `end` event sharing `call_id`:\n\n```json\n{\"type\":\"ai_activity\",\"phase\":\"start\",\"call_id\":\"c1a2b3c4d5e6-0\",\"actor\":\"research-bot\",\n \"actor_kind\":\"agent\",\"actor_id\":\"k_1a2b3c4d\",\"action\":\"read_memory\",\"label\":\"Plan/Index.md\",\n \"paths\":[\"Plan/Index.md\"],\"_ts\":1760600000.12}\n{\"type\":\"ai_activity\",\"phase\":\"end\",\"call_id\":\"c1a2b3c4d5e6-0\",\"actor\":\"research-bot\",\n \"actor_kind\":\"agent\",\"actor_id\":\"k_1a2b3c4d\",\"action\":\"read_memory\",\"label\":\"Plan/Index.md\",\n \"paths\":[\"Plan/Index.md\"],\"ok\":true,\"ms\":2,\"_ts\":1760600000.12}\n```\n\n- `actor`: the API key's name (fallback: key id) with `actor_kind: \"agent\"`; for a\n browser session the username with `actor_kind: \"user\"`. `actor_id` is the key id (or\n the username). Node events (`node_created`, ...) from the call carry the same `actor`.\n- `action`: the tool name.\n- `for` (optional): who the agent acted for and how it was asked. Mnemo, the built-in\n agent (`actor: \"Mnemo\"`, `actor_id: \"mnemo\"`), sets it: `owner · chat`,\n `owner · console`, `<who> · @mnemo in <note>`.\n- `paths`: vault-relative note paths from the arguments (`path`, `paths`, `from`, `to`,\n `old_path`, `new_path`, `into` of `merge_memory`, `source`/`target` of `find_path`)\n plus note paths found in the result (search hits, the created or moved note), at\n most 20, each at most 512 bytes (longer paths are dropped). Whole-vault overviews\n (`get_graph`, `list_memory`, logs, ...) add no result paths.\n- Read-only tools publish `start` after running (so it carries the result paths),\n immediately followed by `end`; mutating tools publish `start` before running and `end`\n after, with the result paths added.\n- `end` adds `ok`, `ms`, and on failure `error` (at most 200 characters). `label` is at\n most 160 characters. `_ts` is the publish time in unix seconds. `end` events are\n realtime only: they are not written to `.events.jsonl` or the replay buffer.\n\n## UI layout\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/api/ui/layout/{name}` | Session only | `{name, data, updated_at}`; `data` and `updated_at` are `null` if never saved. |\n| PUT | `/api/ui/layout/{name}` | Session only (+CSRF) | `{ok:true, updated_at}`. Body: `{data: <any JSON>}`. |\n\n`name` is `[a-z0-9_-]{1,40}` (else `400`). API keys get `403`. `data` is stored as\nserialized JSON of at most 512 KiB (`413` above); the request body limit is 600 KiB.\nNames starting with `srv-` are reserved for server settings (`403`).\nLayouts are stored in the `ui_layout` table of `memora.db`. The web UI uses them for\n`canvas` (card positions and frames) and `graph` (pinned positions).\n\n## Pins\n\nThe owner's pinned notes and folders (the sidebar's Pinned list), shared by every\nbrowser and device of the instance.\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/api/pins` | Session only | `{count, pins:[{kind, path, position, missing}]}` in display order. |\n| PUT | `/api/pins` | Session only (+CSRF) | Same as GET. Body: `{pins:[{kind, path}]}`, the whole ordered list (reorder, remove). |\n| POST | `/api/pins/pin` | Session only (+CSRF) | Same as GET. Body: `{kind, path, position?}`. Pins an existing note or folder at `position` (default: the end), or moves its pin there; `404` if it does not exist. |\n| POST | `/api/pins/unpin` | Session only (+CSRF) | Same as GET plus `removed`. Body: `{kind, path}`. |\n\n`kind` is `note` or `folder`. `path` is vault-relative as the tree shows it (notes end in\n`.md`): absolute paths, `..`, empty or hidden segments, `\\`, control characters and paths\nover 1024 characters get `400`, as do more than 200 pins. API keys get `403` (agents use\nthe MCP tools `list_pins`, `pin` and `unpin`). Bodies are limited to 256 KiB for `PUT`\nand 8 KiB for `pin`/`unpin` (`413`). `missing` is true when the path no longer exists,\nfor example after a rename outside Memora; such a pin is kept until it is removed.\n\nRenames, moves and deletes done by Memora (HTTP or MCP) rewrite or drop pins in the same\ndatabase transaction, including pins on notes and folders inside a moved folder;\nmoving an item to the trash or deleting it removes its pin, and deleting a folder\nremoves every pin under it. Every change publishes a `pins_changed` realtime event with\nno other data; open browsers reload the list. Pins are stored in the `pin` table of\n`memora.db`.\n\n## Mnemo (built-in agent)\n\nMnemo is the notes agent built into Memora. Every route needs the signed-in\nbrowser session (API keys get `403`, writes need CSRF); the console's `/mnemo`\nuses a short local session. Mnemo's data lives in `assistant.sqlite3` beside\n`memora.db` (file mode 0600): providers with their API keys sealed\n(ChaCha20-Poly1305, the same key as the server's other secrets), models,\npreferences, chats and messages. A key is never returned; providers carry a\nfour-character `key_hint`.\n\n| Method | Path | Returns |\n|---|---|---|\n| GET | `/api/assistant/state` | `{name, ready, providers, models, prefs, tools, defaults}`. `ready` is true when a model can answer. `tools` is the fixed list Mnemo may use. Each model has `thinks`: it can think, so the chat offers a thinking level (Claude 3.7 and later by name; any other model, router aliases included, until its provider refuses both the effort and the thinking fields). A level other than `auto` is sent as `output_config.effort` (Anthropic), `reasoning.effort` (Responses API, OpenAI-compatible servers) or `reasoning_effort` (OpenAI chat and OpenAI-style routers), and left out for a model that refuses it. |\n| POST | `/api/assistant/providers` | Adds or changes a provider. Body: `{id?, kind?, label?, api_style?, base_url?, api_key?, enabled?}`. Up to 20 providers, several of the same type allowed. `id` is the owner's own (1-32 characters of `a-z`, `0-9`, `-`; made from `label` when left out; it cannot change, since models are keyed `id/model`). `kind` is `openai`, `anthropic` or `custom` (any OpenAI-compatible server, which needs `base_url`, its `/v1` address); `api_style` is `chat` or `responses` (OpenAI and compatible) or `messages` (Anthropic). For an existing `id`, fields left out keep their value, so `{id, enabled: false}` switches a provider off (its models leave the model pickers). Leaving `api_key` out keeps the saved key; `\"\"` removes it. Returns the state plus `saved` (the id). |\n| POST | `/api/assistant/providers/test` | Body: `{id}`. Lists the provider's models as a connection check: `{ok, models, ms}` or `{ok: false, error}`. |\n| POST | `/api/assistant/providers/delete` | Body: `{id}`. Removes the provider, its key and its models. |\n| POST | `/api/assistant/models/fetch` | Body: `{provider}`. Reads the provider's model list (`GET <base>/models`, every page for Anthropic) with the limits it reports: the context window from `max_input_tokens`, `context_length`, `context_window`, `max_context_length` or `max_model_len`, and the reply limit from `max_tokens` or `max_completion_tokens`. Pinned models stay; unpinned ones the provider no longer lists go. Returns the state plus `fetched`. `502` when the provider refuses. |\n| POST | `/api/assistant/models` | Body: `{provider, model, label?, context_window?, max_output?, pinned?, hidden?}`. Adds a model by hand or changes it; `null` clears a limit. The app sets only pinned, hidden and new models; limits normally come from the provider. |\n| POST | `/api/assistant/models/delete` | Body: `{provider, model}`. |\n| POST | `/api/assistant/prefs` | Any of `default_model` (`provider/model`), `system_prompt` (up to 4000 characters), `temperature` (0-2), `max_output_tokens` (64-200000), `context_tokens` (2000-2000000, for models without a window), `max_steps` (1-30 tool rounds per reply), `launcher` (the floating button), `thinking` (`auto`, `off`, `low`, `medium` or `high`: how hard models that can think do so; `auto` leaves it to the model), `fallback_models` (up to 5 `provider/model` keys: when a reply's model fails after its retries, Mnemo carries on with the next one, streamed as `fallback {from, model, reason}`; with none left the error stands and the owner tries again); `null` resets one. |\n| GET | `/api/assistant/sessions` | `{sessions: [{id, title, scope, model, pinned, created_at, updated_at, messages, running, seen}]}`. `messages` counts the owner's and Mnemo's messages (not tool results); `?about=<path>` lists only the chats about that note or folder (kept for it, with it attached, or naming it in a tool call). `seen` is how many of them the owner has read on any device (the unread count is `messages - seen`). The first list after 2.1.5 counts every existing chat as read. |\n| POST | `/api/assistant/sessions` | Body: `{scope?, model?, title?, fleeting?}`. A fleeting chat is left out of lists, search and Mnemo's look-back tools and is deleted (with the pictures sent in it) by `.../delete` when the owner leaves, or after 30 minutes idle. `scope` is `global`, `note:<path>` or `folder:<path>`. Returns `{session}`. |\n| GET | `/api/assistant/sessions/{id}` | `{session, messages: [{id, role, content, tool_calls, tool_call_id, tool_name, meta, created_at}], context}`. `context` is `{used, window, reserved_output, compact_at, compactions, model}` for the model the chat would use now (approximate tokens), or `null` without a usable model. A message with `meta.compact: true` is a summary that stands in for every message before `meta.keep_from`. |\n| GET | `/api/assistant/search` | Query `q` (every word must appear, any case), `limit` (default 60, at most 200). `{query, hits: [{chat, title, scope, message_id, role, snippet, at}]}`, newest first: the owner's messages and Mnemo's replies whose text or chat title holds the words; `message_id` is `null` for a chat matched by its title alone. |\n| POST | `/api/assistant/sessions/{id}/rerun` | Body: `{message_id?, model?}` (default: the last of the owner's messages). Runs that message's turn again: every message after it is removed, then the reply streams as for `/chat`. `400` when `message_id` is not one of the owner's messages in the chat, `409` while it answers. |\n| POST | `/api/assistant/sessions/{id}/steer` | Body: as for `/chat`. Send this message now: the reply running is cut where it is (what it wrote so far is kept, `meta.stopped`) and Mnemo answers this message as a new turn; with no reply running it goes at once. `{ok, queue}`. (Older chats may hold `meta.steer` messages from before 2.1.9.) |\n| GET | `/api/assistant/sessions/{id}/queue` | `{items: [{id, text, attach, at}], held}`: messages waiting for the reply running. They go out one by one, on the server, as each reply ends (finished, stopped or cut), whichever device queued them. A failed reply pauses the queue (`held`) until a message is sent now or the queue resumes. Kept in memory: a restart empties it. |\n| POST | `/api/assistant/sessions/{id}/queue` | Body: as for `/chat`. Queue a message (it goes at once when no reply runs). `{id, queue}`. |\n| POST | `/api/assistant/sessions/{id}/queue/{qid}` | Body: `{op: del \\| up \\| down \\| move \\| send, to?}` (`to` the new place for `move`). `send` puts it first and sends it now, cutting the reply running. `{qid}` may also be `clear` (drop every queued message) or `resume` (let a paused queue go on). Answers with the queue. |\n| GET | `/api/assistant/sessions/{id}/watch` | What happens in the chat from now on, as server-sent events, so every device with it open stays in step: `hello {running}`, `user {message, via, client}` (a message stored from any device or out of the queue; `client` is the id the sender put in its request), `running`, `idle {outcome}` (`done`, `stopped`, `failed`), `queue {items, held}`, `queue_error {message}`, `compacted`, `reload` (turns were replaced: read the chat again). |\n| GET | `/api/assistant/sessions/{id}/live` | The reply running in the chat as server-sent events: every event since it began, then live, until it ends. `204` when none is running. |\n| GET | `/api/assistant/sessions/{id}/export` | The chat as a Markdown file (`text/markdown`, a download): each message with its time, Mnemo's steps, what it showed, compaction summaries. |\n| GET | `/api/assistant/skills` | `{folder: \"Skills\", skills: [{name, path, description}]}`: the owner's skills (notes in `Skills/`). A message starting `/name` sends that skill's steps with it (`meta.skill`). |\n| GET | `/api/assistant/suggestions` | `{own, ai}`: the owner's suggestions and Mnemo's (from recent notes; written again in the background when older than 12 hours). |\n| POST | `/api/assistant/suggestions` | Body `{own: [text]}` (up to 30): the owner's own suggestions. |\n| POST | `/api/assistant/suggestions/refresh` | Mnemo writes its suggestions again now. `{own, ai, fresh}`. |\n| POST | `/api/assistant/sessions/prune` | Delete many chats: body `{ids}`, `{older_than_days}` (1 to 3650; not active for that long) or `{all: true}`, with `keep_pinned` (default `true`, used with age or all). Chats answering right now are skipped. `{deleted, skipped}`. |\n| POST | `/api/assistant/sessions/{id}/seen` | Body: `{messages}`. The owner has read the chat up to `messages` (capped at what it holds; never goes back). `{ok, seen}`. |\n| POST | `/api/assistant/sessions/{id}/stop` | End the reply running in the chat; what it wrote so far is kept (`meta.stopped`) and the next queued message goes out. `{stopped}`. |\n| POST | `/api/assistant/sessions/{id}/compact` | Fold the older turns into a summary now (the chat's model writes it; the last turn stays as it is). `{ok: true, messages, tokens, summary, context}`, or `{ok: false, reason, context}` when there is nothing older yet. `409` while the chat is answering. |\n| POST | `/api/assistant/sessions/{id}` | Body: `{title?, model?, pinned?}`. A chat keeps its `model` (set when it is created, from the request or the default model at that time); a reply uses it while it is listed and its provider can answer, else the default model, then the fallback models, then the first pinned or visible one. When a fallback model takes over a reply, the chat's `model` becomes that model and the reply's stored message carries `meta.fallback_from`. |\n| POST | `/api/assistant/sessions/{id}/delete` | Deletes the chat and its messages (notes are not touched). |\n| POST | `/api/assistant/sessions/{id}/chat` | Body: `{text, model?, attach?, tz?, tz_offset?, answer?}` (`answer` `{to, approve?, other?}` answers one of Mnemo's questions by its call id; `approve` is set when the tapped option approves a change) (`tz` an IANA zone name and `tz_offset` minutes east of UTC, from the browser, for Mnemo's `current_time`). `attach` lists up to 8 items `{kind, path}`: `note` (its text, up to 8000 characters), `folder` (the notes in it, up to 200) or `image` (`path` is an id from `/api/assistant/uploads`). A snapshot of them is stored with the message (`meta.attach`, `meta.context`) and stays in the chat's context. Replies as server-sent events, one JSON object per `data:` line: `start {model, context}`, `ask {id, question, options: [{label, description, approve}], allow_other}` (Mnemo's `ask_owner`: the reply ends and waits for the answer), `steered {text}`, `compacting` and `compacted {messages, tokens}` (the chat was near full and its older messages were folded into a summary first), `thinking {delta}` (the model's thinking, where the provider shows it), `text {delta}`, `tool_start {id, name, args}`, `tool_end {id, name, ok, summary, ms}`, `notice {text}`, `error {message}`, `done {input_tokens, output_tokens, title, context}`. `409` while the chat is already answering (queue it instead). Also `compact_text {delta}` (the summary as it is written, before `compacted {messages, tokens, summary}`) and `fallback {from, model, reason, detail}` (the model failed: `reason` in a few words, `detail` the provider's error; the next fallback model answers and becomes the chat's model). A model out of quota, refused or not found is not retried. A body may carry `client` (any short id) so the sender can tell its own message in `/watch`. The reply runs on the server: closing the stream does not stop it (watch it again with `/live`, end it with `/stop`); `GET /api/assistant/sessions` and `GET /api/assistant/sessions/{id}` say `running` meanwhile. |\n| POST | `/api/assistant/uploads?name=<file>` | The raw bytes of a PNG, JPEG, WebP or GIF (the Images upload limit applies): `{id, name, bytes, url}`. The image waits in `assistant-uploads/` in the state folder for a week. Attached to a chat message, it goes to the model as an image (OpenAI `image_url`, Responses `input_image`, Anthropic `image` blocks; the newest 6 images of the chat, each up to 4.5 MB; a model that refuses images gets their names instead), and Mnemo's `place_image` tool can put it beside a note through MCP `upload_image`. |\n| GET | `/api/assistant/uploads/{id}` | The staged image, for the chat's thumbnails. |\n\nMnemo runs its tools through the MCP server under the name **Mnemo** (actor id\n`mnemo`), so every call shows in Activity and respects tools switched off on the\nTools page. It has one tool of its own, `place_image {upload, note, name?, alt?,\nappend?}`, which hands a staged chat image to `upload_image` (and is off when\nthat tool is off).\n\nThinking: Anthropic models are asked for adaptive thinking with summaries\n(models that refuse the field are asked without it from then on), OpenAI GPT-5\nand o-series models on the Responses API for reasoning summaries, and\nOpenAI-compatible servers stream `reasoning_content` or `reasoning` on their\nown. A Claude reply that carried thinking is stored block for block\n(`meta.raw`) and sent back verbatim, and each chat keeps the system prompt it\nstarted with (`meta.system` on its first message), so the model's earlier\nthinking stays valid. Thinking from before a compaction is not replayed, and\nwhen the API refuses a replayed thinking block the request is sent again\nwithout it. Permission (`POST /api/assistant/prefs` `{permission: \"ask\" | \"auto\"}`, default `ask`): in Ask first mode a tool call that would change notes is refused until the owner's latest message approves (an `answer` with `approve: true`, or an `@mnemo:` request from a note); Auto lets changes through and runs up to 40 steps a reply (25 otherwise; `max_steps` overrides, up to 60). Besides `place_image` it has `ask_owner` (a question with 2 to 5 options and Other), `current_time` (date, time, weekday and the owner's time zone), `search_docs` and `read_docs` (Memora's own documentation, from `mnemo-docs.json` the web build writes next to the assets; answers link `/docs/<page>#<heading>`), `show_items` (cards in the reply for notes, folders,\nimages or the vault; `tool_end` carries the checked items as `shown`) and tools of its own over its chats: `list_chats` (newest first, optionally by\ntitle), `search_chats` (every word, newest first) and `read_chat` (one chat's\nmessages, 60 at a time with `page`), for when the owner refers to an earlier\nconversation; and over the pages it wrote (```` ```html ```` / ```` ```svg ```` blocks\nin its replies, named by their `<title>`; the same title again is a newer version):\n`list_artifacts` (across chats or in one) and `read_artifact` (a page's source, the\nlatest version unless `version` is given), so it reworks a page instead of starting\nover and can reuse one from another chat. Pages live in their chat's messages and\nare deleted with it. It may use 54 tools for reading and looking after notes, folders,\ntags, links, pins, history and the Trash; it never gets `delete_memory`,\n`bulk_delete`, `delete_folder`, export or import, admin or web tools. A line with `@mnemo: <request>` in a note (outside code; a struck\n`~~@mnemo: …~~` is done) is a request to Mnemo: a few seconds after the owner\nsaves the note (`POST /api/save` or `/api/create`), or after an agent's tool\ncall changes it (Mnemo's own changes from a chat or the console too; not those\nit makes while answering a request), Mnemo runs it in the note's chat (one per\nnote, titled `@mnemo · <note>`, scope `note:<path>`; every later request in the\nnote joins it, unless it is answering right now; each request's message holds it\nas written, `meta.mention` says `{path, line, by}` and `meta.attach` names\nthe note), then saves the note with\nthe request struck through and its reply quoted under it. Activity events of\nMnemo's tool calls carry `for` (\"owner · chat\", \"owner · console\",\n\"<who> · @mnemo in <note>\"). A chat keeps\nits whole conversation for its model: when its history fills all the tokens it\nmay use (the model's context minus the room kept for the reply), the chat's model folds the older turns into a summary (stored as a\nmessage with `meta.compact`, sent in front of the kept turns) before the next\nreply, keeping the last one or two turns as they are. Only if that fails are the\noldest turns left out (a reply and its tool results always stay together).\n\n## Status codes\n\n| Code | Meaning |\n|---|---|\n| 200 | Success. |\n| 201 | OAuth client registered. |\n| 202 | MCP notification accepted. |\n| 204 | `/favicon.ico`. |\n| 302 | Redirect (pages to `/login` without a session, `/login` to `/` when signed in, logout to `/login`, locked instance to `/login?locked=1`, `/oauth/authorize` to the consent page). |\n| 304 | Not modified (`/api/vault/file`, static assets). |\n| 400 | Bad request, for example a missing required field or an invalid value. |\n| 401 | Missing or invalid credentials, or a session-only endpoint called without a session. |\n| 403 | Blocked by an access rule, a CSRF origin mismatch, a missing key scope, a wrong password or setup code, or an endpoint that needs an open setup or reset window. |\n| 404 | Note, key, session, rule, or route not found; also any request for a host outside the domain list. |\n| 405 | `/mcp` called with a method other than `POST`. |\n| 408 | The request took longer than 30 seconds. |\n| 409 | No vault configured (`needs_vault: true`), or a state conflict. |\n| 413 | Body, layout, image, or event too large. |\n| 415 | `/api/vault/file` path is not an image. |\n| 423 | Instance is LOCKED. |\n| 429 | Rate limit or failed-attempt cooldown (`Retry-After` header). |\n| 500 | Internal error, for example the state database failed. |\n| 503 | UI assets are not installed, the password hashing pool is busy, or too many realtime clients. |\n"},{"file":"docs/DEPLOYMENT.md","slug":"deployment","title":"Deployment","text":"# Deployment\n\nThis guide covers health checks, running Memora behind a reverse proxy, in a\ncontainer, and under systemd, first-run and recovery, backups, and upgrades.\nFor the installer and the Compose quick start, see [INSTALL.md](INSTALL.md);\nfor every setting, see [CONFIGURATION.md](CONFIGURATION.md).\n\n## Health check\n\n`GET /healthz` is public, never rate limited, and reachable even while the\ninstance is LOCKED. An outside caller gets only:\n\n```json\n{ \"ok\": true, \"server\": \"memora\" }\n```\n\nA caller on the same machine (loopback) or a signed-in browser gets more\ndetail:\n\n```json\n{\n \"ok\": true,\n \"server\": \"memora\",\n \"version\": \"1.0.0\",\n \"vault_configured\": true,\n \"vault\": \"/var/lib/memora/vault\",\n \"armed\": false,\n \"locked\": false,\n \"base_url\": \"https://memory.example.com\",\n \"base_url_configured\": true\n}\n```\n\nUse it for container health checks and load balancer probes. Run locally, it\nalso tells you whether a setup window is open or the instance is locked.\n\n## Reverse proxy\n\nThe `memora` binary binds `127.0.0.1` by default, which is the intended setup\nbehind a proxy on the same host (`install.sh --behind-proxy` does the same).\nBind `0.0.0.0` only when clients connect directly.\n\nOn the proxy:\n\n- Forward `Host`, and append the client IP to `X-Forwarded-For`.\n Memora reads the right-most `X-Forwarded-For` entry that is not itself a\n trusted proxy; only when there is none does it fall back to\n `CF-Connecting-IP`, then `X-Real-IP`. Forwarding headers count only when the\n connection comes from a trusted proxy. Loopback is always trusted; list any\n other proxy address in `MEMORA_TRUSTED_PROXIES`. A loopback address in a\n header is ignored, so no outside caller can pass as local.\n- Forward `X-Forwarded-Proto: https`. From a trusted proxy, it makes Memora mark\n the session cookie `Secure` and send HSTS.\n- Upgrade WebSockets on `/ws` and allow long-lived connections there.\n\nSet `MEMORA_BASE_URL` to the public URL (OAuth clients and connection snippets\nuse it) and, optionally, `MEMORA_DOMAIN` to refuse requests for other\nhostnames.\n\n### nginx\n\n```nginx\nserver {\n listen 443 ssl;\n server_name memory.example.com;\n\n location / {\n proxy_pass http://127.0.0.1:8400;\n proxy_set_header Host $host;\n proxy_set_header X-Real-IP $remote_addr;\n proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n proxy_set_header X-Forwarded-Proto $scheme;\n }\n\n location /ws {\n proxy_pass http://127.0.0.1:8400;\n proxy_http_version 1.1;\n proxy_set_header Upgrade $http_upgrade;\n proxy_set_header Connection \"upgrade\";\n proxy_set_header Host $host;\n proxy_set_header X-Real-IP $remote_addr;\n proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n proxy_set_header X-Forwarded-Proto $scheme;\n proxy_read_timeout 3600s;\n }\n}\n```\n\n### Caddy\n\n```\nmemory.example.com {\n reverse_proxy 127.0.0.1:8400\n}\n```\n\nCaddy handles WebSocket upgrades and the `X-Forwarded-*` headers itself.\n\n## Running in a container\n\nThe repository ships a `Dockerfile` and a `docker-compose.yml`;\n[docker/README.md](../docker/README.md) is the short practical guide. The\nessentials:\n\n```sh\nmkdir -p data state && sudo chown -R 1000:1000 data state\ndocker compose up -d\ncurl -s http://127.0.0.1:8400/healthz\ndocker compose exec -it gateway memora-cli # then /guide, or /web\n```\n\nThe container runs as uid:gid 1000:1000 by default. Set `MEMORA_UID` and\n`MEMORA_GID` in `.env` to match the owner of the host vault and state\ndirectories. If the container cannot write to them, the entrypoint stops and\nprints the container uid and the directory owner. A root-owned bind mount is\nthe most common startup failure.\n\nInside the container, the vault is `/data` and the state directory is\n`/state`, bind-mounted from `MEMORA_DATA_DIR` and `MEMORA_STATE_DIR` (default\n`./data` and `./state`). Port `8400` is the only port: the HTTP API, MCP, the\nUI, and the WebSocket share it. `MEMORA_HTTP_PORT` sets the host side of the\nmapping.\n\nBehind a proxy on the host, publish on loopback only\n(`MEMORA_HTTP_PORT=127.0.0.1:8400`). The container then sees the proxy as the\nDocker network's gateway address, so add that address to\n`MEMORA_TRUSTED_PROXIES`.\n\nThe entrypoint also accepts `setup`, `reset-password`, `status`, `unlock`,\n`list`, and `cli <args>` as the container command, for one-off runs such as\n`docker compose run --rm gateway cli db check`.\n\n### Restricted container runtimes\n\nSome hosts run containers inside another sandbox that does not grant full\nkernel privileges. The container runtime can then fail before Memora starts,\nwith errors such as:\n\n```\napparmor_parser: Access denied. You need policy admin privileges.\n```\n\nor:\n\n```\nrunc create failed: unable to start container process: error during container init:\nopen sysctl net.ipv4.ip_unprivileged_port_start file: reopen fd 8: permission denied\n```\n\nThese come from the runtime loading an AppArmor profile and writing network\nsysctls, not from anything Memora needs. If you control the runtime, run the\ncontainer with AppArmor unconfined (when the outer sandbox already confines\nit) and without the optional network sysctls, or use a wrapper runtime that\nremoves those fields from the OCI spec. Do not use `--privileged`: it is not\nrequired and does not fix either cause.\n\n## systemd\n\n`install.sh` writes a hardened unit to `/etc/systemd/system/memora.service`;\nits full contents are in [INSTALL.md](INSTALL.md#the-systemd-unit). Put local\nchanges in a drop-in (`sudo systemctl edit memora`), because the installer\nrewrites the unit on every run.\n\nFor a manual install, a minimal unit looks like this:\n\n```ini\n[Unit]\nDescription=Memora memory vault\nAfter=network-online.target\nWants=network-online.target\n\n[Service]\nType=simple\nUser=memora\nGroup=memora\nWorkingDirectory=/var/lib/memora\nEnvironment=HOME=/var/lib/memora\nEnvironment=MEMORA_STATE=/var/lib/memora/state\nEnvironment=MEMORA_VAULT=/var/lib/memora/vault\nEnvironment=MEMORA_ASSETS=/usr/local/share/memora/assets\nEnvironment=MEMORA_BIND=127.0.0.1\nEnvironment=MEMORA_PORT=8400\nEnvironment=RUST_LOG=info\nExecStart=/usr/local/bin/memora\nRestart=on-failure\nRestartSec=3\nTimeoutStopSec=15\nNoNewPrivileges=yes\nPrivateTmp=yes\nProtectSystem=strict\nProtectHome=yes\nReadWritePaths=/var/lib/memora\n\n[Install]\nWantedBy=multi-user.target\n```\n\nMemora needs write access to the vault and the state directory, and `git` on\nthe `PATH` for vault history. Then:\n\n```sh\nsudo systemctl daemon-reload\nsudo systemctl enable --now memora\nsudo memora-cli setup\n```\n\nRun as root, `memora-cli` finds the running server's state directory and does\nits database work as the owner of that directory.\n\n## First-run and recovery\n\nThe CLI opens a short window and the browser completes it:\n\n```sh\nmemora-cli setup # first-run window, prints a one-time code\nmemora-cli reset-password # password reset window, prints a one-time code\nmemora-cli setup --minutes 10 # longer window (1-60 minutes, default 5)\nmemora-cli status # state dir, vault, owner, window, and lock\nmemora-cli disarm # close an open window without locking\nmemora-cli unlock # lift the lock; the owner account stays as it is\nmemora-cli list # the owner and the API keys\nmemora-cli clear-cooldowns # clear login cooldowns in the running server\n```\n\nIn the console (`memora-cli` with no arguments), `/web` does the same as\n`setup` or `reset-password`, and `/guide` walks through the first run.\n\nThen open `/login`, enter the code, and fill in the form before the window\ncloses. A wrong code counts against that IP's budget of 3 (then it waits 5\nminutes); the code stays valid and single-use until the window ends. Only 50\nwrong codes in one window, from any IPs, close it early; open a new one then. If a window expires\nunfinished, the instance locks: API and MCP return `423` and pages go to the lock screen until\n`setup`, `reset-password`, or `unlock` runs. This keeps an unclaimed instance\nfrom being taken over by whoever reaches the port first.\n\n### Failed sign-ins\n\nMemora limits guessing without letting anyone lock you out:\n\n- Per IP: 5 failed sign-ins (or 3 wrong setup codes) within 15 minutes put\n that IP on a cooldown of 5, then 10, then 15 minutes (`429`). A successful\n sign-in from the IP clears it.\n- Across all IPs: 20 failures within 15 minutes switch on slow mode for 15\n minutes after the latest failure. Every sign-in then waits about a second,\n and one failure is enough to put an IP on its cooldown. There is no\n account-wide lockout: a correct password from an IP without recent failures\n still signs in, and that ends slow mode.\n- `memora-cli clear-cooldowns` clears every cooldown in the running server.\n\nBehind a proxy, these limits only work per client when Memora sees the real\nclient IP (see [Reverse proxy](#reverse-proxy)).\n\n## Backups\n\nBack up both the state directory and the vault.\n\nState: one SQLite database, `memora.db`, holding the owner, API keys,\nsessions, settings, access and privacy rules, OAuth grants, and the activity\nlog, plus `key-seal.bin`. It is small but critical: losing it means losing the\naccount and every API key. Back it up online with the CLI; never `cp` a live\ndatabase, because recent commits sit in `memora.db-wal`:\n\n```sh\nsudo memora-cli db backup --to /var/backups/memora-state-$(date +%F).db\nsudo memora-cli db check # exit status 1 on any problem\n```\n\nWithout `--to`, backups go to `state/backups/` and the newest 10 are kept\n(`--keep N`). A daily systemd timer or cron job running `memora-cli db backup`\nis enough; encrypt copies that leave the host. See\n[DATABASE.md](DATABASE.md#operations) for details.\n\nVault: the markdown notes and their git history. Copy the directory, or use\ngit:\n\n```sh\ngit -C /var/lib/memora/vault bundle create /var/backups/memora-vault-$(date +%F).bundle --all\n```\n\n`.events.jsonl` is the event log. (`.fts.db`, the search index of older\nversions, is no longer used and is removed automatically.)\n\nWith Docker Compose, both live in the host directories, so an archive taken\nwith the container stopped covers everything:\n\n```sh\ndocker compose stop gateway\ntar -czf memora-$(date +%F).tar.gz data state\ndocker compose start gateway\n```\n\n### Restore\n\nStop the service, restore the database with `memora-cli db restore FILE` (it\nverifies the file and keeps the replaced database in `state/backups/`), put\nback `key-seal.bin` and the vault, then start the service again.\n\nIf you restore only the vault and start with an empty state directory, Memora\nhas no account and expects a new first-run setup; the notes are intact.\n\n## Upgrades\n\nNative: `sudo /usr/local/share/memora/install.sh --upgrade` or\n`sudo memora-cli update` (see [INSTALL.md](INSTALL.md#upgrading)).\n\nDocker: pull the new image and recreate the container:\n\n```sh\ndocker compose pull && docker compose up -d\n```\n\nThe server migrates `memora.db` on start. Take a `memora-cli db backup` first:\na database migrated by a newer release cannot be opened by an older one.\n"},{"file":"docs/ARCHITECTURE.md","slug":"architecture","title":"Architecture","text":"# Architecture\n\nThis document describes how Memora is put together: the crates, what each one\nowns, the request path from a browser or an agent to the vault, the realtime\nWebSocket fan-out, the auth model, and the storage model. Every claim here maps\nto code under `crates/`.\n\n## Crate layout\n\nMemora is a Cargo workspace with six crates. The web UI is a TypeScript app in\n`web/src`, built with Vite into `crates/http/assets`.\n\n| Crate | Binary | Owns |\n|---|---|---|\n| `memora-core` | (library) | The vault: walking notes, parsing wikilinks and frontmatter, the in-memory note index, search, the graph, git versioning, per-caller path visibility, and the `*_impl` methods that every interface calls. Also the realtime event hub. |\n| `memora-gateway` | (library) | Auth primitives: argon2id password hashing, API key generation and hashing, OAuth token and PKCE helpers, setup codes, the access stack evaluator, host and lock allow lists, scopes and per-key tool permissions, and reading the provisioning environment. No state of its own. |\n| `memora-state` | (library) | The state database `memora.db` (SQLite, WAL): opening, migrations, change detection, and one typed repository per table group (owner, settings, `server_config`, keys, tools, usage, sessions, arm window, access rules, activity, control requests, OAuth, privacy rules, UI layouts, retention), plus the one-time import of JSON state files. No SQL lives outside this crate. |\n| `memora-mcp` | (library) | The MCP server: the tool catalog, JSON-RPC 2.0 handling, the discovery card, client detection, `ai_activity` events, and the privacy view applied to agent callers. |\n| `memora-http` | `memora` | The axum server: routing, middleware, the REST API, OAuth 2.1 endpoints, the privacy API, the WebSocket and intake bus, sealed key copies, and serving the UI assets. |\n| `memora-cli` | `memora-cli` | The operator console (slash commands such as `/guide`, `/web`, `/keys`, `/tools`, `/sessions`, `/config`, `/backup`, `/db`, `/update`) and one-shot commands (`setup`, `reset-password`, `status`, `disarm`, `unlock`, `list`, `clear-cooldowns`, `vault`, `db ...`, `update`, `version`). It opens `memora.db` directly; run as root, it does database work as the state directory's owner. |\n\nDependencies point one way: `http` depends on `core`, `mcp`, `gateway`, and\n`state`; `mcp` depends on `core`, `gateway`, and `state`; `cli` depends on\n`gateway`, `mcp`, and `state`. `core`, `gateway`, and `state` depend on no\nother Memora crate.\n\n## What each crate owns\n\n### memora-core\n\n`MemoryStore` is the single point through which the vault is read and written.\nBoth the HTTP API and the MCP tools call its `*_impl` methods, so a change made\nthrough the UI and one made through an agent take the same code path.\n\n- `walk()` enumerates `.md` files under the vault root, skipping dot\n directories. Walk order is stable, so tools that depend on first-hit order\n behave deterministically.\n- Parsing: wikilinks, inline tags, frontmatter tags, and frontmatter fields.\n- The note index: parsed facts per note (links, tags, frontmatter, text,\n checklist items) kept in memory and checked against each file's mtime and\n size on every call, so notes changed outside Memora are seen at once. Nothing\n is stored on disk.\n- `search()` blends word matching over name and body with `tag:` and `#tag`\n filters, scored by hits, name hits, phrase, and position.\n- The graph: nodes are notes, links are resolved wikilinks.\n- Versioning: when the vault is a git repository, vault changes are committed\n to it (`create:`, `edit:`,\n `rename:`, `move:`, `delete:`, `folder:`); history, diff, restore, and\n snapshot read from that history.\n- Privacy views: while a caller's `PathView` is set, listings skip hidden\n notes, hidden paths resolve as \"not found\", and folder operations that would\n carry hidden items along are refused. A path hook reports renames, moves, and\n deletes so privacy rules follow the notes they protect.\n- The event hub (see below).\n\n### memora-gateway\n\n- `hash_password` and `verify_password` use argon2id.\n- `generate_key` produces `memora_live_` plus 128 random bits as hex.\n `hash_api_key` stores the SHA-256 hex of the key. `verify_key` compares in\n constant time.\n- `AccessStack` evaluates ordered IP, range, CIDR, domain, and catch-all rules.\n Loopback is always allowed.\n- `host_allowed` checks the `Host` against `MEMORA_DOMAIN` and the host of\n `MEMORA_BASE_URL`.\n- `tool_access` combines a key's scopes (`mcp`, `read`, `write`, `admin`), its\n tool list, and the global tool switches.\n\n### memora-state\n\n- `Db::open` creates or opens `memora.db` (0600 in a 0700 directory), refuses\n foreign or newer-schema files, and runs migrations.\n- Every write is one `BEGIN IMMEDIATE` transaction (`Db::write`), so the server\n and `memora-cli` can write concurrently without losing updates.\n- Sessions are looked up per request by the SHA-256 of the cookie value;\n `last_seen` and key usage are buffered and flushed in the background.\n- The arm window, the LOCKED state, and the last burned window live in one\n `arm_state` row.\n- Triggers bump a per-domain revision counter. The server checks\n `PRAGMA data_version` about once a second and reloads only the caches whose\n domain changed, so CLI edits apply without a restart (except\n `server_config`, which is read at startup).\n- Old rows (activity, key events, sessions, trashed keys, control requests) are\n pruned hourly.\n- See [DATABASE.md](DATABASE.md) for the schema and operations.\n\n### memora-mcp\n\n- `catalog()` returns the full tool list. Each tool carries a name, a category,\n a description, a \"when to use\" note, and a JSON input schema. See\n [MCP.md](MCP.md).\n- `handle()` dispatches JSON-RPC methods: `initialize`,\n `notifications/initialized`, `tools/list`, `tools/call`, `resources/list`,\n and `resources/read`. Unknown methods return JSON-RPC error `-32601`.\n- `call_tool()` dispatches to `MemoryStore` under the caller's privacy view.\n- Every tool call publishes `ai_activity` start and end events.\n- `discovery_card()` builds the `/.well-known/mcp.json` document.\n- `detect_client()` classifies a request as MCP, web, or API from the path, the\n `mcp-session-id` header, the JSON-RPC body shape, and the user agent.\n\n### memora-http\n\n- `build_router()` wires every route and stacks the middleware layers listed\n below.\n- `AppState` holds the shared store, the MCP server, the database handle, the\n in-memory caches (owner, keys, tools, access stack, settings, arm window),\n the rate-limit guard, the allowed domains, the asset directory, and the vault\n path.\n- `oauth.rs` is an OAuth 2.1 authorization server for remote MCP clients;\n `privacy.rs` serves `/api/privacy`; `secrets.rs` seals API key copies.\n\n### memora-cli\n\nThe CLI never asks for the owner password. It opens setup and reset windows and\nprints one-time codes; credentials are always typed into the browser form.\n\n## Request path\n\nA request enters through `axum::serve` on the single bound address. Layers run\nin this order, outermost first:\n\n1. Security headers (`mw_security_headers`): CSP, `X-Frame-Options: DENY`,\n `X-Content-Type-Options`, `Referrer-Policy`, COOP/CORP,\n `Permissions-Policy`, `Cache-Control: no-store` for API and auth responses,\n and HSTS when HTTPS is reported by a trusted proxy. Applied to every\n response, including errors produced by inner layers.\n2. `X-Robots-Tag: noindex` (`mw_noindex`).\n3. A global concurrency limit of 1024 requests.\n4. A 30 second request timeout (`408`).\n5. Guard (`mw_guard`): requests for a host outside the domain allow list get a\n bare `404`. Forwarding headers from untrusted peers are dropped. The caller\n IP is resolved, only when the peer is a trusted proxy, from the right-most\n `X-Forwarded-For` entry that is not a trusted proxy, else `CF-Connecting-IP`,\n else `X-Real-IP`; a loopback address in a header is ignored. Per-IP\n token buckets apply to auth endpoints and to all traffic, and callers in a\n cooldown after failed logins or bad API keys get `429`. `/healthz` and\n direct loopback callers (no forwarding headers) are not rate limited.\n6. Access stack (`mw_access`): picks up changes from `memora-cli`, then\n evaluates the caller IP and the `Host` domain against the access rules. A\n block returns `403`. `/healthz` bypasses it.\n7. Auth and lock gate (`mw_auth`):\n - If the instance is LOCKED and the path is neither in the lock allow list\n nor a static asset: `/api/*` and `/mcp` return `423`; other paths redirect\n to `/login`.\n - Public paths pass: `/healthz`, `/.well-known/mcp.json`, `/tools`,\n `/login`, `/logout`, `/_bus`, `/`, `/index.html`, static assets, the OAuth\n discovery and flow endpoints, and the auth endpoints\n `/api/auth/{state,login,logout,bootstrap,reset,verify}`.\n - `/ws` needs a valid session and a same-origin request.\n - A valid session cookie (`memora_sess`) passes and is touched (sliding\n TTL); the response renews the cookie's `Max-Age` too, at most every five\n minutes per session, so an active browser keeps it. The web app pings\n `/api/auth/me` every few minutes while its tab is visible and in use.\n - Remaining `/api/*` and `/mcp` requests need an API key, read from\n `Authorization: Bearer <key>` or `X-API-Key: <key>`. The key must carry\n the scope the route needs (`mcp` for `/mcp`, `admin` for keys, tools,\n access, OAuth clients, privacy, and log settings, otherwise `read` for\n GET and `write` for changes). Usage is recorded; an unknown key is logged\n (`key_fail`) and counts toward the IP's cooldown. `/mcp` answers `401`\n with a `WWW-Authenticate` header so OAuth clients can start sign-in.\n8. Vault gate (`mw_vault`): until a vault folder is configured, every route\n that needs the vault (notes, graph, logs, `/mcp`) answers\n `409 {\"needs_vault\": true}`.\n\nThen the matched handler runs. Unmatched browser navigations get the app shell;\nother unmatched paths get a JSON `404`.\n\nFor a browser: `GET /` without a session redirects to `/login`. After login,\nthe UI calls the `/api/*` endpoints. Reads go to `MemoryStore`. Writes from a\ncookie session pass a same-origin check, then call `MemoryStore` `*_impl`\nmethods, which write the note, update the index, and commit to git.\n\nFor an agent: `POST /mcp` carries a JSON-RPC body. The handler parses it,\ndetects the client kind, and calls the MCP server under the key's privacy view.\nA tool call dispatches to the same `MemoryStore` methods the UI uses. REST\ncalls with an API key run under the same privacy view. See [API.md](API.md)\nand [MCP.md](MCP.md).\n\n## Realtime WebSocket fan-out\n\nThe event hub lives in `memora-core::events` as a process-wide singleton.\n\n- `publish()` stamps `_ts`. Persistable event types (`ai_activity` start\n events, `node_created`, `node_updated`, `node_deleted`, `node_renamed`,\n `folder_meta`, `folder_changed`, `actor_alias`, `key_color`) go into a\n 40-entry replay ring and are appended to `<vault>/.events.jsonl`, which is\n trimmed by the `log_max_mb` and `log_max_days` settings.\n- Events are broadcast on a Tokio broadcast channel (capacity 256); a lagging\n subscriber skips missed events instead of stalling the server.\n- `GET /ws` (signed-in browser, same origin, at most 512 clients) sends a\n `hello` event with the client count, replays the ring (each event marked\n `replay: true`), then streams live events. When a client disconnects, a\n `presence` event announces the new count.\n- `POST /_bus` is the local intake: it publishes a JSON object, but only from a\n loopback peer with no forwarding headers and no browser headers (`Origin`,\n `Sec-Fetch-*`), so a web page cannot post to it. Everyone else gets `403`.\n\nThe WebSocket and the intake bus share the single port. There is no second port\nto open or proxy.\n\n## Auth model\n\nOwner login (browser): the owner posts a username and password to\n`/api/auth/login`. The argon2id hash is verified, a session is created, and the\n`memora_sess` cookie is set (`HttpOnly`, `SameSite=Lax`, `Secure` when HTTPS is\nreported by a trusted proxy). The session slides on activity up to\n`session_ttl`, with an optional absolute cap (`session_max_age`).\n\nAPI keys (agents and scripts): created from the dashboard, the API, or\n`memora-cli` (`/keys`); the raw key is shown once. Only the SHA-256 hex is\nstored, plus an optional encrypted copy (see [Storage model](#storage-model))\nso the owner can show a dashboard-created key again after re-entering the\npassword. Keys carry scopes and an optional tool list.\n\nOAuth 2.1 (remote MCP clients): discovery at\n`/.well-known/oauth-protected-resource` and\n`/.well-known/oauth-authorization-server`; clients register dynamically\n(`/oauth/register`), by a client metadata document URL, or manually by the\nowner. The flow is authorization code with PKCE S256 only. The signed-in owner\napproves the request in the browser, and `/oauth/token` issues an access token\nthat is an ordinary API key, plus a rotating refresh token. Revoking the key\nends the connection.\n\nPrivacy rules: the owner can hide a folder or a note from chosen agents\n(`deny`) or from every agent except chosen ones (`allow_only`). Rules add up;\nthe signed-in owner always sees everything. Rules are managed through\n`/api/privacy` and the admin MCP tools.\n\nFirst-run and recovery (the arm window):\n\n- `GET /api/auth/state` is public and reports `bootstrap` (true when no owner\n exists), `armed`, `locked`, the setup hint, and readiness checks.\n- `memora-cli setup` (or `/web` in the console) arms a `bootstrap` window in\n the `arm_state` row, clearing any lock, and prints a one-time code. The\n browser submits the code and creates the owner through\n `/api/auth/bootstrap`, which works only while armed and only when no owner\n exists.\n- `memora-cli reset-password` arms a `reset` window; `/api/auth/reset`\n replaces the password.\n- A wrong code spends that IP's small budget (3, then a cooldown); 50 wrong\n codes in one window void it. A window that expires unfinished just closes\n (back to idle; agents and signed-in browsers keep working). LOCKED is only\n entered on purpose. While locked, only the lock allow list and static assets\n are reachable. `memora-cli unlock`, `setup`, or `reset-password` clears the lock.\n\nLock allow list (`LOCK_ALLOWED`): `/login`, `/logout`, `/api/auth/state`,\n`/api/auth/verify`, `/api/auth/login`, `/api/auth/logout`,\n`/api/auth/bootstrap`, `/api/auth/reset`, `/healthz`, `/favicon.ico`.\n\n## Storage model\n\nMemora keeps two directories apart on purpose.\n\n### Vault (markdown, portable)\n\nChosen in the browser after the first sign-in (`MEMORA_VAULT` is the\nsuggestion) and stored in the `settings` table.\n\n- One `.md` file per note. Frontmatter and inline `#tags` are both supported.\n- Wikilinks use `[[Note Name]]` and resolve by name, so moving or renaming a\n note does not break links.\n- `.git/` is the vault history. Changes commit automatically.\n- `.events.jsonl` is the append-only event log.\n- `.folders.json` stores folder color, icon, and description.\n- `.locks.json` stores soft locks used for collaboration.\n- `.actors.json` stores actor aliases.\n- `.Trash/` holds soft-deleted notes, recoverable with `restore_trash`.\n\n### State (credentials, operational)\n\nSet by `MEMORA_STATE` (default `state`).\n\n- `memora.db` is the single SQLite database for all server state: the owner\n (argon2id hash), API keys (SHA-256 hex, with a trash for restore), scopes\n and tool lists, global tool switches, OAuth clients and grants, privacy\n rules, sessions (hashed ids), the arm window and lock, access rules, instance\n settings, `server_config`, UI layouts, and the activity log. It is created\n and migrated on first start; WAL mode, mode 0600.\n- `key-seal.bin` is the 32-byte master key (0600) for the sealed API key copies\n (ChaCha20-Poly1305). The database holds only ciphertext, so a copy of\n `memora.db` alone reveals no key.\n- `backups/` holds `memora-cli db backup` copies.\n- `legacy-json-<unix time>/` holds JSON state files found at startup, moved\n there after their one-time import.\n- `internal.token` is created by the container entrypoint. Memora does not use\n it.\n\nState changes are transactional: a crash leaves either the old or the new\nstate, never a mix.\n"},{"file":"docs/DATABASE.md","slug":"database","title":"Database","text":"# State database\n\nMemora keeps all server state in one embedded SQLite file,\n`<MEMORA_STATE>/memora.db`, managed by the `memora-state` crate. The vault\n(markdown notes plus git) is separate and stays plain files.\n\nNo SQL lives outside `crates/state`. The server (`memora`) and the operator\nconsole (`memora-cli`) both open the file directly; there is no database\nserver, port, or password.\n\n## Files and permissions\n\n| Path | Mode | Content |\n|---|---|---|\n| `<state>/` | 0700 | The state directory. Created if missing; its mode is tightened on open. |\n| `memora.db` | 0600 | The database. |\n| `memora.db-wal`, `memora.db-shm` | 0600 | WAL journal and shared memory. Part of the live database; never copy `memora.db` without them while the server runs. |\n| `key-seal.bin` | 0600 | Master key for the sealed API key copies (`api_key_secret`). Not inside the database. |\n| `assistant.sqlite3` (+ `-wal`, `-shm`) | 0600 | Mnemo's own small database (`memora_state::assistant`): `providers` (API keys sealed with `key-seal.bin`, a four-character hint), `models`, `prefs`, `sessions` and `messages`. Kept apart from `memora.db`, so the main schema and its migrations are unchanged and an older binary simply ignores it. |\n| `backups/` | 0700 | Output of `memora-cli db backup` and the pre-restore snapshot. |\n| `legacy-json-<unix time>/` | 0700 | JSON state files found at startup, moved here after their one-time import. |\n\nThe state directory must be on a local filesystem. WAL needs shared memory\nand does not work on NFS or SMB; the server refuses to start when WAL cannot be\nenabled.\n\nRun as root, `memora-cli` does every database operation as the owner of the\nstate directory (in a child process that drops privileges), so no root-owned\n`memora.db*` files appear and the server can always open them.\n\n## Connection settings\n\nEvery connection, server and CLI, uses: `journal_mode=WAL`,\n`synchronous=FULL`, `foreign_keys=ON`, `busy_timeout`, `secure_delete=ON`\n(deleted rows are zeroed), `trusted_schema=OFF`, SQLite defensive mode, and a\n4 MiB `journal_size_limit`.\n\nThe file is marked with `PRAGMA application_id = 0x4D454D4F` (`MEMO`). Memora\nrefuses to open a file with another application id, or one whose\n`user_version` is newer than the binary supports.\n\n## Schema\n\nConventions: times are `INTEGER` unix seconds UTC; booleans are\n`INTEGER CHECK (x IN (0,1))`; every table is `STRICT`. Constraints (CHECK,\nUNIQUE, foreign keys, triggers) reject invalid data at the database level; the\nRust repositories validate first to return readable errors. The DDL is in\n`crates/state/migrations/*.sql`.\n\n### Auth and settings\n\n| Table | Content |\n|---|---|\n| `meta` | Key/value markers (for example the legacy import marker). |\n| `owner` | The single owner account: `id` is always 1, so a second account is impossible. Lowercase username (1-32 chars of `a-z0-9._-`), argon2id password hash, display name, timestamps. |\n| `settings` | One row (`id = 1`): `realm`, `session_ttl`, `session_max_age`, `min_password_len`, `log_max_mb`, `log_max_days`, `vault_path` (absolute or NULL). Ranges are listed in [CONFIGURATION.md](CONFIGURATION.md#instance-settings-web-ui). |\n| `server_config` | Server settings that override the environment. Only the ten known keys are accepted, with range checks for `MEMORA_PORT`, `MEMORA_ARM_TTL`, and `MEMORA_VAULT_AUTO`. `MEMORA_ADMIN_PASSWORD` and `MEMORA_API_KEY` cannot be stored. |\n| `arm_state` | One row: `idle`, `armed`, or `locked`, the window mode (`bootstrap` or `reset`), start time, length (30-86400 s), the SHA-256 of the one-time code, lock time, and the last burned window. Checks make an armed row without a code, or a code outside an armed window, impossible. |\n| `session` | Browser sessions keyed by `sid_hash`, the SHA-256 of the cookie value (the cookie itself is never stored). Source, alias, IP, user agent, `created_at`, `last_seen`. The CLI addresses sessions by a prefix of at least 8 characters of `sid_hash`. |\n\n### API keys and tools\n\n| Table | Content |\n|---|---|\n| `api_key` | `id` (`k_...`), name, SHA-256 hex `hash` (unique), display `prefix`, `enabled`, `tools_all`, `color` (`#rrggbb` or NULL), `created_at`, `deleted_at` (trash). `grace_until` is unused and always NULL. |\n| `api_key_scope` | Scopes per key: `mcp`, `read`, `write`, `admin`. |\n| `api_key_tool` | Allowed tools per key, only when `tools_all = 0` (a trigger enforces this and clears the list when `tools_all` is set back to 1). |\n| `api_key_secret` | Optional sealed copy of a dashboard-created key: `base64url(nonce || ChaCha20-Poly1305 ciphertext)` under `key-seal.bin`. |\n| `api_key_usage` | Last use, last IP, and use count per key. Separate from `api_key` so usage flushes do not trigger a key reload. |\n| `api_key_event` | Per-request key events (time, IP, tool or route, path). Used for activity views and new-IP detection. |\n| `tool` | Mirror of the MCP tool catalog, synced at server start. Tools missing from the catalog are marked `retired`. |\n| `tool_disabled` | Globally disabled tools (foreign key to `tool`). |\n\n### OAuth\n\n| Table | Content |\n|---|---|\n| `oauth_client` | Registered clients: `client_id`, name, redirect URIs (JSON array), kind (`dcr`, `cimd`, or `manual`). |\n| `oauth_code` | One-time authorization codes (SHA-256), PKCE S256 challenge, redirect URI, resource, expiry. |\n| `oauth_grant` | Refresh tokens (SHA-256), one per connection, rotated on every use. Each grant points at the API key that serves as its access token and is deleted with it. |\n\n### Access, privacy, and logs\n\n| Table | Content |\n|---|---|\n| `access_policy` | One row: the default action when no rule matches. |\n| `access_rule` | Ordered rules (`position`): kind (`ip`, `range`, `cidr`, `domain`, `all`), value, `allow` or `block`, enabled flag, note. |\n| `privacy_rule` | Hides a vault path from agents: kind `folder` (the folder and everything below it) or `node` (one note), mode `deny` (hidden from the listed keys) or `allow_only` (hidden from every key not listed). Paths are vault-relative and matched case-insensitively. |\n| `privacy_rule_key` | Keys a privacy rule lists. |\n| `privacy_trail` | Earlier paths of a rule after renames and moves (at most 64 per rule), used only to keep log and event lines that name the item away from hidden agents. |\n| `activity` | Audit log: time, event name, IP, actor (username, key id, or `cli`), detail. |\n| `control_request` | Requests from `memora-cli` to the running server for state that lives in server memory (`limiter_reset`, `reload_all`), with an acknowledgement (`done_at`, `result`). |\n| `ui_layout` | One JSON document per web UI layout name (canvas positions, pinned graph positions), at most 512 KiB each. |\n| `pin` | The owner's pinned notes and folders in sidebar order (`position`): kind `note` or `folder`, vault-relative path. At most 200. Renames, moves and deletes done by Memora rewrite or drop them in the same transaction. |\n| `revision` | One counter per cache domain (`auth`, `keys`, `tools`, `access`, `settings`, `arm`), bumped by triggers. |\n\nRevision triggers (one per insert, update, and delete) map tables to domains:\n`owner` to `auth`; `api_key`, `api_key_scope`, `api_key_tool` to `keys`;\n`tool_disabled` to `tools`; `access_policy`, `access_rule` to `access`;\n`settings`, `server_config` to `settings`; `arm_state` to `arm`. Sessions,\nusage, events, activity, OAuth, privacy rules, pins, and UI layouts have no revision\nand are read from the database when needed.\n\n## Concurrency and change detection\n\n- Every write is one transaction started with `BEGIN IMMEDIATE`, so the server\n and `memora-cli` can write at the same time without losing updates.\n `busy_timeout` makes a concurrent writer wait instead of failing.\n Multi-step changes are atomic, for example a password change also deletes the\n other sessions and writes the activity row in the same transaction.\n- The server keeps caches of the owner, keys, tools, access stack, settings,\n and arm window. It checks `PRAGMA data_version` on requests and at least once\n a second; when another connection committed, it reads `revision` and reloads\n only the changed domains. Changes made with `memora-cli` therefore apply on\n the next request, without a restart. `server_config` is the exception: it is\n read at startup.\n- Sessions are not cached: each request looks up `session.sid_hash`, so a\n sign-out from the CLI applies on the next request.\n- Hot-path writes are buffered: session `last_seen` is flushed every 5 seconds\n and key usage every 30 seconds. Pending control requests are served every 2\n seconds. Buffers are flushed on shutdown.\n- Window expiry is a conditional update (`armed` to `idle`, never `locked`), and a setup code\n is checked and consumed in the same transaction, so a code works at most\n once.\n\nKept in memory on purpose: rate-limit token buckets and login cooldowns (a\nrestart resets them; cooldown starts are still written to `activity`), the\ntrusted proxy list, and the caches above.\n\n## Retention\n\nThe server prunes in small batches every hour, and `memora-cli db vacuum` runs\nthe same pruning:\n\n| Data | Kept |\n|---|---|\n| `activity` | 365 days, at most 200,000 rows |\n| `api_key_event` | 30 days, at most 100,000 rows |\n| `session` | Until idle longer than `session_ttl` or older than `session_max_age` |\n| Trashed `api_key` rows | 90 days after `deleted_at` (scopes, tools, usage, and events cascade) |\n| `control_request` | 1 day after `done_at`; unanswered requests expire after 1 hour |\n\n## Migrations\n\nMigrations are SQL files embedded in the binary\n(`crates/state/migrations/0001_init.sql` and onward) and tracked with\n`PRAGMA user_version`. Each one runs in its own `BEGIN IMMEDIATE` transaction\ntogether with the version bump, so a crash leaves either the old or the new\nschema, and two processes opening a fresh file apply it exactly once. The\nserver and `memora-cli` migrate the database when they open it. A binary\nrefuses a database with a newer schema; to go back to an older release,\nrestore the backup taken before upgrading.\n\n| Version | File | Adds |\n|---|---|---|\n| 1 | `0001_init.sql` | Base schema and revision triggers |\n| 2 | `0002_ui_layout.sql` | `ui_layout` |\n| 3 | `0003_colors_logs.sql` | `api_key.color`, `settings.log_max_mb`, `settings.log_max_days` |\n| 4 | `0004_oauth.sql` | `oauth_client`, `oauth_code`, `oauth_grant` |\n| 5 | `0005_key_secret.sql` | `api_key_secret` |\n| 6 | `0006_privacy.sql` | `privacy_rule`, `privacy_rule_key`, `privacy_trail` |\n| 7 | `0007_pins.sql` | `pin` |\n| 8 | `0008_windows_vault_path.sql` | `settings.vault_path` accepts Windows absolute paths (table rebuilt) |\n\n### JSON state import\n\nWhen the server starts on a state directory that holds JSON state files\n(`gateway.json`, `config.json`, `memora.env`, `tools.json`,\n`access_stack.json`, `sessions.json`, `arm.json`, `lock.json`,\n`key-usage.json`, `activity.jsonl`, and related files), it imports them once,\nin one transaction, then moves them to `legacy-json-<unix time>/`. Auth data\nmust be valid or nothing is imported; bad log lines are skipped and counted.\nPlaintext `MEMORA_ADMIN_PASSWORD` and `MEMORA_API_KEY` values are dropped. A\nsummary is written to the log and the `activity` table. On a fresh state\ndirectory the import is a no-op.\n\n## Operations\n\n| Task | Command | Notes |\n|---|---|---|\n| Backup (server running) | `memora-cli db backup [--to PATH] [--keep N]` | `VACUUM INTO` a consistent copy, checked with `integrity_check`, mode 0600. Default target `state/backups/memora-<UTC time>.db`; the newest 10 there are kept (`--keep N`). `--to` takes a file or a directory. |\n| Backup without memora-cli | `sqlite3 memora.db \".backup '/var/backups/memora.db'\"` | Never `cp` a live WAL database: recent commits sit in `memora.db-wal`. |\n| Restore | `memora-cli db restore FILE [--force]` | The server must be stopped (the CLI checks for it and for any process holding `memora.db*`; `--force` skips the check). Verifies `application_id`, schema version, `integrity_check`, and foreign keys, saves the current database to `state/backups/memora-<time>-pre-restore.db`, then replaces it and removes stale `-wal`/`-shm` files. |\n| Health | `memora-cli db check` | Directory and file permissions, application id, schema version, `integrity_check`, `foreign_key_check`, file sizes, last backup age. Exit status 1 on any problem, for timers and health checks. |\n| Maintenance | `memora-cli db vacuum` | Prune by retention, `PRAGMA optimize`, `VACUUM`, `wal_checkpoint(TRUNCATE)`. |\n| Inspect | `memora-cli db shell [--write]` | Runs `sqlite3` (must be installed), read-only unless `--write`. Writes through the shell bypass Memora's checks and the activity log. |\n| Export | `memora-cli db export-json [DIR]` | Writes the database out as JSON state files (default: the state directory). |\n\nIn the console: `/backup`, and `/db` with `check`, `vacuum`, or `backup`.\n\nIn Docker, run the same commands through the container:\n\n```sh\ndocker compose exec gateway memora-cli db backup # lands in ./state/backups/\ndocker compose exec gateway memora-cli db check\n```\n\nFor a restore, stop the service first and run the CLI in a one-off container:\n\n```sh\ndocker compose stop gateway\ndocker compose run --rm gateway cli db restore /state/backups/memora-<time>.db\ndocker compose start gateway\n```\n\nA daily systemd timer or cron job running `memora-cli db backup` is enough for\nmost installs. Back up `key-seal.bin` with the database; without it, sealed key\ncopies cannot be shown again (the keys themselves keep working).\n\n## Encryption at rest\n\nThe database is not encrypted. Every credential in it is a one-way hash\n(argon2id for the owner password, SHA-256 for API keys, OAuth codes and refresh\ntokens, setup codes, and session ids), and sealed key copies are encrypted\nunder a key stored outside the database. What remains (IPs, user agents,\nactivity) is low sensitivity. Use a 0700 state directory, host disk\nencryption, and encrypt backups that leave the host (for example with `age` or\n`gpg`).\n"},{"file":"docs/contracts/tools-permissions.md","slug":"tool-reference","title":"Tool reference","text":"# Tool switches and per-key permissions\n\nThis page describes how Memora decides which MCP tools an agent may see and\ncall. Two controls combine:\n\n- **Global tool switches** turn a tool off for every API key on the server.\n- **Per-key permissions** (scopes and a tool list) limit what one key may do.\n\nThey are managed in the web UI, with `memora-cli` (`/tools` and `/keys`), over\nthe HTTP API, and with the MCP admin tools. All of them write the same state\ndatabase (`state/memora.db`, see [../DATABASE.md](../DATABASE.md)). Tool\nswitches and per-key tool lists from older installs (`state/tools.json` and the\n`tools` field of keys in `gateway.json`) are imported into the database once.\n\n## Tool catalog\n\nThe switchable catalog is `memora_mcp::catalog()`: every tool with its `name`,\n`category`, `description`, when to use it, and input schema (74 tools; see\n[../MCP.md](../MCP.md#tools)). At startup the server mirrors the catalog into\nthe `tool` table, so switches and per-key grants can refer to tools by name.\nA tool that leaves the catalog is marked retired, not deleted: its switch and\ngrants are kept but have no effect, and they apply again if the tool returns.\n\nThe admin tools (`admin_list_tools`, `admin_set_tool`, `privacy_list`,\n`privacy_set`, `privacy_clear`) are not part of the catalog. They cannot be\nswitched off or granted through a tool list; only the `admin` scope controls\nthem.\n\n## Global tool switches\n\nTable `tool_disabled` holds one row per switched-off tool. No row means the tool\nis on. A switched-off tool is hidden from `tools/list` and refused by\n`tools/call` for every caller, browser sessions included. It is still listed in\nthe discovery card and on the `/tools` page, marked as disabled.\n\nSwitching a tool that is already in the requested position changes nothing.\nA change made by another process (for example `memora-cli` while the server\nruns) reaches the server within about a second, without a restart.\n\n## Scopes\n\nEach key has a set of scopes (table `api_key_scope`):\n\n| Scope | Allows |\n|---|---|\n| `mcp` | Calling `/mcp` at all, and every read-only MCP tool. |\n| `read` | `GET` and `HEAD` on the `/api/*` vault routes. |\n| `write` | Mutating `/api/*` vault routes, and every MCP tool that is not read-only. |\n| `admin` | Managing tools, keys, access rules, log settings, OAuth clients and privacy rules (`/api/tools`, `/api/keys`, `/api/access`, `/api/logs/settings`, `/api/oauth/clients`, `/api/privacy` and everything below them), and the MCP admin tools. |\n\nA key created without explicit scopes gets `mcp`, `read` and `write` and every\ntool. Keys that MCP clients obtain through OAuth start with the same defaults.\n`admin` is never granted by default. An empty scope list on create also means\nthe defaults.\n\n## Per-key tool list\n\nEach key either may use every catalog tool (`\"tools\": \"*\"`, stored as\n`api_key.tools_all = 1`, the default) or only the tools listed for it\n(`\"tools\": [\"search_memory\", \"read_memory\"]`, stored as `tools_all = 0` plus one\n`api_key_tool` row per tool). An empty list allows no catalog tools. Tool names\nmust be catalog tools; unknown names are refused with `unknown tool: <name>`.\n\nThe tool list does not replace scopes: a tool that changes the vault still\nneeds `write`, even when the list names it.\n\n## Effective access\n\nA key may call catalog tool T over MCP when all of these hold:\n\n1. The key is enabled.\n2. The key has the `mcp` scope.\n3. T is not switched off globally.\n4. The key's tool list is `\"*\"` or contains T.\n5. T is read-only, or the key has the `write` scope.\n\nRead-only tools are the ones listed as read-only in `crates/mcp/src/activity.rs`\n(the R tools in [../MCP.md](../MCP.md#tools)). Every other catalog tool needs\n`write`, including tools added later until they are marked read-only.\n\nAn admin tool may be called when the key is enabled and has both `mcp` and\n`admin`. Browser sessions have full access, including the admin tools, but\nglobal switches still apply to them.\n\nDisabled keys are rejected before MCP runs (HTTP `401`, `invalid API key`), and\na key without `mcp` gets HTTP `403` with\n`{\"error\":\"API key lacks the 'mcp' scope\",\"required_scope\":\"mcp\"}`.\n\n## How refusals look\n\n`tools/list` returns only the tools the caller may use (plus the admin tools for\nadmin keys).\n\n`tools/call` on a tool the caller may not use returns JSON-RPC error `-32003`\nwith one of these messages:\n\n| Message | Cause |\n|---|---|\n| `tool not allowed for this API key: <name>` | The key's tool list does not include the tool, or the caller lacks `admin` for an admin tool. |\n| `tool disabled on this server: <name>` | The tool is switched off globally. |\n| `API key lacks the 'write' scope for tool: <name>` | The tool is not read-only and the key has no `write` scope. |\n\nA name that is neither a catalog tool nor an admin tool is not refused with\n`-32003`; the call returns a tool result with `isError: true` and\n`unknown tool: <name>`.\n\n## HTTP API\n\nThese routes need a signed-in browser session or an API key with the `admin`\nscope. For browser sessions, `POST` requests must be same-origin.\n\n| Route | Body | Response |\n|---|---|---|\n| `GET /api/tools` | | `{tools: [{name, category, description, enabled}]}` |\n| `POST /api/tools` | `{name, enabled}` | `{ok, name, enabled}`. Unknown tool or missing `enabled`: `400`. |\n| `GET /api/keys` | | `{count, keys}`. Each key includes `tools` (`\"*\"` or a list) and `scopes`. |\n| `POST /api/keys` | `{name, tools?, scopes?, color?}` | `{ok, id, key, name, prefix, persisted, color, tools, scopes}`. The raw `key` is returned once. |\n| `POST /api/keys/update` | `{id, name?, enabled?, color?, tools?, scopes?}` | `{ok, id, name, enabled, color, tools, scopes, persisted}` |\n\n`tools` is `\"*\"` or an array of catalog tool names. `scopes` is an array of\n`mcp`, `read`, `write` and `admin`. Fields left out stay unchanged. Unknown tool\nor scope names return `400` (`unknown tool: <name>`, `unknown scope: <name>`).\n\n## MCP admin tools\n\nListed only for keys with the `admin` scope:\n\n- `admin_list_tools`: no arguments. Same shape as `GET /api/tools`.\n- `admin_set_tool`: `{name, enabled}`. Same effect as `POST /api/tools`.\n\nThe privacy admin tools (`privacy_list`, `privacy_set`, `privacy_clear`) are\ndescribed in [../MCP.md](../MCP.md#admin-tools-admin).\n\n## Activity log\n\nEvery change is written to the `activity` table in the same transaction:\n\n| Event | When | Detail |\n|---|---|---|\n| `tool_enabled` | A tool is switched on | The tool name |\n| `tool_disabled` | A tool is switched off | The tool name |\n| `key_permissions` | A key's scopes or tool list are set on create or changed on update | `<id> tools=[...] scopes=[...]` |\n\nCreating and updating a key also logs `key_created` and `key_updated`. The actor\nis the signed-in user, or `key:<id>` when an API key made the change.\n"},{"file":"SECURITY.md","slug":"security","title":"Security","text":"# Security Policy\n\n## Supported versions\n\nSecurity fixes are applied to the latest release. Run the newest published\nversion to receive them.\n\n| Version | Supported |\n|---|---|\n| Latest release | Yes |\n| Older releases | No |\n\n## Reporting a vulnerability\n\nDo not open a public issue for a security problem. Report it privately:\n\n- Use GitHub's private vulnerability reporting on the repository\n (Security tab, \"Report a vulnerability\"), or\n- Email the maintainers at the address listed in the repository profile.\n\nInclude as much as you can:\n\n- A description of the issue and its impact.\n- Steps to reproduce, or a proof of concept.\n- Affected version and deployment method (binary or container).\n- Any suggested fix or mitigation.\n\nWe aim to acknowledge reports within a few business days and to provide a\ntimeline for a fix. We will credit reporters who wish to be named once a fix is\nreleased.\n\n## Security model\n\nMemora is designed to run as a single-owner service, usually behind a reverse\nproxy. Relevant properties:\n\n- User passwords are stored as argon2id hashes and verified in constant time.\n- API keys are random, shown once, and stored only as SHA-256 hex. Verification\n is constant time. Unknown hash formats are rejected.\n- Browser sessions use an `HttpOnly`, `SameSite=Lax` cookie with a sliding TTL.\n Only a hash of the session id is stored. The `Secure` attribute is set when\n the request arrives over HTTPS through a trusted proxy.\n- Cookie-based writes are protected by an origin check (`Origin`/`Referer`\n against `Host`). Pages are served with a nonce-based Content-Security-Policy.\n- API keys carry scopes (`mcp`, `read`, `write`, `admin`) and an optional tool\n list; tools can be switched off for every key, and privacy rules hide notes or\n folders from chosen agents.\n- MCP clients that use OAuth get an ordinary API key after the owner approves\n them in the browser (authorization code with PKCE S256), so the same scopes,\n revocation and activity log apply.\n- An unclaimed instance is protected by the setup window: the CLI opens a\n short-lived session and the browser completes it. If the window expires\n unfinished, the instance locks and only recovery paths stay reachable.\n- The access stack can restrict access by IP, range, CIDR, and domain, with\n loopback always allowed to prevent lockout.\n- The local event intake (`POST /_bus`) accepts loopback only, and refuses\n requests a browser marks as its own (`Origin`, `Sec-Fetch-*`).\n- Failed sign-ins are limited per IP: after 5 failures in 15 minutes that IP\n waits 5, then 10, then 15 minutes. Failures from many IPs never lock the\n owner out: 20 failures in 15 minutes across all IPs switch on a slow mode in\n which every sign-in waits about a second and a single failure puts that IP on\n its cooldown. A correct password from an IP without recent failures is still\n accepted, and a successful sign-in ends slow mode.\n- A wrong setup code counts against that IP's budget of 3 wrong codes (then a\n cooldown). The code stays single-use and the window time-limited; only 50\n wrong codes in one window (from any IPs) close it early.\n- Dynamic OAuth client registration is limited per IP, and registered clients\n that never complete an authorization are removed after an hour.\n\n## Deployment guidance\n\n- Terminate TLS at the reverse proxy and forward `X-Forwarded-Proto: https`.\n- Keep the state directory private. Its database, `memora.db`, holds credential\n hashes and the activity log.\n- Back up `memora.db` with `memora-cli db backup`; losing it loses the owner\n account, API keys and settings.\n- Do not expose the service directly on a public interface without a proxy and\n without the access stack configured.\n- Rotate API keys periodically (web UI, `memora-cli` -> `/keys`, or\n `POST /api/keys/roll`).\n\n## Dependencies\n\nCI checks the dependency trees for published advisories on every push and pull\nrequest:\n\n- `cargo audit` checks `Cargo.lock` against the RustSec advisory database. A\n vulnerability advisory fails the build; unmaintained, unsound and yanked\n notices are shown as warnings. Advisories reviewed and found not to apply\n are listed with their reason in `.cargo/audit.toml`.\n- `npm audit --omit=dev` checks the web UI packages that end up in the built\n assets.\n\nDependabot proposes updates for Cargo, npm, GitHub Actions and the Docker base\nimages. GitHub Actions are pinned to full commit SHAs. These checks only cover\nadvisories that have been published; they do not replace a review of the code.\n\n## Out of scope\n\n- Misconfiguration of a reverse proxy or TLS termination.\n- Issues that require an already-compromised host or root access.\n- Denial of service from an attacker with unlimited network access, absent a\n specific, novel amplification vector.\n"},{"file":"CHANGELOG.md","slug":"changelog","title":"Changelog","text":"# Changelog\n\nAll notable changes to this project are documented in this file.\n\nThe format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),\nand this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).\n\n## [Unreleased]\n\n## [2.1.11] - 2026-11-18\n\n### Changed\n\n- The Think chip shows for every model that is not an old Claude model,\n router aliases included, so the thinking level can be set even when the\n model's name says nothing. It hides once the provider refuses both the\n effort and the thinking fields.\n\n## [2.1.10] - 2026-11-18\n\nEach chat keeps its own model, and a model change is always marked.\n\n### Changed\n\n- A chat keeps the model it began with or was switched to (stored with the\n chat); the default model only applies to new chats. When a chat's model is\n gone or cannot answer, it takes the default, then the fallback models, then\n the first pinned model.\n- When a fallback model takes over, the chat switches to it, says so, and a\n divider marks every change of model in the conversation (also inside a\n reply), so it is clear which model wrote what.\n- A model that is out of quota, has its key refused or is not found goes\n straight to the next fallback model; a provider that is only busy gets one\n quick retry when a fallback is lined up. The reason shows in a few words.\n- The model picker and the memory ring sit under the prompt, on the right;\n the prompt keeps the thinking level and Send.\n- The fleeting button shows only on a new chat (and in a fleeting chat, to\n leave it).\n\n### Fixed\n\n- The thinking level was missing for models whose name gives nothing away\n (router aliases): a model that has shown its thinking is now offered it,\n and OpenAI-style routers get `reasoning_effort`.\n\n## [2.1.9] - 2026-11-18\n\nChats stay in step on every device, and the queue never gets stuck.\n\n### Added\n\n- Live chats on every device: a message sent from one device shows on every\n other device that has the chat open, and Mnemo's reply streams on all of\n them (`GET /api/assistant/sessions/{id}/watch`).\n- Fallback models (Settings, Mnemo): up to five models, in order. When a\n reply's model fails after its retries, the next one carries on by itself;\n with none left the error stands and the owner tries again by hand\n (`@mnemo` requests keep their own retries).\n- Thinking level next to the model, for models that can think: Auto, Off,\n Low, Medium or High (Anthropic `output_config.effort`, OpenAI\n `reasoning.effort` / `reasoning_effort`, OpenRouter-style `reasoning.effort`).\n- Switching the model of a chat that has begun asks first.\n\n### Changed\n\n- The queue lives on the server, shared by every device: queued messages go\n out one by one as each reply ends, whether it finished, was stopped or was\n cut. A failed reply pauses the queue until a message is sent now or the\n queue resumes. Send now, Clear and Resume are always available\n (`/api/assistant/sessions/{id}/queue`).\n- Send now (a queued message, or Ctrl/Cmd+Enter) no longer slips the message\n into the running reply: the reply is cut where it is and the message is\n answered as a new turn of its own (`/steer`).\n- Stop keeps what the reply wrote so far in the chat (`meta.stopped`).\n- A long queue shows three rows with a fade and scrolls; Show all opens it.\n\n### Fixed\n\n- The compaction summary shows as it is written and can always be opened,\n instead of an empty divider until the chat was opened again.\n- After Stop, queued messages could lose their buttons and never go out.\n\n## [2.1.8] - 2026-11-17\n\n`@mnemo` requests are never dropped.\n\n### Fixed\n\n- An `@mnemo:` request Mnemo could not answer (the AI provider or the\n network down, or no model yet) is no longer struck through with \"Could\n not answer\": it stays open in the note and is tried again after 1, 3, 10\n and 30 minutes, then hourly (up to about a day; any change to the note\n starts over). A retry runs the same message in the note's chat instead of\n asking twice, and only the answer to that request is written back.\n- What's new: the release row starts flush left and fades only on a side\n with more to scroll to; an arrow shows only where there is somewhere to go.\n- Opening Mnemo at `/mnemo/<id>` shows that chat's title right away instead\n of \"New chat\" while it loads.\n- Fresh ideas shows a shimmer on the button and placeholder cards while\n Mnemo writes, instead of a spinning icon.\n\n## [2.1.7] - 2026-11-17\n\nSkills, fleeting chats, suggestions that change, and a note's chats that\nfollow the note.\n\n### Added\n\n- Skills: notes in the vault's `Skills` folder (file name = skill name, a\n `description:` line, then the steps). Typing `/` in Mnemo's message box\n lists them; `/name ...` sends the skill's steps with the message\n (`meta.skill`). Mnemo makes, changes and removes skills with its note\n tools. New endpoint `GET /api/assistant/skills`.\n- Fleeting chats (the eye in Mnemo's header): not kept, left out of the chat\n list, search and Mnemo's look-back tools, and deleted with the pictures\n sent in them when the owner leaves (or after 30 minutes idle). Changes to\n notes stay. `POST /api/assistant/sessions` takes `fleeting: true`.\n- Suggestions on a new chat change each time: the owner's own (Your\n suggestions, kept), ones Mnemo writes from recent notes (refreshed at most\n every 12 hours, or now with Fresh ideas) and built-in ones; skills show as\n chips. Endpoints `GET/POST /api/assistant/suggestions` and\n `POST /api/assistant/suggestions/refresh`.\n- Mnemo tool `view_image`: look at a picture in the vault (a note's\n picture by its path); a web address is refused with a note to send or add\n the picture instead.\n- Ask Mnemo from a note's page offers that note's earlier chats\n (`GET /api/assistant/sessions?about=<path>`).\n\n### Changed\n\n- All `@mnemo:` requests in one note go to that note's one chat (titled\n `@mnemo · <note>`), and a note's chats follow it when it is renamed,\n moved, sent to the Trash or restored.\n- An `@mnemo:` request Mnemo writes into a note from a chat or the console\n is answered like the owner's; what it writes while answering a request\n never asks again.\n- Deleting chats also deletes the pictures sent in them (pictures placed in\n notes stay in the vault).\n- What's new: arrows show only where there is more, and a new footer with\n the GitHub star count.\n- A page open beside the chat folds the chat list and \"In this chat\" away\n so the chat keeps its room; the list comes back when the divider leaves\n room for it, and everything returns when the page closes. When the chat\n and the page cannot both fit, the page opens full screen.\n\n### Fixed\n\n- Pictures in notes are capped at about 60% of the screen height (480 px).\n- Leaving a chat while Mnemo answers no longer shows a network error; the\n chat reconnects to the running reply.\n- Chats left with their question's first words as the title (the model\n could not name them) get a proper title on the next reply; titles have\n room for models that think first.\n\n## [2.1.6] - 2026-11-17\n\nMnemo's pages become versions of one file, chats can be cleaned up in bulk,\nand a chat is compacted only once it is full.\n\n### Added\n\n- Page versions: an HTML or SVG page Mnemo rewrites under the same title is\n the next version of the same file. Cards show v1, v2 and latest (older\n ones dimmed), the preview panel steps between versions, and the newest\n opens beside the chat by itself on a wide screen (or replaces what an open\n panel shows). Mnemo is told to rework its latest version when asked to\n change or tidy a page, and to start a new page only when asked.\n- A draggable divider between the chat and an open page (keyboard arrows\n too; double-click resets). The page keeps at least 360 px, the chat at\n least 420 px, and the page at most 75% of the width; the width is\n remembered per device.\n- Deleting many chats: Select chats (pick several, then Delete), Clean up\n chats (untouched for 7, 30 or 90 days) and Delete all chats, from the ⋯\n beside New chat and the chat menu. Pinned chats are kept unless asked; a\n chat answering right now is left alone. New endpoint\n `POST /api/assistant/sessions/prune` (`ids`, `older_than_days` or `all`,\n with `keep_pinned`).\n- Mnemo tool `list_chats` (the owner's chats, newest first, optionally by\n title) and paging for `read_chat`, so Mnemo can connect a chat with\n earlier ones.\n- Mnemo tools `list_artifacts` and `read_artifact`: the pages Mnemo wrote,\n across chats, and a page's full source by version, so a page can be\n reworked or reused from another chat. Pages live in their chat's messages\n and are deleted with it; the \"In this chat\" panel lists them under Pages.\n\n### Changed\n\n- Auto-compaction starts only when a chat's history fills all the tokens it\n may use (the model's context minus the room kept for the reply), instead\n of at 80%. While it runs, a working divider with a clock shows in the\n chat; it turns into Compacted (with how long it took) and the reply goes\n on. Compact now shows the same divider.\n- Page cards are as wide as the reply, tinted with an accent edge and an\n accent Open button, and long titles end in an ellipsis.\n- Mnemo's chat list foot: Appearance is one wide button (showing the theme\n and background in use) above Activity, Settings and Memora.\n- Thin rounded scrollbars in the chat, the message box and the chat list\n that show only while scrolling; the track keeps its width, so nothing\n shifts.\n- What's new: releases slide in one row with arrows (newest first) and the\n footer stacks neatly on phones.\n\n### Fixed\n\n- The New chat button in Mnemo's chat list header on phones no longer takes\n the unread badge's look.\n\n## [2.1.5] - 2026-11-17\n\nUnread chats agree on every device, Mnemo's chat list ends in one tidy row,\nand phones no longer send a message on Enter.\n\n### Changed\n\n- Unread chats are remembered on the server instead of per browser: a chat\n read on one device is read on all of them. New endpoint\n `POST /api/assistant/sessions/{id}/seen`; the chat list carries each\n chat's `seen` count. The first list after updating counts everything\n there as read.\n- The scroll-down button in Mnemo's chat is a plain scroll to the bottom;\n the \"New messages\" label is gone (it also showed for older messages).\n- On touch keyboards Enter adds a new line in Mnemo's message box and the\n send button sends; on physical keyboards Enter still sends and\n Shift+Enter adds a line.\n- Mnemo's chat list: theme, chat background and text size moved into an\n Appearance panel (a bottom sheet on phones), and the foot of the list is\n one row of four tiles: Appearance, Activity, Settings and Memora.\n\n## [2.1.4] - 2026-11-17\n\nMnemo's pages open like files, a button takes you back to the latest\nmessage, and chats with news are marked.\n\n### Added\n\n- A scroll-down button in Mnemo's chat: it appears in the middle above the\n message box when the latest message is out of sight, and turns into \"New\n messages\" when a reply arrives while you are reading further up.\n- Unread chats: the sidebar's Mnemo item (and its menu entry) shows how many\n chats have news you have not seen, and the Mnemo chat list marks each one\n with its number of new messages, in bold. Kept per device; a chat counts\n as read once it is open on screen.\n\n### Changed\n\n- An HTML or SVG answer now shows in the chat as a file card (title, kind\n and length, Open and Download). Opening it shows the page in a panel\n beside the chat on a wide screen, with the chat making room, and full\n screen on tablets and phones; the panel has Preview and Code, Copy,\n Download and a clear Close (Esc). A page Mnemo has just written opens\n beside the chat by itself when there is room.\n\n### Fixed\n\n- The \"Compacted\" divider sits in the middle of the chat column again (its\n own margin overrode the column's centring).\n\n## [2.1.3] - 2026-11-17\n\nMnemo can answer with a picture: charts, diagrams and small pages show as a\nlive preview right in the chat.\n\n### Added\n\n- HTML and SVG answers: when a chart, graph, diagram, timeline or mock-up\n explains better than text, Mnemo writes one self-contained page and, once\n the reply is done, the chat shows it as a live preview (the eye) with Code,\n Copy, Download and Full screen. The page runs in a sandboxed frame with no\n access to your notes, your session or the network beyond scripts and\n styles from https, so it costs the server nothing. Older chats learn it\n too.\n\n### Changed\n\n- The divider where a chat's memory was compacted now just says\n \"Compacted\", centred between its lines on every screen size; open it to\n read the summary.\n\n## [2.1.2] - 2026-11-16\n\nMnemo fits your screen and rides out a provider that is down for a moment:\nfull width on phones, a text size you choose, and plain errors with Try again.\n\n### Added\n\n- Text size for Mnemo's chat: Auto, Small, Medium or Large, from Appearance\n in the chat list or Settings, Mnemo (kept per device). Auto is small on\n phones, so more fits on the screen, and medium elsewhere. Replies, your\n messages, questions, steps and thinking all follow it.\n\n### Changed\n\n- On phones Mnemo's replies drop the avatar beside them and use the full\n width, with equal margins on both sides; the timeline narrows into the\n right margin.\n- When a reply fails (the provider answers 503, 404, 401, 429, times out…)\n Mnemo says what went wrong in plain words with Try again (and Open\n settings when the key or model needs a look); the provider's full error\n shows only when you open it. In the console `/details` prints it.\n- A provider that is briefly down or busy (502, 503, 504, 429, a dropped\n connection) is asked again up to three times over about half a minute,\n with a note in the reply, before Mnemo shows an error; never once text has\n started to stream. An HTML error page from a proxy is cut down to its\n title in the error.\n\n## [2.1.1] - 2026-11-16\n\nMnemo asks before it guesses, works on its own when you let it, and takes\nmessages while it works.\n\n### Added\n\n- Mnemo can ask you a question with options listed one under another, and\n Other, which opens a box in the card for your own answer; its reply ends\n there and your answer goes on. Sending something else instead marks the\n question skipped. In the console the options are a pick list.\n- Permission: **Ask first** (the default: Mnemo reads freely, but a change to\n your notes waits until you approve it through one of its questions) or\n **Auto** (changes go ahead without asking and long jobs keep going, up to 40\n steps a reply). Switch it from the chip in the composer, Settings, Mnemo,\n or `/auto` and `/ask` in the console. Requests written with `@mnemo:` in a\n note count as approved.\n- A queue: what you send while Mnemo is answering waits above the prompt,\n can be reordered (arrows or drag) or removed, and goes out by itself when\n the reply ends (not after Stop). Ctrl/Cmd+Enter, or the Enter button on a\n queued message, steers the running reply instead: Mnemo reads it before its next\n step, and it shows inside the reply. While a reply runs the button is Stop,\n and turns back into Send (to the queue) as soon as you type.\n\n### Changed\n\n- On the Mnemo page notices appear at the top right, clear of Send and Stop.\n- The composer reads left to right: attach, the permission chip, then the\n model (with its pin) beside the memory ring and Send.\n- Mnemo's replies sit on a frosted card that stays readable over any chat\n background; the chat scrolls without a scrollbar (the timeline and the\n edge fades show where you are).\n- Thinking, steps and every other detail start closed; an open section keeps\n its header in view while you scroll through it, so it closes from anywhere.\n- A reply without approval runs up to 25 steps before it pauses (was 10).\n\n### Fixed\n\n- Mnemo no longer shows as \"key removed\" in Your AIs, nor greyed out in Live\n activity: it is built in. Your AIs lists five agents, with Show all for\n the rest.\n- The note panel's Contents and Details tabs, and Outline, Links, Mentions\n and Images, follow the reading theme, so they stay readable in every\n theme; the four tabs always fit, each count above its name.\n- A long note path no longer runs over the step's title and result.\n- The ⋯ on each chat in the list works on touch screens (iOS spent the first\n tap on a hover), and All chats opens a folded chat list.\n\n## [2.1.0] - 2026-11-16\n\nMnemo, a notes agent built into Memora, and images that live beside their\nnotes. The state database needs no migration: Mnemo keeps its chats, models\nand sealed API keys in a separate `assistant.sqlite3` beside it, so 2.0 can\nstill roll back by swapping the binary.\n\n### Added\n\n- **Mnemo**, the notes agent built into Memora. Add as many providers as\n you like, each with its own name and ID: OpenAI (Chat Completions or the\n Responses API), Anthropic (Messages) or any OpenAI-compatible server\n (OpenRouter, Groq, Ollama, LM Studio, vLLM…), with your own API key; the\n key is sealed on the server and never sent back. Each provider can be\n tested, switched off (its models leave the pickers) or deleted.\n Mnemo finds, reads, writes, tags, links, moves and tidies notes with\n Memora's own tools, under its own name in Activity. It has no web, shell,\n admin or delete-for-good tools.\n - A full-screen chat page at `/mnemo` (no app header or tab bar; close it\n with the X or Esc, or go back to Memora from the chat list) with a chat\n list (search, pin, rename, delete). Opening Mnemo (the menu, the floating\n button on every page, Ctrl/Cmd+J or \"Ask Mnemo\" on notes and folders)\n always starts a new chat, with the open note or folder ready to attach;\n earlier chats are in the list. Drag the button to either side; drop it on the X (or\n use its × on hover) to hide it on that device, and bring it back from\n More, Show the Mnemo button.\n - Thinking as the model writes it: Claude's and OpenAI's reasoning\n summaries, the raw reasoning that OpenAI-compatible servers send\n (`reasoning_content`, `reasoning`, `reasoning_details`; Mnemo asks for it\n and stops asking a server that refuses), and the `<think>` blocks open\n models such as DeepSeek-R1, Qwen and Hermes write into their answers.\n - Mnemo knows the time where you are (its `current_time` tool uses your\n device's time zone) and Memora's own documentation (`search_docs`,\n `read_docs`): it answers questions about Memora and links the Docs page\n it used.\n - Streaming replies with live thinking (where the provider shows it) and an\n Activity block per reply: each step as it happens, then what Mnemo did,\n how long it took and the notes it read or changed (tap to open).\n Wikilinks open notes. The composer rests as a one-line capsule and opens\n on focus with +, the model picker (pinned first, hidden left out), a pin\n that makes the model the default for new chats (browser and console) and\n the memory ring. A timeline rail at the right edge, in thumb reach, has a\n bar per question: tap one to jump, hover it, or press and slide along the\n rail to scrub through the chat (the bars swell under the finger, a label\n names the question, phones tick). The transcript fades under its edges\n while you scroll.\n - Each chat keeps its whole conversation for its model. Near full, Mnemo\n folds the older messages into a summary written by the same model and\n carries on (a marker in the chat opens the summary); the memory ring\n shows how full the chat is, where compaction starts, and compacts on\n request.\n - Attach notes, folders and images to a message with + (or paste and drop\n images): they show as chips above the prompt, each with an ×, in one row\n that slides left and right (arrows on wide screens, no scrollbar). Up to\n four images per message; tap one to preview it. Images go to the model\n as real image input (OpenAI, Responses and Anthropic formats), so it can\n see them; a model without vision gets their names and a notice. Mnemo\n can also put an attached image beside the note it belongs to with its\n `place_image` tool. A big folder or the whole vault goes along as a list\n that Mnemo reads one note at a time, in batches, saying how far it got.\n - In the chat, the pictures that came with a message are tiles (tap for\n the full view, with the others of that message) next to its note chips,\n in the order they were attached, in a sliding row. Under every reply a\n Related row lists what it changed, showed and read.\n - Models: fetch them from the provider, with the context window and\n reply limit it reports in its standard model list, or add them by name;\n pin, hide and pick a default (with no default, new chats take the first\n pinned model, the same one everywhere).\n - Settings, Mnemo: providers, models, your own instructions in plain\n words and the floating button. Temperature, limits and tool steps keep\n sensible defaults (and stay adjustable over `POST /api/assistant/prefs`).\n - Ask Mnemo inside a note: a line with `@mnemo: <request>` (the editor\n offers it as you type `@` or `/mn`; also in a quote or a list item, never\n in code) runs a few seconds after the note is saved. Each request gets a\n chat of its own, titled `@mnemo · <note>: <request>` and shown with an\n \"@ note\" tag, where its steps and thinking stay; then Mnemo strikes the\n request through\n (`~~@mnemo: …~~`) and quotes its reply right under it; a struck request\n never runs again. Agents can ask the same way with\n `mention_agent` and agent `mnemo`.\n - Every chat has its own address (`/mnemo/<id>`): a reload, a link or Back\n opens the same chat. A new chat is called \"New chat\" until Mnemo's first\n reply, then the model names it in a few words in your language (a chat\n you renamed keeps your name).\n - The Mnemo sidebar has an Appearance card: the theme switch (light, dark,\n system) and the chat background, picked from preview tiles: Glow (the\n default), Aurora, Mesh, Dusk, Dawn, Deep, Dots, Grid, Lines, Waves, Grain\n or Plain. Quiet and theme-aware (a touch stronger on dark), remembered\n per device.\n - \"In this chat\", a panel on the right (a drawer on smaller screens):\n every note, folder, image and the vault the chat attached, read, changed\n or showed, grouped, each opening on a tap. The chat list folds away on\n wide screens too; both are remembered.\n - Phones: the Mnemo page follows the part of the screen the keyboard\n leaves, so the composer stays right above it (iOS, Android and the\n installed app).\n - Replies keep going on the server when you leave: open another chat,\n leave the page or lose the network, and the reply goes on; its chat\n spins in the list, and opening it shows the reply still streaming (or\n done). Only Stop ends a reply early.\n - Regenerate under every reply, and Try again on every message of yours\n and on errors: the turn runs again with the chat's model (later turns\n are replaced, after you confirm).\n - Mnemo hands things over: with its `show_items` tool, notes, folders,\n images or the whole vault appear as cards in its reply that open on a\n tap. The model picker links straight to Settings (Manage models and\n providers).\n - Export a chat: Download as Markdown, or Save as a note (in \"Mnemo\n chats\"), from the chat's menu; `/export` in the console.\n - Search every chat: the chat list's search box finds words in what you\n and Mnemo said (and in titles), marks them, and opens the chat at the\n message. Mnemo can look back too, with its own `search_chats` and\n `read_chat` tools, when you refer to an earlier conversation.\n - Mnemo has its own activity (Mnemo page, Activity; or its row on the\n Activity page): every tool call, each marked with who it was for and how\n it was asked (\"owner · chat\", \"owner · console\",\n `research-bot · @mnemo in Inbox`). Activity events carry this as `for`.\n - The console has it too: `/mnemo` chats with the same Mnemo (same chats,\n models and keys), shows its thinking and a summary of each reply, and\n takes `/attach` (a note or folder) and `/image` (a picture file),\n `/pin` (this model for new chats), `/memory`, `/compact`, `/activity`,\n `/search` and `/retry`, and opening a chat with a reply still running\n streams it;\n `/mnemo setup` adds, tests, switches and deletes providers and manages\n models.\n - Routes under `/api/assistant/` (signed-in browser only; API keys are\n refused). See docs/API.md.\n- **Images beside notes.** Upload PNG, JPEG, WebP or GIF from the editor\n (button, paste or drop). An image is stored in the note's own folder and\n shown with `![alt](path:name.png)`; a `path:` to an image in another\n folder is copied beside the note on save, so a note never points across\n folders. URLs still work.\n - Images follow their note: moved with it, soft-deleted to the Trash with\n it, restored with it (to the same or another folder) and deleted for\n good with it. An image another note in the folder still shows is kept.\n - A gallery view of a folder's images (that folder only), and an Images\n tab beside a note (this note or its folder). The viewer shows which\n notes and sections show an image and opens the note at that spot.\n - Settings, Images: the largest upload (0.1 to 50 MB, 5 MB by default)\n and how much notes and images take.\n - MCP tools `upload_image` and `list_images` (77 tools in all), and\n `POST /api/vault/image`, `POST /api/vault/image/delete`,\n `GET /api/vault/images`, `GET /api/vault/storage`,\n `GET|POST /api/settings/media`.\n- Reading settings offer nine colours (from paper and sepia to night and\n high contrast), nine fonts (including Literata, Atkinson Hyperlegible,\n Nunito, IBM Plex and OpenDyslexic, served by Memora itself) and nine text\n sizes.\n- The sidebar can be dragged wider (up to 440 px) while it is open;\n double-click the edge to reset. Collapsing works as before.\n- Version history shows a calm loading animation while it reads.\n\n### Fixed\n\n- Staying signed in while you work: the browser's session cookie used to keep\n the lifetime it got at sign-in, so it was dropped after the idle timeout (3\n hours by default) however active you were, although the server kept the\n session alive. Every request now renews the cookie too (at most every five\n minutes), and an open, visible tab you are using renews it while you read\n or scroll. An idle or hidden tab still signs out after the timeout.\n- The Brain, Graph and Canvas toolbar no longer lets the search box, its\n shortcut and the badges overlap or spill out on medium widths. On phones\n the search is a plain \"Search\" pill, and touch screens no longer show the\n \"/\" keyboard hint.\n\n### Security\n\n- SQLite updated (bundled with `rusqlite` 0.41 / `libsqlite3-sys` 0.39) for\n RUSTSEC-2026-0459.\n\n## [2.0.1] - 2026-10-24\n\nA calmer reader. Notes read like a clean page whatever the reading settings.\n\n### Changed\n\n- Note text has a new type scale: clearer headings, even list spacing,\n quieter code, quotes and tables, and real check boxes for tasks.\n- The side panel beside a note has two tabs, Contents and Details. Contents\n has its own tabs for the outline, links and mentions.\n- Reading settings keep the choices that look right on every system: Sans,\n Serif and Mono; Default, Sepia and High contrast. Justified text, the\n Rounded and Legible fonts and the Night, Paper and Mint colours are gone;\n a saved choice moves to the nearest one left.\n\n## [2.0.0] - 2026-10-24\n\nA redesign of every page around one calm look, with new tools where people\nspend their time: version history for notes, tag patterns, an Activity summary\nand a cleaner way to read. The license changes to the GNU AGPL. The state\ndatabase needs no migration: a 1.3 install updates in place and can roll back\nby swapping the binary.\n\n### Added\n\n- Version history for every note: browse versions with who made them, preview\n one, compare it with the current text and restore it. Restoring adds a new\n version, so nothing is lost. Over HTTP: `GET /api/history`,\n `GET /api/note-at`, `GET /api/diff` and `POST /api/history/restore`; the MCP\n tool `get_history` now also returns `version` and `total`.\n- A Trash page at `/trash`: restoring asks where the note goes (its folder,\n another folder or the top level), and deleting for good asks you to type\n DELETE (DELETE ALL to empty the Trash).\n- Tags: pick or tick tags to see their notes at once, preview a note in the\n map's card, merge, rename or remove tags in bulk, and find notes by a\n pattern of tags joined with and, or and not.\n- Activity is a summary page (numbers, actions over time, what agents do most,\n problems, most touched notes, agents) with every action on its own\n Timeline tab at `/activity/timeline`. An agent's activity lives on its own\n page at `/agents/<id>/activity`.\n- Reading: Contents (outline, links, mentions and details) beside the note,\n and a fold-away toolbar (F) for a clean page.\n- Maps: a clean view that hides every control (C), a dot grid switch, note\n titles on the maps, and a first-setup guide while the vault is empty.\n- Settings: edit the server name and how long browsers stay signed in\n (`POST /api/settings/server`, admin); the folder switch says what moves\n with each notes folder.\n- What's new: the notes of each release, shown once after an update and from\n the profile menu or Settings, Version, with a quiet link to star the project.\n- New notes keep their title as the file name, spaces included, and the web\n app shows display titles (front matter title or first heading).\n- Refused MCP calls are logged, so Activity and the Overview can show what an\n agent tried and was not allowed to do.\n\n### Changed\n\n- **License: GNU AGPL v3.0 or later** (was MIT). You may use, modify and share\n Memora, including commercially; a modified version that you distribute or\n run as a service must publish its source and keep the attribution in\n `NOTICE` (\"Based on Memora by Codrihub Tech\"). The name and logo are covered\n by `TRADEMARK.md`. Versions 1.3.8 and earlier stay MIT.\n- Every page is redesigned: Overview, Brain, Graph and Canvas, Notes and the\n reader, Tags, Activity, Agents, Trash, Settings, Docs, sign-in, welcome and\n setup, with layouts for tablets and phones and the Geist typeface.\n- Deleting a note for good also erases it from the vault's version history,\n so no one, agents included, can read it again. Other notes keep their\n versions; their revision ids change.\n- Deleting a note for good over HTTP (`POST /api/delete` without\n `mode: \"trash\"`) needs an admin key, like MCP `delete_memory` with\n `permanent`. Moving to the Trash is unchanged.\n- Notes saved from the web app are committed with the signed-in user as the\n author, so version history can tell people from agents.\n- The theme follows the device by default, sign-in and setup included.\n- The release check also reads the repository's star count (off with\n `MEMORA_UPDATE_CHECK`, like the release check itself).\n\n### Fixed\n\n- An unused setup or reset code that ran out locked the instance; it now goes\n back to idle, and locks older versions took on expiry are lifted.\n- Activity summarised only the newest 800 events whatever range was chosen.\n- The update offer appeared when nothing had changed; it now follows a\n content hash of the built app.\n- Pins are checked again right after the notes folder is switched.\n\n### Performance\n\n- Signed-in `GET` answers under `/api/` are gzip-compressed (pages, writes,\n sign-in and `/mcp` are not), about a twelfth of the size for activity pages.\n- Activity shows the newest page at once, fills the range behind it and\n remembers each range.\n- The boot splash is plain HTML that paints at once and leaves as soon as the\n app is ready.\n\n\n## [1.3.8] - 2026-10-21\n\nA security and reliability pass: dependencies checked against published\nadvisories, Memora's own code reviewed for common vulnerability classes, and a\nlong load test for leaks. This covers what was found; it is not a guarantee\nthat nothing else is there.\n\n### Security\n\n- Dependencies: updated rustls-webpki (RUSTSEC-2026-0382) and webpki-roots\n (RUSTSEC-2026-0381), used by the release check and OAuth metadata fetch, and\n zip (RUSTSEC-2026-0367, -0368, -0369; Memora never extracted archives, so it\n was not exposed). `cargo audit` and `npm audit` now run in CI, Dependabot is\n on, GitHub Actions are pinned to commits, and the Docker image is based on\n Debian 13.\n- A note containing a crafted embed could crash the server every time it was\n viewed. Fixed.\n- Behind a reverse proxy, a client-sent `CF-Connecting-IP` or `X-Real-IP` could\n choose the caller's address, including `127.0.0.1`, and skip sign-in rate\n limits. Memora now uses the right-most `X-Forwarded-For` entry that is not a\n trusted proxy and ignores loopback addresses in headers.\n- Many failed sign-ins no longer lock the owner out: the server slows down\n instead, and a correct password from a device without recent failures still\n works. A wrong setup code no longer closes the setup window on the first try.\n- OAuth client registration is rate-limited per address and unused clients are\n removed after an hour. The public client metadata fetch also refuses IPv4\n addresses wrapped in IPv6 (such as NAT64).\n- Paths that pointed at `.git` or other store files through a symlink or a\n Windows short name (`GIT~1`), and respelled paths that slipped past soft\n locks, are refused. Windows device names, `:` streams and trailing dots or\n spaces are refused too.\n- Privacy rules now also cover the trash, the activity log of `create_memory`,\n the history of a hidden note's former path, and `import_memory` replies.\n- Text replacements (`bulk_replace`, patch `replace`, templates) are capped so\n they cannot exhaust memory.\n- `/logout` accepts POST only, with the same-origin check. `/_bus` refuses\n requests made by a browser.\n- Folder colours and icons read from `.folders.json` are validated.\n- The state folder is tightened to owner-only, and Memora's own files in the\n vault (`.events.jsonl`, `.locks.json` and others) are created owner-only.\n\n### Fixed\n\n- `memora.log` grew without limit (one line per MCP request); it is now\n bounded. The server raises its open-file limit so connection spikes do not\n run out of file handles.\n- Memora's own files (`.events.jsonl`, `.locks.json`) were committed to the\n vault's git history on every write.\n- The activity log endpoint kept every parsed event of its window in memory.\n- Leaving the Brain view kept its node card and controller in memory, and a\n paused Activity page queued events without limit.\n\n### Changed\n\n- The npm package needs Node.js 22 or newer (18 and 20 no longer get security\n updates).\n\n## [1.3.7] - 2026-10-21\n\n### Added\n\n- Drag and drop in the sidebar tree, with the mouse, a pen or touch (hold for a\n moment, then drag): drop on a folder to move into it, on a note to move into\n that note's folder, or on \"All nodes\" to move to the top level. A hint says\n where the item will go, places it cannot go are marked, the list scrolls when\n you drag near its top or bottom edge, and a closed folder opens when you hold\n over it. Every drop asks \"Move \"X\" to \"Y\"?\" first; Escape cancels a drag.\n- A folder picker shaped like the sidebar tree in New node, Move to, Move\n contents to and the folder delete dialog: expand and collapse, keyboard\n navigation, and a search that finds folders by name or path at any depth.\n- `GET /api/folders` lists every folder you can see, empty ones included.\n\n### Changed\n\n- Very deep folder trees stay readable: indentation stops growing after six\n levels and deeper rows show their level; long names end with an ellipsis and\n show the full path on hover.\n\n### Fixed\n\n- A new subfolder could not be chosen in New node (it only listed top-level\n folders), and empty folders were missing from the sidebar, Move to and the\n folder delete dialog.\n- A word made only of digits after `#` (for example \"PR #2\") was read as a tag.\n- The sidebar kept jumping back to the top when the tree redrew.\n\n## [1.3.6] - 2026-10-21\n\n### Added\n\n- Rows in the sidebar have a \"⋯\" button that opens the same menu as a right\n click. It shows on hover and keyboard focus, and always on touch screens.\n- Copy path and Copy wikilink in every note and folder menu (sidebar, Nodes list,\n node cards and the reader), so you can point an agent at an exact note. Copy\n wikilink now copies the full path, e.g. `[[Projects/Launch plan]]`.\n- Deleting a folder that holds notes now asks what to do with them: move them to\n the parent folder, the top-level folder, Root or any other folder, or send\n everything to `.Trash`. The MCP tool `delete_folder` and `/api/delete-folder`\n take the same choice as optional arguments (`into`, `mode: \"trash\"`); without\n them nothing changes.\n- An \"Update & uninstall\" guide in the documentation (web, console and\n `docs/INSTALL.md`), including how to remove versions before 1.3.2 by hand,\n safely: it stops Memora, removes only Memora's program and state folder by\n exact path, asks before deleting, and keeps the vault unless you choose\n otherwise.\n- A real \"Page not found\" / \"Node not found\" view instead of a silent redirect\n to Overview.\n\n### Changed\n\n- Windows is installed with npm (`npm install -g @codrihub/memora`); releases no\n longer carry a separate Windows zip. The npm package for Windows x64 is built\n and tested as before. Zips of 1.3.0 to 1.3.5 stay on their release pages.\n- The note delete dialog says plainly that a note is deleted for good (there is\n no trash for single notes) and when an agent can still restore it.\n- `memora-cli update`, `/update` and `/restart` detect how Memora was installed\n (npm, Docker, the installer, a release folder or a source build) and give the\n matching steps. The npm launcher and the Docker image set `MEMORA_INSTALL`.\n- `memora-cli help` lists start, stop, restart, update and uninstall, and an\n unknown command prints the version and points to `memora-cli update`.\n\n### Fixed\n\n- An npm install was reported as \"built from source\" by `/update`, and\n `/restart` suggested systemctl on Windows.\n- `memora-cli start`, `stop`, `restart` and `uninstall` without `--state` could\n act on another install's running server (for example a systemd service). They\n now name the state folder and service first, and refuse to drive a service\n that belongs to a different kind of install.\n- `#tags` inside inline code, code blocks, URLs (`…#install`) and link targets\n were read as tags, and a tag written twice was listed twice. Tag rename and\n merge no longer rewrite text in code or URLs either.\n- Activity: rows of read-only calls (including `pin`/`unpin`) no longer stay\n \"running\"; the Live popover only says \"now\" for agents that are active; agent\n colours match everywhere; counts that may be cut off by the log limit show\n \"2,000+\".\n- The sidebar footer lines no longer overlap when they switch.\n- Nodes list excerpts load as rows come into view instead of queueing; folder\n paths and tags end with an ellipsis on phones.\n- Agent labels in the brain no longer cover the map controls on phones, and the\n Overview Agents card no longer shows 0 while loading.\n\n## [1.3.5] - 2026-10-20\n\n### Fixed\n\n- Memora slowed to a crawl under steady agent traffic: with a few hundred notes\n and a few MCP calls per second, the web UI (tree, notes, agents) took tens of\n seconds to answer. Tag lookups (`search_by_tag`, `list_tags`) re-rendered every\n note while holding the vault lock, MCP calls and vault reads blocked the\n server's async workers, and the note view walked the vault once per link. Tag\n lookups now read the note cache, reads run off the async workers on a snapshot\n of the vault, and a write refreshes only the note it changed. Under the same\n traffic the tree and note requests answer in about 20 ms instead of 20-35 s.\n- The node card in Brain, Graph and Canvas no longer flashes its loading state\n and refetches the note on every realtime update; it refreshes only when that\n note changes.\n- The Tags page builds its index in one request instead of one per note.\n\n## [1.3.4] - 2026-10-20\n\nEvery MCP tool was tested against bad, missing, hidden and extreme input. This\nrelease fixes what that found. Some calls that used to be accepted, and did\nsomething other than what was asked, are now refused with a clear message.\n\n### Added\n\n- Agent instructions come in five styles: Balanced (recommended), Remember\n everything, Private, Session journal and Read only, each in a full and a\n short version, on the docs page, in the connect guide and in the console.\n Remember everything warns that secrets end up as plain Markdown and how to\n hide them with privacy rules. Where to paste covers more clients.\n- The live panel in the header opens an agent's page; in Activity, an agent's\n name on any row, the event drawer and an agent's activity page do too.\n- `list_trash` (MCP): the notes in the trash, with where they came from.\n- Version history can be turned on with a plain `git init` in the vault;\n `docs/CONFIGURATION.md` explains how.\n\n### Changed\n\n- `tools/call` checks arguments against the tool's schema: unknown names,\n missing required arguments, wrong types, values outside an enum and numbers\n below the minimum are refused. Every tool error starts with the tool name.\n- Search no longer keeps a `.fts.db` index. Search and the graph, query and\n digest tools read one in-memory cache that follows the files on disk, so\n results are right at startup and include notes changed outside Memora.\n Old `.fts.db` files are removed.\n- `bulk_delete` moves notes to the trash, and refuses the whole call when any\n path is wrong. `restore_trash` puts a note back where it was.\n- Moving or renaming a note or folder rewrites the wikilinks that pointed to\n it, in MCP and in the web UI; results report `links_updated`.\n- `delete_folder` moves notes to the parent folder and keeps their subfolders.\n- Soft locks are enforced: an agent cannot write to a note another agent has\n locked, and only the holder (or the owner) can release a lock.\n- Tags may contain letters, digits and `- _ / .`; tag tools ignore case.\n Frontmatter fields refuse line breaks.\n- `follow_ups` returns `{notes, count, truncated}` and takes `limit`; it also\n counts `waiting` and `blocked`. `digest` reports all events and takes `limit`.\n- Export and import use an exchange folder inside the state folder (0700),\n not a folder shared by every instance in `/tmp`.\n- `template_create` only reads templates from `Templates/`.\n\n### Fixed\n\n- `move_memory` without `folder` moved the note to the top level, and\n `create_memory` with an unknown argument created the note somewhere else.\n- `bulk_replace` with an empty `find` inserted text between every character.\n- Tags or fields with line breaks or YAML characters could break a note's\n frontmatter; `mention_agent` could add fake mention lines.\n- `privacy_set` with an empty agent list removed the rule, exposing a hidden\n folder; an agent could take another agent's display name or \"owner\".\n- An agent could release or create locks in another agent's name.\n- `template_create` could read any note, including hidden ones.\n- Search snippets mixed highlight tags with raw note HTML.\n- `get_subgraph` reversed edges, dropped one side of two-way links and\n returned one node too many; nested folders were ignored by `query_memory`,\n `digest`, `bulk_replace` and `bulk_delete`; `list_memory` showed nested\n notes under their top-level folder.\n- `merge_memory` skipped missing sources silently, merged a note into itself\n and pasted frontmatter into the body; `batch_create` ignored typos.\n- `create_folder` accepted `Root`; `move_folder` into a note created a folder.\n- History tools returned empty results when the vault has no git repository;\n they now say version history is off. `snapshot` explains its refusals.\n- Many tools returned an empty success for paths that do not exist; they now\n say what is missing.\n- Parallel calls of one tool could close each other's rows in Activity.\n- `batch_create` did not tell open browsers about the notes it created.\n\n## [1.3.3] - 2026-10-20\n\n### Added\n\n- Agents see new tools without reconnecting. The MCP session id now carries\n the tool catalog it was issued for; when tools are added or switched off\n (after an update, or in Settings), the next request on an older session is\n answered as a short SSE stream that first sends\n `notifications/tools/list_changed`, once, and then the normal response.\n `initialize` advertises `tools.listChanged: true`. Old sessions are never\n refused, so clients that do not re-initialize keep working. This is what\n made `list_pins`, `pin` and `unpin` missing for agents connected before\n 1.2.2.\n- Pins animate when they are added, moved or removed, in every open browser,\n and a toast names the agent or person who pinned or unpinned (following the\n activity toast setting).\n- `memora-cli stop` stops a background server gracefully on every OS through\n `POST /_stop`, a loopback-only request that needs the token the server\n writes to `<state>/stop.token`. It falls back to SIGTERM or `taskkill`.\n\n### Fixed\n\n- Windows: `memora-cli stop` without `--force` could not stop a server it\n started, because Windows refuses a polite `taskkill` for a process without\n a console.\n- Windows: `memora-cli start` handed its console pipes to the server, so a\n script or CI step reading its output waited until the server exited.\n- Windows: the vault chooser in the browser (first run and Settings) refused\n paths such as `C:\\Users\\you\\memora`; it accepts drive and UNC paths.\n- Windows: `memora-cli db backup` always failed with \"Access is denied\",\n which also stopped the final backup during uninstall (nothing was\n deleted). `db restore` finds a server started by `memora-cli start` and\n says clearly when the database is in use.\n- Windows: paths are stored and printed without the `\\\\?\\` prefix\n (`memora-cli vault`, uninstall output, the npm assets path in the log).\n- Windows: Ctrl+C in the console restores the console input mode, so the\n shell never stays without echo after a password prompt.\n\n## [1.3.2] - 2026-10-20\n\n### Added\n\n- `memora-cli start`, `stop` (`--force`), `restart` and `uninstall`, and\n `/start`, `/shutdown` (alias `/stop`), `/restart` and `/uninstall` in the\n console. They detect how the install runs: a systemd service is driven\n with `systemctl`; an npm, release zip or source install runs the server in\n the background with `memora.pid` and `memora.log` in the state folder;\n inside Docker the console prints the host commands.\n- Uninstall explains what it removes, then offers a checklist (space to\n select) to also delete the settings and accounts and the vault. Both are\n kept by default; deleting the vault needs its folder name typed, a final\n database backup is offered before the state goes, and system folders, the\n home folder and the program folder are never deleted. Without a terminal\n it needs `--yes` and only deletes what `--delete-config` and\n `--delete-vault` say.\n- `/guide` gains a \"Run and manage the server\" step; `memora-cli docs manage`\n covers it per install.\n\n### Changed\n\n- The install guide's introduction names Windows and the npm and zip\n installs and leads with `memora-cli setup`.\n\n## [1.3.1] - 2026-10-20\n\n### Added\n\n- Shut the server down from the browser: Settings, Server, Shut down (owner\n only, after a confirmation). The server stops gracefully and exits with\n status 0. When systemd (`Restart=always`) or Docker starts it again, the\n confirmation says so and shows the stop command to use instead.\n `POST /api/server/shutdown` refuses API keys and cross-site requests.\n- One floating back-to-top button on every scrolling page, at the bottom\n right and above the tab bar on phones.\n\n### Changed\n\n- The welcome screen of a new instance is a wider two-column card, and its\n steps use `memora-cli setup` (it prints the code and the link) with the\n install's own command prefix.\n- At tablet widths the profile menu opens as a popover next to the sidebar\n instead of a bottom sheet.\n- README and the install guide list start, stop and restart per install.\n\n### Fixed\n\n- Code in reading themes: inline code and code blocks take the theme's\n colours (Paper on the dark app was 1.3:1, now about 12:1).\n- The `web/node_modules` symlink of a work tree slipped into 1.2.3; it is no\n longer tracked and the ignore rules now match a folder or a link.\n\n## [1.3.0] - 2026-10-19\n\n### Added\n\n- Native Windows support: `memora` and `memora-cli` build and run on Windows\n 10/11 (x64), and `npm install -g @codrihub/memora` installs the new\n `@codrihub/memora-win32-x64` package there. The release workflow builds it\n with a static C runtime.\n- A Windows zip on every GitHub release\n (`memora-<version>-x86_64-windows.zip`, listed in `SHA256SUMS`) with\n `memora.exe`, `memora-cli.exe` and the web UI: unzip and run, no installer\n or Node needed.\n\n### Changed\n\n- On Windows, `memora-cli` runs database work in-process (there is no root\n privilege drop), reports state files as private, and finds `sqlite3.exe`\n on `PATH` for `db shell`.\n- The vault folder may be a Windows absolute path (`C:\\...` or\n `\\\\server\\share`). Migration 8 rebuilds the `settings` table so the\n database accepts it; Unix paths are unchanged. On Windows, system folders\n (`%SystemRoot%`, `%ProgramFiles%`, `%ProgramData%`) are refused as vaults.\n- `memora` finds its web UI in an `assets` folder next to the executable\n (an unpacked release zip or tarball) when `MEMORA_ASSETS` is not set.\n\n### Fixed\n\n- The Windows system-folder check compares paths without regard to case, so\n `C:\\Windows` is refused even when `%SystemRoot%` reads `C:\\WINDOWS`.\n\n## [1.2.3] - 2026-10-19\n\n### Added\n\n- Pins are saved on the server instead of in each browser. They follow a\n note or folder when it is renamed, moved, trashed or deleted (including\n everything inside a moved folder), show on every device, and update live\n in open browsers. A pin whose item disappeared outside Memora stays\n visible as \"Not found\" with a remove button. Existing browser pins are\n uploaded once. Migration 7 adds the `pin` table.\n- Pins over HTTP (`GET`/`PUT /api/pins`, `POST /api/pins/pin`,\n `POST /api/pins/unpin`, signed-in owner only) and over MCP: `list_pins`\n (read), `pin` and `unpin` (write), under the usual key scopes, tool grants\n and privacy rules.\n\n### Changed\n\n- Install in three steps: one command (the installer, a single\n `docker run` with named volumes, or npm), `memora-cli setup` for a\n one-time code, then the link it prints. README, the install guide and the\n in-app Get started page lead with it.\n- The desktop sidebar is a little wider (288 px) and the profile menu fits\n its width. While dragging onto Pinned, only the drop box is highlighted.\n\n### Fixed\n\n- `patch_memory`: an op missing a required field is an error instead of an\n empty value. A `replace` without its replacement used to delete the\n matched text; an empty `find` or one that matches nothing now fails too.\n `replace` accepts `replace` as an alias of `with`, and the tool\n description lists every op and its fields.\n- Wikilinks written as `[[target\\|alias]]` (the escape used inside tables)\n no longer count the backslash as part of the target, so the graph,\n backlinks and broken-link checks see the right note.\n- `docker-compose.yml` pointed at an old image; it now follows the release.\n\n## [1.2.2] - 2026-10-19\n\n### Added\n\n- npm install for Linux x86_64 and arm64: `npm install -g @codrihub/memora`\n provides the `memora` and `memora-cli` commands. npm picks the matching\n `@codrihub/memora-linux-x64` or `-linux-arm64` package with the prebuilt\n release binaries; nothing is downloaded by an install script. The web UI\n ships in the package. Other platforms get a clear message pointing to\n Docker or a source build. The release workflow builds, smoke tests and\n publishes the packages at the release version when the `NPM_TOKEN` secret\n is set.\n- `memora-cli update` recognises an npm install and prints the npm command\n to update it.\n\n## [1.2.1] - 2026-10-19\n\n### Changed\n\n- Each agent has its own page at `/agents/<id>` with tabs for Overview,\n Setup, Activity, Access and Settings, each with its own address, instead\n of a long sheet. Overview shows its stats, recent calls, app, access and\n key; Activity groups calls by day with search, status and range filters.\n- An agent's app is locked once it is known. Setup shows only that app's\n guide; there is no switching an agent to another app any more. A guessed\n app is confirmed once, and an agent without an app picks it once. For\n another app or device, create a new agent.\n- New agents are made on a page at `/agents/new` with a stepper that stays\n in view, a summary panel, and a recommendation of one agent per app or\n device so Activity shows who did what. Old `/agents#connect` links still\n work.\n\n### Fixed\n\n- Tables: an aliased wikilink such as `[[Folder/Note|name]]` in a cell no\n longer splits the cell and adds a column. Escaped pipes (`\\|`) work, and\n rows with too few or too many cells fit the header.\n\n## [1.2.0] - 2026-10-18\n\n### Added\n\n- Settings, Notifications: turn agent activity toasts off for every agent,\n or for single API keys. The main switch always wins: when it is off, no\n activity toast appears, even for keys that are turned on.\n- Node editor: Save and Cancel buttons. On phones they sit in a large bar\n pinned to the bottom of the screen while editing. Cancel asks before\n discarding changes, Esc cancels, and Ctrl+S saves without closing.\n\n### Changed\n\n- The node editor no longer saves while you type; changes are saved with\n Save or Ctrl+S, and closing the tab with unsaved changes asks first.\n Leaving the node still keeps your changes.\n\n## [1.1.5] - 2026-10-18\n\n### Fixed\n\n- Folder icons given by name (for example `credit-card`, `cpu` or `key`, as\n agents often set them) showed the name as text. More icons are built in,\n common names and aliases map to them, and an unknown name falls back to\n the folder icon. The `set_folder_meta` MCP tool lists the icon names.\n\n## [1.1.4] - 2026-10-18\n\n### Fixed\n\n- \"On this page\" in the node reader and the documentation: the last\n sections are now marked when scrolled to the bottom, a clicked entry is\n marked right away and stays marked while the page scrolls to it, and the\n current section is picked earlier while scrolling.\n\n### Changed\n\n- README: a centered header with the logo, badges and links, and screenshots\n as JPEG so they display everywhere.\n\n## [1.1.3] - 2026-10-18\n\n### Fixed\n\n- After an update, a normal reload or a hard reload could show the offline\n page. The service worker now only serves the offline page when the server\n really cannot be reached (after a retry); pages, scripts and styles always\n come from the network, the app script URL carries a content hash, and the\n service worker itself is never served from the HTTP cache.\n- The offline page retries on its own and returns as soon as the server is\n back.\n\n## [1.1.2] - 2026-10-18\n\n### Changed\n\n- Agents & API keys page redesigned: a stats strip (agents, active now, calls\n in 24 hours, MCP endpoint), and an agents list that is a table on wide\n screens, condensed rows on tablets and cards on phones, with the app each\n agent uses, its status, access summary, a 24-hour sparkline and last call.\n- Clicking an agent opens a detail sheet with its stats, the app it is used\n with, access, key details, activity and every action (rename and color,\n show key, new key, turn off or on, delete, edit permissions, set up again).\n- Connecting an app: pick the app, name the agent and choose Read & write,\n Read only or Custom access, then follow the setup with the new key filled\n in and a live \"Connected\" check. Setting up an existing agent goes straight\n to its app, with an inline unlock for a sealed key.\n- Permissions editor: a live summary, capability toggles with plain\n descriptions, and a searchable tool picker grouped by category.\n- Every dropdown in the web UI is a custom, keyboard-accessible select that\n works inside sheets and opens as a bottom sheet on phones.\n\n## [1.1.1] - 2026-10-18\n\n### Added\n\n- Documentation in the web UI at `/docs`: getting started, agent\n instructions, connecting agents, install, configuration, MCP, a live tool\n reference, API, security, deployment, architecture, database, changelog and\n keyboard shortcuts, with search, an on-page table of contents and copy\n buttons. Reachable from the profile menu, the help dialog, the search\n palette and Settings.\n- `/docs` in the setup console and `memora-cli docs [topic]`: the same topics\n in the terminal, including the recommended agent instructions.\n- Recommended agent instructions (a full and a short prompt) that tell an\n agent to recall from Memora before answering and to save what is worth\n keeping, with where to paste them for each client.\n\n### Changed\n\n- Connecting an app is a four-step wizard (app, key, set up, instructions)\n instead of a sideways carousel: searchable app grid, inline key creation,\n filled-in config with a copy button, a live \"Connected\" check and the\n agent instructions. `/agents#connect` opens it directly.\n\n## [1.1.0] - 2026-10-18\n\n### Changed\n\n- Search engines and AI crawlers are kept out of every page: `robots.txt`\n now disallows the whole instance (with explicit rules for common AI\n crawlers), and every response and page carries\n `noindex, nofollow, noarchive, nosnippet, noimageindex`.\n- README: one-command install and screenshots of the web UI.\n\n## [1.0.0] - 2026-10-18\n\nFirst public release.\n\n### Added\n\n- Vault of plain Markdown files with folders, wikilinks, tags, backlinks,\n pins, trash and history.\n- MCP server over Streamable HTTP with 71 tools (read, search, write, organize,\n graph, interop) and admin tools for keys and tool switches.\n- API keys per agent with scopes (`mcp`, `read`, `write`, `admin`), per-key tool\n lists, global tool switches, key rolling and revocation. MCP tools that change\n the vault require the `write` scope.\n- OAuth 2.1 sign-in for MCP clients (authorization code with PKCE, dynamic\n client registration, client metadata documents).\n- Per-agent privacy for folders and notes; rules follow renames and moves.\n- Access rules by IP, network, range or domain, first match wins.\n- Web UI: Overview, Brain (3D), Graph, Canvas, Nodes with reader and editor,\n Tags, Activity with per-agent pages, Agents and API keys, Tools, Access rules\n and Settings; light, dark and system themes; installable PWA.\n- Activity log of every agent call with filters, export and retention settings.\n- State in one SQLite database (`<state>/memora.db`) with migrations, backup,\n restore and integrity check.\n- `memora-cli` with an interactive setup console (`/welcome`, `/setup`, `/web`,\n `/keys`, `/tools`, `/mcp`, `/status`, ...), one-time setup codes and updates.\n- Release check: the server looks up the newest GitHub release every 6 hours\n and the web UI shows when an update is available (`MEMORA_UPDATE_CHECK=false`\n turns it off).\n- Docker image, Docker Compose file and an installer script with checksum\n verification.\n\n[2.0.1]: https://github.com/Codrihub/memora/releases/tag/v2.0.1\n[2.0.0]: https://github.com/Codrihub/memora/releases/tag/v2.0.0\n[1.3.8]: https://github.com/Codrihub/memora/releases/tag/v1.3.8\n[1.3.7]: https://github.com/Codrihub/memora/releases/tag/v1.3.7\n[1.3.6]: https://github.com/Codrihub/memora/releases/tag/v1.3.6\n[1.3.5]: https://github.com/Codrihub/memora/releases/tag/v1.3.5\n[1.3.4]: https://github.com/Codrihub/memora/releases/tag/v1.3.4\n[1.3.3]: https://github.com/Codrihub/memora/releases/tag/v1.3.3\n[1.3.2]: https://github.com/Codrihub/memora/releases/tag/v1.3.2\n[1.3.1]: https://github.com/Codrihub/memora/releases/tag/v1.3.1\n[1.3.0]: https://github.com/Codrihub/memora/releases/tag/v1.3.0\n[1.2.3]: https://github.com/Codrihub/memora/releases/tag/v1.2.3\n[1.2.2]: https://github.com/Codrihub/memora/releases/tag/v1.2.2\n[1.2.1]: https://github.com/Codrihub/memora/releases/tag/v1.2.1\n[1.2.0]: https://github.com/Codrihub/memora/releases/tag/v1.2.0\n[1.1.5]: https://github.com/Codrihub/memora/releases/tag/v1.1.5\n[1.1.4]: https://github.com/Codrihub/memora/releases/tag/v1.1.4\n[1.1.3]: https://github.com/Codrihub/memora/releases/tag/v1.1.3\n[1.1.2]: https://github.com/Codrihub/memora/releases/tag/v1.1.2\n[1.1.1]: https://github.com/Codrihub/memora/releases/tag/v1.1.1\n[1.1.0]: https://github.com/Codrihub/memora/releases/tag/v1.1.0\n[1.0.0]: https://github.com/Codrihub/memora/releases/tag/v1.0.0\n"}]