Generated banner for Basic Memory
Generated logo for Basic Memory

Basic Memory

Memory serverOfficial Basic Machines project

Created by Basic Machines

Published in basicmachines-co/basic-memory. Publisher page

4,552 GitHub stars

What it is

AI conversations that actually remember. Never re-explain your project to your AI again. Join our Discord: https://discord.gg/tyvKNccgqN
— the description by Basic Machines

AutoGineer overview, from the brain’s own files

Basic Memory is a memory system designed to give AI agents persistent, long-term recall. It operates as an MCP server that bridges the gap between human-readable Markdown files and AI agent context. By treating a directory of Markdown files as a knowledge graph, it allows agents to read, write, and search information across sessions. It supports both local-first operation for privacy and an optional cloud-hosted service for cross-device synchronization. The system includes advanced features like semantic vector search, hybrid full-text retrieval, and a schema system for validating knowledge structure, ensuring that agents can reliably store and retrieve project context, learnings, and documentation.

How it works

Memory model: Hybrid

AutoGineer overview, from the brain’s own files

Basic Memory functions as an MCP server that monitors and manages a collection of Markdown files on your disk. It uses a hybrid memory model that combines standard file-based storage with a database layer (SQLite or Postgres) to enable semantic search and vector indexing. When an agent interacts with the server, it uses specific tools to ingest, curate, or retrieve information from these files. The system automatically handles file synchronization and provides metadata-rich search results, allowing agents to maintain context across different tasks and projects without needing to re-learn information.

Folders
FolderRoleFiles
.claudeagent-config15
.codexagent-config1
.githubagent-config20
docsdocs41
scriptsscripts16
skillsagent-instructions33
srcsource-code529
teststests595
.agentsfolder58
.claude-pluginfolder1
benchmarksfolder155
integrationsfolder175
pluginsfolder72
test-intfolder179

The agent reads

The agent writes

Requirements

Runtimes: Python >=3.12

Databases: Milvus, PostgreSQL, Redis, SQLite

API keys (by name): COHERE_API_KEY, OPENAI_API_KEY

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Google Antigravity, Kiro, OpenCode, Amp, Roo Code, Cline, JetBrains Junie, Devin (ex-Windsurf)

Set it up

  1. This brain runs code automatically: 4 hooks (claude-code, codex), 1 script. Review plugins/claude-code/hooks/hooks.json, plugins/codex/hooks/hooks.json, src/basic_memory/cli/commands/install.py before opening the folder in Claude Code. No step below turns a hook on for you.

    • plugins/claude-code/hooks/hooks.json: uv run --quiet --script "${CLAUDE_PLUGIN_ROOT}/hooks/session_start.py"
    • plugins/claude-code/hooks/hooks.json: uv run --quiet --script "${CLAUDE_PLUGIN_ROOT}/hooks/pre_compact.py"
    • plugins/codex/hooks/hooks.json: uv run --quiet --script "${PLUGIN_ROOT}/hooks/session_start.py"
    • plugins/codex/hooks/hooks.json: uv run --quiet --script "${PLUGIN_ROOT}/hooks/pre_compact.py"
    • src/basic_memory/cli/commands/install.py: python src/basic_memory/cli/commands/install.py
  2. Not scanned by AutoGineerIts dependencies are installed by pip or uv when you run it and were not scanned by AutoGineer (43 declared). https://pypi.org/project/basic-memory/
  3. Created by Basic Machines. Published in basicmachines-co/basic-memory. Licence: GNU Affero General Public License v3.0 only.

Usage

AutoGineer overview, from the brain’s own files

  • Connect the server to an MCP-compatible AI client like Claude Desktop, Cursor, or Codex.
  • Use natural language prompts to save project decisions, research findings, or daily logs directly into your memory vault.
  • Query the agent to retrieve specific information from past conversations or project documentation.
  • Edit notes manually in any Markdown editor while the agent simultaneously updates or references the same files.
“Create a note about our project architecture decisions.”
The agent creates a new Markdown file in the vault containing the documented architecture, which is then indexed for future retrieval.
“Find information about JWT auth in my notes.”
The agent performs a semantic search across the vault and returns relevant snippets or links to notes discussing JWT implementation.
“What have I been working on this week?”
The agent analyzes the recent file activity and notes to provide a summary of your progress and active tasks.

Documentation by Basic Machines

<!-- mcp-name: io.github.basicmachines-co/basic-memory -->

Image: MCP Toplist

Image: License: AGPL v3 Image: PyPI version Image: Python 3.12+ Image: Tests Image: Ruff Image: untitled Image: untitled Image: Ask DeepWiki

Skip the install — try Basic Memory in the cloud

Claude, Codex, or Cursor connected in 30 seconds. No Python, no JSON, no terminal. $15.00/mo locked in for life (12.50/mo yearly pricing). 7-day free trial — cancel any time before day 7 if it's not for you. Beta pricing — sign up now and your rate never goes up. OSS users: code BMFOSS takes another 20% off for 3 months.

Start free trial →

Basic Memory Teams is now available!

Give your team a single, shared cloud workspace. Knowledge isn't confined to one person — anything a teammate writes is immediately available to everyone else and to their AI assistants. Edit a note together in real time, hand work off between humans and agents, and build one connected knowledge base instead of scattered copies. Same pricing - start with one user and add more as needed.


Basic Memory

Your AI never forgets again.

Pick up right where you left off — in Claude, Codex, Cursor, ChatGPT, or anything that speaks MCP. Your knowledge lives as Markdown files that both you and your AI can read, write, and search.

  • Local-first. Plain text on your disk. Forever.

  • Two-way. AI and humans write to the same files; sync keeps them in step.

  • A real knowledge graph. Observations and wikilinks compound into context.

  • Semantic search. Find notes by meaning, not just keywords, with optional cross-encoder reranking for higher-quality vector and hybrid results.

  • MCP-native. Works with every major AI client and IDE.

  • Progressive tool discovery. Every tool is tagged with behavior hints (read-only, destructive, idempotent) so agents pick the right tool on demand — no wasted context trying things to see what they do.

  • Cloud, optional. Sync across devices when you want — never required.

Get started

Pick the path that fits you. Both run the same product on the same Markdown.

<table> <tr> <th width="50%">☁️ &nbsp; Cloud</th> <th width="50%">💻 &nbsp; Local install</th> </tr> <tr> <td valign="top">

30 seconds. Sign up, connect your AI client, done.

  • Works in any browser

  • Mobile, web, desktop

  • Cross-device sync built in

  • We handle hosting, backups, snapshots

$15.00/mo locked for life · 7-day free trial · cancel any time

Start free trial →

</td> <td valign="top">

2 minutes. Install, configure your AI client, run.

  • Free forever (AGPL-3.0)

  • All data on your disk

  • Air-gapped friendly

  • Requires Python via uv

uv tool install basic-memory --prerelease=allow

--prerelease=allow is required: Basic Memory 0.23 depends on a FastMCP 4 pre-release, and uv only accepts pre-releases of transitive dependencies when told to — without the flag it silently installs an older release. The same flag goes on every uvx / uv tool upgrade command below.

For Postgres deployments that store semantic vectors in Milvus, install the first-party optional extra instead:

uv tool install "basic-memory[milvus]" --prerelease=allow

Configure your client ↓

</td> </tr> </table>

What people are saying

Basic Memory changed my whole relationship with LLMs. I switched from GPT and Gemini to exclusively Claude and Claude Code because of this integration and am completely revamping all our company's processes around a Basic Memory workflow.

— Alex, TrainerDay

Basic Memory is the missing 'wow' factor in AI chatbots. Now I can't imagine Claude or Claude Code without it.

— Caleb, Caleb Picker Consulting

I don't code without Basic Memory anymore. It's such a time saver to be able to refer to projects I don't currently have active and keep a running log of all my learnings and ProTips.

— @groksrc, Developer

More on basicmemory.com.

Basic Memory Cloud

The hosted version of Basic Memory. Same product, same Markdown files, same MCP tools — we just host the database, run the sync, and put it on your phone.

What you get
  • Every device, same brain. Your knowledge graph on web, mobile, and desktop. No copy-paste between machines.

  • Connect any MCP client. Claude Desktop, Claude Code, Codex, Cursor, ChatGPT (Custom GPTs), VS Code — one-click connect from the web app.

  • Bidirectional sync to local. Edit on your phone, see it in Obsidian on your laptop. rclone-powered with conflict resolution.

  • Snapshots and backups. Point-in-time restore. Browse history. Never lose a note.

  • No lock-in. Your notes are plain Markdown. Export to local Markdown any time — same files, same format, same wikilinks. Cancel anytime, your data stays yours.

Built on WorkOS AuthKit, Neon Postgres, and Tigris S3.

Pricing

$15.00/mo, locked in for the life of your subscription (regular price $19). Sign up during beta and the rate never goes up — as long as you stay subscribed, you keep the price. One plan, no tiers, no surprise upgrades. Unlimited notes, unlimited projects, every feature.

  • 7-day free trial. Cancel any time before day 7 if it's not for you.

  • Cancel anytime after that too — export your notes whenever you want.

  • OSS users: code BMFOSS for another 20% off for 3 months (~$11.40/mo).

Start your 7-day free trial →

Cloud vs. local

CloudLocal
Setup time30 seconds2 minutes (requires Python)
Cost$15.00/mo, locked for life (7-day trial)Free
StorageWe host (Tigris S3)Your disk
Cross-device syncBuilt inManual (Git, Syncthing, etc.)
Mobile accessYes (web + app)No
Air-gappedNoYes
Your data stays yoursYes — export anytimeYes — already there
Source codeAGPL-3.0AGPL-3.0
Snapshots & backupsBuilt inRoll your own

Both paths use the same OSS engine and the same Markdown files. There's no lock-in either way — flip between them when your needs change.

Works with the tools you already use

ClientTransportNotes
Cloud web apphttpsSign in at basicmemory.com — no install
Claude Desktopstdio/httpsmacOS / Windows / Linux
Claude Codestdio/httpsclaude mcp add
Codexstdio/httpsOpenAI's coding agent
Cursorstdio/https.cursor/mcp.json
VS Codestdio/httpsNative MCP support
ChatGPThttpsCustom GPT actions (search / fetch)
Obsidian—Reads/writes the same Markdown directly
Anything MCPstdio/httpsIf it speaks MCP, it works

Official agent packages

This repository is also the canonical home for Basic Memory's host-native agent packages. The core Python package, Claude Code plugin, shared skills, Hermes plugin, and OpenClaw plugin all ship from the same source tree.

Maintainers can verify the whole consolidated surface from the repo root:

just package-check

Package-local justfiles are also available when working inside one host:

just package-check-claude-code
just package-check-skills
just package-check-hermes
just package-check-openclaw
Claude Code plugin

The Claude Code plugin is the bridge between Claude's working memory and Basic Memory — session-start briefings, pre-compaction checkpoints, an opt-in capture output style, and /basic-memory:bm-setup · :remember · :share · :status.

Connect the Basic Memory MCP server first — see Connect your AI client. The plugin's hooks and skills call it, so it's a hard prerequisite. Then install the plugin:

bm install claude-code

That registers the marketplace and installs the plugin through Claude Code. Add --scope project to declare both in the repository's settings for a team, or --dry-run to see the underlying claude plugin commands without running them.

Source: plugins/claude-code.

Shared skills

Framework-agnostic SKILL.md files live in skills/. If your Skills CLI supports repository subdirectory sources:

npx skills add basicmachines-co/basic-memory/skills -g

For Claude and ChatGPT, upload basic-memory.zip or basic-memory-chatgpt.zip from the skills-latest release; see skills/README.md.

If your installed Skills CLI cannot load that source, update the CLI or copy the memory-* directories from skills/ into your agent's skills directory.

Hermes

Hermes keeps its native plugin shape under integrations/hermes:

hermes plugins install basicmachines-co/basic-memory/integrations/hermes

Hermes does not install a plugin's Python dependencies, so also add the mcp package to the Hermes venv — see the plugin README for that step and the supported Hermes releases.

OpenClaw

OpenClaw stays package-native and publishes from integrations/openclaw:

openclaw plugins install @basicmemory/openclaw-basic-memory

Pick up where you left off

https://github.com/user-attachments/assets/a55d8238-8dd0-454a-be4c-8860dbbd0ddc

Connect your AI client

If you went the Cloud route, the web app walks you through client connect. The snippets below are for local installs.

Claude Desktop

Edit ~/Library/Application Support/Claude/claude_desktop_config.json:

{
  "mcpServers": {
    "basic-memory": {
      "command": "uvx",
      "args": ["--prerelease=allow", "basic-memory", "mcp"]
    }
  }
}

Restart Claude Desktop. Notes live in ~/basic-memory by default.

<details> <summary><b>Claude Code, Codex CLI, Cursor, VS Code, ChatGPT, Obsidian</b></summary>

Claude Code
claude mcp add basic-memory -- uvx --prerelease=allow basic-memory mcp

For the full memory bridge — session briefings, pre-compaction checkpoints, and the /basic-memory:* commands — also install the Claude Code plugin on top of this.

Codex CLI

Add to ~/.codex/config.toml:

[mcp_servers.basic-memory]
command = "uvx"
args = ["--prerelease=allow", "basic-memory", "mcp"]

Codex can keep its default MCP approval behavior, or you can pre-approve eligible Basic Memory tools by adding this server-scoped setting to the same table:

[mcp_servers.basic-memory]
command = "uvx"
args = ["--prerelease=allow", "basic-memory", "mcp"]
default_tools_approval_mode = "approve"

This does not disable Codex approvals globally or expand which Basic Memory projects the server can access. Codex still requires approval for tools that advertise a destructive annotation, including Basic Memory's writes, edits, and deletes. If you installed the Basic Memory Codex plugin, use its plugin-scoped configuration instead.

Cursor

Add to .cursor/mcp.json (project) or ~/.cursor/mcp.json (global):

{
  "mcpServers": {
    "basic-memory": {
      "command": "uvx",
      "args": ["--prerelease=allow", "basic-memory", "mcp"]
    }
  }
}
VS Code

Add to your User Settings (JSON):

{
  "mcp": {
    "servers": {
      "basic-memory": {
        "command": "uvx",
        "args": ["--prerelease=allow", "basic-memory", "mcp"]
      }
    }
  }
}
ChatGPT

Basic Memory exposes OpenAI-compatible search and fetch tools for Custom GPT actions. See the ChatGPT integration guide.

Obsidian

No setup. Point Obsidian at ~/basic-memory (or your project folder) and the same wikilinks, frontmatter, and Markdown your AI writes appear in your graph view. Edit either side — sync handles the rest.

</details>

Try a prompt:

"Create a note about our project architecture decisions."
"Find information about JWT auth in my notes."
"What have I been working on this week?"

What's New

  • Automatic updates. Basic Memory keeps itself up to date for uv tool and Homebrew installs; bm update triggers a manual check.

  • Semantic vector search. Find notes by meaning, not just keywords. Hybrid full-text + vector ranking with FastEmbed embeddings, on SQLite or Postgres.

  • Optional search reranking. Rescore the strongest vector and hybrid candidates with a local FastEmbed cross-encoder or a LiteLLM-backed provider.

  • Schema system. Infer, validate, and diff the structure of your knowledge base with bm_schema_infer(), bm_schema_validate(), and bm_schema_diff().

  • Per-project cloud routing. Route individual projects through the cloud while others stay local, via API key (bm project set-cloud).

  • Explicit note changes. bm_edit updates existing notes; bm_write creates notes and guards against accidental overwrites.

  • Richer search results. Matched chunk text is included so the LLM gets context, not just hits.

  • FastMCP 3.0 + tool annotations. Every tool ships with MCP behavior hints (readOnlyHint, destructiveHint, idempotentHint, openWorldHint) so agents can discover capabilities progressively at runtime instead of guessing or burning tokens.

  • CLI overhaul. --json output for scripting, workspace-aware commands, and an htop-inspired project dashboard.

Full CHANGELOG for v0.18 → v0.20.

Optional cross-encoder reranking

Reranking adds a second relevance pass after vector or hybrid retrieval. It is disabled by default because it adds inference latency and, for the local provider, a first-run model download. Text, title, and permalink searches keep their existing ranking.

Enable the default local FastEmbed reranker:

export BASIC_MEMORY_RERANKER_ENABLED=true

The default model is jinaai/jina-reranker-v1-tiny-en. To use a hosted reranker through LiteLLM instead, first install the optional LiteLLM SDK, then configure it:

export BASIC_MEMORY_RERANKER_ENABLED=true
export BASIC_MEMORY_RERANKER_PROVIDER=litellm
export BASIC_MEMORY_RERANKER_MODEL=cohere/rerank-v3.5
export COHERE_API_KEY=...

The feature fails fast on invalid configuration and does not silently fall back to retrieval order when an enabled provider fails. See the semantic search guide for provider setup, all settings, tuning, pagination, and failure behavior.

Why Basic Memory

Most LLM conversations are ephemeral. You ask a question, get an answer, then everything is forgotten. Workarounds have limits:

  • Chat history captures conversations but isn't structured knowledge.

  • RAG lets the LLM query your documents but not write back to them.

  • Vector DBs need complex infra and usually live in someone else's cloud.

  • Knowledge graphs need specialized tooling to maintain.

Basic Memory takes a simpler path: structured Markdown files that humans and LLMs both read and write.

  • All knowledge stays in plain files you control.

  • Both sides read and write to the same files.

  • Familiar Markdown with semantic patterns — no new format to learn.

  • A traversable graph the LLM can follow link by link.

  • Works with the editors you already use (Obsidian, VS Code, anything).

  • Just files plus a local SQLite index. No servers required.

How it works

You're chatting normally about coffee:

I've been experimenting with brewing methods. Pour over gives more clarity than French press, water at 205°F seems best, and freshly ground beans make a huge difference.

Ask the LLM to capture it:

"Make a note on coffee brewing methods."

A Markdown file appears in your project directory in real time:

---
title: Coffee Brewing Methods
permalink: coffee-brewing-methods
tags: [coffee, brewing]
---

# Coffee Brewing Methods

## Observations
- [method] Pour over highlights subtle flavors over body
- [technique] Water at 205°F (96°C) extracts optimal compounds
- [principle] Freshly ground beans preserve aromatics

## Relations
- relates_to [[Coffee Bean Origins]]
- requires [[Proper Grinding Technique]]
- affects [[Flavor Extraction]]

Next session, the LLM picks up the thread. It follows the relations to surface what you already know about Ethiopian beans and burr grinders, and builds on it instead of starting over. You see the same files in Obsidian or your editor. Edit them by hand — the AI sees your changes too.

Real two-way flow: humans edit Markdown, LLMs read/write through MCP, sync keeps everything consistent, and the source of truth is always your files.

The Markdown format

Each file is an Entity. Entities have Observations (facts about them) and Relations (links to other entities). That's the whole grammar.

Frontmatter
---
title: <Entity title>
type: note
permalink: <uri-slug>
tags: [optional, list]
---
Observations

Facts about the entity. Categories in [brackets], tags with #, optional context in parens.

- [method] Pour over highlights subtle flavors
- [tip] Grind medium-fine for V60 #brewing
- [fact] Lighter roasts contain more caffeine than dark
- [resource] James Hoffmann's V60 technique on YouTube
- [question] How does temperature affect compound extraction?
Relations

Wiki-style links that form the graph. Single-token relation types, or quote multi-word ones.

- pairs_well_with [[Chocolate Desserts]]
- grown_in [[Ethiopia]]
- requires [[Burr Grinder]]
- "pairs well with" [[Dark Chocolate]]

Bare - [[Target]] and prose - Worth checking out [[Target]] index as links_to. Full reference in the docs.

MCP tools

Basic Memory exposes these tools to any MCP client. Every tool is annotated with MCP behavior hints (read-only, destructive, idempotent, open-world) so agents can pick the right one without trial-and-error:

  • Content: bm_write, bm_read, bm_edit, bm_move, bm_delete

  • Search & discovery: bm_search, bm_list, bm_find

  • Knowledge graph: bm_context

  • Projects: bm_project_list, bm_project_create, bm_recent; bm_project_delete is separate and requires server opt-in.

  • Schema: bm_schema_validate, bm_schema_infer, bm_schema_diff

  • Manual: bm_man

  • Cloud connector adapters: search and fetch are registered by Cloud only. Local diagnostics use bm doctor.

Most tools default to text; bm_context defaults to JSON. Pass output_format="json" for structured responses. Project-scoped tools accept a name, workspace/project, or external UUID through project. Use bm_man(page="bm-search(3)") for the installed contract, or see the tool guide. CLI commands retain their shell names.

CLI essentials

# Projects
basic-memory project list
basic-memory project add research ~/research
basic-memory project set-cloud research   # route through cloud
basic-memory project set-local research   # revert

# Config
basic-memory config list                        # all settings, effective values, env overrides
basic-memory config set cli_output_style plain  # validated through the config model
basic-memory config unset cli_output_style      # revert to default

# Health & maintenance
basic-memory status
basic-memory doctor              # report project problems and the commands that fix them
basic-memory tool edit ...  # CLI access to MCP tools
basic-memory update              # check for and install updates

# Imports
basic-memory import claude conversations
basic-memory import chatgpt
basic-memory import memory-json

Routing flags (--local / --cloud) force a target when you're in mixed mode. Full CLI reference in the docs.

Auto-updates

CLI installs check for updates every 24 hours by default and apply them silently (so the MCP server keeps responding).

  • Supported install sources: uv tool, Homebrew

  • Skipped for uvx (ephemeral runtime managed by uv)

  • Manual: bm update (check + apply) or bm update --check (check only)

Disable in ~/.basic-memory/config.json:

{ "auto_update": false }

Telemetry

Minimal, anonymous events to understand the CLI-to-cloud conversion funnel.

What we collect: cloud promo impressions, cloud login attempts and outcomes, promo opt-out events.

What we don't: file contents, note titles, knowledge base data, PII, IP addresses, per-command or per-tool tracking.

Events go to our Umami Cloud instance (open-source, privacy-focused) on a background thread — never blocks the CLI.

Opt out:

export BASIC_MEMORY_NO_PROMOS=1

This disables promos and all telemetry.

Logging

Basic Memory uses Loguru. Defaults vary by entry point:

Entry pointDefaultWhy
CLI commandsFile onlyDoesn't interfere with command output
MCP serverFile onlyStdout would corrupt JSON-RPC
API serverFile (local) or stdout (cloud)Docker/cloud uses stdout

Log file: ~/.basic-memory/basic-memory.log (10MB rotation, 10 days retention).

Environment variables
VariableDefaultDescription
BASIC_MEMORY_LOG_LEVELINFODEBUG / INFO / WARNING / ERROR
BASIC_MEMORY_CLOUD_MODEfalseAPI logs to stdout with structured context
BASIC_MEMORY_FORCE_LOCALfalseForce local API routing
BASIC_MEMORY_FORCE_CLOUDfalseForce cloud API routing
BASIC_MEMORY_EXPLICIT_ROUTINGfalseMark route selection as explicit
BASIC_MEMORY_ENVdevSet to test for test mode (stderr only)
BASIC_MEMORY_NO_PROMOSfalseDisable cloud promos and telemetry
BASIC_MEMORY_IMPORT_UPLOAD_MAX_BYTES104857600Max uploaded import size
BASIC_MEMORY_LOG_LEVEL=DEBUG basic-memory reindex
tail -f ~/.basic-memory/basic-memory.log

Development

Basic Memory supports SQLite (default, fast, no Docker) and Postgres (via testcontainers — Docker required).

just install          # Install with dev dependencies
just test-sqlite      # All tests, SQLite
just test-postgres    # All tests, Postgres (testcontainers)
just test             # Both backends
just fast-check       # fix/format/typecheck + impacted tests
just doctor           # File <-> DB consistency check (temp config)
just package-check    # Claude Code, skills, Hermes, OpenClaw package checks
just lint
just typecheck        # Pyright (primary)
just typecheck-ty     # ty (supplemental)
just format
just check            # All quality checks
just migration "msg"  # New Alembic migration

Tests use pytest markers: windows, benchmark, smoke. See justfile for the full list.

Contributions welcome — see CONTRIBUTING.md.

License

AGPL-3.0.

Built with ♥️ by Basic Machines

docs/REDIS_READ_CACHE_PLAN.md

Redis Read Cache Plan

Status

Accepted implementation plan. Basic Memory owns semantic read caching; Basic Memory Cloud owns tenant and principal rate limiting. The datasets are logically isolated even when they share a Redis instance.

Goals

  • Reduce latency and database work for repeated entity and note reads.

  • Keep Redis optional so the default local-first installation has no external service requirement.

  • Make cache semantics, typed serialization, TTLs, and invalidation part of Basic Memory.

  • Let a host such as Basic Memory Cloud inject an existing Redis client and opaque namespace.

  • Preserve independent key prefixes, metrics, ownership, and failure behavior for read caching and rate limiting.

Ownership Boundary

Basic Memory owns:

  • cacheable read operations;

  • canonical request keys;

  • typed serialization;

  • TTL and payload-size policy;

  • project-scoped invalidation;

  • the model-bound read-through facade and Redis read-cache implementation.

Cloud owns:

  • tenant and principal identity;

  • rate-limit policy and enforcement;

  • the Redis deployment topology;

  • the opaque cache namespace supplied to Basic Memory;

  • capacity, eviction, and availability decisions when Redis is shared.

Physical topology is deliberately outside the Basic Memory cache contract. Cloud may point the read cache and limiter at separate Redis instances or clients, or reuse one client and connection pool when both concerns share an instance.

Tenant isolation on shared Redis

Cloud does not create a Redis instance or connection pool per tenant. It reuses one long-lived Redis client and connection pool and constructs a lightweight RedisReadCache adapter from trusted request or worker context:

  • namespace: the stable tenant/workspace UUID;

  • project_id: the Basic Memory project external UUID;

  • prefix: the Basic Memory read-cache keyspace, separate from rate limiting.

The adapter hashes (namespace, project_id) into the Redis Cluster scope. Two tenants with the same project identifier therefore cannot share a generation or data key. Tenant isolation must not rely on project UUID uniqueness alone: every Cloud read and invalidation supplies the authenticated tenant/workspace UUID, even when project UUIDs are globally unique in practice.

The namespace is host-owned isolation context, not an API input. Never derive it from a display name or slug, accept it from a caller, or include API keys and other secrets in it. API requests and background workers must use one canonical tenant-to-namespace function so an index worker invalidates the exact scope populated by the request path.

Cloud host requirements

Basic Memory Cloud must satisfy all of these requirements when composing cached reads:

  1. Derive one stable namespace from authenticated Cloud context. The preferred value is the tenant UUID or workspace UUID already owned by Cloud. Project UUID alone is not a tenant boundary, even if current database constraints make it globally unique.

  2. Complete authorization and tenant database/schema selection before cache lookup. The namespace prevents key collisions; it does not replace Cloud's access-control boundary.

  3. Override the low-level get_read_cache dependency at the Cloud composition root. Construct RedisReadCache(client=shared_redis_client, namespace=trusted_namespace) as a lightweight request-scoped adapter; reuse the long-lived client and connection pool. A single Cloud composition function owns this choice so the cache can move to a separate client or instance later without changing Basic Memory routes or workers. FastAPI route dependencies then create lightweight ModelReadCache facades from that shared backend and bind Basic Memory's response type, TTL, and payload-size policy. Cloud should not duplicate those policy constants or construct Redis clients per response model.

  4. Pass the trusted tenant/workspace identity through internal queue payloads, or include enough trusted identifiers for workers to derive the exact same namespace. Never copy a namespace from a public request field.

  5. Inject the namespace-bound cache into every mutation-producing runtime: accepted note materialization, object-storage events, direct and project indexing, directory moves/deletes, watcher-detected paired moves, relation-resolution workers, and startup recovery or reconciliation. Request-path invalidation alone is insufficient because a worker can update a cached entity after the request returns.

  6. Invalidate after semantic vector publication, including partial-failure paths. Vector sync can run after the mutation and file-index generation bumps, so VECTOR/HYBRID responses filled while embeddings are stale must not survive the later derived-state update. Queue-backed Cloud vector workers use the same trusted tenant namespace and canonical project UUID as request reads.

  7. Treat each asynchronous state transition as a separate freshness boundary. Invalidate after the accepted-note transaction commits, immediately after terminal materialization/status publication before indexing begins, again after indexing, and again after relation resolution completes. This prevents a read filled between phases from surviving the later worker commit or remaining pending throughout a slow index.

  8. Make committed-mutation invalidation cancellation-safe. Accepted-note writes, directory deletion, and each file in a directory move can be cancelled after their database commit succeeds but before the transaction context returns. Finish the namespace-bound generation bump before re-propagating cancellation so committed state cannot remain hidden behind the previous generation.

  9. Invalidate after each committed project-index move, delete, and file-index batch, while retaining the final failure-safe completion boundary for later-phase errors. Local inline file batches invalidate when their runner returns; queued Cloud file batches invalidate in the child worker after its durable commit, not merely when the coordinator enqueues the job.

  10. Put full search reindexing in a failure-safe invalidation scope owned by the worker that runs the rebuild. Reindexing drops and repopulates search rows incrementally, so fuzzy resolutions filled during a partial or completed rebuild must not survive its final generation bump.

  11. Put direct single-file and watcher file-index invalidation in failure-safe boundaries. Entity transactions can commit before search refresh or note-content reconciliation raises, so a failed index attempt can still publish cache-relevant state. Wrap the transaction-bearing watcher index and entity-delete operations themselves in cancellation-safe invalidation because cancellation can land during transaction exit before their completion callbacks run. Once a watcher callback runs, retain its generation bump before relation and search cleanup.

  12. Pass the namespace-bound cache into hosted note-content read repair. A resource or entity read can bootstrap a missing accepted-content row. Put cancellation-safe invalidation around the transaction-bearing repair call, not only after it returns, so cancellation during transaction exit still advances the generation before the repaired response can reach read-through storage.

  13. Pass the namespace-bound cache into pre-mutation content freshening. Freshening can index an externally edited file before the accepted mutation begins, so invalidate after every freshening attempt that may have published state, including when the later mutation is rejected or raises.

  14. Inject the namespace-bound cache into import endpoints and workers. Invalidate after every attempted file write before the next item, including writes that raise after partial progress, and retain the final failure-safe invalidation around the complete import attempt.

  15. Invalidate directory deletion immediately after its acceptance transaction commits, then again after file cleanup and surviving-relation refresh. A slow or failed cleanup must not keep deleted entities reachable through the pre-acceptance generation.

  16. Invalidate every committed watcher-detected move batch, then retain the final invalidation after search refresh. Paired delete/create events are consumed by move processing and therefore bypass the ordinary watcher callbacks; a large watcher run commits bounded batches before the final refresh.

  17. Invalidate directory moves after each individual file/database move commits, then again after the final search and relation follow-ups. Directory moves are incremental batches, so a long or partially failed request must not keep earlier files under the pre-move generation.

  18. Inject the namespace-bound cache into project-root path mutations. A root change preserves the project and entity UUIDs while changing the filesystem source behind resource reads, so invalidate in a failure-safe boundary around the committed path update.

  19. If startup recovery or reconciliation attempts can publish materialization, vacate, index, or relation state, invalidate through the same namespace-bound cache before releasing the serving barrier or resuming tenant traffic. Treat materialization and move-vacate recovery as separate freshness phases: invalidate a completed first phase before starting the second so a later setup/query failure cannot skip the earlier generation bump. Terminal conflict and failure publication count even when the recovery did not produce a written file. Put each transaction-bearing phase inside a cancellation-safe invalidation scope so shutdown cannot interrupt the generation bump after recovery commits.

  20. Keep bm:read:v1 separate from rate-limit and Cloud control-plane prefixes, metrics, timeouts, and failure policies. The clients may target one Redis deployment, but a read-cache timeout must bypass while a rate-limit decision keeps its Cloud-owned security behavior.

  21. Activate request reads and worker invalidation together in the same Cloud release, using the same namespace function. The cache is fail-open and TTL-bounded, so do not add tenant cohorts, shadow reads, or a second rollout switch; use integration coverage and cache telemetry to verify the direct activation.

  22. Coordinate rolling deployments around the bm:read:v1 payload/key contract. Bump the prefix for incompatible serialized response changes so mixed application versions never interpret one another's payloads with different schemas.

If Cloud ever changes the namespace source, treat that as a cache-key migration. A new namespace is safe because it cannot read the old tenant scope, but old keys remain until their TTLs expire and every worker must switch atomically enough to avoid missing invalidations.

Architecture

flowchart LR
    H["Cloud or standalone API host"] -->|"optional client plus opaque namespace"| B["Raw ReadCache backend"]
    B --> F["Typed ModelReadCache facades"]
    API["Basic Memory read routes"] --> F
    F -->|"hit"| API
    F -->|"miss"| DB["Services, repositories, and storage"]
    DB -->|"successful result"| F
    W["Writes, indexing, recovery, and storage events"] -->|"invalidate after commit"| B

    RL["Cloud tenant rate limiter"] --> RLD["Cloud rate-limit keyspace"]
    B --> BMD["Basic Memory read-cache keyspace"]
    RLD -. "same or separate instance" .-> R["Redis"]
    BMD -. "same or separate instance" .-> R

Core Contract

Introduce src/basic_memory/read_cache/ with:

  • a narrow ReadCache protocol;

  • a narrower ReadCacheInvalidator protocol for mutation and repair paths;

  • immutable request/key values;

  • canonical key construction;

  • a generic ModelReadCache[ModelT] facade that owns one Pydantic response type and policy;

  • an optional RedisReadCache adapter.

The raw backend is namespace-bound at construction. Its public operations are:

  • lookup(key), which returns the generation observed with a hit or miss;

  • store(key, lookup, payload, ttl), which reports stored or superseded;

  • invalidate_project(project_id).

Cloud can create a lightweight namespace-bound adapter around a long-lived, Basic Memory-specific async Redis client. Basic Memory then creates separate model-bound facades for entity, resolution, and resource responses over that same adapter. Facades do not own clients or connections. Basic Memory does not receive tenant, subscription, or rate-limit concepts.

Keys And Invalidation

Use versioned, cluster-compatible keys:

bm:read:v1:{scope_digest}:generation
bm:read:v1:{scope_digest}:<operation>:<request_digest>

scope_digest hashes the host-supplied tenant/workspace namespace and project external ID. The Redis Cluster hash tag keeps that tenant-project scope's generation and data keys in one slot.

Each value records the random generation token under which it was created:

  1. Read the generation and data key together.

  2. Accept the cached value only when its embedded generation matches.

  3. After a successful mutation commit, replace the generation with a new random token.

  4. Give generation metadata a bounded TTL, renew it to at least each stored response's remaining lifetime, and reset that TTL on invalidation. A lookup also migrates a legacy persistent generation key to a bounded TTL.

  5. Let unreachable entries and inactive-project generation metadata expire; never scan or bulk-delete keys.

Random tokens prevent an evicted generation key from returning to an old integer generation and reviving stale data. A read that fills after concurrent invalidation also remains safe because its old token no longer matches.

Cache Surface And Production TTL

Phase one:

OperationProduction TTLConstraints
Entity by external ID300 secondsCache validated EntityResponseV2 JSON
Identifier resolution300 secondsInclude body and workspace context
Markdown note resource300 secondsCache only below an explicit size limit
Directory structure300 secondsFolder-only tree; two MiB payload cap
Directory tree300 secondsFull hierarchy; two MiB measured payload cap
Paginated directory listing300 secondsInclude path, depth, glob, page, and page-size keys

Additional measured surfaces:

OperationProduction TTLConstraints
Search30 secondsImplemented; complete query plus pagination key
Context and recent activity15-30 secondsFuture; normalize or bound time-relative inputs

Do not initially cache failures, missing entities, graph/orphan responses, large or arbitrary binary resources, schema inference, writes, or Cloud control-plane data.

Caching is semantic rather than HTTP-method based. The POST identifier-resolution and search operations can be cached without changing their public API. Identifier resolution depends on the request-local workspace permalink context, so its request digest includes the workspace slug and workspace type in addition to the validated request body.

Placement

Cache typed boundary values rather than SQLAlchemy models. Use an explicit read-through scope in the API routes so hit, miss, serialization, and fallback behavior remain visible. FastAPI injects a route-specific ModelReadCache[ResponseType] | None; its provider binds the optional backend to Basic Memory's response type, TTL, and payload-size policy at the dependency boundary. Routes keep the authoritative read inline inside a Python async context manager instead of constructing loader callbacks:

cache_key = ReadCacheKey(
    project_id=project_external_id,
    operation=ReadCacheOperation.entity,
    request_digest=read_cache_request_digest(entity_id),
)
cache_scope = (
    read_cache.read(key=cache_key)
    if read_cache is not None
    else nullcontext(ReadCacheScope[EntityResponseV2]())
)
async with cache_scope as cached:
    if cached.value is not None:
        return cached.value

    entity = await entity_repository.get_by_external_id(session, entity_id)
    result = EntityResponseV2.model_validate(entity)
    cached.value = result
    return result

The context manager performs lookup before entering the body and stores an eligible miss when the body exits normally. Exceptions and cancellation propagate without storing. When no backend is configured, callers do not invoke cache lookup, store, or invalidation; there is no disabled cache result or no-op implementation. A route that performs read repair passes the model-bound facade itself through the narrow ReadCacheInvalidator capability when present; it never reaches through the facade to a Redis/backend attribute.

Mutation and indexing code uses the same direct scope pattern when invalidation is unconditional:

async with invalidate_cache(read_cache, project_id):
    await importer.import_data(...)

Callers enter this scope only when a backend is present. Conditional and multi-phase invalidation remains explicit so the freshness boundary is visible. The scope finishes its generation bump before re-propagating cancellation, which makes it safe around operations whose transaction can commit during async context-manager exit.

Primary integration points:

  • src/basic_memory/api/container.py

  • src/basic_memory/api/app.py

  • src/basic_memory/deps/read_cache.py

  • src/basic_memory/api/v2/routers/directory_router.py

  • src/basic_memory/api/v2/routers/knowledge_router.py

  • src/basic_memory/api/v2/routers/resource_router.py

  • later, src/basic_memory/api/v2/routers/search_router.py

Invalidation belongs at portable mutation and indexing completion boundaries, not only in FastAPI routes. It must cover accepted note writes, terminal deferred materialization and status publication, direct file indexing, filesystem watcher updates, project indexing, directory mutations, imports, watcher-detected paired moves, startup recovery or reconciliation, Cloud storage events, full search reindexing, and relation-resolution changes that affect cached responses. Each later phase invalidates again so a value filled after an earlier generation bump cannot outlive the state that phase publishes. Hosted read repair invalidates after bootstrapping accepted content and before a repaired entity or resource is stored, including cancellation during the repair transaction's exit. Directory moves invalidate after every committed file plus the final reindex; directory deletion invalidates after acceptance and after cleanup. Imports invalidate after every attempted file write and again around the complete attempt so partial failures cannot escape. Project indexing and full search reindexing invalidate even after a partial failure. Direct single-file and watcher file indexing invalidate even when a follow-up fails after the entity commit. Watcher move batches invalidate after every commit, and watcher index and entity-delete operations wrap their transaction-bearing executors so cancellation cannot escape between a commit and completion callback. Watcher index/delete completion callbacks retain a later generation bump before relation and search cleanup. Recovery phases invalidate independently before the serving barrier is released, include terminal conflict or failure publication, and finish their generation bump before startup cancellation propagates. Deferred accepted-note materialization similarly advances the generation immediately after terminal status publication, before potentially slow indexing, and retains the outer post-index bump.

Dependency And Lifecycle

Use the official asynchronous redis-py client behind the Basic Memory protocol. Add it only as an optional package extra. A host may instead supply a compatible, already-owned client.

The Core ApiContainer carries ReadCache | None and defaults to None. A managed host activates caching by injecting or dependency-overriding a namespace-bound implementation and owns that client's lifecycle; Cloud therefore reuses its long-lived Basic Memory cache client.

Standalone bm mcp activates the cache when BASIC_MEMORY_REDIS_URL is set. A bare hostname such as redis is normalized to redis://redis; complete redis:// and rediss:// URLs are preserved. The optional BASIC_MEMORY_REDIS_MAX_CONNECTIONS setting tunes that process-owned connection pool and defaults to 20; it does not activate caching by itself. The MCP lifespan owns one async client and shares its namespace-bound cache with both in-process FastAPI requests and watcher/index invalidation, then closes the client after those paths shut down. After project reconciliation and before accepting requests, every standalone MCP lifespan replaces each active project's persisted generation. This prevents entries from an earlier process from hiding a source-of-truth file edit made while MCP was stopped. If Redis cannot complete every startup invalidation, caching is disabled for that lifespan and requests use the authoritative path; a later Redis recovery cannot revive the untrusted generation. When the URL is absent, the dependency remains None and callers take only the authoritative path. Cloud runtime mode ignores this standalone composition because Cloud injects a separately owned cache using its trusted tenant namespace and capacity policy.

get_read_cache is the host override point and returns ReadCache | None. Core-owned, route-specific FastAPI providers call create_model_read_cache to return a correctly typed facade when that backend exists. Portable mutation and indexing runtimes continue to depend only on the optional backend or narrower invalidation capability; they do not depend on FastAPI.

The FastAPI Redis SDK is not the foundational dependency for this work. The cache contract must also participate in portable indexing and hosted storage-event invalidation, and Basic Memory's local ASGI transport does not run FastAPI lifespan.

The end-to-end MCP benchmark is documented in benchmarks/docs/read-load-benchmark.md. It removes ambient Redis configuration for the authoritative run and sets BASIC_MEMORY_REDIS_URL only for the warmed-cache run, so both cases exercise the same bm mcp process boundary. The harness also sets BASIC_MEMORY_REDIS_MAX_CONNECTIONS to the largest requested workload or seed concurrency and records that non-secret value in the manifest. Without this capacity guarantee, Redis pool exhaustion would correctly bypass to authoritative reads but mislabel the resulting benchmark row as a warmed-cache measurement.

Cloud Production Calibration

A bounded production snapshot from 2026-07-30 00:00-19:03 UTC changed directory reads from a phase-two idea into a phase-one requirement:

Cloud web routeCallsAveragep95
GET /api/v2/projects/tree1,0731,794 ms4,656 ms
GET /api/v2/notes7891,688 ms3,295 ms
GET /api/v2/projects1451,536 ms3,269 ms

Cloud's existing user-scoped gateway response cache already proved that the directory work is cacheable, but also exposed the misses that remain expensive:

Gateway route familyAttemptsHitsHit rateTenant dispatches
directory_structure14,1638,84562.5%5,318
directory_list72216623.0%556
directory_tree881314.8%75
note_entity2,77987731.6%1,896

Across the preceding seven days, cached directory-tree response bodies had a p99 of 573 KiB and a maximum of 1.29 MiB. Directory-node facades therefore use a two MiB payload cap rather than the one MiB default; otherwise the largest and usually slowest tree in the measured workload would always bypass storage. Paginated listings retain the one MiB default—their measured maximum was 183 KiB.

For folder file navigation, a directory-list miss plus a tenant project-list dispatch averaged 2,407 ms; when both dependencies avoided tenant dispatch, the same composed endpoint averaged 636 ms. Project-tree requests with no directory miss and no project-list dispatch averaged 673 ms, while requests with six or more directory misses plus a project-list dispatch averaged 3,571 ms. These are associations within the snapshot, not a controlled benchmark, but they show that cache locality materially changes end-to-end latency.

The same snapshot contained 6,338 hosted MCP tool calls. read_note accounted for 2,636 calls at 2,782 ms average, search for 723 at 3,386 ms, and list_directory for 231 at 1,960 ms. Their instrumented Basic Memory API dependencies included 3,947 identifier resolutions, 3,064 resource reads, and 1,140 searches. This preserves resolution and resource as the primary MCP targets while adding directory reads for the web explorer and list_directory.

Project enumeration remains a Cloud-owned concern. GET /api/v2/projects combines access to multiple workspaces, user visibility, project soft-delete state, and tenant database selection. Even after loading a cached project-list body, the current Cloud service opens each tenant database and queries active project IDs. Basic Memory's project-scoped semantic cache must not absorb that authorization-aware composition. Cloud should optimize that active-project reconciliation and its own project-list cache independently.

Directory caching in Basic Memory is intended to replace overlapping route families after Cloud reaches namespace, invalidation, and observability parity. During the transition away from the overlapping outer cache, the inner cache can also share tenant-project directory results across already-authorized users while Cloud's current outer key remains user-specific. Do not keep both response-cache layers as the final design.

Failure Behavior

  • Operational Redis command failures, including connection, timeout, capacity, replica-read-only, and server response failures, are represented explicitly as cache-unavailable outcomes.

  • Reads bypass Redis and use the authoritative path when the cache is unavailable.

  • Cache-store failures do not fail an otherwise successful read.

  • Cache-invalidation failures do not fail committed writes, but they emit prominent telemetry.

  • Bounded operation TTLs limit stale-data exposure after an invalidation failure and Redis recovery.

  • Redis client-input errors plus local serialization, decoding, and programming errors fail fast rather than masquerading as cache misses.

Rate-limit failure behavior remains entirely Cloud-owned.

Observability

Record:

  • distinct lookup and store outcomes, including hit, miss, bypass, store, invalidation, unavailable, corrupt, and oversize;

  • operation name and configured TTL without tenant or project metric labels;

  • remaining TTL on cache hits;

  • Redis operation latency;

  • cached payload size;

  • authoritative read latency on misses;

  • hashed scope, request, and generation identifiers on diagnostic spans only.

Do not add public cache headers in the first version.

Integration Tests

Redis behavior must be tested against a real Redis server, not a mocked or in-memory substitute. Integration tests will start Redis through testcontainers or use an explicitly configured CI Redis URL.

Run the focused suite with:

just test-read-cache

BASIC_MEMORY_TEST_REDIS_URL selects an externally managed test server. Otherwise the fixture starts redis:8.8-alpine; BASIC_MEMORY_TEST_REDIS_IMAGE can override that image without changing the test contract.

The real-Redis suite must prove:

  • namespace, project, operation, and request isolation;

  • distinct model-bound facades share one raw backend while retaining their own response type;

  • deterministic canonical keys;

  • cache hit and TTL expiry behavior;

  • project invalidation;

  • a fill that completes after invalidation is never served;

  • loss of the generation key cannot revive an older value;

  • generation metadata expires for inactive projects, including legacy persistent keys, and stores keep it alive at least as long as their response data;

  • Redis restart or unavailability produces explicit bypass behavior;

  • a fresh standalone MCP lifespan replaces persisted project generations before serving, so offline file edits cannot remain hidden behind cache entries from the previous process;

  • no invalidation operation touches keys outside the Basic Memory prefix;

  • payload size limits;

  • repeated API entity reads use the real cached representation;

  • successful writes invalidate; a rejected write also invalidates when pre-write freshening may already have published external file state, while a rolled-back transaction without such a publication does not;

  • cancellation after a real accepted-note, directory-delete, or per-file directory-move transaction commits cannot interrupt the real Redis generation bump, including repeated cancellation while invalidation is in progress;

  • cancellation during a real hosted read-repair transaction's commit exit cannot interrupt the real Redis generation bump;

  • cancellation during watcher index or delete completion cannot interrupt the first real Redis generation bump after the durable event;

  • cancellation during a watcher entity-delete transaction's commit exit cannot escape before the real Redis generation advances, even when the completion callback is never reached;

  • cancellation during a watcher file-index transaction's commit exit cannot escape before the real Redis generation advances, even when the completion callback is never reached;

  • real Redis no-eviction capacity failures bypass cache storage and cannot fail committed-write invalidation;

  • authoritative read exceptions propagate without populating the missed cache key;

  • watcher-detected paired moves invalidate even though their events bypass ordinary callbacks;

  • consecutive watcher move batches each advance the real Redis generation before the next batch, while retaining the final post-refresh bump;

  • a partial or completed full search reindex invalidates fuzzy resolutions filled while the search index was being rebuilt;

  • startup recovery that publishes written, conflict, or failed materialization state invalidates before serving resumes;

  • accepted-note materialization advances the generation after terminal status publication while a following index is still blocked, then advances it again after indexing;

  • cancellation after materialization or move-vacate recovery commits cannot interrupt the phase-specific real Redis generation bump;

  • project-index failures invalidate any earlier committed batches;

  • consecutive project-index move, delete, and inline file batches each advance the real Redis generation before the next batch begins;

  • direct and watcher file-index failures invalidate any entity state committed before failed search or reconciliation follow-ups;

  • hosted read repair invalidates cached entity metadata before storing the repaired resource;

  • multi-item imports advance the real Redis generation after every attempted file write, while retaining the final success and partial-failure bump;

  • directory moves invalidate after each committed file and again after final reindexing;

  • project-root path changes invalidate cached resources whose project/entity UUID keys remain stable;

  • directory deletion invalidates before cleanup starts and again after cleanup completes.

  • startup materialization recovery remains invalidated when a later move-vacate phase fails.

Run route behavior against both SQLite and Postgres where persistence behavior differs. Redis semantics themselves are asserted only against the real Redis integration fixture.

Delivery Sequence

1. Cache infrastructure
  • Add the protocol, key values, Redis adapter, typed facade, optional dependency, telemetry, and real Redis integration tests.

  • Do not cache production routes yet.

2. Hot semantic and directory reads
  • Cache entity, resolution, bounded markdown-resource, directory tree, directory structure, and paginated directory-list reads behind default-off configuration.

  • Wire project invalidation through accepted writes and indexing paths.

  • Add full-stack API, repeated read_note, and directory refresh integration coverage.

3. Cloud integration
  • Inject a Basic Memory-specific Redis client and tenant namespace.

  • Derive that namespace from trusted request and worker context with one canonical function.

  • Invalidate after accepted-note commit, immediately after terminal materialization/status publication before indexing, again after indexing, and after relation-resolution workers using the same tenant namespace as the request path.

  • Invalidate after semantic vector publication, including partial failures, because vector sync is derived work that can complete after the note/index freshness boundaries.

  • Invalidate watcher-detected paired moves at move completion, and invalidate any recovery or reconciliation attempt that can publish terminal state before releasing the serving barrier or resuming tenant traffic.

  • Invalidate project indexing from a failure-safe completion boundary, and invalidate directory deletion both after acceptance commit and after cleanup/relation refresh.

  • Invalidate full search reindexing from the worker that executes the rebuild so partial or completed search rows cannot leave cached fuzzy resolutions behind.

  • Invalidate direct and watcher file indexing from failure-safe boundaries because entity commits precede some search and reconciliation follow-ups.

  • In Cloud's build_cloud_index_file_runtime, decorate the transaction-bearing FileIndexer with InvalidatingIndexFileExecutor using the namespace-bound cache and canonical project UUID. Both single-file jobs and every child of index_file_batch then invalidate at the same committed-file boundary as the local filesystem watcher.

  • Retain Cloud's existing post-entrypoint GatewayCache invalidation until directory/entity route-family overlap is removed, but do not treat that later live-update side effect as the Basic Memory cache correctness boundary.

  • Wrap the watcher index and entity-delete transactions themselves in cancellation-safe invalidation because cancellation can escape before their completion callbacks are reached.

  • Finish watcher index and delete completion invalidation before cancellation propagates from the post-event callback.

  • Invalidate every committed watcher move batch before the next batch starts, then retain the final post-refresh invalidation.

  • Wrap hosted note-content read repair in cancellation-safe invalidation so cancellation during transaction exit cannot skip the bump before a repaired entity or resource reaches read-through.

  • Invalidate pre-mutation content freshening even when a later accepted mutation is rejected or fails, because the freshening index may already have committed external file state.

  • Invalidate every imported file write before the next item, and retain whole-import invalidation for partial failures.

  • Finish directory-delete acceptance invalidation before re-propagating cancellation that lands after the delete transaction may have committed.

  • Finish each directory-move file invalidation before re-propagating cancellation that lands after its move transaction may have committed, and invalidate again after search/relation follow-ups.

  • Invalidate project-root path changes in a failure-safe boundary because the filesystem source can change while every cache identity remains stable.

  • Put each startup recovery phase inside a cancellation-safe invalidation scope before beginning the next phase.

  • Land request reads and the worker invalidation boundaries in one Cloud change, using the same tenant namespace function everywhere.

  • Do not add shadow reads, tenant cohorts, or a cache-specific rollout switch. Observe hit rate, Redis latency, database query volume, and end-to-end tool latency after direct activation.

4. Expand from evidence
  • Add graph-context and recent-activity reads when measured reuse supports them.

  • Refine project-wide invalidation only if unrelated writes materially reduce the entity hit rate.

5. Remove overlap
  • Remove matching Cloud gateway response-cache families once Basic Memory caching reaches behavioral and observability parity.

Verification Gates

  • Focused unit and real Redis integration tests.

  • Entity/read API integration tests on SQLite and Postgres.

  • just fast-check.

  • just doctor.

  • The appropriate broader SQLite and Postgres suites before opening a pull request.

  • A before/after benchmark showing cache-hit latency and reduced authoritative reads.

512 files · 461 not served here

Advantages

  • Local-first architecture ensures data remains on your disk, providing air-gapped compatibility and full ownership. evidence: README.md
  • Bidirectional synchronization allows both humans and AI agents to edit the same files, keeping the knowledge base consistent. evidence: README.md
  • Progressive tool discovery via MCP behavior hints allows agents to select the most appropriate tool for a task without wasting context. evidence: README.md

Limitations

  • Local installation requires Python 3.12+ and familiarity with command-line tools. evidence: README.md
  • Cross-device synchronization for local-only setups requires manual configuration of tools like Git or Syncthing. evidence: README.md
  • Advanced features like cross-encoder reranking may introduce inference latency and require additional model downloads. evidence: README.md

Security

Risk level: Medium risk

This brain runs

Agent instructions that run or fetch something (322)

  • .agents/skills/adversarial-review/SKILL.md: To **run** it, use `"${DIFF[@]}"` (quoted, no word-splitting).
  • .agents/skills/adversarial-review/SKILL.md: Run `"${DIFF[@]}"`.
  • .agents/skills/adversarial-review/SKILL.md: `RUN=$(mktemp -d)` — scratch dir for the other model's output.
  • .agents/skills/adversarial-review/SKILL.md: **The other model's pass** — run, from the repo root, the row that matches you:
  • .agents/skills/adversarial-review/SKILL.md: # You are Claude → run Codex:
  • .agents/skills/adversarial-review/SKILL.md: -o "$RUN/other_findings.json" \
  • .agents/skills/adversarial-review/SKILL.md: # You are Codex → run Claude (read-only via plan mode; parse the JSON block it returns):
  • .agents/skills/adversarial-review/SKILL.md: $(cat "$SKILL_DIR/schemas/findings.schema.json")" </dev/null > "$RUN/other_raw.json"
  • .agents/skills/fix-pr-issues/SKILL.md: Run the smallest meaningful verification first, then widen as needed.
  • .agents/skills/fix-pr-issues/SKILL.md: Commit changed code or documentation with `git commit -s`.
  • .agents/skills/fix-pr-issues/SKILL.md: For each addressed comment or blocker, reply with the fix commit, verification run, and current Codex gate status.
  • .agents/skills/infographics/SKILL.md: uv run --script scripts/generate_pr_infographic.py \
  • .agents/skills/infographics/SKILL.md: uv run --script scripts/generate_pr_infographic.py \
  • .agents/skills/infographics/SKILL.md: `--dry-run` is an alias for `--print-prompt`;
  • .agents/skills/infographics/SKILL.md: changed-file orientation: `git diff --stat` plus key file reads
  • .agents/skills/infographics/SKILL.md: uv run --script scripts/generate_infographic.py \
  • .agents/skills/instrumentation/SKILL.md: The reason this skill exists is that Claude tends to get a few things subtly wrong with Logfire - especially the ordering of `configure()` vs `instrument_*()` calls, the structured logging syntax, and which extras to install.
  • .agents/skills/instrumentation/SKILL.md: Install `logfire` with extras matching the detected frameworks.
  • .agents/skills/instrumentation/SKILL.md: uv add 'logfire[pydantic-ai]'
  • .agents/skills/instrumentation/SKILL.md: For PydanticAI, each agent run becomes a parent span containing child spans for every tool call and LLM request.
  • .agents/skills/instrumentation/SKILL.md: Launch with: `node --require ./instrumentation.js app.js`
  • .agents/skills/instrumentation/SKILL.md: Run `logfire auth` to check authentication (or set `LOGFIRE_TOKEN`)
  • .agents/skills/pr-create/SKILL.md: Return the PR URL, current head SHA, validation run, check status, and Codex gate evidence.
  • .agents/skills/pr-description/SKILL.md: git log --oneline --decorate -n 10
  • .agents/skills/pr-description/SKILL.md: Testing section must include exact commands run and outcomes.
  • .agents/skills/pr-review-loop/SKILL.md: If the comment identifies a real issue, patch it, run focused validation, push, and restart the loop on the new head.
  • .agents/skills/pr-review-loop/SKILL.md: Only run `gh pr merge` when the gate is `approved` or `overridden` and tests are passing on that same head.
  • .agents/skills/pull-request/SKILL.md: After activation, run Python scripts as `python ...`.
  • .agents/skills/pull-request/SKILL.md: For one-off commands where activation is awkward, prefer `./.venv/bin/python ...` or the repo's `uv run ...` patterns.
  • .agents/skills/pull-request/SKILL.md: Run focused tests for the changed surface.
  • .agents/skills/pull-request/SKILL.md: Run the repo's required gate, such as `just fast-check` for source changes or `just package-check` for agent/package changes, before calling the branch ready.
  • .agents/skills/pull-request/SKILL.md: `Testing`: exact commands run and whether they passed.
  • .agents/skills/pull-request/SKILL.md: If the feedback is correct and in scope, patch, run focused validation, push, and restart the loop on the new head.
  • .agents/skills/pythonic-code/SKILL.md: Run the narrowest command that proves the change, then widen according to risk:
  • .agents/skills/pythonic-code/evals/context/AGENTS.md: Run the focused tests under `evals/files` and the configured Ruff checks for changed Python.
  • .claude/commands/release/beta.md: When the user runs `/beta`, execute the following steps:
  • .claude/commands/release/beta.md: While `pyproject.toml` pins a FastMCP pre-release (`fastmcp==X.Y.Zb1`), `just beta` refuses to run: every documented install passes `--prerelease=allow`, which uv applies to basic-memory itself, so a beta on PyPI would become the default install for stable users (#1338).
  • .claude/commands/release/beta.md: Execute the automated beta release process:
  • .claude/commands/release/beta.md: Test beta installation: `uv tool install basic-memory --pre`
  • .claude/commands/release/beta.md: # Install/upgrade to beta
  • .claude/commands/release/beta.md: uv tool install basic-memory --pre
  • .claude/commands/release/beta.md: uv tool upgrade basic-memory --prerelease=allow
  • .claude/commands/release/beta.md: Install/test with:
  • .claude/commands/release/beta.md: uv tool install basic-memory --pre
  • .claude/commands/release/beta.md: **Test features**: Install and validate new functionality
  • .claude/commands/release/changelog.md: When the user runs `/changelog`, execute the following steps:
  • .claude/commands/release/changelog.md: git tag -l "v*" --sort=-version:refname | grep -v "b\|rc" | head -1
  • .claude/commands/release/changelog.md: git log --oneline ${last_tag}..HEAD
  • .claude/commands/release/changelog.md: uv tool install basic-memory --prerelease=allow
  • .claude/commands/release/release-check.md: When the user runs `/release-check`, execute the following validation steps:
  • .claude/commands/release/release-check.md: 2. Run `/release v0.13.0` when ready
  • .claude/commands/release/release-check.md: Can be run multiple times safely
  • .claude/commands/release/release.md: When the user runs `/release`, execute the following steps:
  • .claude/commands/release/release.md: Execute the automated release process:
  • .claude/commands/release/release.md: ✅ Builds the package using `uv build`
  • .claude/commands/release/release.md: Test installation: `uv tool install basic-memory --prerelease=allow`
  • .claude/commands/release/release.md: Test Homebrew installation: `brew install basicmachines-co/basic-memory/basic-memory`
  • .claude/commands/release/release.md: gh workflow run mcp-registry-publish.yml
  • .claude/commands/release/release.md: curl "https://registry.modelcontextprotocol.io/v0.1/servers?search=basic-memory" · uses the network
  • .claude/commands/release/release.md: Pull latest from GitHub: `git pull origin main` · uses the network
  • .claude/commands/release/release.md: Create release branch: `git checkout -b release/v{VERSION}`
  • .claude/commands/release/release.md: Commit (`git commit -s -m "..."`), push, and open a PR against `basicmachines-co/basicmemory.com`
  • .claude/commands/release/release.md: Pull latest from GitHub: `git pull origin main` · uses the network
  • .claude/commands/release/release.md: Create release branch: `git checkout -b release/v{VERSION}`
  • .claude/commands/release/release.md: Commit: `git commit -s -m "docs: add v{VERSION} release notes"`
  • .claude/commands/release/release.md: Install with pip/uv:
  • .claude/commands/release/release.md: uv tool install basic-memory --prerelease=allow
  • .claude/commands/release/release.md: Install with Homebrew:
  • .claude/commands/release/release.md: brew install basicmachines-co/basic-memory/basic-memory
  • .claude/commands/release/release.md: uv tool upgrade basic-memory --prerelease=allow
  • .claude/commands/release/release.md: To bump only the plugin/agent artifacts out of band, use `just set-packages-version <version>` (preview with `just set-packages-version-dry-run <version>`).
  • .claude/commands/spec.md: Execute the spec command: `/spec $ARGUMENTS`
  • .claude/commands/test-live.md: Execute comprehensive real-world testing of Basic Memory using the installed version.
  • .claude/commands/test-live.md: `phase` (optional): Specific test phase to run (`recent`, `core`, `features`, `edge`, `workflows`, `stress`, or `all`)
  • .claude/commands/test-live.md: When the user runs `/project:test-live`, execute comprehensive test plan:
  • .claude/commands/test-live.md: Run `git log --oneline -20` to examine recent commits
  • .claude/commands/test-live.md: Run the bash `date` command to get the current date/time.
  • .claude/commands/test-live.md: Execute test scenarios systematically
  • AGENTS.md: Install: `just install` or `pip install -e ".[dev]"`
  • AGENTS.md: Run all tests (SQLite + Postgres): `just test`
  • AGENTS.md: Run all tests against SQLite: `just test-sqlite`
  • AGENTS.md: Run all tests against Postgres: `just test-postgres` (uses testcontainers)
  • AGENTS.md: Run unit tests (SQLite): `just test-unit-sqlite`
  • AGENTS.md: Run unit tests (Postgres): `just test-unit-postgres`
  • AGENTS.md: Run integration tests (SQLite): `just test-int-sqlite`
  • AGENTS.md: Run integration tests (Postgres): `just test-int-postgres`
  • AGENTS.md: Run impacted tests: `just fast-test` or `just testmon` (pytest-testmon;
  • AGENTS.md: Run MCP smoke test: `just test-smoke`
  • AGENTS.md: Run all consolidated agent package checks: `just package-check`
  • AGENTS.md: Run Claude Code plugin checks: `just package-check-claude-code`
  • AGENTS.md: Run shared skills checks: `just package-check-skills`
  • AGENTS.md: Run Hermes plugin checks: `just package-check-hermes`
  • AGENTS.md: Run OpenClaw plugin checks: `just package-check-openclaw`
  • AGENTS.md: Run host-native agent harness checks: `just agent-harness-check`
  • AGENTS.md: Run benchmarks: `pytest test-int/test_sync_performance_benchmark.py -v -m "benchmark and not slow"`
  • AGENTS.md: Type check: `just typecheck` or `uv run ty check src tests test-int`
  • AGENTS.md: Type check (pyright): `just typecheck-pyright` or `uv run pyright`
  • AGENTS.md: Format: `just format` or `uv run ruff format .`
  • AGENTS.md: Run all static code checks: `just check` (runs lint, format, typecheck)
  • AGENTS.md: Run development MCP Inspector: `just run-inspector`
  • AGENTS.md: **Test:** `just fast-test` for pytest-testmon impacted tests, or a targeted `uv run pytest ...` command.
  • AGENTS.md: Run `just test-smoke` when you specifically need the MCP smoke flow.
  • AGENTS.md: If testmon is “cold,” the first run may be long.
  • AGENTS.md: `just package-check-openclaw` — runs the OpenClaw package install, copies top-level skills into the generated bundle, typechecks, lints, builds `dist/`, runs Bun tests, and performs `npm pack --dry-run`.
  • AGENTS.md: Before opening or updating a PR, run the checks that mirror the common required CI failures:
  • AGENTS.md: Run `just typecheck` in addition to targeted `ruff` and `pytest` commands when tests were added or changed.
  • AGENTS.md: Sign commits with `git commit -s` so DCO passes.
  • AGENTS.md: Add or update meaningful regression tests for bugs and risky behavior, prefer real code paths over mocks, and run the narrowest command that proves the change before widening verification.
  • AGENTS.md: connection.execute("PRAGMA journal_mode=WAL")
  • AGENTS.md: By default, tests run against SQLite (fast, no Docker needed)
  • AGENTS.md: Set `BASIC_MEMORY_TEST_POSTGRES=1` to run against Postgres (uses testcontainers - Docker required)
  • AGENTS.md: The recipes bump version metadata, run pre-flight checks, land the bump on `main` through a release PR, tag, and push the tag.
  • AGENTS.md: PyPI consumers install with `pip install basic-memory --pre`.
  • AGENTS.md: The recipe refuses a beta whenever `pyproject.toml` pins a FastMCP pre-release (`fastmcp==X.Y.ZbN`): installs then need `--prerelease=allow`, which uv also applies to basic-memory itself, so a beta on PyPI would become the default install for stable users.
  • AGENTS.md: **Release dry run:** `just release-dry-run v0.21.4` previews the consolidated version update without writing files.
  • AGENTS.md: **Development builds are not published to PyPI.** Documented installs pass `--prerelease=allow` (published releases through v0.23.2 pin a FastMCP pre-release), and uv applies that flag to basic-memory itself, so a `.devN` build on PyPI would outrank the stable release for every fresh install.
  • AGENTS.md: To try unreleased `main`, install from git: `uv tool install "basic-memory @ git+https://github.com/basicmachines-co/basic-memory" --prerelease=allow`.
  • AGENTS.md: **Post-release tasks** the recipe surfaces but doesn't run:
  • AGENTS.md: MCP Registry — after the version is live on PyPI, dispatch `.github/workflows/mcp-registry-publish.yml` (`gh workflow run mcp-registry-publish.yml`);
  • CLAUDE.md: Install: `just install` or `pip install -e ".[dev]"`
  • CLAUDE.md: Run all tests (SQLite + Postgres): `just test`
  • CLAUDE.md: Run all tests against SQLite: `just test-sqlite`
  • CLAUDE.md: Run all tests against Postgres: `just test-postgres` (uses testcontainers)
  • CLAUDE.md: Run unit tests (SQLite): `just test-unit-sqlite`
  • CLAUDE.md: Run unit tests (Postgres): `just test-unit-postgres`
  • CLAUDE.md: Run integration tests (SQLite): `just test-int-sqlite`
  • CLAUDE.md: Run integration tests (Postgres): `just test-int-postgres`
  • CLAUDE.md: Run impacted tests: `just fast-test` or `just testmon` (pytest-testmon;
  • CLAUDE.md: Run MCP smoke test: `just test-smoke`
  • CLAUDE.md: Run all consolidated agent package checks: `just package-check`
  • CLAUDE.md: Run Claude Code plugin checks: `just package-check-claude-code`
  • CLAUDE.md: Run shared skills checks: `just package-check-skills`
  • CLAUDE.md: Run Hermes plugin checks: `just package-check-hermes`
  • CLAUDE.md: Run OpenClaw plugin checks: `just package-check-openclaw`
  • CLAUDE.md: Run host-native agent harness checks: `just agent-harness-check`
  • CLAUDE.md: Run benchmarks: `pytest test-int/test_sync_performance_benchmark.py -v -m "benchmark and not slow"`
  • CLAUDE.md: Type check: `just typecheck` or `uv run ty check src tests test-int`
  • CLAUDE.md: Type check (pyright): `just typecheck-pyright` or `uv run pyright`
  • CLAUDE.md: Format: `just format` or `uv run ruff format .`
  • CLAUDE.md: Run all static code checks: `just check` (runs lint, format, typecheck)
  • CLAUDE.md: Run development MCP Inspector: `just run-inspector`
  • CLAUDE.md: **Test:** `just fast-test` for pytest-testmon impacted tests, or a targeted `uv run pytest ...` command.
  • CLAUDE.md: Run `just test-smoke` when you specifically need the MCP smoke flow.
  • CLAUDE.md: If testmon is “cold,” the first run may be long.
  • CLAUDE.md: `just package-check-openclaw` — runs the OpenClaw package install, copies top-level skills into the generated bundle, typechecks, lints, builds `dist/`, runs Bun tests, and performs `npm pack --dry-run`.
  • CLAUDE.md: Before opening or updating a PR, run the checks that mirror the common required CI failures:
  • CLAUDE.md: Run `just typecheck` in addition to targeted `ruff` and `pytest` commands when tests were added or changed.
  • CLAUDE.md: Sign commits with `git commit -s` so DCO passes.
  • CLAUDE.md: Add or update meaningful regression tests for bugs and risky behavior, prefer real code paths over mocks, and run the narrowest command that proves the change before widening verification.
  • CLAUDE.md: connection.execute("PRAGMA journal_mode=WAL")
  • CLAUDE.md: By default, tests run against SQLite (fast, no Docker needed)
  • CLAUDE.md: Set `BASIC_MEMORY_TEST_POSTGRES=1` to run against Postgres (uses testcontainers - Docker required)
  • CLAUDE.md: The recipes bump version metadata, run pre-flight checks, land the bump on `main` through a release PR, tag, and push the tag.
  • CLAUDE.md: PyPI consumers install with `pip install basic-memory --pre`.
  • CLAUDE.md: The recipe refuses a beta whenever `pyproject.toml` pins a FastMCP pre-release (`fastmcp==X.Y.ZbN`): installs then need `--prerelease=allow`, which uv also applies to basic-memory itself, so a beta on PyPI would become the default install for stable users.
  • CLAUDE.md: **Release dry run:** `just release-dry-run v0.21.4` previews the consolidated version update without writing files.
  • CLAUDE.md: **Development builds are not published to PyPI.** Documented installs pass `--prerelease=allow` (published releases through v0.23.2 pin a FastMCP pre-release), and uv applies that flag to basic-memory itself, so a `.devN` build on PyPI would outrank the stable release for every fresh install.
  • CLAUDE.md: To try unreleased `main`, install from git: `uv tool install "basic-memory @ git+https://github.com/basicmachines-co/basic-memory" --prerelease=allow`.
  • CLAUDE.md: **Post-release tasks** the recipe surfaces but doesn't run:
  • CLAUDE.md: MCP Registry — after the version is live on PyPI, dispatch `.github/workflows/mcp-registry-publish.yml` (`gh workflow run mcp-registry-publish.yml`);
  • benchmarks/AGENTS.md: Install: `uv sync --group dev`
  • benchmarks/AGENTS.md: Run tests: `uv run pytest -q`
  • benchmarks/AGENTS.md: Lint: `uv run ruff check .`
  • benchmarks/AGENTS.md: Type check: `uv run pyright`
  • benchmarks/AGENTS.md: `uv run pytest -q`
  • benchmarks/AGENTS.md: `uv run ruff check .`
  • benchmarks/AGENTS.md: `uv run pyright`
  • benchmarks/AGENTS.md: CLI entrypoint: `uv run bm-bench ...`
  • benchmarks/AGENTS.md: `uv run bm-bench datasets fetch --dataset locomo`
  • benchmarks/AGENTS.md: `uv run bm-bench convert locomo --dataset-path benchmarks/datasets/locomo/locomo10.json --output-dir benchmarks/generated/locomo`
  • benchmarks/AGENTS.md: `bash benchmarks/datasets/beam/download.sh` (BEAM data is never vendored;
  • benchmarks/AGENTS.md: `uv run bm-bench convert beam --tier 100K --output-dir benchmarks/generated/beam-100k`
  • benchmarks/AGENTS.md: Run retrieval:
  • benchmarks/AGENTS.md: `uv run bm-bench run retrieval --providers bm-local,mem0-local --dataset-id locomo --dataset-path benchmarks/datasets/locomo/locomo10.json --corpus-dir benchmarks/generated/locomo/docs --queries-path benchmarks/generated/locomo/queries.json --output-root benchmarks/runs --allow-provider-skip`
  • benchmarks/AGENTS.md: Run end-to-end QA scoring:
  • benchmarks/AGENTS.md: `uv run bm-bench run qa --run-dir benchmarks/runs/<run-id> --answerer claude:claude-haiku-4-5 --judge claude:claude-sonnet-4-6`
  • benchmarks/AGENTS.md: BEAM nugget scoring (post-hoc, after `run qa` on a BEAM run):
  • benchmarks/AGENTS.md: `uv run bm-bench run beam-score --run-dir benchmarks/runs/<run-id> --judge claude:claude-sonnet-4-6`
  • benchmarks/AGENTS.md: `uv run bm-bench run agent-tasks --surfaces bm --model openai-compat:<model>@<base_url> --bm-local-path <bm-checkout>`
  • benchmarks/AGENTS.md: `uv run bm-bench validate-artifacts --run-dir benchmarks/runs/<run-id>`
  • benchmarks/AGENTS.md: `uv run bm-bench publish --run-dir benchmarks/runs/<run-id> --destination benchmarks/results/public`
  • benchmarks/AGENTS.md: `just bench-run-beam-100k`
  • benchmarks/AGENTS.md: `just bench-beam-score benchmarks/runs/<run-id>`
  • benchmarks/AGENTS.md: `just bench-run-bm-local`
  • benchmarks/AGENTS.md: `just bench-run-mem0-local`
  • benchmarks/AGENTS.md: `just bench-run-full`
  • benchmarks/AGENTS.md: `just bench-qa benchmarks/runs/<run-id>`
  • benchmarks/AGENTS.md: `just bench-publish benchmarks/runs/<run-id>`
  • benchmarks/AGENTS.md: `src/basic_memory_benchmarks/runner.py` - run orchestration
  • benchmarks/AGENTS.md: `benchmarks/runs/` - raw run artifacts
  • benchmarks/AGENTS.md: The benchmark command is typically invoked through `uv run ...` so `.venv/bin/bm` is used.
  • benchmarks/AGENTS.md: Ingest and search use a stable benchmark `user_id` namespace per run.
  • benchmarks/AGENTS.md: Prefer setting only required credentials for run reproducibility.
  • benchmarks/AGENTS.md: Always publish conversion code and run artifacts.
  • benchmarks/AGENTS.md: Sign commits: `git commit -s`.
  • integrations/hermes/skill/SKILL.md: **Search before answering.** If the user asks "what did we decide about X?", run `bm_search` first.
  • integrations/openclaw/AGENTS.md: **Build output** — `bun run build` emits `dist/` for `runtimeExtensions`;
  • integrations/openclaw/AGENTS.md: `scripts/bm-local.sh` runs BM from the monorepo root via `uv run --project ...` when available, then falls back to `bm` on PATH
  • integrations/openclaw/AGENTS.md: **Package CI** (root `.github/workflows/consolidated-packages.yml`): validates skills, typechecks, lints, builds, tests, and runs `npm pack --dry-run`.
  • integrations/openclaw/CLAUDE.md: **Build output** — `bun run build` emits `dist/` for `runtimeExtensions`;
  • integrations/openclaw/CLAUDE.md: `scripts/bm-local.sh` runs BM from the monorepo root via `uv run --project ...` when available, then falls back to `bm` on PATH
  • integrations/openclaw/CLAUDE.md: **Package CI** (root `.github/workflows/consolidated-packages.yml`): validates skills, typechecks, lints, builds, tests, and runs `npm pack --dry-run`.
  • integrations/pi/skills/basic-memory-pi-setup/SKILL.md: If the user wants MCP mode, install the adapter and switch transport:
  • integrations/pi/skills/basic-memory-pi-setup/SKILL.md: pi install npm:pi-mcp-adapter
  • integrations/pi/skills/basic-memory-pi-setup/SKILL.md: Run `/bm-status` and check the effective auto recall/capture state, then `/bm-recall setup` or `/bm-capture Pi setup checkpoint` to verify the path.
  • integrations/pi/skills/basic-memory-pi-setup/SKILL.md: For local Basic Memory development in a trusted workspace, set `BASIC_MEMORY_PI_TRUST_BM_COMMAND=1` and use `bmCommand` as an argv array such as `["uv", "run", "--project", "/path/to/basic-memory", "basic-memory"]`;
  • integrations/tau/skills/basic-memory-setup/SKILL.md: Locate the integration directory: the installed `~/.tau/extensions/basic-memory` from `bm install tau`, or `integrations/tau` in an explicitly identified Basic Memory checkout.
  • integrations/tau/skills/basic-memory-setup/SKILL.md: A packaged install does not require a source checkout.
  • integrations/tau/skills/basic-memory-setup/SKILL.md: If the extension is loaded, ask the user to run `/bm-status`.
  • integrations/tau/skills/basic-memory-setup/SKILL.md: A text reply does not run a slash command or control the current Tau session.
  • integrations/tau/skills/basic-memory-setup/SKILL.md: Consult current Basic Memory install docs rather than guessing package versions or changing the user's global Tau installation.
  • integrations/tau/skills/basic-memory-setup/SKILL.md: For a packaged install, with approval for dependency installation, use:
  • integrations/tau/skills/basic-memory-setup/SKILL.md: bm install tau --sync
  • integrations/tau/skills/basic-memory-setup/SKILL.md: Then give the user this command to run in their terminal:
  • integrations/tau/skills/basic-memory-setup/SKILL.md: uv run --project ~/.tau/extensions/basic-memory tau
  • integrations/tau/skills/basic-memory-setup/SKILL.md: For source development, with approval, run `uv sync --project <integration-directory>` and launch `uv run --project <integration-directory> tau -e <integration-directory>`.
  • integrations/tau/skills/basic-memory-setup/SKILL.md: `bm install tau` installs this setup skill and the prompt templates separately;
  • plugins/claude-code/skills/bm-checkpoint/SKILL.md: `git status --short`
  • plugins/claude-code/skills/bm-checkpoint/SKILL.md: tests or checks actually run
  • plugins/claude-code/skills/bm-checkpoint/SKILL.md: `## Verification`, for checks actually run and their outcomes
  • plugins/claude-code/skills/bm-orient/SKILL.md: If no config is present, continue against the default Basic Memory project and mention that setup has not been run.
  • plugins/claude-code/skills/bm-setup/SKILL.md: Run a short, adaptive interview (~2-3 minutes) and then write the configuration.
  • plugins/claude-code/skills/bm-setup/SKILL.md: Install it: `uv tool install basic-memory --prerelease=allow` (or `pip install basic-memory`), a version exposing the 1.0 `bm_*` tools.
  • plugins/claude-code/skills/bm-setup/SKILL.md: A purely local server (`uvx --prerelease=allow basic-memory mcp`) treats the path as a local directory and fails to create it (e.g. read-only `/`).
  • plugins/claude-code/skills/bm-setup/SKILL.md: Run `bm_project_list()`.
  • plugins/claude-code/skills/bm-setup/SKILL.md: Inspect it: `bm_list(path="/", project="<primaryProject>")` for the top-level folder layout (`bm_find` for recursive discovery), sample a few notes per folder (and, where a folder holds recurring typed notes, you may run `bm_schema_infer()` to see their shape).
  • plugins/claude-code/skills/bm-setup/SKILL.md: (This is the single knob for how proactive the assistant is — the hooks always run regardless.)
  • plugins/claude-code/skills/bm-setup/SKILL.md: I can install them alongside this plugin." These are the canonical, framework-agnostic skills (the same set OpenClaw bundles).
  • plugins/claude-code/skills/bm-setup/SKILL.md: (See "Install the shared skills" below.)
  • plugins/claude-code/skills/bm-setup/SKILL.md: **First, guard against clobbering a source checkout.** If `./skills` already exists, is tracked in git, and holds `memory-*` directories, you're inside the skills' own source repo (e.g. `basic-memory` itself) — the install would overwrite the working copy with published versions.
  • plugins/claude-code/skills/bm-setup/SKILL.md: In that case **skip the install** and tell the user the skills are already present as source;
  • plugins/claude-code/skills/bm-setup/SKILL.md: Otherwise, run:
  • plugins/claude-code/skills/bm-setup/SKILL.md: If `npx` / the `skills` CLI isn't available, point the user at the manual install in the top-level [`skills/README.md`](../../../../skills/README.md).
  • plugins/claude-code/skills/bm-setup/SKILL.md: Writing the `basicMemory` block is also what stops the SessionStart hook's first-run nudge — the config's presence is the signal that setup has run.
  • plugins/claude-code/skills/bm-setup/SKILL.md: Use the CLI the hook uses (`basic-memory` / `bm` / `uvx --prerelease=allow basic-memory`).
  • plugins/claude-code/skills/bm-setup/SKILL.md: **Primary:** run the open-decision query the SessionStart hook runs against `primaryProject`: `… tool search --note-types decision --filters '{"status": "open"}' --page-size 5 --project <primaryProject>`.
  • plugins/claude-code/skills/bm-setup/SKILL.md: **Hook health:** run `basic-memory hook status --harness claude --project-dir <project-root>` with the first available `basic-memory`, `bm`, or `uvx --prerelease=allow basic-memory` launcher.
  • plugins/claude-code/skills/bm-setup/SKILL.md: the hooks already run.
  • plugins/claude-code/skills/bm-setup/SKILL.md: Run `/basic-memory:bm-status` anytime to see what I'm tracking."*
  • plugins/claude-code/skills/bm-status/SKILL.md: **CLI reachable?** Run `basic-memory --version`, then `bm --version`, then `uvx --prerelease=allow basic-memory --version`.
  • plugins/claude-code/skills/bm-status/SKILL.md: **Core hook health.** With the first available launcher, run `basic-memory hook status --harness claude --project-dir <project-root>`.
  • plugins/codex/skills/bm-checkpoint/SKILL.md: `git status --short`
  • plugins/codex/skills/bm-checkpoint/SKILL.md: tests or checks actually run
  • plugins/codex/skills/bm-checkpoint/SKILL.md: `## Verification`, for checks actually run and their outcomes
  • plugins/codex/skills/bm-orient/SKILL.md: Mention that setup has not been run.
  • plugins/codex/skills/bm-orient/SKILL.md: Run the `coding_session` topic search separately and include it only when `sessionProfile=coding` and the configured `repository` is present.
  • plugins/codex/skills/bm-setup/SKILL.md: If MCP tools are not available, run `basic-memory --version` or `bm --version`.
  • plugins/codex/skills/bm-setup/SKILL.md: If neither works, stop and tell the user to install Basic Memory and connect the MCP server.
  • plugins/codex/skills/bm-setup/SKILL.md: The plugin bundles an `.mcp.json` that starts `uvx --prerelease=allow basic-memory mcp`.
  • plugins/codex/skills/bm-setup/SKILL.md: `checkpointOnCompact`: whether post-compaction SessionStart asks Codex to run `bm-checkpoint`.
  • plugins/codex/skills/bm-setup/SKILL.md: Run `basic-memory hook status --harness codex --project-dir <repo-root>` (using `bm` or `uvx --prerelease=allow basic-memory` if needed).
  • plugins/codex/skills/bm-setup/SKILL.md: Tell the user that plugin hooks need to be reviewed and trusted in Codex before they run.
  • plugins/codex/skills/bm-share/SKILL.md: If no team projects are configured, stop and ask the user to run setup or add a target.
  • plugins/codex/skills/bm-status/SKILL.md: fallback `uvx --prerelease=allow basic-memory --version`
  • plugins/codex/skills/bm-status/SKILL.md: with the first available launcher, run `basic-memory hook status --harness codex --project-dir <repo-root>`
  • plugins/codex/skills/bm-status/SKILL.md: check `uv --version` in the current environment independently of CLI reachability;
  • plugins/codex/skills/bm-status/SKILL.md: uv is a required hook prerequisite
  • plugins/codex/skills/bm-status/SKILL.md: remind the user that Codex plugin hooks must be reviewed and trusted before they run
  • skills/AGENTS.md: Skills can be installed via `npx skills add` or copied manually into any agent's skills directory.
  • skills/AGENTS.md: memory-agents/SKILL.md # Create, run, and check Basic Memory Cloud agents
  • skills/AGENTS.md: memory-doctor/SKILL.md # Run bm doctor, explain findings, and apply fixes with consent
  • skills/AGENTS.md: Run `just check` from `skills/` or `just package-check-skills` from the monorepo root to validate the `memory-*/SKILL.md` frontmatter before committing changes.
  • skills/CLAUDE.md: Skills can be installed via `npx skills add` or copied manually into any agent's skills directory.
  • skills/CLAUDE.md: memory-agents/SKILL.md # Create, run, and check Basic Memory Cloud agents
  • skills/CLAUDE.md: memory-doctor/SKILL.md # Run bm doctor, explain findings, and apply fixes with consent
  • skills/CLAUDE.md: Run `just check` from `skills/` or `just package-check-skills` from the monorepo root to validate the `memory-*/SKILL.md` frontmatter before committing changes.
  • skills/memory-agents/SKILL.md: Agents run in Basic Memory Cloud only, on plans that include them.
  • skills/memory-agents/SKILL.md: Asked to create, change, run, or turn off an agent
  • skills/memory-agents/SKILL.md: Asked how an agent run went, what it changed, or why it did not run
  • skills/memory-agents/SKILL.md: with `agent`, whether that agent can run | | `bm_agent_run(agent="<agent>", project="<project>")` | Starts an agent on a note (`identifier`), a folder, or nothing;
  • skills/memory-agents/SKILL.md: returns the run id | | `bm_agent_get(run_id="<run id>")` | One run: status, notes changed, and the agent's last reply;
  • skills/memory-agents/SKILL.md: `whole_workspace=True` lists every run waiting for review | | `bm_agent_mark(decision="kept", run_id="<run id>")` | Mark a run `kept` or `dismissed`;
  • skills/memory-agents/SKILL.md: with no `run_id`, `kept` keeps every waiting run |
  • skills/memory-agents/SKILL.md: Read the meeting note you run on.
  • skills/memory-agents/SKILL.md: An agent changes notes only in its own project, and it runs only if both the person who last edited the agent note and the person the run is for can edit that project.
  • skills/memory-agents/SKILL.md: An agent note last edited by another agent cannot run.
  • skills/memory-agents/SKILL.md: **Ask for a reply.** The last reply is the run's summary: what it created, linked, or left alone, and anything it was unsure about.
  • skills/memory-agents/SKILL.md: **Keep each run small.** A run has about seven minutes, including startup.
  • skills/memory-agents/SKILL.md: | Agent | Run it on | |---|---| | Cleanup | A hub or project index note;
  • skills/memory-agents/SKILL.md: # -> run id. Runs usually take one to a few minutes.
  • skills/memory-agents/SKILL.md: bm_agent_get(run_id="<run id>", project="work")
  • skills/memory-agents/SKILL.md: Ask before running one, unless the user has just asked for that run.
  • skills/memory-agents/SKILL.md: `bm_agent_get(run_id="<run id>", project="<project>")` shows the status, the notes the run created, edited, moved, or deleted, and the agent's last reply.
  • skills/memory-agents/SKILL.md: Every reply is also kept in a run log note, `agents/runs/<agent> run <id>`.
  • skills/memory-agents/SKILL.md: A queued run may be waiting: for the target note to settle, for a free slot (a workspace runs a few agents at once), or for another run on the same note.
  • skills/memory-agents/SKILL.md: When a run is skipped, its reason says why:
  • skills/memory-agents/SKILL.md: the detail names the field | | `agent_disabled` | Set `enabled: true` | | `agent_changed` | The agent note changed after the run was queued;
  • skills/memory-agents/SKILL.md: run it again | | `agent_not_by_a_person` | A person, or an assistant acting for one, saves the agent note again | | `agent_removed`, `trigger_changed` | The agent note or the target note was deleted | | `instruction_author_has_no_access`, `requester_has_no_access` | That person needs a …[+123 chars]
  • skills/memory-agents/SKILL.md: A failed run says why as well: `timeout` (the run ran out of time;
  • skills/memory-agents/SKILL.md: give it a smaller job) or a model error (run it again).
  • skills/memory-capture/SKILL.md: **Always run the same-thread lookup** before deciding to create or update.
  • skills/memory-ci-capture/SKILL.md: Treat it as the immutable source of truth for repository, event type, PR number, workflow run, SHA, source URL, timestamps, and deployment environment.
  • skills/memory-ci-capture/SKILL.md: For production deploys, focus on what reached production, the deployed SHA, environment, workflow run, and verification evidence.
  • skills/memory-comark/SKILL.md: In Basic Memory Cloud, `bm_read(identifier="<note>", view="text", project="<project>")` returns the note as a reader sees it: every component as plain Markdown, with live queries run now.
  • skills/memory-comark/SKILL.md: Elsewhere, only the browser runs the query, so run the equivalent read yourself (for example `bm_search` with metadata filters;
  • skills/memory-doctor/SKILL.md: The fixes it suggests do change things, so run them only after the user agrees.
  • skills/memory-doctor/SKILL.md: Without `--skip-self-test`, doctor also runs a self-test: it writes, indexes and searches a note in a throwaway sandbox, which takes a few seconds and proves the install itself works.
  • skills/memory-doctor/SKILL.md: Run it when the report is clean but something still seems broken.
  • skills/memory-doctor/SKILL.md: Run the commands the user approves.
  • skills/memory-doctor/SKILL.md: Run `bm doctor --skip-self-test --json` again and confirm the findings are gone.
  • skills/memory-ingest/SKILL.md: **A file instead of pasted text.** For a PDF, Word, PowerPoint, or CSV file in the project, and if the `bm` CLI is available, run `bm import document <path>`.
  • skills/memory-literary-analysis/SKILL.md: The two rules that matter across a 100+ chapter run:
  • skills/memory-literary-analysis/SKILL.md: Store the map in the project (a note or a small JSON file) so later batches — and a resumed run after context compaction — do not have to rediscover it.
  • skills/memory-literary-analysis/SKILL.md: fix the spelling or add the alias, then re-run the chapter.
  • skills/memory-literary-analysis/SKILL.md: **Validate periodically.** Run `bm_schema_validate(project="<work-name>")` after each batch, not just at the end.
  • skills/memory-notes/SKILL.md: Day points run "from that date onward", so a due-date window also returns items that are already overdue.
  • skills/memory-okf/SKILL.md: With the `bm` CLI and a local project, you can run the export and check it:
  • skills/memory-okf/SKILL.md: Run `bm okf check` on a bundle, not on the project.
  • skills/memory-onboarding/SKILL.md: **Check the live docs when unsure.** Basic Memory's documentation is agent-readable: fetch `https://docs.basicmemory.com/llms.txt` for an index, and any page as clean markdown via its `raw/....md` URL (e.g. `raw/reference/mcp-tools-reference.md`, `raw/concepts/schema-system.md`). · uses the network
  • skills/memory-onboarding/SKILL.md: **Migrate existing notes** *(restructure path)* → execute the approved old→new mapping from Phase 2 before seeding anything: move each existing note to its new home, set its note type, add the observations its schema requires, and update indexes as notes land.
  • skills/memory-onboarding/SKILL.md: **Validate** → run `bm_schema_validate` on the seed notes AND any migrated notes;
  • skills/memory-onboarding/SKILL.md: Run short exercises:
  • skills/memory-quest/SKILL.md: When you tell the user to run Memory Quest again, use their host's form: `/memory-quest` in Claude Code, `$memory-quest` in Codex, or just asking for it in a chat app.
  • skills/memory-quest/SKILL.md: Tell the user to connect it and run Memory Quest again.
  • skills/memory-quest/SKILL.md: Tell the user to install the Basic Memory plugin for their assistant, or to save the memory routine from the Memory Quest panel in their assistant's instructions, then start a fresh conversation and run Memory Quest again.
  • skills/memory-quest/SKILL.md: Ask the user to open **https://app.basicmemory.com/memory-quest** and paste the code it shows. · uses the network
  • skills/memory-quest/SKILL.md: Say that the mission stays incomplete and they can run Memory Quest again any time.
  • skills/memory-quest/SKILL.md: When this machine has a local project with the same name as a cloud one, which is common because every local install creates `main`, a local Basic Memory server writes the note to the local copy however you address it, by name, workspace-qualified name, or ID.
  • skills/memory-quest/SKILL.md: If no project is listed as `cloud`, stop and tell the user to create one in Basic Memory Cloud (or connect their cloud account), then run Memory Quest again.
  • skills/memory-quest/SKILL.md: If Memory Quest still shows Mission 8 as current after a minute, the usual cause is an expired or replaced code: get a new code and run Memory Quest again.
  • skills/memory-schema/SKILL.md: **Run diff** to see current state: `bm_schema_diff(note_type="Meeting", project="<project>")`
  • skills/memory-tasks/SKILL.md: **Schema validation is your friend** — Run `bm_schema_validate(note_type="Task", project="<project>")` periodically to catch incomplete tasks

MCP servers (4)

  • README.md (basic-memory): uvx --prerelease=allow basic-memory mcp
  • README.md (basic-memory): uvx --prerelease=allow basic-memory mcp
  • plugins/chatgpt/.mcp.json (basic-memory): https://cloud.basicmemory.com/mcp · uses the network
  • plugins/codex/.mcp.json (basic-memory): uvx --prerelease=allow basic-memory mcp

Hooks (4)

  • plugins/claude-code/hooks/hooks.json (SessionStart): uv run --quiet --script "${CLAUDE_PLUGIN_ROOT}/hooks/session_start.py"
  • plugins/claude-code/hooks/hooks.json (PreCompact): uv run --quiet --script "${CLAUDE_PLUGIN_ROOT}/hooks/pre_compact.py"
  • plugins/codex/hooks/hooks.json (SessionStart): uv run --quiet --script "${PLUGIN_ROOT}/hooks/session_start.py"
  • plugins/codex/hooks/hooks.json (PreCompact): uv run --quiet --script "${PLUGIN_ROOT}/hooks/pre_compact.py"

Install scripts (1)

  • src/basic_memory/cli/commands/install.py: python src/basic_memory/cli/commands/install.py
  • Medium risk: runs-instruction-instruction-network (.claude/commands/release/release.md:106)
  • Medium risk: runs-instruction-instruction-network (.claude/commands/release/release.md:119)
  • Medium risk: runs-instruction-instruction-network (.claude/commands/release/release.md:135)
  • Medium risk: runs-mcp-server-unpinned-runner (README.md:284)
  • Medium risk: runs-mcp-server-unpinned-runner (README.md:340)
  • Medium risk: runs-mcp-server-unpinned-runner (plugins/codex/.mcp.json)
  • Medium risk: runs-instruction-instruction-network (skills/memory-onboarding/SKILL.md:66)
  • Low risk: network-instructions (AGENTS.md:17)
  • Low risk: network-instructions (CLAUDE.md:17)
  • Low risk: scripts-present (plugins/claude-code/hooks/pre_compact.py)
  • Low risk: scripts-present (plugins/claude-code/hooks/session_start.py)
  • Low risk: network-instructions (plugins/claude-code/skills/bm-setup/SKILL.md:24)
  • Low risk: scripts-present (plugins/codex/hooks/pre_compact.py)
  • Low risk: scripts-present (plugins/codex/hooks/session_start.py)
  • Low risk: scripts-present (src/basic_memory/cli/commands/install.py)

Attribution and licence

Created by
Basic Machines
Declared authors
  • Basic Machines (declared in pyproject.toml)
  • Paul Hernandez (declared in CITATION.cff)
Publisher
Basic Machines (Official Basic Machines project)
Source
basicmachines-co/basic-memory · commit 370ae9d
Licence
GNU Affero General Public License v3.0 only (files served here)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by Basic Machines.

Install from source

461 of its files are not served here, so there is no ZIP. basicmachines-co/basic-memory at 370ae9d