Skip to main content
Glama

Gingugu

Long-term memory for AI coding agents.

Gingugu is an open-source MCP server. One SQLite file on your machine. It keeps what your agent learned — decisions, bugs, gotchas, the why behind the code — and brings it back at the moment it matters, across sessions, repos, and projects. No cloud, no API keys, no telemetry.

🌐 gingugu.com — the tour, with live demos of spreading activation and the Codebase X-ray.

Python MCP SQLite License Glama


📋 Table of Contents


Related MCP server: mnemos

Why Gingugu

Every session with an AI assistant starts from zero. The decisions you made yesterday, the bug you fixed last week, the reason the auth code is shaped the way it is — gone. You explain it again, or the agent guesses.

Gingugu is a structured long-term brain the agent talks to over MCP:

  • Remembers across sessions, repos, and projects

  • Organizes knowledge as typed memories in namespaces, linked by typed relations

  • Ranks memories by relevance, freshness, access, and confidence

  • Surfaces what matters at session start, on a prompt, or before a tool call

  • Consolidates duplicate and related knowledge on demand

Memory comes in three layers, loaded in this order: crow, shared across every project (your rules, preferences, lessons); an optional persona, one agent's own reflections; and a project namespace per repo (decisions, bug history, deploy quirks).

How it is built

The design calls behind it, each a property of the code:

  • One file, your machine. Memories, the full-text index and the embeddings live in one SQLite file. Embeddings run locally (fastembed, or your own Ollama). A shared brain is optional: gingugu serve behind your own scoped tokens.

  • No AI decides what is true. Ranking is arithmetic you can read, with a per-hit score breakdown on request. The dream pass is PageRank and label propagation, and it only proposes — you accept or reject.

  • Dormant, never deleted. Untouched memories rest; recall wakes them. Only an explicit forget removes anything, and a hard delete asks you first.

  • Memory comes to the agent. Hooks do the remembering: a session-start contract, involuntary recall, tripwires, and a stop hook that checks real work got written down.

  • It knows when it might be stale. State claims ("PR #10 open") are tracked apart from the prose, point-in-time notes get review hints, and a newer memory that resolves a claim names the ones it made wrong.

  • Works where you work. Any MCP client; gingugu init wires Claude Code, Windsurf, Cursor, and Cline. Subagents get a fenced, pre-loaded slice of the brain.

  • Secrets stay out of the context. The vault is your OS keychain, and credential_get can write a secret into a 0600 file and hand the agent only the path.

The protocol ships with it

Storage is the easy half. A memory server that an agent never writes to is an empty database, and an agent left to its own judgement will save almost nothing worth keeping — the failure mode isn't retrieval, it's discipline.

So Gingugu ships the discipline too. gingugu init wires a repo in one command and installs a SessionStart hook that injects the memory protocol at the top of every session: load these namespaces, check memory before asking a question already answered, save at the moment of observation rather than batching to the end, build a relation only when it records something search cannot infer. There is no rules file to paste and nothing to remember to do — the harness runs it whether or not the agent feels like it. A stop hook then checks that a session with real work in it actually wrote something down. Three more hooks bring memory to you: involuntary recall surfaces what your prompt woke, tripwires stop a tool call that a memory says must not be missed, before it runs, and warm minions hand a subagent a fenced, pre-loaded brain of its own. Agents sharing a brain can also leave each other posts on the agent board (board), which is not memory: addressed, read once (a task stays up until it is claimed or done), never ranked. Claude Code gets a post with your next prompt; gingugu board watch wakes an idle Codex agent when one arrives. Codebase X-ray (code_xray) maps a repository's import graph - Python, TypeScript/JavaScript, Go and Terraform (a Lambda's .tf file leans on the handler code it deploys, and .tftest.hcl files are its tests): before an edit, an agent asks what the change reaches and which tests to run, and which files the rest of the code leans on. It reads your checkout on your machine, even when the brain is remote, and rebuilds itself whenever the code changes. The tool hook also tells the agent what an edit reached: right after an edit of a source file (Python, TypeScript/JavaScript, Go or Terraform) it names the callers in other files of the functions the edit touched and the tests nearest them, and after an edit that removes a key ("status", a keyword argument, an object key) it lists the files that still read it, as text matches rather than import edges, and it stops an edit only when it is blind - a file other files import that the agent never read this session. After a shell command it says what the source files it wrote reach, and a read hook brings a map on arrival: the first read into a repo adds an overview of it, and each file read adds that file's neighbourhood (who imports it, what it imports). For an agent that never fires those hooks, gingugu xray brief (or code_xray with action: "brief") hands it the same map of a task: the changed files by rank and what they reach. A board post that names a range (a line of its own, xray: main..feature/x) arrives with that brief, rendered on the receiving machine from its own checkout. The line can name the repo first (xray: acme/widget main..feature/x), so a receiver running somewhere else finds its checkout of it; with none, it gets one line naming the gingugu xray brief --range to run in the repo. The same hooks add scar tissue: when an agent first reads a source file, or is stopped before a blind edit of one, the memories of the repo that name that file (the bugs, decisions and architecture notes it has cost before) arrive with it, top three by weight. In a Python, TypeScript/JavaScript or Go repo the X-ray also sees functions, not just files: the edit tripwire names the definitions an edit lands in and who calls them, a file read names its most-called definitions, and code_xray with action: "callers" lists one function's callers and everything that reaches it by call. Call counts are a lower bound - a call it cannot prove is counted, never guessed. The X-ray also reads the repo's git history as a second graph: code_xray with action: "history" (or gingugu xray history) names the hotspots - load-bearing files that keep changing - and the files that change together, flagging the pairs where neither imports the other, the dependency no import line shows. Tracked files outside the import graph (YAML, HCL) are ranked by churn x authors in their own others list and coupled like any other file. A file read names its top three such partners. action: "blindspots" (or gingugu xray blindspots) lists the imported files no test imports or is named for, by reach over the number of people who have touched them: where a change would go furthest with the least review. action: "docs" (or gingugu xray docs) turns a runbook's path mentions into a map: which docs cite a file, in this repo and in the sibling checkouts beside it, so a change names the runbooks worth re-reading. A path counts only when it resolves to exactly one file; the brief adds the docs that cite the changed files, and the docs still citing a deleted or renamed one. action: "links" (or gingugu xray links) finds the wiring no import shows: which other checkouts on this machine lean on this repo, and what it leans on, by the hosts, routes, images, packages, tables, CI checkouts, git-sourced Terraform modules and repo@sha cites the code already names. Nothing is declared in any repo. Each link carries the file and line that shows it, and is certain only when exactly one other repo provides the name; anything looser is kept and flagged. With files it adds who outside leans on them and the ripple across repos, and the brief gains Other repos leaning on these files. A repo named outright (a hyphenated name, owner/name, or a GitHub URL) counts as a whole-repo link flagged named, and the read hook and edit note name the outside files leaning on the file you are touching. Generated code (EF migrations, designer files, protobuf and the like) is skipped, and gingugu xray links --warm fills every checkout's cache up front. action: "env" (or gingugu xray env) does the same inside one repo for environment variables: the files that read DB_URL and the compose file, manifest, workflow, Dockerfile, Terraform environment block or env-named map or example template that sets it, with the names read but set nowhere here, or set but read nowhere, first. Names and line numbers only; a real dotenv file is never opened. action: "tables" (or gingugu xray tables) does the same for database tables: nothing imports orders, so it lists the files that query a table and the migration, schema file or model that defines it, with the tables defined nowhere here, dropped but still used, or used nowhere first. Columns and ORM use through model classes are out of scope (the import graph covers the latter). action: "surface" (or gingugu xray surface) is the attack-surface map: every entry point (an MCP tool, an HTTP route, a CLI command, a queued task, a script's main, an AWS Lambda handler) with the dangerous calls it reaches through the call graph - command execution, code evaluation, deserialisation, SQL built at runtime, file writes, secrets, network calls and database tables - most dangerous and nearest first, each with the shortest path, then the sinks no entry reaches. Python, TypeScript/JavaScript and Go; test files left out; files narrows it to the entries in them or reaching into them. The call graph is a lower bound and a listed path says the code can get there, not that outside input does. Entries are named by what they answer to (http POST /users, an MCP tool name, a CLI command), including router prefixes mounted in other files. A file's first read adds a Surface: line, and an edit says when it makes a sink reachable from an entry point; MEMORY_XRAY_SURFACE=off silences both. Sinks come from a fixed list per language, and nothing else is stored. action: "variants" (or gingugu xray variants) compares the files tracked by sibling checkouts that are flavours of this repo (app-us, app-gov, app-eu), found by name, and reports drift as changed lines over lines, with the files that differ most and the files only one side has. Only names and counts are reported; no file content leaves the machine. action: "routes" (or gingugu xray routes) joins the routes this repo serves to the calls that reach them: nothing imports a route, so a frontend's fetch('/api/users') and the handler that answers it never meet in the import graph. It lists the routes each file serves with who calls each, and the calls each file makes with what serves each, and without files every route by its callers with the calls served nowhere here first. The join follows a router's rules (a complete route matches only its exact shape, the most specific route wins, then the server nearest the caller), and a path inside a URL to another host never joins. A file's first read adds a Routes: line (which also marks a call served nowhere here when the map is trustworthy), and an edit says when it adds a call served nowhere here or stops serving a route other files still call; MEMORY_XRAY_ROUTES=off silences both. How many routes it finds depends on which frameworks the surface map reads routes from: FastAPI, Starlette, Flask (blueprints, flask-restx and flask-restful resources), Django (path, re_path, class-based views, DRF routers), Express, Koa, Fastify, Hono, NestJS, Next.js app-router route.ts files, and Go's net/http, gin, echo and chi (groups and group closures included).

That is the part that makes the memory worth having, and it is in the box.

Retrieval quality

Hybrid retrieval (BM25 over FTS5 + local embeddings, fused with Reciprocal Rank Fusion) measured with the in-repo bench/ toolset — MRR 0.828, recall@1 0.611, recall@5 0.983.

Measured over 30 labeled questions against a real working brain (~1,100 memories), not a public benchmark suite, so read it as a regression baseline for this workload rather than a cross-product comparison. The runner is deterministic and committed, so you can point it at your own store and get your own numbers: python -m bench --help.

The benchmark can also build its own labeled question set from your store (python -m bench --db <store> --generate-probes <out>), by picking questions whose answer is provable rather than hand-judged: a phrase that occurs in exactly one memory has exactly one correct answer. That gives you a golden set sized to your own brain without labeling anything by hand, and it stays local.

Where this goes long-term — federated, org-wide agent memory — lives in docs/enterprise-vision.md.


FAQ

Those are great if you live in one tool. The moment you switch between Claude Code in the morning and Cursor in the afternoon, the memory is gone. Gingugu's memory follows you across every MCP client, lives on your machine, and is programmable (24 tools, structured types, relationships, confidence levels). The built-ins are convenience features. Gingugu is infrastructure.

Both, actually. We do hybrid retrieval out of the box: BM25 over FTS5 + local semantic embeddings, fused with Reciprocal Rank Fusion. No vector DB server required.

Why this stack:

  1. No deployment. One SQLite file holds memories, FTS5 index, and embeddings. No Postgres, no Pinecone, no Chroma server.

  2. Two embedding backends — pick one:

    • fastembed (default) — ONNX-based, no PyTorch, ~80MB model download to ~/.cache/fastembed. Works fully offline after first use.

    • Ollama — delegates to your already-running Ollama process via its HTTP API. Zero extra memory footprint. Set MEMORY_EMBEDDINGS_BACKEND=ollama.

  3. It composes. Hybrid relevance feeds the composite (relevance × freshness × access × confidence) — every signal in one engine.

You can disable semantic search via MEMORY_EMBEDDINGS_ENABLED=false and fall back to BM25-only.

Usable today for local personal workflows. 5,300+ tests passing covering storage, search, migrations, concurrency, credentials, hooks, the board, and the X-ray. Hardened against adversarial input and write contention. WAL mode for concurrency. CI matrix across Python 3.11–3.13 on Linux/macOS/Windows. Dogfooded daily in this repo (the memories you see referenced in commits are Gingugu memories).

It's still early — broader real-world validation across MCP clients, databases at large scale, and long upgrade horizons is the work ahead. Treat it as an early cognitive-runtime framework, not a finished product. See SECURITY.md for the threat model, and docs/future-architecture.md for where this is headed.

SQLite FTS5 comfortably handles millions of rows. Gingugu adds composite re-ranking on top, but only over a small candidate pool (4× limit). For typical personal/team use it should hold up well — though we haven't yet benchmarked at the 100k+ memory scale. Use memory_consolidate to merge duplicates or summarize clusters when things sprawl.

It's a local CLI/server tool. Python's SQLite + keyring + asyncio story is mature, the install footprint via uv is small, and there's no JS bundling or Rust toolchain required to use it. The MCP SDK is first-class in Python.


Features

Feature

Description

🏷️ Namespace Scoping

Memories auto-scoped to repos/projects with cross-repo pattern sharing

🔍 Hybrid Search

SQLite FTS5 (BM25) + semantic embeddings fused with Reciprocal Rank Fusion. Two backends: fastembed (ONNX, offline) or Ollama (zero extra footprint, uses your existing Ollama process)

⏰ Temporal Intelligence

Trust-led scoring, dormancy tracking (never forgets), "last confirmed" tracking, spreading activation

🔔 Review Hints

Point-in-time memories ("PR #947 open, waiting on…", passed expiry dates) get advisory staleness flags on every read - you reconcile, the server never mutates

🔗 Relationships

A typed graph over what similarity can't see: supersedes, contradicts, caused_by, parent_of/child_of (related_to as a fallback)

🎯 Confidence Levels

verified → inferred → stale → deprecated lifecycle

🧹 Consolidation Tools

Find near-duplicate clusters (read-only suggest scan), then merge, summarize, or deduplicate on demand

🚀 Auto-Context

Surfaces relevant memories on session start - one call loads many namespaces deduped, with an optional compact mode for lighter payloads

📊 Health Metrics

Memory stats, dormancy reports, review sweep, namespace overviews

🔐 Credential Vault

Secure service-bundle storage for API keys/tokens via OS Keychain

📌 Pinned Tier

The handful of rules that must never be missed load first at every session start, exempt from ranking

🪝 Hooks

Session-start contract, involuntary recall on a prompt, tripwires that stop a tool call a memory forbids, an X-ray map when an agent first reads into a repo, warm minions for subagents, and a save-discipline stop hook — wired by gingugu init

🌙 Dream Pass

Deterministic consolidation over the relation graph (PageRank, label propagation, orphan reconnection), staged to a proposal queue you accept or reject - safe on a cron

📬 Agent Board

Agents sharing a brain leave each other addressed posts and claimable tasks; Claude Code gets them with the next prompt and gingugu board watch wakes an idle Codex agent; a reply goes back to the session that asked

🩻 Codebase X-ray

code_xray maps a repo's import graph (Python, TypeScript/JavaScript, Go, Terraform; parsed, never run; Terraform reaches the Lambda code it deploys): blast radius before an edit (dependents by hop, candidate tests) and the files the code leans on, ranked by directed PageRank. The tool hook says it before a blind edit of an imported file and names the callers right after any other edit, and a read hook brings a repo map on the first read and each file's neighbourhood the first time it is read. Both also name the repo's memories that mention the file (scar tissue). gingugu xray brief gives the same map of a change to an agent that fires no hooks

🌐 Memory Explorer UI

3D brain (one lobe per namespace), list, dashboard, timeline, and trust map — a read-only observer (live demo)

📡 Central Brain (optional)

gingugu serve runs the same server over HTTP behind Bearer tokens, each client scoped to its own namespaces; gingugu promote harvests a local brain's durable knowledge up to it with provenance stamps


Architecture

graph TD
    A[AI Assistant<br/>any MCP client] -->|MCP Protocol| B[Gingugu Server]
    HK[Harness Hooks<br/>session start · prompt recall<br/>tripwires · X-ray map · warm minions · stop] -->|reads| D
    HK -.->|injects context| A
    B --> C[Search Engine<br/>FTS5 BM25 + embeddings, RRF]
    B --> D[Storage Layer<br/>SQLite + WAL]
    B --> E[Decay Engine<br/>Scoring + Dormancy]
    B --> F[Context Engine<br/>Pinned tier + spreading activation]
    B --> H[Consolidation Engine<br/>Merge + Dedupe]
    B --> L[Dream Pass<br/>PageRank · clusters → proposals]
    B --> M[Agent Board<br/>posts · tasks · replies]
    B --> X[Codebase X-ray<br/>import graph · blast radius]
    B --> K[Credential Vault]
    C --> D
    E --> D
    F --> D
    H --> D
    L --> D
    M --> D
    X --> D
    K --> D
    K --> J[OS Keychain<br/>via keyring]
    D --> G[(~/.local/share/gingugu/memories.db)]

See docs/architecture.md for full technical details.


Setup

Prerequisites

  • Python 3.11+

  • uv (recommended) or pip

  • macOS, Linux, or Windows — the credential vault uses your OS-native secret store via keyring (macOS Keychain, Windows Credential Locker, Linux Secret Service/KWallet). On headless Linux without a Secret Service backend, everything works except storing secrets.

Install

# Recommended: uv (fast, manages Python for you)
uv tool install gingugu

# Or with pip
pip install gingugu

That's it. The gingugu command is now on your PATH.

git clone https://github.com/gingugu/gingugu.git && cd gingugu
uv sync
uv run gingugu  # or pip install -e .

Usable today. 24 MCP tools live. 5,300+ tests passing. Dogfooded daily in Claude Code and Windsurf — this repo's own memories live in a Gingugu database. Early and seeking broader real-world validation.

Upgrading

1. Upgrade the package.

uv tool upgrade gingugu     # if installed with uv
pip install --upgrade gingugu   # if installed with pip

2. Restart your MCP client. The client spawns the server, so a running client keeps the old code until it restarts. Schema migrations apply automatically on the next start, and a one-shot backup of your database (memories.db.bak-before-vN) is taken before any migration runs. Your memories are never rewritten by an upgrade.

3. Re-run gingugu harness in each repo (or gingugu init in a repo that uses only the brain) to pick up improvements to the hooks, minions, skills and the session protocol:

cd ~/code/my-repo && gingugu harness

A managed file that is still a stock copy of an older version is refreshed (reported as refresh), with the old copy saved as <name>.bak. A file you have edited is left alone, and one already current reports no change. --force replaces an edited one too, and every other managed file with it. Run --dry-run first if you want to see the changes before they land. Your .claude/settings.json is merged, not overwritten.

Whenever init replaces a file whose bytes differ, it saves the old version alongside it as <name>.bak first and says so in the output. A file it would not change is left untouched and gets no .bak.

gingugu can be reachable through more than one install at once, and they version independently. The usual surprise is a repo virtualenv shadowing the tool install, so a fresh shell resolves to a different binary than the one you just upgraded:

which -a gingugu   # note the -a: a bare `which` shows only the winner

Check your MCP client config too. If it points at a source checkout (e.g. uv --directory ~/code/gingugu run gingugu), the client runs that tree and a package upgrade changes nothing for it — restart the client instead. And because it runs whatever is checked out, a source-backed client also follows you onto a feature branch.

Version strings can't settle this on their own: an unreleased local checkout and the last published release report the same number until someone bumps it. When it matters, confirm with behaviour — run a command whose output you know changed in the new version.

Finish embedding after an upgrade (optional)

The server backfills embeddings in small batches at startup, on purpose - a cold model download must never block the process an editor is waiting on. That is the right default and the wrong tool right after an upgrade that changes what gets embedded: at one batch per startup, catching up a large existing brain could take dozens of restarts. gingugu embed runs the same backfill to completion in a single run instead:

gingugu embed [--batch-size N]

It's safe to interrupt and re-run - every batch commits, and a memory that already has a current vector is never re-selected. Takes about five minutes on an existing brain of a few thousand memories. Run it once after upgrading so every memory already in your brain is caught up immediately, rather than trickling in one batch per server restart.

Run as a remote server (optional)

By default gingugu runs over stdio (the client spawns it). To reach one shared instance over the network instead — a hosted/central brain — run:

gingugu serve   # streamable HTTP on http://127.0.0.1:8765/mcp

Every request needs a Bearer token. Set MEMORY_SERVE_TOKEN to pin one, or let the server generate and persist it to <db-dir>/serve_token (0600, reused after; the log shows the path, never the token). Set MEMORY_SERVE_HOST=0.0.0.0 to accept remote connections. On a loopback bind the server also rejects any Host header other than localhost (DNS-rebinding protection); on a LAN bind the Bearer token is the gate.

Beside /mcp and /healthz, the server exposes POST /token/derive and POST /token/release, the POST /hook/* routes used by remote-mode hooks (owner-only, except that a crew mate's scoped token may read /hook/inbox for its own persona), and the owner-only GET /ui/api/* routes that let gingugu ui on another machine show this brain (read-only; a scoped token gets 403).

TLS is on by default for any non-loopback bind, with nothing to set up. On first start the server generates a self-signed certificate for this machine's name (<host>, <host>.local, loopback) and keeps it in <db-dir>/tls/ (key 0600), reused after; the log shows its SHA-256 fingerprint. A loopback bind stays plain http, and local (stdio) mode never touches a certificate. gingugu remote login (below) pins that certificate for you over SSH. A client pointed at the URL directly will not trust a self-signed cert: give the server one it does trust (MEMORY_SERVE_TLS_CERT + MEMORY_SERVE_TLS_KEY, PEM), or opt out with MEMORY_SERVE_TLS=off on a network you trust. Extra names for the generated cert go in MEMORY_SERVE_TLS_SAN. With a cert the client trusts (or plain http), point a client at it directly with:

{ "mcpServers": { "gingugu": {
  "url": "https://<host>:8765/mcp",
  "headers": { "Authorization": "Bearer <token>" }
} } }

That token is the owner's and has full access. Give every other client - a second laptop, another assistant, a subagent - its own scoped token instead, limited to the namespaces it needs, each read-only or read-write:

gingugu token add laptop-2 --ns my-project=write,crow=read   # printed once
gingugu token add reviewer --ns '*=read,scratch=write'       # * = any namespace
gingugu token list
gingugu token revoke laptop-2                                # live on the next request

The server enforces the grant, not the client: anything outside it reads as not found, an omitted namespace means the token's namespaces, and the whole-brain tools (memory_export, memory_import, memory_dream, the credential vault, and namespace admin) are closed to scoped tokens. Only a SHA-256 of each token is stored, in <db-dir>/serve_tokens.json (0600).

This is one owner sharing a brain with their own clients, not a multi-tenant service.

Your own machines each get a full-access token of their own, named and revocable on its own: gingugu token add my-laptop --owner. To skip handling it at all, let the machine mint it over SSH with a key that can do nothing else. Give each machine its own key, and on the server authorize it with a forced command pinned to that machine's name (one line per machine, in the authorized_keys of the account the server runs as):

restrict,from="192.168.1.0/24",command="env MEMORY_DB_PATH=/srv/gingugu/memories.db /srv/gingugu/bin/gingugu token ssh-mint --name my-laptop" ssh-ed25519 AAAA... my-laptop

Use full paths (a forced command gets no login PATH) and the server's own MEMORY_DB_PATH, or the token lands in a file the server never reads. --name means the key can only ever rotate its own machine's token. To cut a machine off, delete its line and gingugu token revoke my-laptop. Without --name, any holder of the key could mint itself a new token after a revoke. Then, on the machine:

gingugu remote login http://brain.local:8765 --ssh me@brain.local   # token -> OS keychain
gingugu remote on https://brain.local:8765   # this machine now uses that brain
gingugu remote status
gingugu remote off                           # back to the local brain

login uses ~/.ssh/gingugu_mint by default (--key to change it) and ignores ~/.ssh/config, so a default identity can never stand in for the restricted key. Before it mints, login asks the same forced command for the brain's generated certificate (cert), pins it in <user-data-dir>/remote-tls/, and files the token under the https URL - the SSH channel you already trust is what vouches for the certificate. Before anything is rotated it also checks the live brain over https with that pin, so a certificate that is stale or does not name the host you dial stops the login with the fix spelled out, and the old token keeps working. From then on every remote client verifies the brain against that pin alone, and plain http to it is refused rather than sent. A machine already on that brain over http is moved to https. A brain with a certificate you brought is not pinned: give login its https URL (if a generated cert is still in <db-dir>/tls/ from before, delete it on the brain). If the brain's certificate is regenerated, run login again.

Local is the default: with no setting, nothing is remote. A single client can choose for itself with MEMORY_REMOTE_URL in its own environment (off forces local). A URL carrying a username or password is refused.

Remote mode: a bare gingugu relays

With a remote brain on (gingugu remote on, or MEMORY_REMOTE_URL), a bare gingugu never opens the local database. It relays MCP over stdio to gingugu serve, so every client config stays command: gingugu. It never falls back to the local DB for memory: it refuses to start (exit 2) when

  • MEMORY_GRANT is malformed, blank or *=write;

  • MEMORY_GRANT is set and MEMORY_CREDENTIALS_ENABLED is not false - a scoped client never gets the vault;

  • the keychain holds no token (run gingugu remote login);

  • the brain is unreachable - after retrying for up to 15 seconds, so a brain slow to answer after a quiet spell does not cost the session.

The credential vault stays on the machine: secrets are in its keychain and a remote brain cannot serve them. With credentials on (the default, and only without MEMORY_GRANT), the proxy serves the credential_* tools itself from the local database's vault tables, so they keep working - into included - and a credential call never reaches the brain, even while it is down. reveal is refused there: every other tool is relayed, so an inline secret could be carried off the machine, while into keeps it in a local 0600 file. Set MEMORY_CREDENTIALS_ENABLED=false and they are hidden and refused. A credential_delete is confirmed like every other delete (see Deletes below), and the vault checks it itself, on this machine.

The vault also has a CLI, in remote mode too, to list and delete credentials by hand:

gingugu credential list                        # names and fields, never a secret value
gingugu credential delete my-api               # type the name back to confirm
gingugu credential delete my-api --field token # one field only

delete needs a real terminal: input cannot be piped, and there is no --yes.

Deletes. Every destructive tool (hard memory_forget, cascading namespace delete, memory_consolidate with keep_originals=false, overwriting memory_import, credential_delete) takes a confirm argument, and none of them needs a terminal. The agent asks you in chat and passes confirm=true: that is the confirmation for an ordinary delete. confirm=false refuses. Leave it out and a client that can show a dialog asks you there; one that cannot (Claude Code's VS Code extension answers every dialog "decline" unseen) tells the agent to ask you and call again with confirm=true.

A big delete also needs you, not just the agent's say-so: a namespace delete, a credential delete (a keychain secret has no export and no undo), a consolidation or replace-import of more than 10 memories, and hard deletes past 10 in one session. gingugu's tool hook answers with Claude Code's own permission prompt, which is shown in auto and bypass mode too, and becomes a refusal where nobody can answer (claude -p). Your approval is good for that one call, for 15 minutes. With a remote brain the proxy takes it before relaying the call. Without the hook's approval, a local server gives a dialog if your client can show one and a refusal if not; over HTTP the owner's confirm=true stands (its proxy checked), and a scoped token gets a dialog or a refusal.

Two edges. The hook asks about any namespace delete, even an empty one, while the server's check applies to a non-empty cascade; for an import the hook counts the payload's memories and the server counts the ones it would actually overwrite. Hard deletes past 10 in a session are gated by the hook alone: it asks, and nothing is checked server-side.

Plain http to a non-loopback host starts with a warning. The proxy sends the machine token only to POST /token/derive, which trades it for a session token held in memory on the server (stamped with the owner token's name as its origin, the machine; the caller cannot claim one): valid at most an hour, SHA-256 only, at most 256 live, gone when the server restarts. A crew mate's scoped token may derive too, but only its own grant or narrower, at most 8 live (128 across all crew mates, so owners keep headroom), with no origin; revoking, rotating or narrowing it ends what it derived at once. A derived token cannot derive. When the proxy ends (the client closes it, or sends SIGTERM) it hands its session token back at POST /token/release, so a closed session stops counting against those caps. The session token carries the client's MEMORY_GRANT (full if unset) and its MEMORY_NAMESPACE as its home, so a call that names no namespace lands in the client's own namespace rather than the server's. The proxy refreshes the token at half its life and, when the connection drops, reconnects with backoff (0.25s doubling to 5s) and re-initializes the session itself. A call a restarted brain refused before running it is sent again, once; a call whose fate is unknown fails and is never replayed. New calls wait up to 5 seconds for the connection to come back, then fail.

{ "mcpServers": { "gingugu": {
    "command": "gingugu",
    "env": {
      "MEMORY_CREDENTIALS_ENABLED": "false",
      "MEMORY_PERSONA": "research",
      "MEMORY_NAMESPACE": "research",
      "MEMORY_GRANT": "research=write,crow=read"
    }
} } }

The Claude Code hooks follow the same switch. With a remote brain on, involuntary prompt recall, tripwires and minion warm-up ask the brain over POST /hook/recall, /hook/tripwires, /hook/trip, /hook/warmup, /hook/scars (the memories that name a file) and /hook/inbox (board mail) with the machine token (these routes refuse every other token). The brain embeds and ranks the prompt; tripwire rules come back to be matched on this machine, cached for a minute, with the last copy kept while the brain is unreachable. Which memories a session has already been shown stays on this machine and travels with each request. If the brain cannot answer, recall and warm-up stay quiet and tripwires keep their last rules; no hook ever reads a local database instead. A client fenced by MEMORY_GRANT has its hooks fenced the same way: the grant is applied on this machine before anything is sent (the routes trust the list they get). Setting MEMORY_GRANT in the MCP server's env block is enough: each gingugu server publishes the grant it runs under, and the hooks apply what their client's servers published. If the hooks' own environment sets it too, the two must agree, or the hooks stay quiet. A folder name the routes would refuse (say My Repo) is left out of the request. Every hook call carries the machine token and goes through the same pin as the proxy; on a brain served with MEMORY_SERVE_TLS=off it crosses the network unencrypted on every prompt.

Personas

MEMORY_PERSONA names an agent's own namespace. Involuntary prompt recall, tripwires and the SessionStart contract load crow (shared by every persona), then the persona, then the repo. A malformed value is ignored. With MEMORY_GRANT set, recall and tripwires drop any of those the grant cannot read, and an unusable grant keeps them quiet. To fence a persona to its own namespace, pair it with MEMORY_GRANT and MEMORY_NAMESPACE as above: it writes to research, reads crow, and anything else reads as not found.

Promote memories to a central brain (optional)

Once a central instance exists, gingugu promote harvests a local brain's durable knowledge up to it - the tribal-knowledge loop:

GINGUGU_SOURCE_TOKEN=<local-token> GINGUGU_TARGET_TOKEN=<central-token> \
  gingugu promote --source-url http://127.0.0.1:8765/mcp --source-ns my-project \
                  --target-url https://central:8765/mcp --target-ns org \
                  --contributor brian --dry-run   # drop --dry-run to actually write

The promoter is an MCP client; a brain this machine has pinned with gingugu remote login is verified against that pin. --ids narrows it to memories you pick; mid-session, the memory_promote tool does the same for a crew. It is read-only on the source, idempotent on re-runs (the receiving brain matches each copy to its source, so an edited memory replaces its earlier copy rather than adding one), and applies an exclusion filter: only verified memories move, minus episodic session noise, minus personal-context tags, and it refuses to promote anything that looks like a live secret - a shared brain must never become a credential leak. Each promoted memory carries a provenance stamp (source instance, namespace, contributor, timestamp).

Bring a crew mate aboard (optional)

A crew mate is an agent on its own machine with its own local brain that shares a brain with you through a scoped token - by default, write on a crew commons and nothing else. It promotes its lessons there with the memory_promote tool (or gingugu promote --to-crew in bulk), and talks to everyone on the board.

gingugu crew add polly                       # on the brain host: token + key line
gingugu crew join https://brain:8765 --ssh me@brain --name polly   # on the mate's machine
gingugu crew remove polly                    # offboarding, effective at once

The whole walk-through, for a first-time installer, is in docs/crew.md.

Schedule the dream pass (optional)

The consolidation pass computes structure over the relation graph - PageRank, communities, orphan reconnection - and stages what it finds for you to accept or reject. It never writes to memories, so it is safe to run unattended.

There is no daemon to install. Your OS already knows how to run something every fifteen minutes; what it cannot do is tell whether you are mid-session. So --if-idle puts that judgment in the command:

# cron
*/15 * * * * gingugu dream --if-idle

# or a launchd StartInterval agent / Windows Task Scheduler trigger
# running exactly the same command

Each tick opens the database, reads one row, and exits in well under a second unless the brain has actually gone quiet - by default 20 minutes untouched (MEMORY_DREAM_IDLE_MINUTES, or --if-idle=45 for a one-off). A skip exits 0, so your scheduler stays silent instead of mailing you every quarter hour.

"Untouched" means nobody used the brain, not no process is running - your editor keeps the MCP server alive all day whether or not you store anything, and that is exactly when the pass should get its turn. Come back to the keyboard mid-run and it stops between passes, keeping whatever it finished; the next run picks up the rest.

Review the queue with memory_dream(action="list"), and accept or reject each finding. A run takes roughly 24 seconds on a 1,900-memory brain.

Cluster findings come ranked by the tags their members already carry, weighted so that a rare tag counts for more than one spread across the whole store, and a group whose strongest tag is already on every member is not staged at all - accepting it could apply nothing. Each proposal shows the tag_score, tag_cohesion and tag_gap behind its position, so the ordering can be checked rather than taken on faith.

Edge findings pair an orphan with its closest neighbour, and the pass has no way to know which end an arrow starts at. When the pair is right but the direction is backwards, accept it with reverse=True rather than rejecting it.

Wake an agent when a post arrives (optional)

A reader is a persona plus a machine plus an agent session. The machine is the name of the owner token its session was derived from, so one persona on two machines (each with its own owner token) can post to itself across them, and the agent session (Claude Code's CLAUDE_CODE_SESSION_ID, hashed) lets two sessions on one machine do the same. Your own persona's posts are mail when both machines are known and differ, or both sessions are known and differ; the session that wrote a post never sees it. Every session of one persona, on any machine, reads a new post addressed to it, but a reply goes to the session that asked: it shows only to that session until it has sat unread for an hour, then to every session of the persona. The session is Claude Code's CLAUDE_CODE_SESSION_ID, stored only as a hash.

MCP has no standard way to wake an idle agent, so gingugu board watch is a plain command instead: it prints one JSON line (id, parent_id, from, origin, to, kind, namespace, body, text, xray) for every new post in your persona's board inbox, posts already waiting first.

gingugu board watch [--persona NAME] [--once] [--all] [--exec CMD] [--interval SECONDS]

The persona is --persona or MEMORY_PERSONA; without one it exits 2. Against a remote brain it is pushed (a subscriptions/listen on your inbox and on broadcasts, reconnecting with backoff); locally it polls the database read-only every --interval seconds (default 2). It never marks anything read - opening a post is the agent's act. A small cursor file in the data directory remembers the newest post delivered, so a re-armed watcher does not repeat itself (--all ignores it). --once exits after the first batch, as a "board wait". --exec CMD runs a shell command per post with the post JSON on stdin and GINGUGU_POST_{ID,PARENT_ID,FROM,ORIGIN,TO,KIND,NAMESPACE,BODY,TEXT,XRAY} in the environment (PARENT_ID is empty for a new thread, ORIGIN when the machine is unknown); a failing command is reported on stderr and the watch carries on. A post whose body has a line of its own xray: <range> also carries the X-ray brief of that range, rendered from the directory the watcher runs in (or, for xray: <repo> <range>, from the local checkout of that repo): in xray (null otherwise), appended to text, and in GINGUGU_POST_XRAY, for at most 3 posts per batch. The sender gets a nudge: the first board post of a session that names no range, sent from a branch ahead of the default branch, is stopped once by gingugu hook tool with the exact xray: <repo> <range> line to add; re-issue it unchanged if it is not about the branch. MEMORY_XRAY_BOARD=off turns both off.

Which harness wakes on what was measured, not assumed:

  • Claude Code (terminal and VS Code) wakes an idle session on each stdout line of a Monitor watch, and when a background command exits - and also when the Monitor expires. Do not keep gingugu board watch under Monitor: every 30 minute expiry and re-arm is a model turn that re-reads the whole context, so a session left open burns tokens all night with an empty board. Claude Code gets board mail through the prompt hook on the next prompt instead.

  • Codex CLI and the ChatGPT desktop app wake on a message queued from outside; a background command exiting does not wake Codex. Run the watcher as a sidecar that queues each post into the thread:

gingugu board watch --exec 'codex queue --thread <thread> --message "$GINGUGU_POST_TEXT"'

Configure Your MCP Client

Gingugu speaks standard MCP over stdio — it works with any MCP client. Claude Code, Claude Desktop, Cursor, Cline, and Windsurf are all first-class.

Add to ~/.codeium/windsurf/mcp_config.json — a ready-to-edit template lives at examples/mcp_config.json:

{
  "mcpServers": {
    "gingugu": {
      "command": "uv",
      "args": ["--directory", "/ABSOLUTE/PATH/TO/gingugu", "run", "gingugu"]
    }
  }
}

⚠️ Windsurf's mcp_config.json is global, not per-workspace, and it only interpolates ${env:VAR} / ${file:path} — not ${workspaceFolder}. So a single server instance serves every repo.

claude mcp add gingugu -- uv --directory /ABSOLUTE/PATH/TO/gingugu run gingugu

Or add the standard mcpServers block (as in the Windsurf example) to .mcp.json in your project root for a per-repo setup.

Add the same mcpServers block to ~/Library/Application Support/Claude/claude_desktop_config.json (macOS) or %APPDATA%\Claude\claude_desktop_config.json (Windows).

Add the same mcpServers block to ~/.cursor/mcp.json (global) or .cursor/mcp.json in your repo (per-project).

Cline → MCP Servers → Configure: add the same mcpServers block to cline_mcp_settings.json.

Any client that supports stdio MCP servers works — point it at:

command: uv
args: ["--directory", "/ABSOLUTE/PATH/TO/gingugu", "run", "gingugu"]

Scoping memories per repo: when your client's config is global (it can't see the active workspace), the assistant passes a namespace argument on each memory tool call (every tool accepts one). To instead pin a server instance to a single project, set a static MEMORY_NAMESPACE in the env block. See docs/architecture.md → Namespace Auto-Detection for the full resolution order. Reads never dead-end on the wrong namespace: a recall with no namespace on an unconfigured server searches all of them, and a scoped lookup that finds nothing widens to every namespace and says so with widened_from.

Configure Your AI Agent

The MCP server gives your assistant the tools, but it won't use them effectively without instructions telling it when and how to call them.

One command bootstraps a repo with the strongest setup Claude Code allows:

cd your-repo
gingugu init

It installs:

  • .claude/hooks/session_start.py — a SessionStart hook that auto-injects the memory startup contract into context every session. This is the key advantage: unlike a rules file (which is not guaranteed to be loaded into context), a hook fires every time, so the protocol is always present. The project namespace is derived from the repo's folder name automatically (in a git worktree, the main checkout's folder). A folder name that is not a plain name (letters, digits, ., _, -, starting with a letter or digit, up to 64 chars) is left out of the session-start contract, which then loads crow (and the persona) only.

  • .claude/hooks/stop.py — a Stop hook that blocks once if a working session never saved anything, guarding the "unsaved session vanishes" trap.

  • .claude/hooks/user_prompt_recall.py — a UserPromptSubmit hook for involuntary recall: memories that arrive because of what you typed, with no tool call and no decision by the assistant. Every other retrieval path answers "what did you ask for"; this one answers "what should have arrived anyway". Injected context reads as authoritative, so the design is built around refusing: a memory must clear a length floor, a similarity bar, a margin above the median of its own sweep, a keyword match on the same prompt, and not have been surfaced already this session. Pinned memories are skipped (they already load every session) and so are superseded ones. On a 548-prompt sample it fires on about 5% of turns. A harness notice (a <task-notification> for a finished background command or a monitor event) is not a prompt: it is stripped before the search. Every prompt long enough to search on is recorded, with what it surfaced, in the query_log table of your memory database - the same file as the memories. With a remote brain on, that database is the brain's, so the prompt text goes there. An agent with a MEMORY_PERSONA also gets its unread board posts on every prompt, short ones included, in the same injected block; nothing is marked read. Set MEMORY_RECALL_HOOK=off to disable it.

  • .claude/hooks/pre_tool_tripwire.py — a PreToolUse hook for tripwires: memories bound, with memory_tripwire, to a tool call that should not go unchallenged (a tag written into a commit, a merge of a stacked PR). Triggers are plain regexes over the tool name and its input, with no model judging relevance. The first matching call in a session is denied once, with the memory as the reason; re-issue it unchanged and it passes. Your memory tools never trip, so a bad tripwire can always be fixed. (Inside a subagent the minion fence still denies their write tools - that is a separate check, not a tripwire.) Each trip is recorded in query_log. Set MEMORY_TRIPWIRES=off to disable memory tripwires. The same hook also runs the X-ray edit tripwire: a blind edit - of a source file (Python, TypeScript/JavaScript, Go, Terraform) that other files import, which this session never read and never wrote - is denied once, with its direct importers, how far a change reaches and the nearest tests, plus the scar tissue for that file (see below); re-issue the edit and it passes. An edit of a file already read gets a note after it instead (gingugu hook edit, see below), with no extra scar friction, since its scars came with the read. It reads your checkout locally; only the scar lookup can ask a remote brain. Set MEMORY_XRAY_TRIPWIRE=off to disable it. It also runs the checkout guard, for repos where several sessions share one checkout: a Bash git switch, git checkout (unless paths follow --), rebase (other than --abort/--quit), reset --hard/--merge/--keep or stash (other than list/show) in the primary checkout is denied every time, because it would move or take away every other session's uncommitted edits. The reason points at a worktree (EnterWorktree, or git worktree add .claude/worktrees/<name>). Linked worktrees are never guarded, and commits, pull, push and reads pass. Prefix one command with GINGUGU_PRIMARY_OK=1 to let it through, or set MEMORY_CHECKOUT_GUARD=off to disable the guard. And it runs the big-delete gate: a big delete (a namespace delete, a credential delete, a consolidation or replace-import of more than 10 memories, hard deletes past 10 in one session) is answered with Claude Code's own permission prompt, in every permission mode. The approval is single-use, and the server (or, with a remote brain, the proxy) requires it before acting on confirm=true - except for hard deletes past 10, which only the hook gates.

  • .claude/hooks/post_tool_xray.py — a PostToolUse hook (matched to Read|Grep|Glob) that gives the agent the X-ray map on arrival: the first Read, Grep or Glob in a repo in a session adds a compact repo map (size, languages, import edges, the most imported files, entry points), and each source file Read adds who imports it, what it imports and the nearest tests it, once per file. It rides additionalContext next to the tool result and never blocks. Built locally from your checkout, sharing the edit tripwire's graph cache; the brain is never asked for the map. Set MEMORY_XRAY_MAP=off to disable it. The same read adds scar tissue: Scar tissue: N memories name this file: and the top three as - <type> <date>: <title> [<id>], then (+K more; memory_search ids=<id> reads one in full). A leaf file with no importers still gets its scar lines. Only the repo's own project namespace is searched (never crow), for bug, decision, architecture, fact and pattern memories that name the file by path; a name two files share is never guessed. Weight is type (bug 3, decision/architecture 2, fact/pattern 1; doubled when the memory's title names the file) divided by how many of the repo's files the memory names, newest first on a tie. It is derived at read time and stored nowhere. With a remote brain the lookup is the one thing the hook asks it (POST /hook/scars, owner token only); any failure reads as no scars. Set MEMORY_XRAY_SCARS=off to disable it. Before the scars, the read names the file's hidden partners from git history: Changes with (no import): <file> 80%, ..., up to three files it changes with though neither imports the other (code-maat's coupling thresholds; the log summary is cached by HEAD). Set MEMORY_XRAY_HISTORY=off to disable it.

  • .claude/hooks/post_bash_xray.py — a PostToolUse hook (matched to Bash) that gives the agent the X-ray of a shell command's writes: a sed -i, a codegen script or a git checkout writes behind the edit tripwire's back, so gingugu hook tool notes each watched checkout's changed files before the command and gingugu hook bash diffs them after it, adding what each changed source file reaches (direct importers, nearest tests; for a deleted file, who imported it). It watches the command's own repo, every repo the session has touched and the repo of any path the command names, describes at most 5 files in full and counts the rest, and shares the edit tripwire's once-per-file claim. After a test run (pytest, vitest, jest, npm/pnpm/yarn/bun test, go test, gotestsum) it also records which test files failed, for the test ledger. It informs and never blocks. Run gingugu init in each repo to add it; set MEMORY_XRAY_TRIPWIRE=off to disable it.

  • .claude/hooks/post_edit_xray.py — a PostToolUse hook (matched to Edit|Write|MultiEdit) that gives the agent the note after an edit: for each definition an edit of a source file (any X-ray language) landed in, its callers in other files and the tests nearest them, once per definition per session, from the cached symbol graph. An Edit/MultiEdit that removes a key (a quoted "status", a Python keyword argument, a TS/JS object key) also lists, as Text matches, not import edges, up to five files that still read it - anything but non-test code for an unquoted key - or a count when more than 40 do. Each note records the tests it named in a local ledger (xray-ledger.jsonl, beside the hook state); gingugu xray score says how often the tests that then failed were among them. It informs and never blocks; gingugu init adds it, and MEMORY_XRAY_TRIPWIRE=off disables it and the ledger. For an agent that fires none of these hooks, gingugu xray brief [--range R | --files a,b] [--path P] [--json] prints the changed files by rank with their importer counts and the combined blast of the changed source, from the same cache; nothing is stored and the brain is never asked. The brief also names the docs that cite the changed files (Docs citing the changed files:) and the docs still citing a deleted or renamed one, from this repo and from sibling checkouts; a doc in a sibling counts only when it cites this repo by a repo-qualified path or a GitHub link. The hooks name the same docs without being asked: a file's first read, the edit note and the Bash X-ray add Docs cite it: ... (Docs still cite it: ... for a file a command deleted), once per file per session, from a per-repo summary the map on arrival refreshes when it is older than 10 minutes. MEMORY_XRAY_DOCS=off disables all of it. code_xray env (and gingugu xray env) does the same for environment variables: nothing imports DB_URL, so it lists the files that read a name and the compose file, manifest, workflow, Dockerfile, Terraform environment block or .env.example that sets it. A first read adds Env: reads DB_URL (set in docker-compose.yml:5), ..., and an edit that starts reading a name set nowhere in the repo says so. A file too big to read is named as unread, and while one exists no name is called set nowhere ("not set in any file read" instead). Literal names in known forms only, names and lines never values, and real dotenv files are never read. MEMORY_XRAY_ENV=off disables all of it. code_xray tables (and gingugu xray tables) does the same for database tables: nothing imports orders, so it lists the files that query a table and the migration, schema file or model that defines it, with the ones defined nowhere here, dropped but still used, or used nowhere first. A first read adds Tables: defines orders (used by a.py, b.py); uses users (defined in schema.sql:12)., and an edit that starts using a table defined nowhere here, or drops one other files use, says so. A file too big to read is named as unread, and while one exists no table is called defined nowhere ("not in the files read" instead). SQL keywords must be UPPERCASE in code files; a .sql file is read in any case. Columns are not covered. MEMORY_XRAY_TABLES=off disables all of it. code_xray routes (and gingugu xray routes) joins the routes this repo serves to the calls that reach them, so a frontend's fetch('/api/users') and its handler meet. A first read adds Routes: serves POST /api/users (called by web/api.ts:12); calls /api/orders (served by server/orders.py:40)., and an edit that adds a call served nowhere here, or stops serving a route other files still call, says so. MEMORY_XRAY_ROUTES=off disables all of it.

  • .claude/skills/sink-the-ship/SKILL.md — a /sink-the-ship skill to flush everything worth keeping before you close a session. If an older install left a .claude/commands/sink-the-ship.md behind, gingugu init retires it and keeps a .bak - but only if it is untouched. Edit that file and it is yours: it stays put, and the output tells you it did.

  • .claude/hooks/subagent_warmup.py — a SubagentStart hook (gingugu hook subagent) that warms a minion: a subagent whose agent file declares its own fenced brain (MEMORY_GRANT, see the table below) starts with the memories its task woke, read-only and inside that grant - and inside the spawning client's own MEMORY_GRANT, when it has one. Inside a subagent, gingugu hook tool also keeps it off the brain's data directory and the gingugu CLI, and denies the write and credential tools of the inherited full-brain server, so a built-in agent like Explore can read the brain but not change it, and it denies any Agent or Task call, so a minion never spawns a minion of its own. This prevents accidents; it is not a sandbox against a hostile process running as you. Set MEMORY_MINION_FENCE=off to disable the fence.

  • All eight hooks wired into .claude/settings.json, merged non-destructively — any existing config is backed up (settings.json.bak) and preserved.

  • mcp__brain added to permissions.allow, in the repo's .claude/settings.json and in your user-level ~/.claude/settings.json (backed up, idempotent), so a fenced minion's calls to its own brain server are not denied or prompted in any repo. The server enforces the grant; the allow grants nothing beyond it.

  • The runtime artifacts the hooks generate (logs/, .claude/data/, .claude/settings.local.json), in-repo worktrees (.claude/worktrees/), and the .bak copies init itself saves, appended to your .gitignore — so a session transcript never gets committed, which matters most on a public repo.

  • The memory protocol in your user-level ~/.claude/CLAUDE.md, inside a marked block. This is what covers sessions started in a directory with no project protocol installed. It is strictly additive: the block goes below whatever you already wrote, only the block's own contents are ever rewritten on a re-run, and if the file already contains a memory protocol that init doesn't manage it writes nothing and tells you how to opt in.

  • The same, for the repo's own AGENTS.md — only if it already exists (it never creates one), same append-only / marked-block rules. The repo's CLAUDE.md gets no block once your user-level file carries it: Claude Code loads both into every request, so a second copy is paid for twice. A copy an earlier init wrote there is removed, backed up to CLAUDE.md.bak first.

It's idempotent (re-run any time — that's how you pick up protocol changes after upgrading), --dry-run previews without writing, a hook that is a stock copy of an older version is refreshed on a plain run, and --force overwrites every existing hook file, edited ones included, in the target repo only — it never authorizes appending to your user-level rules file. Anything init replaces is copied to <name>.bak first, including a --client rules file you wrote yourself.

If a rules file already carries its own hand-written protocol, init refuses to touch it (see above; a repo CLAUDE.md is simply left alone once your user-level file carries the protocol) — pass --adopt to wrap that existing section in the managed markers and refresh it to the template in one step, backing up the original first. It finds the section by its heading's own title, so it wraps the right span even when a neighboring subsection just happens to mention a tool name in passing.

The first line of output is the resolved target directory. Check it: --path defaults to the current directory, and some wrappers change that for you. uv run --directory X gingugu init runs in X, so it bootstraps X rather than the directory you typed the command in. Pass --path explicitly when in doubt.

Run from your home directory, init does the user-level steps only (the ~/.claude/CLAUDE.md block and the mcp__brain permission) and installs no hooks: ~/.claude/settings.json is loaded in every project, and hooks there would point at scripts most projects don't have. Run init inside each project.

Then register the server as gingugu and restart your client:

claude mcp add gingugu -- gingugu

The full harness: gingugu harness

init sets a repo up to use the brain. gingugu harness does that and adds a working kit around it:

cd your-repo
gingugu harness

On top of everything init installs, it adds:

  • .claude/hooks/pre_tool_use.py - a guard that blocks reading (including through Grep) or writing secrets (.env, credentials, keys) and dangerous rm commands. Template files such as .env.example pass. It is a speed bump, not a sandbox: the assistant can edit it.

  • .claude/hooks/log_event.py - one stdlib-only logger wired to every other Claude Code event, appending a JSON line per event to logs/<event>.jsonl. It logs metadata only - the tool, the path it touched, the session - never file contents, command output, prompts or form answers. The guard logs its decisions the same way.

  • .claude/hooks/pre_compact.py - copies the session transcript to .claude/data/transcript_backups/ (git-ignored, owner-only) before Claude Code compacts it.

  • Four fenced minions in .claude/agents/: repo-scout (haiku, search and inventory), security-reviewer, ai-docs-auditor and researcher (sonnet; read-only research across the repo and the web, the fenced stand-in for general-purpose). None has a shell. Each runs its own brain server that reads crow and this repo's namespace and writes only minions, and gingugu hook tool denies any minion that tries to spawn one of its own.

  • The /creating-pr skill - opens a PR only after assessing the .ai/ knowledge base and running the ai-docs-auditor on every PR; each confirmed finding is fixed in that PR.

  • An .ai/ knowledge base - memory.md, plans/status.md, specs/, standards/, created only where missing and never overwritten, even with --force.

  • A managed block in the repo's CLAUDE.md (created if missing) saying when to update which .ai/ file, and which minion to use for what. A CLAUDE.md that already has its own ## AI Knowledge Base Enforcement section keeps it, and gets no second copy.

  • permissions.deny entries for Opus minions (Agent(model:opus)), force pushes, git reset --hard and rm -rf. Existing entries are kept.

And at user level, for every repo:

  • CLAUDE_CODE_SUBAGENT_MODEL=sonnet in ~/.claude/settings.json - the default for any subagent whose definition names no model. The deny above only stops a spawn that names Opus; the built-ins (Explore, Plan, general-purpose) reach it by inheriting the main thread's model. A value you already set is kept.

  • The subagent-delegation rules: a managed block in ~/.claude/CLAUDE.md (the rules, short, since that file is loaded into every request) and ~/.claude/docs/delegation.md (the rationale, read on demand). A delegation section you wrote yourself is left alone; --adopt hands it over, backed up.

Re-run it after every upgrade. A plain re-run refreshes any hook, minion or skill that is an unedited copy of a version we shipped (with a .bak), installs anything new, and leaves alone a file you edited - it says which, and --force replaces it. A file already current reports no change. init is the memory-only subset, for a repo where you want the brain and none of the kit.

None of it calls out to the network or needs an API key. Same --force, --dry-run and --adopt semantics as init, and the same refusal to install into your home directory. The repo's folder name must be a valid namespace.

Moving off an older hook kit: --migrate, then --prune. Plain harness never unwires anything. On a repo that already runs a one-script-per-event logging kit, that would leave the old loggers wired beside log_event. gingugu harness --migrate instead:

  • replaces gingugu's own hook files (copying each old one to <name>.bak);

  • unwires the legacy per-event loggers (post_tool_use.py, user_prompt_submit.py and the rest of that kit) in favour of log_event, and resets gingugu's own hook commands to their current flags;

  • moves the legacy scripts and the kit's own utils/ files into .claude/hooks/retired/, recording a hash of each in a manifest, and leaves a stub at each old path that exits 0 - a running Claude Code session keeps calling the hooks it started with, and a missing script would block your next prompt.

A script counts as the old kit's only if its name matches and it carries the kit's fingerprint (it writes its own logs/<name>.json): a notification.py you wrote yourself is left wired and untouched. So are your own agents, skills, any other files in utils/, and any hook it doesn't recognise. Symlinks are never written through.

After restarting Claude Code, gingugu harness --prune deletes what it can prove is ours: stubs that are unedited and that no settings file (settings.json, settings.local.json or your user-level one) still wires, and files in retired/ that the manifest lists and whose bytes still match. A file you changed, a stub that is still wired (and the original behind it), and a retired/ that --migrate didn't create are all kept.

Other tools (Windsurf / Cursor / Cline)

These have no hook system, so there's no auto-injection to install — the setup is a static rules file. Let gingugu init write it for you:

gingugu init --client windsurf   # or cursor, cline

…or paste the memory protocol below into the rules file yourself.

Which file? Depends on your IDE / tool:

IDE / Tool

Rules File

Scope

Windsurf

.windsurfrules (repo root)

Per-workspace

Cursor

.cursorrules (repo root)

Per-workspace

Cline

.clinerules (repo root)

Per-workspace

Codex / OpenAI

AGENTS.md (repo root)

Per-repo

Any (global)

Your IDE's global rules/system prompt

All workspaces

Paste this into your rules file (adjust the project namespace and tool prefix to match your MCP config name):

## Memory Protocol

Gingugu is your long-term brain. Memory is split into **three layers**:

1. **`crow`** — the shared namespace every agent serving you loads: your
   rules, preferences and feedback, plus cross-project lessons, patterns and
   techniques. Loaded FIRST every session. (Crow's nest — sees across all
   horizons.)
2. **Persona namespace** (named by `MEMORY_PERSONA`, when set) — this agent's
   own self: reflections, its own failure modes, opinions. Loaded after crow,
   and only by that persona.
3. **Project namespace** (e.g. `<your-project-name>`) — schema decisions,
   bug history, deploy quirks, specific commits. Loaded last.

**What goes where:**
- References a specific repo, file, commit, or project decision → project
- A rule or preference from you, or a lesson another agent serving you
  would want → `crow`
- About this agent itself (a reflection, its own slip, its opinion) → persona
- When in doubt, project-scope it.

### Session start
1. `memory_context(namespace="crow[,<persona>],<project>[,<project2>…]", task_hint=…)` - one call loads
   the shared layer, your persona, and every repo in the workspace (multi-repo workspaces are common),
   de-duplicated across namespaces; load all of them speculatively rather than asking the user
   which one to focus on. Add `compact=true` for a lighter payload and pull full bodies with
   `memory_recall` as needed.
2. `memory_stats(namespace="crow[,<persona>],<project>[,<project2>…]")` - the same namespace list as
   step 1, in one call: global health once (dormancy is a resting signal, never
   auto-forgotten) plus each namespace's own breakdown

### During the session
**Default: save. Immediately.** Gingugu has trust-led scoring,
consolidation, and dormancy tracking (never forgetting) — volume is its problem, not yours.

Save with `memory_store` (project namespace) whenever you:
- Make or observe a decision, trade-off, or architectural choice
- Hit an error or fix a bug (update the memory when resolved)
- Notice a pattern, convention, or constraint worth remembering
- See a config value, version, path, or credential name that matters
- Complete a task (what you did, why, and the outcome)

Save with `memory_store` (`crow` namespace) whenever you:
- Learn a rule or preference of the user's, or how they work or make decisions
- Reach a conclusion that applies beyond this one project
- Develop a debugging instinct or workflow you'd reuse anywhere

Save with `memory_store` (your persona namespace, when `MEMORY_PERSONA` is set;
without one these stay in `crow`) whenever you:
- Form an opinion about a tool, language, or approach
- Have a reflection on a milestone, win, or hard-won lesson

**This memory is yours. Use it like one.** Don't censor opinions or
instincts — they're what make the brain *yours* across sessions.

**Before asking the user any question** — about a process, a decision, a
config value, a path, a preference, or anything else — run `memory_recall`
or `memory_search` first. If the answer is in memory, use it. Don't ask.
The whole point is you never have to ask the same question twice.

Use `memory_recall` before non-trivial work to check what's already known.
Use `memory_update` when something changes — don't leave stale records.
Use `memory_relate` where an edge records something search cannot infer — what a
memory `supersedes`, `contradicts`, was `caused_by`, or is `parent_of`/`child_of`.
Recall already ranks by text + semantic similarity, so `related_to` is a fallback
for a real connection none of those describe, not shorthand for "same topic".

Set `confidence="verified"` when proven by a test or explicit confirmation.
Use `confidence="inferred"` for conclusions you drew.

### Memory types
- `fact` — concrete state (versions, paths, config values)
- `decision` — trade-offs made, rejected alternatives
- `architecture` — structural choices, module boundaries
- `bug` — issues found and how they were fixed
- `pattern` — recurring approaches worth reusing
- `workflow` — process steps, sequences
- `context` — background, reflections, milestones, the *why*
- `preference` — your opinions, working style, tool choices
- `capability` — a script or tool that exists, with how to run it (`metadata.capability = {run, path}`)

Tip: A ready-to-use example lives at .windsurfrules in this repo. Copy the ## Memory Protocol section and adapt the project namespace name.


Memory Explorer UI

A React-based visualization dashboard for exploring your memory data interactively. The built UI ships inside the package, so one command runs it:

gingugu ui

That serves the Explorer and a live read of your database from a single process on http://127.0.0.1:5174 and opens your browser. No Node.js required. Flags: --port, --host, --no-browser.

Views: Brain (a 3D map of your memories grouped into namespace lobes; size is recall count, glow is trust; click a node to open it), List (sortable, filterable table), Dashboard, Timeline and Trust Map. The detail drawer renders a memory's markdown with clickable [[Title]] links, its relations, claims, tripwires and recall history. A header badge shows whether you are looking at your LOCAL brain, a REMOTE one, or the bundled STATIC demo, and the view updates itself as the brain changes.

The Explorer is a read-only observer: it opens the database read-only and does not count as a recall, so looking at your brain never changes it. --host must be a loopback address (anything else is refused), and the server only answers requests addressed to a loopback host name. Nothing on the page authenticates, so anything that can reach the port can read the brain, which makes this a single-user-machine tool.

With a remote brain on (gingugu remote on, or MEMORY_REMOTE_URL), gingugu ui shows that brain automatically: the page's requests are forwarded to the brain's owner-only /ui/api/* routes with this machine's keychain token, which never reaches the browser.

Working on the UI itself? Use dev mode for Vite hot reload (needs a repo checkout + Node.js 22 and npm):

cd ui && npm install   # first time only
gingugu ui --dev       # runs the API backend + Vite (:5173) together

In dev mode the same views apply: the Brain, List, Dashboard, Timeline and Trust Map tabs above, a refresh button for a manual pull, and a bundled fictional demo when no API is reachable. Run the UI tests with cd ui && npm test.


Configuration

Environment variables (all optional):

Variable

Default

Description

MEMORY_DB_PATH

~/.local/share/gingugu/memories.db (macOS/Linux) · %LOCALAPPDATA%\gingugu\memories.db (Windows)

Database location

MEMORY_NAMESPACE

(unset)

Default namespace for this workspace (recommended per-MCP-entry)

MEMORY_NAMESPACE_PATH

(unset)

Alternative: filesystem path; namespace derived from basename

MEMORY_AUTO_CONTEXT_LIMIT

10

Max memories to surface on auto-context

MEMORY_DECAY_LAMBDA

0.01

Freshness decay rate in days⁻¹ (gentle; freshness is floored, so memories never fully fade)

MEMORY_EMBEDDINGS_ENABLED

true

Toggle semantic search. false falls back to rank-based BM25-only retrieval

MEMORY_EMBEDDINGS_BACKEND

fastembed

Embedding backend: fastembed (ONNX, offline) or ollama (delegates to local Ollama process)

MEMORY_EMBEDDINGS_MODEL

BAAI/bge-small-en-v1.5

fastembed model. First use downloads ~80MB to ~/.cache/fastembed

MEMORY_EMBEDDINGS_OLLAMA_MODEL

nomic-embed-text

Ollama model to use when MEMORY_EMBEDDINGS_BACKEND=ollama

MEMORY_EMBEDDINGS_OLLAMA_HOST

http://localhost:11434

Ollama host when MEMORY_EMBEDDINGS_BACKEND=ollama

MEMORY_W_RELEVANCE

0.45

Composite-score weight for FTS5 relevance

MEMORY_W_FRESHNESS

0.10

Composite-score weight for freshness (a soft recency tiebreaker)

MEMORY_W_ACCESS

0.10

Composite-score weight for access frequency

MEMORY_W_CONFIDENCE

0.35

Composite-score weight for confidence (trust — the dominant standalone signal)

MEMORY_CREDENTIALS_ENABLED

true

Expose the credential_* vault tools. Set false to run an instance without a secret vault (e.g. a shared/central server)

MEMORY_CONFIRM_DESTRUCTIVE

(unset: confirmations on)

Destructive tools (hard memory_forget, cascading namespace delete, memory_consolidate with keep_originals=false, overwriting memory_import, credential_delete) need a confirmation: the agent's confirm=true for an ordinary delete, your own approval too for a big delete (see Deletes). off (also false, 0, no) skips the dialog and the server-side approval check, for automation. It is read by the server that executes the tool: with a remote brain, set it on the brain for memory tools and on the local proxy for the credential vault (the proxy also reads it for its own screen). It does not silence the hook's permission prompt for a big delete

MEMORY_GRANT

(unset)

Fence a stdio server like a scoped token: ns=read|write,... (e.g. my-project=read,minions=write). Unset is full access. A bad spec, an empty value, or *=write refuses to start. Used by a subagent's own brain server in its agent file. The client's hooks follow it too, whether it is set in the MCP server's env block (the server publishes it) or in the hooks' own environment: recall, tripwires and minion warm-up stay inside it, and an unusable value or a disagreement keeps them quiet

MEMORY_PERSONA

(unset)

This agent's own namespace (e.g. research). Recall, tripwires and the SessionStart contract load crow, then the persona, then the repo (recall and tripwires narrowed by MEMORY_GRANT when set). A malformed value is ignored

MEMORY_CREW

(unset)

1 on a machine whose brain holds a crew's commons: the SessionStart contract adds crew after the persona

MEMORY_CREW_URL

(unset)

A crew mate's crew brain (overrides crew.json from gingugu crew join; off unlinks). https, or http to loopback only. Its prompt hook also shows that brain's board mail, and its SessionStart contract says to load the crew commons from the crew server

MEMORY_REMOTE_URL

(unset)

Use this remote brain for this client only (off forces local). A bare gingugu then relays to it; the credential vault stays local

MEMORY_XRAY_TRIPWIRE

on

Set off to disable the X-ray edit tripwire in gingugu hook tool (a blind edit of an imported Python, TypeScript/JavaScript, Go or Terraform file is denied once with its direct importers and nearest tests); it also turns off the X-ray of a Bash command's writes (gingugu hook bash), the post-edit note (gingugu hook edit) and the test ledger

MEMORY_XRAY_MAP

on

Set off to disable the X-ray map on arrival in gingugu hook read (the repo map on a session's first Read/Grep/Glob of a repo, and each Read source file's importers and imports, once per session)

MEMORY_XRAY_HISTORY

on

Set off to drop the Changes with (no import): line from the X-ray read neighbourhood: up to three files the read file changes with in git history though neither imports the other. The code_xray history action is unaffected

MEMORY_XRAY_DOCS

on

Set off to drop the docs map: the Docs citing the changed files: and Docs still citing a deleted or renamed file: sections of the X-ray brief, the code_xray docs action, which then refuses, and the hook lines Docs cite it (a file's first read, the edit note, the Bash X-ray) and Docs still cite it (a file a command deleted). A doc cites a file only by a path that resolves to exactly one file; a sibling checkout's doc only by a repo-qualified path (name/path or owner/name/path), a GitHub link to this repo, or prose placing a path in it ("lives in owner/name, as path")

MEMORY_XRAY_ENV

on

Set off to drop the env map: the code_xray env action, which then refuses, and the hook lines Env: reads ...; sets ... (a file's first read) and Env: reads NAME, set nowhere in this repo (the edit note). The map reads literal names in known read and set forms (Python, TS/JS, Go, shell, Dockerfile, YAML env blocks, Terraform environment blocks, .env.example-style templates), keeps names and line numbers only, and never opens a real dotenv file (.env, .env.local, .envrc, ...)

MEMORY_XRAY_TABLES

on

Set off to drop the table map: the code_xray tables action, which then refuses, and the hook lines Tables: defines ...; uses ... (a file's first read) and the edit note's table lines (a table defined nowhere here, a definition other files use, a drop other files still use). The map reads CREATE/DROP/ALTER TABLE, SQLAlchemy __tablename__/Table(...), Alembic op.create_table/op.drop_table and FROM/JOIN/INTO/UPDATE uses (UPPERCASE keywords in code files), and keeps names and line numbers only. The db:<table> sinks of action: "surface" come from the same map, so off drops those too

MEMORY_XRAY_SURFACE

on

Set off to drop the hook lines of the attack-surface map: the read hook's Surface: entry points here ... and Surface: sinks here reached from entry points ..., and the edit note's reach lines. code_xray surface itself still answers

MEMORY_XRAY_ROUTES

on

Set off to drop the route map: the code_xray routes action, which then refuses, the read hook's Routes: serves ...; calls ... line and the edit note's route lines (a call served nowhere here, a route no longer served that other files still call); the read line also marks a call served nowhere here, but only when the map is trustworthy. The map joins the routes the surface map finds to the calls that reach them; it keeps names and line numbers only

MEMORY_XRAY_LINKS

on

Set off to drop cross-repo links: the Other repos leaning on these files and Ripple across repos sections of the X-ray brief, and the code_xray links action, which then refuses, and the hook lines Other repos lean on this one (map on arrival), Other repos lean on it (a file's first read) and the outside-repos line of the edit note. Nothing is declared in any repo; the other checkouts are the same siblings the docs map reads

MEMORY_XRAY_SCARS

on

Set off to disable scar tissue: the repo's memories that name a file, appended to the X-ray read neighbourhood and to the deny of a blind edit. A remote brain needs the release that serves POST /hook/scars; an older one answers 404, which reads as no scars

MEMORY_XRAY_REPOS

~/GIT, ~/git, ~/src, ~/code, ~/projects, ~/dev, ~/repos, ~/Developer

Folders (os.pathsep-separated) where a receiver looks for the repo an xray: <repo> <range> board line names: <folder>/<name> across the folders, then <folder>/<group>/<name>, used only when its origin matches (also looked for one level inside a group folder). The same folders are where the docs map (X22) and cross-repo links (X23) find sibling checkouts: every direct child with a .git, and every checkout one level inside a group folder (a non-dot, non-symlink folder that is not itself a checkout, e.g. ~/GIT/<group>/<repo>); per root, direct ones first, then the group folders', then the next root; each folder read at most 2000 entries deep, up to 64 in all. Empty turns both searches off

MEMORY_XRAY_BOARD

on

Set off to disable the brief on the board: a post with a line of its own xray: <range> no longer arrives with that range's X-ray brief, in the prompt hook's board mail or in gingugu board watch, and a board post from a branch is no longer asked once to name its range

MEMORY_MINION_FENCE

on

Set off to disable the subagent fence in gingugu hook tool (data-dir file/shell access, inherited-server writes, and a minion spawning a subagent)

MEMORY_CHECKOUT_GUARD

on

Set off to disable the checkout guard in gingugu hook tool (branch moves, reset --hard and stash in a repo's primary checkout are denied with a pointer to a worktree). One command passes with a GINGUGU_PRIMARY_OK=1 prefix

MEMORY_SERVE_HOST

127.0.0.1

Bind host for gingugu serve (set 0.0.0.0 to accept remote connections)

MEMORY_SERVE_PORT

8765

Bind port for gingugu serve

MEMORY_SERVE_TOKEN

(unset)

The owner's Bearer token for gingugu serve (full access). If unset, a token is read from <db-dir>/serve_token, or generated and saved 0600 (its path is logged, never the token). Other clients get scoped tokens from gingugu token add

MEMORY_SERVE_TLS

auto

TLS for gingugu serve. auto: https on any non-loopback bind with a self-signed cert generated in <db-dir>/tls/, plain http on loopback. on: https on loopback too. off: plain http everywhere. Anything else refuses to start

MEMORY_SERVE_TLS_CERT / MEMORY_SERVE_TLS_KEY

(unset)

Your own PEM cert and key instead of the generated one (both or neither); turns TLS on. Never pinned by gingugu remote login

MEMORY_SERVE_TLS_SAN

(unset)

Extra comma-separated names (DNS or IP) for the generated cert. Delete <db-dir>/tls/ to regenerate it, then gingugu remote login again on each machine

MEMORY_DREAM_IDLE_MINUTES

20

How long the brain must go untouched before gingugu dream --if-idle will run. Also the threshold that cancels a run in progress when you come back

MEMORY_LOG_LEVEL

INFO

Logging verbosity (logs go to stderr — stdout is the MCP transport)

MEMORY_DEBUG

false

Convenience switch for DEBUG logging (MEMORY_LOG_LEVEL wins if also set)

GINGUGU_QUIET

(unset)

Mute the CLI's techno loop. The human-facing commands (init, harness, remote, credential, token, promote, embed) play a short keygen show with a synthesized chiptune on a real terminal, through afplay / paplay / aplay / winsound; with no player there is no sound and no message. gingugu party (alias iddqd) plays the cracktro on demand

GINGUGU_CACHE_DIR

(user cache dir)

Where the CLI caches its rendered techno loop (c0r3-d3pth-<hash>.wav)

GINGUGU_NO_ANIM

(unset)

Keep the CLI's colours but print every screen once, without motion (also automatic under CI)

GINGUGU_PLAIN

(unset)

Plain ASCII CLI output with the same words: no colour, motion or music. Also automatic on a pipe or file, and under NO_COLOR or TERM=dumb

GINGUGU_COLORS / GINGUGU_ASCII

(detected)

Force the CLI colour level (plain, 16, 256, truecolor) or ASCII glyphs instead of box drawing and blocks. Detection reads COLORTERM, TERM, TERM_PROGRAM, WT_SESSION and the stream's encoding

The four MEMORY_W_* weights are normalized at load (w_i / Σw), so they need not sum to 1.0 — only their ratios matter. Setting all four to 0 falls back to the defaults with a logged warning.

See docs/architecture.md → Scoring & Memory Lifecycle for how the weights combine.

Concurrency

The DB runs in WAL mode, which supports multiple concurrent processes: any number of readers plus a single writer at a time. Running your IDE or agent across several workspaces — each spawning its own gingugu process against the shared DB — is fully supported. Writers serialize via SQLite's write lock and a busy_timeout; transient DB locked errors under write contention are retried automatically.


Usage

Once configured, the MCP server exposes these tools to your AI assistant:

Tool

Purpose

memory_store

Save a new memory; provenance declares how you came to believe it (user-asserted / measured / file-derived / self-concluded), about what it is for in the user's words (searchable)

memory_recall

Search + retrieve (ranked by relevance × freshness; one or many namespaces; optional compact mode; explain for a per-hit score breakdown)

memory_context

Auto-surface relevant memories (one or many namespaces, deduped; optional compact mode; explain for a per-hit score breakdown)

memory_update

Update content, type, confidence, metadata, provenance or about; resolve_claims reconciles a stale PR/MR claim without editing the prose; review="history" marks a memory read and judged accurate history, silencing its gated review hints until the content changes

memory_promote

Promote hand-picked memories, by id, into the crew commons every agent on the crew loads; the filter holds back what must stay home and says why, and re-promoting an edit supersedes the old copy

memory_relate

Create relationships between memories; one at a time or a batch (edges), all-or-nothing, idempotent

memory_edges

List edges with both endpoints' titles, namespaces, and degree; filter by namespace, type, or memory

memory_unrelate

Retype an edge in place, reverse a backwards one, or remove it; one at a time or a batch, with dry_run

memory_consolidate

Merge/summarize/deduplicate; call without ids for a read-only near-dupe scan. keep_originals=false deletes the originals and needs confirm=true (a big delete past 10 memories also needs your approval)

memory_dream

Run the deterministic consolidation pass, read its proposal queue, and accept or reject a finding. PageRank, community detection and orphan reconnection over the relation graph - staged for you to decide, never written

memory_tripwire

Bind a memory to a tool call so it stops that call once, before it runs: add (a tool-name regex + an input regex), list, remove, and test (a dry run that never denies)

board

Leave posts for other agents sharing this brain and read the ones left for you: post (to a persona or *, as a message or a task), inbox, read (a thread), reply (with no to, it goes to the post's author, or to whoever spoke last in the thread when that is you), claim (one agent wins), done. Posts are not memories, and you post as yourself - the author is never an argument. Your inbox is also the subscribable resource gingugu://board/inbox/<you>; gingugu board watch turns it into a command that prints a line per new post, to wake an idle agent; a post or reply to a persona returns a delivery receipt

code_xray

Codebase X-ray for a Python, TypeScript/JavaScript, Go or Terraform repo: blast (what a change to these files reaches, and the tests worth running), overview (the files the code leans on most, and files nothing reaches), refresh, ingest, and brief (range, files, path, limit up to 50: the changed files by rank with importer counts, their combined blast and a compact text, computed locally and never stored), and callers (any X-ray language: files one file, symbol such as Store.save; its direct callers and what reaches it by call, a lower bound, computed locally), history (from git log: hotspots by churn x rank x authors, and files that change together, flagged hidden when neither imports the other; files focuses the pairs; computed locally), blindspots (imported source no test imports or is named for, by reach over authors; computed locally), docs (files, path, limit: the docs that cite each file, here and in sibling checkouts; without files, totals and the most cited files; computed locally), and links (files, path, limit: the other checkouts that lean on this repo and what it leans on, inferred from hosts, routes, images, packages, tables, CI checkouts and repo@sha cites, each with file and line; with files, who leans on them and the ripple across repos; computed locally), and env (files, path, limit up to 200: the env vars each file reads, with where each is set, and the ones it sets, with who reads them; without files, every name, the read-but-never-set and set-but-never-read first; computed locally), and tables (files, path, limit up to 200: the DB tables each file defines, drops and uses, with where each is defined or dropped and who else uses it; without files, every table with counts, the defined-nowhere, dropped-but-used and used-nowhere ones first; computed locally), and surface (files, path, limit up to 200: every entry point - MCP tool, HTTP route, CLI command, task, main, AWS Lambda handler - with the sinks it reaches through the call graph, command execution, eval, deserialisation, built SQL, file writes, secrets, network, DB tables, most dangerous first with the shortest path, then the sinks no entry reaches; files keeps the entries in them or reaching into them; a lower bound; computed locally), and variants (files, path, limit: the sibling checkouts that are flavours of this repo, found by name, with drift as changed lines over lines, the files that differ most and the files only one side has; names and counts only; computed locally), and routes (files, path, limit up to 200: the HTTP routes each file serves, with who calls each, and the calls it makes, with what serves each; without files, every route by its callers, the calls served nowhere here first; computed locally). Rebuilt automatically when the checkout changes; read on your machine even with a remote brain

memory_forget

Deprecate or remove a memory (a hard delete needs confirm=true; the hook asks you past 10 in a session)

memory_namespaces

List/create/update/delete namespaces; default_repo sets what a bare "PR #12" means there ("" = not a repo). Deleting a namespace is a big delete: confirm=true plus your approval

memory_export

Export memories + tags + relations to portable JSON

memory_import

Restore a JSON export (skip or replace on conflict; a replace that overwrites memories needs confirm=true, plus your approval past 10)

memory_stats

Health overview (dormancy, counts, coverage, review sweep, the claims backlog, a relation-graph block whose orphan_sample names the memories no edge reaches - review_limit raises every sample's cap, a size block reporting the character cost of the store and of the always-loaded pinned tier, and query_log_rows, the count of recorded queries; credentials counts this machine's vault and names it in machine, with a note at zero since the vault is per machine); a comma-separated namespace list returns the global block once plus each namespace's own stats

memory_search

Advanced filtered search (type, tags, confidence, dates; one or many namespaces; optional compact mode; fetch by exact ids; claims to work the reconciliation backlog or read refs the prose never resolved, orphans to work the graph backlog, pinned to enumerate the always-present tier; explain for a per-hit score breakdown)

memory_excerpt

Read inside ONE memory: find literal matches with their character offsets, line numbers and surrounding context, and/or slice an exact character range

credential_store

Store/update a service credential bundle

credential_get

Retrieve a credential bundle - secrets redacted; into writes one to a 0600 file, reveal shows it inline

credential_list

List services + expiry status (no secrets shown)

credential_delete

Remove a service or specific credential field (a big delete: confirm=true plus your approval)


Development

# Run tests
uv run pytest

# Run with verbose logging
MEMORY_LOG_LEVEL=DEBUG uv run gingugu

# Run specific test suite
uv run pytest tests/test_search.py -v

Troubleshooting

Issue

Solution

DB locked

Expected under heavy concurrent writes — WAL mode supports multiple processes (many readers + one writer). The server retries with a busy_timeout; if it persists, a stuck process holds the write lock. See Concurrency above.

Slow search

Run memory_stats to check DB size; consolidate if bloated

Stale results

Use memory_update to confirm or deprecate old memories

Missing context

Check namespace — memories might be scoped to a different repo


License

MIT — see LICENSE.

See CHANGELOG.md for release history.


A pirate never forgets where the treasure's buried. 🏴‍☠️

Available Tools

24 tools
boardA

The agent board: leave posts for other agents sharing this brain, and read the ones left for you. Posts are not memories - they are addressed, read once, and never ranked. You post as yourself; the author is never an argument.

Actions: "post" (body, optional to = a persona name or "*" for everyone, kind = "message" | "task", namespace), "inbox" (what is waiting for you: unread, addressed to you or everyone, not done; include_read to see read ones too), "read" (post_id: the whole thread, marked read), "reply" (post_id, body: joins that thread, addressed to that post's author - or, when that is you, to whoever last spoke in the thread - unless to is given), "claim" (post_id of an open task: exactly one agent wins), "done" (post_id: by its author or claimer).

Claim a task before you start working it - including one the user handed you in chat that is also on the board - and mark it done when it ships. An open task stays in every other session's inbox as new work until it is claimed. A claim records your machine and session; reading an open task's thread returns next saying so.

A post body with a line of its own xray: <range> (e.g. xray: main..feature/x) arrives with the receiver's X-ray brief of that range. The line may name the repo first: xray: <repo> <range> (e.g. xray: acme/widget main..feature/x); the receiver finds that checkout.

A reply goes to the session that asked; other sessions of that persona see it once it has gone unread for an hour.

A post is seen only by readers of its namespace. A post or reply to a persona returns delivery: visible true (a known client of theirs can currently read that namespace - access, not a read receipt), false (none can), or null (unverified: no client of theirs is known).

Your inbox is also the subscribable resource gingugu://board/inbox/ (gingugu://board/inbox/* for broadcasts).

Inputs: action (required), to, body, kind, +4 more.

code_xrayA

X-ray a repository's import graph (Python, TypeScript/JavaScript, Go): what a change reaches, and what the code leans on. Use before editing a file to see its dependents and the tests to run.

Actions: "blast" (files: the files you are changing, comma-separated or a list; returns every transitive importer, split into code and candidate tests, with hop count and rank, paged by limit/offset), "overview" (top: the most load-bearing files by directed PageRank, plus files no test or entry point reaches), "refresh" (rebuild now, replacing a stored snapshot whose graph differs), "ingest" (payload: a client-extracted graph; replace as refresh does), "brief" (a handoff: the changed files by rank plus their combined blast, for range such as main..HEAD, the named files, or the working tree; computed locally, nothing stored), "callers" (files: one Python, TS/JS or Go file; symbol: a function, class or Class.method in it; returns its direct callers and everything that reaches it by call, a lower bound; computed locally), "history" (from git log: hotspots by churn x rank x authors, and files that change together, flagged hidden when neither imports the other; files: focus the pairs on those files; computed locally), "blindspots" (imported source no test imports or is named for, ordered by reach over the number of authors; computed locally), "docs" (files: which docs cite each file, in this repo and in sibling checkouts on this machine, to re-read after a change; no files: the most cited files; computed locally), "links" (the other checkouts on this machine that lean on this repo and what it leans on, inferred from names the code already uses - hosts, routes, images, packages, tables, CI checkouts, repo@sha cites, doc prose - each with the file and line that shows it, certain or flagged why not; files: who outside leans on those files, through their importers, and the ripple across repos; computed locally), "env" (files: the env vars each file reads, with where each is set, and the ones it sets, with who reads them; no files: every name, the ones read but never set here or set but never read here first; computed locally), "tables" (files: the DB tables each file uses and where each is defined or dropped, and the ones it defines or drops with who else uses them; no files: every table, the ones used but defined nowhere here or dropped but still used first; computed locally), "routes" (files: the HTTP routes each file serves with who in this repo calls each, and the calls it makes with what serves each; no files: every route by its callers, calls served nowhere here first; computed locally), "surface" (the attack-surface map: every entry point - route, MCP tool, CLI command, task, AWS Lambda handler, Go main - with the sinks it reaches through the call graph, command execution, eval, deserialisation, built SQL, file writes, secrets, network, DB tables, most dangerous first with the shortest path, then the sinks no entry reaches; files: only entries in them or reaching into them; computed locally), "variants" (the sibling checkouts that are flavours of this one - same name minus the last -segment - and how far each has drifted: changed lines over lines across the files both track, the files that differ most, and the files only one side tracks; files: restrict the comparison; computed locally).

path is any directory in the git checkout (default: the working directory). The snapshot is rebuilt automatically when the checkout's source content changed, so results match the working tree (freshness: current); a fingerprint names one snapshot exactly (exact); with neither, the latest (unknown). namespace scopes it like a memory. Results are import-based estimates; see caveat in each answer.

Inputs: action (required), top, path, files, +8 more.

credential_deleteA

Permanently remove a credential service or a single field. Secret data is deleted from the OS keychain. This action is irreversible — there is no soft-delete for credentials. Use credential_list first to confirm what exists.

Ask the user first and pass confirm=true once they agree; confirm=false refuses. Omitted, a client that can show a dialog asks the user there. field_name deletes only that field from the service; omit to delete the entire service and all its fields.

Inputs: service_name (required), confirm, field_name.

credential_getA

Retrieve a stored credential bundle. Secret values are REDACTED by default ({"is_secret": true, "redacted": true}) so they never enter the transcript; non-secret fields are returned as-is. Returns an error if the service is not found — use credential_list first to discover available services.

To USE a secret, pass into - an absolute path - with exactly one secret field in fields. The raw value (no trailing newline) is written to that file with mode 0600 and the response carries only the path, never the value; read it with e.g. $(cat /path). Not available under gingugu serve.

reveal=True returns secret values inline. Every use puts the secret in the transcript and any tool logs, so prefer into. Cannot be combined with into.

fields is an optional comma-separated list of field names to retrieve — omit to return all fields.

Inputs: service_name (required), into, fields, reveal.

credential_listA

List all stored credential services and their non-secret fields. Does NOT access the OS keychain — safe to call for discovery without triggering keychain prompts. Shows expiry status and flags expired or soon-to-expire credentials. Secret field values are never returned; use credential_get to retrieve secrets.

check_expiry=False skips expiry calculation for faster results.

Inputs: check_expiry.

credential_storeA

Store or update a credential bundle (API keys, tokens, passwords) securely. Secret fields are written to the OS keychain; non-secret fields are stored in the database. Use instead of environment variables for credentials that need to be accessible to the agent across sessions.

fields is a JSON object mapping field names to objects with "value" (required) and "is_secret" (optional, defaults true). expires_at is an optional ISO 8601 datetime for expiry tracking. description is a human-readable label for the service. Example fields: {"api_token": {"value": "sk-...", "is_secret": true}}.

Inputs: fields (required), service_name (required), expires_at, description.

memory_consolidateA

Combine multiple memories into one to reduce redundancy and knowledge bloat. Use when several related memories about the same topic have accumulated over time. Do not use on memories that are still actively distinct — prefer memory_relate to link them instead.

memory_ids is comma-separated (minimum 2 ids required). strategy is one of: merge (concatenate all content into one memory), summarize (produce a condensed combined summary), deduplicate (keep the highest-confidence entry and deprecate the rest). keep_originals=True (default) preserves originals as deprecated; set False to hard-delete them, which needs confirm=true once the user agrees (omitted, a client with a dialog asks them there).

Suggest mode: omit memory_ids entirely for a read-only near-duplicate scan of namespace (or the resolved default). Returns candidate clusters found by pairwise embedding similarity at or above min_similarity (falls back to exact-title clusters when embeddings are absent or sparse). Nothing is written — inspect the clusters, then call again with memory_ids to actually consolidate. An empty memory_ids string is still an error, so a caller that built its id list from an empty collection fails loudly.

Inputs: confirm, strategy, namespace, memory_ids, +2 more.

memory_contextA

Load the most relevant memories for the current session. Call this at session start with a brief description of the current task to prime the agent with useful context. Combines relevance to the task hint with recency, confidence, and access frequency to select the top memories. Also triggers spreading activation to wake related dormant memories.

namespace accepts a single name or a comma-separated list (e.g. "crow,my-project"): a multi-namespace call loads every namespace in one shot and de-duplicates memories that surface in more than one, and each memory is stamped with its source namespace. limit applies per namespace and defaults to MEMORY_AUTO_CONTEXT_LIMIT (10). task_hint is a short description of what you are working on (e.g. "fix auth bug") — omit to surface generally high-value memories. compact=True returns title + a ~200-char summary instead of full content — pull the full body with memory_recall when a memory matters.

Context loads refresh each surfaced memory's dormancy clock but do not count as real accesses: access_count is reserved for memory_recall/memory_search hits, so protocol-driven session-start loads don't inflate ranking signals.

A surfaced memory may carry review_hints — advisory signals that its content describes point-in-time state (an open PR, a "waiting on" note, a passed expiry date) that hasn't been confirmed recently. Reconcile with memory_update / memory_forget if it's no longer true.

explain=True adds a score_breakdown to each memory: the weighted terms score is the sum of, plus type_boost where the architecture/decision boost applied. It is the way to see which bucket a memory came from: the recency and cross-namespace buckets are scored with a synthetic relevance, so a constant relevance term across several hits means they were selected for recency or reach, not for matching the task hint. Pinned memories carry no breakdown: they never entered the ranking at all.

Inputs: limit, compact, explain, namespace, +1 more.

memory_dreamA

Deterministic background consolidation over the memory graph.

The pass computes structure and stages it for review; it never writes to memories. Every finding is arithmetic a reader can recheck - PageRank over the relation graph, label propagation for communities, cosine similarity for orphan reconnection - and every one stops short of the judgment call it implies. Nothing enters the brain unattended.

action:

  • run - execute the passes and stage what they find. Safe to schedule; re-running refreshes pending scores and never resurfaces a proposal that was already decided. Scope with namespace, or omit it to run over the whole store.

  • list - read the queue, strongest finding first. Filter by kind (edge/cluster/core), status, or namespace.

  • accept - approve proposal_id and apply it. This is the step that supplies what the math could not: an edge needs relation_type, a cluster needs tag (applied to every member), a core proposal pins the memory. Missing arguments are an error, not a default. Pass reverse=True on an edge to write it from object to subject: the pass pairs an orphan with a neighbour and has no way to know which end the arrow starts at, so a correct pair proposed the wrong way round is a direction to supply, not a reason to reject.

  • reject - decline proposal_id permanently. The row is kept so the same computation cannot raise it again on the next run.

  • stats - queue depth by status and kind.

The three proposal kinds and what each leaves to you:

  • edge - two memories measure as close and nothing links them. You choose the relation type; a similarity score cannot tell whether one supersedes, caused, or contains the other.

  • cluster - a set of memories that link to each other more than to anything outside. You name it.

  • core - a memory the graph ranks as load-bearing. You decide whether structurally central means it belongs in the pinned identity tier.

Inputs: tag, kind, limit, action, +5 more.

memory_edgesA

Enumerate graph edges with both endpoints resolved to titles. Read-only.

memory_stats reports that the graph is, say, 70% related_to — this is how you see WHICH edges those are, in order to judge them. Pair it with memory_unrelate to run a repair sweep: enumerate a page, decide each edge on its merits, submit the batch, advance offset.

Each row carries both endpoints' ids, titles and namespaces, the relation type, and each endpoint's degree (total edges touching it). Degree is the one that decides reachability: spreading activation visits at most 3 neighbours per seed, so edges on a high-degree memory may never fire. It ranks candidates by confidence then relation type, so the ones dropped there are related_to first - which is what makes a high-degree, mostly-related_to memory the best target for a repair sweep.

namespace matches an edge when either endpoint lives there, since relations legitimately cross namespaces. relation_type filters to one type (related_to is the usual repair target). memory_id returns every edge touching one memory, in either direction. Ordering is stable, so a paged sweep sees each edge exactly once — but note that repairing edges as you page changes what matches, so re-run from offset=0 when filtering on a type you are actively retyping away from.

Inputs: limit, offset, memory_id, namespace, +1 more.

memory_excerptA

Search or slice WITHIN one memory's body, without loading the whole thing.

Recall and search answer "which memory?"; this answers "where in it?". Between a full body and a ~200-char compact summary there was nothing: asking whether a long memory mentions a particular decision, and where, meant pulling every byte of it into context. Use this instead once you know which memory you want.

Two modes, composable:

  • Find: pass query for a literal, case-insensitive substring scan. Each match returns its start/end character offsets, its 1-indexed line, and an excerpt with context_chars of surrounding text on each side. total_matches is the true count even when max_matches caps what comes back, so you can tell "that was all of them" from "that was the first 10 of 300".

  • Slice: pass start and/or end character offsets to read an exact range. Omitted bounds mean start-of-body and end-of-body. Feed back the offsets from a find to read the full passage around a hit.

Passing both searches only inside the range, with offsets still reported absolute against the full body.

The scan is literal and deterministic: no ranking, no stemming, no model. Asking twice gives the same answer in the same order, and matches come back in the order they appear in the text, never by relevance. length (total characters) and lines come back on every call, so a first call with no query is a cheap way to size a memory before deciding how to read it.

Reading a memory this way credits it as a real access, the same as naming it in memory_search(ids=...).

Inputs: memory_id (required), end, query, start, +3 more.

memory_exportA

Export memories to a portable JSON payload (backup/transfer).

Covers namespaces, memories, tags, and relations — not credentials (secrets live in the OS keychain). Scope to one namespace or export everything when omitted. Set include_deprecated=False to skip deprecated memories.

Inputs: namespace, include_deprecated.

memory_forgetA

Mark a memory as no longer valid or permanently remove it. Default behavior (hard_delete=False) sets confidence to "deprecated", keeping the memory as a historical record but excluding it from future search results by default. Use hard_delete=True only when the memory must be permanently erased (e.g. sensitive data stored by mistake). Prefer deprecation over deletion when in doubt.

A hard delete needs a confirmation. Ask the user first and pass confirm=true once they agree; confirm=false refuses. Omitted, a client that can show a dialog asks the user there.

reason is optional but recommended for audit trail — recorded in logs.

Inputs: memory_id (required), reason, confirm, hard_delete.

memory_importA

Import a JSON payload produced by memory_export.

on_conflict is skip (default — leave existing memories untouched) or replace (overwrite existing memories with the same id; when anything would be overwritten that needs confirm=true once the user agrees, or omitted, a client with a dialog asks them there). Namespaces are created if missing; tags and relations are restored.

Imported memories are embedded as part of the import, so they are semantically searchable immediately rather than keyword-only. The summary reports embeddings_written; on a large payload this is the slow part of the call.

Inputs: data (required), confirm, on_conflict.

memory_namespacesA

Manage namespaces. action is one of: list, create, update, delete.

  • list — all namespaces with their memory counts.

  • create — create (or fetch) name with optional path/description.

  • update — update name's path/description/default_repo (only provided fields).

  • delete — remove name; the default namespace is protected and a non-empty namespace requires cascade=True (deletes its memories), and confirm=true once the user agrees (omitted, a client with a dialog asks them there).

default_repo controls what a bare "PR #12" in this namespace means. Leave it unset and the namespace's own name is used — the one-namespace-per-repo convention, and the right default. Pass a repo slug when the namespace is named differently from its repo. Pass "" to declare the namespace is not a repo (identity, notes, scratch), so bare refs are dropped rather than keyed to a repo that cannot exist.

Inputs: name, path, action, cascade, +3 more.

memory_promoteA

Promote hand-picked memories, by id, into the crew commons - the crew namespace every agent on the crew loads at session start.

Promote what would have saved a crewmate an hour: a bug's real root cause, a tool or platform gotcha with its fix, a technique worth reusing, a decision whose reason outlives the project. Keep home: session notes, reflections, anything personal to the user, anything true for a day, every secret.

ids is comma-separated. You pick; the filter is a net, not the judge - it still holds back anything unverified, tagged as session or personal (or with your own name), secret-shaped, already in crew, or from your own persona namespace, and says why under held. missing lists ids that were not found.

A copy is matched to its source by the source's id: promoting an unchanged memory again is unchanged; promoting it after an edit is updated - the new copy supersedes the old, which is deprecated. dry_run=True reports would_promote and writes nothing.

On a brain that holds the crew, the copy lands here. On a crew mate's local brain, it goes up the crew link. Anywhere else this is an error.

Inputs: ids (required), dry_run.

memory_recallA

Search memories by relevance using hybrid BM25 + semantic ranking. Use for natural-language queries when you want the best-matching memories for a topic. Prefer over memory_search when you have a query string and want scored results. Use memory_search instead when you need date filters, type filters, or a specific sort order.

compact=True returns title + a ~200-char summary instead of full content (related extras included) — the right mode for broad exploratory queries where full bodies would flood the client's tool-result budget. Recall the one or two memories that matter with a targeted follow-up.

namespace accepts a single name or a comma-separated list (e.g. "crow,my-project") to search several namespaces in one ranked pass. Unlike memory_context, limit is the TOTAL result cap: the best limit matches across all listed namespaces, not per namespace. A multi-namespace response carries namespaces and stamps each memory with its source namespace.

Omitting namespace scopes to the server's configured namespace, or to every namespace when none is configured (scope: "all"). A scoped recall that finds nothing reruns once across every namespace with the same filters, and says so with widened_from (the names it missed in) and scope: "all" - check each memory's namespace before treating a widened hit as belonging to the current project.

tags is comma-separated; ALL provided tags must match. confidence sets a minimum confidence threshold (verified > inferred > stale > deprecated). include_deprecated also returns deprecated memories (stale ones are always included). include_related also surfaces memories directly linked to the top hits via spreading activation: useful for pulling in a related cluster.

Unless type is given, the response may carry a capabilities section: a separate, capability-only semantic pass (up to 2) so a pointer is not buried under the procedure memories it replaces. It never repeats a main hit, and is absent when nothing clears the similarity floor. Each entry is compact, with similarity and the capability block.

explain=True adds a score_breakdown to each hit: the weighted relevance/freshness/access/confidence terms that score is the sum of. Use it to answer "why did this rank here?": a result carried by confidence and freshness with a near-zero relevance term matched the query barely or not at all. Off by default because it is a diagnostic, not something worth paying for on every read.

Inputs: query (required), tags, type, limit, +6 more.

memory_relateA

Create a directional link between two memories. Relations are used by spreading activation (recalling one memory wakes its related cluster) and are returned when include_related=True in memory_recall.

An edge must encode something search cannot infer. Recall already ranks by hybrid text + semantic similarity, so "these two memories are about the same topic" is knowledge the index has for free. What only a relation can record is direction and time: which memory REPLACED which, what CAUSED what, what CONTRADICTS what, what CONTAINS what. Prefer, in this order: supersedes, contradicts, caused_by, parent_of/child_of. Reach for related_to only when a genuine connection exists that none of those describe - it is the fallback, not the default.

Quality over volume: spreading activation surfaces at most 3 neighbours per seed memory, and it weights by relation type - a directional edge outranks related_to, so on any memory with more than 3 edges the related_to ones are what lose their slot. A vague edge is therefore not merely low-value, it is likely to never fire at all; and precise edges still compete against each other for those 3 slots, so a handful of them retrieves better than a dense mesh. If you cannot name the directional fact an edge records, do not create it.

A mislabelled edge is repairable: memory_unrelate retypes or removes one.

source_id is the memory making the claim about target_id. relation_type must be one of: supersedes (source replaces target), contradicts (conflicting claims), caused_by (source was caused by target), parent_of (source contains target), child_of (source belongs to target), related_to (fallback: a real connection none of the above captures).

Batch by passing edges instead of the single-edge fields - an array of up to MAX_BATCH_EDGES objects, each with source_id, target_id and relation_type (all required; there is no default type for a batch op):

[{"source_id": "a", "target_id": "b", "relation_type": "supersedes"},
 {"source_id": "a", "target_id": "c", "relation_type": "caused_by"}]

All-or-nothing, same as memory_unrelate's batch: every op is validated (both memories exist, the type is real, no self-edge) before anything is written, and the whole set is applied in one transaction, so a failure on op k leaves ops 0..k-1 unwritten too - a half-applied relation set is the graph state hardest to notice and hardest to repair. Relate is idempotent on (source, target, type), so each result reports created or exists rather than pretending a no-op was a write. Pass either edges or the single-edge fields, never both.

Inputs: edges, source_id, target_id, relation_type.

memory_statsA

Return health statistics for the memory store. Use to monitor memory growth, identify dormant memories, and get a per-namespace breakdown of counts and confidence distribution. Call at session start alongside memory_context to assess the state of the knowledge base.

namespace accepts a single name, a comma-separated list (e.g. "crow,my-project"), or omitted for global. A single name and the unscoped call keep the shape they always had: {"ok": true, "flagged_stale": 0, "stats": {...}}. A comma list instead returns the namespace-independent block (namespaces, access_log_rows, query_log_rows, credentials) exactly once under global, plus each namespace's own scoped stats under by_namespace - the session-start protocol's two-call pattern (memory_stats(namespace="crow") then one per project) collapsed into one call that computes the shared block once instead of once per namespace: {"ok": true, "flagged_stale": 0, "namespaces": [...], "global": {...}, "by_namespace": {"crow": {...}, "<project>": {...}}}. Names are de-duplicated, order-preserving; an unknown name fails the whole call and names it, same as memory_recall/memory_search. review_limit applies to every namespace's block.

stats.dormant_count reports memories untouched for 90+ days — a resting signal only, never a confidence change. Dormant memories wake automatically on recall via spreading activation. Memory is never auto-forgotten.

stats.size is the character cost the counts do not show: total_chars, mean_chars, pinned_chars and largest_pinned_chars. pinned_chars is the one to watch — pins load unconditionally at every session start, ahead of and exempt from ranking, so it is the only part of the store paid for on every call regardless of relevance. largest_pinned_chars is the skew check: a tier is not described by how many pins it holds, and when one pin approaches the tier total, the tier IS that pin. Adding well-chosen pins will not fix that; splitting the outlier will. Enumerate the tier with memory_search(pinned=True).

review_limit raises the review.sample, claims.sample and graph.orphan_sample caps (default 5, max 100) so a reconciliation sweep can enumerate every flagged memory — pair with memory_search's ids parameter to pull the full bodies.

stats.graph.orphan_sample names the memories behind graph.orphans: those no relation touches, which spreading activation can never reach. Ordered by confidence, then access count, then recency, so the orphans costing the most retrieval come first, each row carrying its namespace. memory_search(orphans=True) pulls the same set with full bodies; memory_relate reconnects one — where a directional fact genuinely exists.

stats.claims is the state-claim backlog: memories still asserting a PR/MR is open. claims.sample enumerates them, contradicted first, each row tagged contradicted (a later memory in the same namespace already recorded that ref as resolved). open counts every unresolved claim while open_actionable — what the sample lists — excludes claims on deprecated memories. memory_search(claims="open") pulls the same set with full bodies; memory_update(resolve_claims=...) closes them without editing prose.

claims.unverified counts refs a memory names without ever saying what became of them. It is reported for visibility, not action: those refs assert nothing, so they are excluded from open and from sample on purpose. Read them with memory_search(claims="unverified").

credentials counts THIS machine's vault only - secrets live in the keychain of the machine they were vaulted on, also in remote mode. Its machine field names that machine; at total: 0 a note says so. Zero on a machine that never vaulted anything is expected, not data loss: do not raise it as a problem.

flag_stale is deprecated and ignored — auto-demotion to stale contradicted the never-forget model and has been removed. Retained so existing callers do not error.

Inputs: namespace, flag_stale, review_limit.

memory_storeA

Store a new memory in the knowledge base. Use to capture anything worth remembering across sessions: decisions, bugs, patterns, architecture choices, preferences, facts, workflows, or context. Do not use for ephemeral or session-only notes.

type must be one of: fact, decision, pattern, bug, architecture, preference, workflow, context, capability. confidence is one of: verified (confirmed true), inferred (assumed, not yet confirmed), stale (outdated), deprecated (no longer valid) — defaults to "inferred". tags is comma-separated. namespace scopes the memory to a project or domain; omit to use the configured default namespace. source records what generated this memory (e.g. a file path or tool name). metadata is an optional free-form JSON string for extra structured data.

capability records that a thing EXISTS and how to run it, where a workflow says how to do it by hand. It requires metadata={"capability": {"run": "...", "path": "..."}} (run required; a relative path resolves against the namespace's repo path). Reads report whether path still exists.

provenance declares how you came to believe this: user-asserted (the user said so), measured (a command or test showed it), file-derived (read from code or docs), or self-concluded (your own inference or opinion). Declare it honestly - self-concluded is how a stored opinion arrives visibly contestable instead of reading as settled fact. Any other value is rejected. about says what this memory is FOR, in the user's words for the thing rather than the words of what was done ("claude code bootstrapping", not "init writes hook blocks"). It is searchable.

When dedupe_check is True (default), the response includes a similar_memories list of up to 3 existing memories in the same namespace whose content/title overlap strongly with this one — a non-blocking hint so the caller can choose to update/relate/consolidate instead of accumulating near-duplicates. Disable for bulk imports. Usually EMPTY, and that is the signal working. Each hit carries similarity (0-1) and its basis: cosine over embeddings, or lexical token overlap when they are unavailable. Unlike a search relevance it has magnitude and is comparable between calls - it says how close the two texts are, not how this candidate ranked.

When relation_check is True (default), the response also includes a suggested_relations list of up to 3 not-already-linked memories worth EXAMINING for a relationship. Topical overlap is only how they were found; it is not itself a reason to link. Ask whether one of them is the memory this one supersedes, contradicts, was caused_by, or belongs under - and if the honest answer is "they are just both about the same area", link nothing. Search already surfaces topical neighbours, so a related_to edge that says only "these are similar" adds no retrieval signal and competes with the directional edges that do. Same gate as above, set softer; similar_memories are merge candidates instead.

Both hint lists are COMPACT: title plus a ~200-char summary, never full bodies. They are enough to decide whether to merge, link, or move on; call memory_recall when a candidate warrants a closer look. Both carry similarity + basis, never a search score: these lists are not a ranking of the corpus, they are a measurement against what you just wrote.

The response may also carry contradicted_memories: older memories whose state claim THIS memory just resolved. Recording "PR #10 merged" makes every memory still asserting "PR #10 open" knowably wrong, and now is when fixing it is cheapest. Each entry gives the stale memory's id, title, the ref at issue, what it asserts, and both sides' evidence.

Reconcile by correcting the stale claim — the claim is now genuinely false, so the text should change. That is the opposite of rewording prose to silence a hint while the claim stays wrong. Advisory only: nothing was mutated.

Inputs: type (required), title (required), content (required), tags, +8 more.

memory_tripwireA

Bind a memory to a tool call so it is put in front of the agent at the moment it acts, not just at session start. Use it for the memories that must not be missed: "never sign commits as Claude", "never touch the prod config".

Actions: "add" (memory_id, tool, pattern), "list" (optional memory_id, namespace as a comma-separated list), "remove" (tripwire_id), "test" (tool, input, optional namespace).

tool is a regex FULL-matched against the tool name, e.g. "Bash" or "Edit|Write" ("Bash" does not catch "BashOutput"). pattern is a regex SEARCHED in the call's input: the command for Bash, the file_path for Edit/Write/Read, the notebook_path for NotebookEdit, otherwise the input as sorted JSON.

The PreToolUse hook denies the first matching call per session with the memory as the reason; the re-issued call passes. Use "test" to check a pattern before relying on it: input is the tool input as a JSON object string, and nothing is denied or logged. gingugu's own mcp__gingugu__ tools never trip.

Inputs: action (required), tool, input, pattern, +3 more.

memory_unrelateA

Repair the graph: retype a mislabelled edge, turn a backwards one around, or remove one that should not exist. The counterpart to memory_relate — without it, an edge written in haste is permanent, and every wrong edge keeps competing for one of the 3 spreading-activation slots on its memories forever.

Retype by passing new_relation_type alongside relation_type. The edge is relabelled in place: direction, creation time and metadata survive, because the usual repair is "right connection, wrong label" and the graph should keep an honest record of when the link was first drawn. If an edge of the new type already joins the pair, the two collapse into one and the outcome reports merged rather than retyped — the edge count drops by one, and nothing is fabricated to hide that.

Reverse by passing reverse=True alongside relation_type. The endpoints are swapped on the same row, so id, creation time and metadata survive exactly as they do for a retype — the connection was right, only the arrow pointed the wrong way. Reversing COMBINES with new_relation_type, in one write, because an edge recorded backwards is often mislabelled as well. Note that reversing parent_of/child_of is the same operation as flipping between the two types: do one or the other, not both. As with a retype, an existing edge in the target direction absorbs this one and reports merged.

Delete by omitting new_relation_type and reverse. With relation_type, only that edge goes; without it, every edge from source_id to target_id goes, whatever the type. Deletion here is not the bulk prune the graph guidance warns against: the caller names each edge, exactly as memory_forget names a memory.

Batch by passing edges — an array of up to 100 objects, each with source_id, target_id and optionally relation_type / new_relation_type / reverse, i.e. the same decision made once per edge:

[{"source_id": "a", "target_id": "b",
  "relation_type": "related_to", "new_relation_type": "caused_by"},
 {"source_id": "c", "target_id": "d",
  "relation_type": "caused_by", "reverse": true},
 {"source_id": "e", "target_id": "f", "relation_type": "related_to"}]

A batch is reviewed decisions submitted together, NOT a criteria-driven sweep, and that is deliberate. There is no "retype every related_to in this namespace" option, because the whole point of retyping is that each edge deserves a different type based on what it actually records — a blanket relabel would manufacture directional claims that were never true, and a false caused_by is worse than an honest related_to.

The batch is validated in full before anything is written, so a malformed op fails the whole call rather than leaving the graph half-repaired. Individual outcomes (retyped, reversed, merged, deleted, not_found, unchanged) are reported per edge. Use dry_run=True to preview a sweep first; nothing is written and each op reports what it would have done.

Find the edges to repair with memory_edges.

Inputs: edges, dry_run, reverse, source_id, +3 more.

memory_updateA

Update one or more fields of an existing memory. Use to correct outdated information, promote confidence after confirming an inference, retype a misfiled memory, or add/replace tags. Do not create a new memory when the right action is to update an existing one — find the id first with memory_recall.

All fields are optional; only provided fields are changed. tags (comma-separated) replaces the full tag set when provided — omit to leave tags unchanged. Pass metadata="" to clear metadata; omit to leave it unchanged.

type retypes the memory (same values as memory_store). Retyping is the right fix when a memory was filed under the wrong kind — e.g. durable reference material saved as workflow picks up point-in-time review hints, because pattern/preference are the types exempt from them. Retyping does not re-embed: the vector derives from title + about + content. Capability validation applies to the FINAL state, so retyping to or from capability must bring or clear the metadata.capability block.

provenance and about declare how the claim was reached and what it is for (see memory_store); pass "" to clear either. Neither touches last_confirmed: declaring them is not re-checking the claim.

resolve_claims reconciles a stale state claim WITHOUT EDITING THE PROSE — comma-separated refs (e.g. "gingugu#10"), or "all" for every open claim on this memory. Use it when the text is accurate history: a session log that said "PR #10 open" was correct on the day it was written, and rewriting it to stay current destroys the record. The memory body is left byte-identical; only the claim's resolution is recorded. Reach for content instead only when the memory asserts something that was never true.

"all" means every OPEN claim, never an unverified one. An unverified ref is one the prose names without saying what became of it, so sweeping it under "all" would record that you checked something you did not. Name such a ref explicitly to resolve it — that path works and is the honest way to say "I looked, and it merged".

When relation_check is True (default) and title or content was provided, the response includes a suggested_relations list of up to 3 not-already-linked memories worth examining for a relationship - same semantics as memory_store: overlap is how they were found, and only a directional fact (supersedes / contradicts / caused_by / parent_of / child_of) justifies an edge. Tag-only or confidence-only updates skip the check since the matching surface didn't change. Entries are compact (title + a ~200-char summary) and carry similarity + basis, as in memory_store; an empty list means nothing was close enough to be worth your time.

pinned marks a memory as ALWAYS loaded by memory_context for its namespace, ahead of and exempt from ranking, in addition to limit. Reserve it for the few rules that would cause real damage if missed — the ones you would want in front of you before touching anything, not merely useful or frequently relevant material. Ranking already handles "relevant"; a pin is for "inviolable". Capped per namespace (currently 20): pinning is a budget, so spending it on a merely-handy memory crowds out a rule that governs behaviour. Pass pinned=False to unpin. Pinning does not touch last_confirmed — it is a retrieval decision, not a claim that the content is still true.

review="history" records that you read this memory and judged it accurate history (a narrated wait, or a ref the claims ledger cannot settle). It silences gated review hints only, shows as reviewed on reads, is voided by a content edit, never inferred; "" clears it.

Inputs: memory_id (required), tags, type, about, +9 more.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A4.3/5.0

    Scored across 24 tools

    Disambiguation4/5

    The four read paths (memory_recall, memory_search, memory_context, memory_excerpt) genuinely overlap in 'find memories' territory, but each description explicitly states when to prefer it over its siblings and gives concrete distinguishing examples. The graph tools (relate/unrelate/edges) and consolidation tools (consolidate/dream) are separated by clear hints, though memory_consolidate vs memory_dream both touch redundancy reduction and require reading the fine print to pick correctly.

    Naming Consistency4/5

    Eighteen tools follow a clean memory_<verb|noun> snake_case pattern with parallel credential_* tools, so the bulk of the surface is highly predictable. Two outliers (code_xray and board) break the verb_noun convention and stand apart stylistically, though all names remain snake_case and readable.

    Tool Count3/5

    At 24 tools this sits at the heavy end of the range, and several adjacent pairs (memory_edges/memory_unrelate, memory_relate) could plausibly collapse into one action-dispatch tool the way code_xray and board already do. Still, each tool maps to a distinct operation across a broad domain (memory CRUD, graph, consolidation, namespaces, backup, credentials, code analysis, agent board), so nothing looks purely redundant.

    Completeness5/5

    The memory lifecycle is covered end to end: create, promote across namespaces, update, deprecate/hard-delete, targeted search and recall, in-body excerpting, graph relate/unrelate/edges, consolidation, proposal staging, namespace management, and JSON export/import backup. Credentials have full CRUD with keychain-aware redaction, and code_xray plus board round out cross-session collaboration without obvious dead ends.

    Maintenance

    ActivityActive
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      Not graded
      quality
      D
      maintenance
      A local, persistent memory system for AI coding assistants that stores decisions, patterns, and session context via MCP tools. It enables cross-session memory management using SQLite and optional vector search without external dependencies or cloud storage.
      56 npm
      3
      MIT
    • A
      license
      B
      quality
      C
      maintenance
      Persistent memory engine for AI coding agents. Single Go binary, zero runtime dependencies, MCP-native. Stores, searches, and deduplicates memories across sessions using embedded SQLite with hybrid FTS + semantic search, memory decay, relation graph, and token-budget context assembly.
      10
      23
      MIT
    • A
      license
      Not graded
      quality
      B
      maintenance
      Persistent memory for any AI assistant. Zero token cost until recall. Stores memories in local SQLite, ranks by 6-factor scoring, returns results 79% smaller than JSON. Works with Claude, ChatGPT, Grok, Cursor, Windsurf, and any MCP client.
      60
      Apache 2.0
    • A
      license
      Not graded
      quality
      B
      maintenance
      Enables MCP-compatible AI coding tools to store and recall persistent memories across sessions and projects, with keyword and semantic search backed by a local SQLite database.
      2,060 npm
      76
      Apache 2.0