Awesome Go

graymatter

CategoryArtificial Intelligence
SubcategoryArtificial Intelligence
Stars489

Local persistent memory layer and MCP server for AI agents with hybrid search, knowledge graph, and TUI

About graymatter

This large README is shown as a plain-text preview. Read the full README at the source

<div align="center">
  <img width="1500" height="276" alt="graymatter-banner" src=".github/assets/graymatter-banner-1.jpg" />
</div>

<h1 align="center"> GrayMatter </h1>


<p align="center">
  <a href="https://graymatter.nickcerutti.workers.dev"><img src="https://img.shields.io/badge/docs-live-brightgreen" alt="Documentation"></a>
  <a href="https://github.com/angelnicolasc/graymatter/actions/workflows/ci.yml"><img src="https://github.com/angelnicolasc/graymatter/actions/workflows/ci.yml/badge.svg" alt="CI"></a>
  <a href="https://pkg.go.dev/github.com/angelnicolasc/graymatter"><img src="https://pkg.go.dev/badge/github.com/angelnicolasc/graymatter.svg" alt="Go Reference"></a>
  <a href="https://github.com/angelnicolasc/graymatter/releases/latest"><img src="https://img.shields.io/github/v/release/angelnicolasc/graymatter" alt="Latest Release"></a>
  <a href="https://glama.ai/mcp/servers/angelnicolasc/graymatter"><img src="https://glama.ai/mcp/servers/angelnicolasc/graymatter/badges/score.svg" alt="Glama MCP server score"></a>
  <a href="https://github.com/avelino/awesome-go"><img src="https://awesome.re/mentioned-badge.svg" alt="Mentioned in Awesome Go"></a>
  <a href="https://mcpservers.org/servers/angelnicolasc/graymatter"><img src="https://mcpservers.org/badge.svg" alt="Listed on mcpservers.org"></a>
  <a href="https://github.com/angelnicolasc/graymatter/actions/runs/44426388996/job/135238443022"><img src="https://img.shields.io/badge/coverage-core%2082.5%25%20%C2%B7%20cli%2080.8%25-brightgreen" alt="Measured cross-platform statement coverage, core 82.5% and CLI 80.8%"></a>
  <img src="https://img.shields.io/badge/platforms-linux%20%7C%20macOS%20%7C%20windows-blue" alt="Platforms">
  <img src="https://img.shields.io/github/license/angelnicolasc/graymatter" alt="License">
</p>
<div align="center">
<br />
<strong>Persistent memory for AI agents, in one local binary.</strong>
<br /><br />
When a release moves from Friday to Monday, your next session can pick up the new date and the decision behind it.
<br />
Run GrayMatter with Claude Code, Codex, Cursor, or another MCP client, or embed it in Go.
<br /><br />
<a href="#quick-start">Try the offline demo</a> · <a href="#library-usage">Use the Go library</a>
</div>

---

## Why

<p align="center">
  <strong>90% fewer context tokens per query</strong> after 100 sessions compared with full history.<br>
  <strong>8.4% lower inference cost per task</strong> with empty memory and <strong>10.4% lower</strong> with 1,000 prior facts.<br>
  <strong>Zero retired values in the top eight</strong> after explicit revisions.
</p>

<p align="center">
  <a href="#token-efficiency"><img src=".github/assets/token-reduction-readme.png" width="800" alt="At 1, 10, 30, and 100 sessions, selective recall reduced context tokens per query by 0%, 12%, 71%, and 90% compared with full history."></a>
  <br>About 670 tokens with selective recall, compared with 6,960 for the full history.
</p>

<p align="center">
  <a href="benchmarks/agent_memory/RESULTS.md"><img src=".github/assets/graymatter-inference-by-family.png" width="800" alt="GrayMatter cost less on 94 of 113 paired tasks. Mean inference cost was lower in all eight task families at both starting memory sizes."></a>
  <br>GrayMatter’s optional <code>core</code> profile cost less than an organized notes folder on <strong>94 of 113 paired tasks</strong>.<br>
  Each task spanned three sessions with the same model and limits. GrayMatter solved <strong>50 tasks</strong>, compared with <strong>44</strong> for the folder.
</p>

<p align="center">
  <a href="benchmarks/revision_currency/RESULTS.md"><img src=".github/assets/graymatter-revisions-and-citations.png" width="800" alt="Explicit revisions reduced retired appearances from 35 to zero. A separate MCP check showed that core retained the source and exact quote with the fact."></a>
  <br>Saving corrections as independent facts surfaced old versions 35 times in 35 queries.<br>
  With <code>core</code>, an agent can replace the current fact for a subject and keep the source’s exact words.
</p>

<p align="center">
  <a href="#token-efficiency">Context tokens</a> · <a href="benchmarks/agent_memory/RESULTS.md">Inference cost and task completion</a> · <a href="#what-happens-when-a-fact-changes">Revisions and citations</a>
</p>

---

## Knowledge Graph

Your agent doesn't just remember facts — it builds a map of how they connect.

Run the daemon with `--kg` and every consolidation cycle extracts typed
entities (person, organization, project) and links the ones that appear
together. No manual tagging. No configuration. The graph builds itself from
ordinary use.

<p align="center">
  <img src=".github/assets/kg-graph-view.png" alt="Knowledge Graph in Obsidian" width="800px" style="max-width: 900px;">
</p>

<p align="center">
Every edge carries <strong>receipts</strong>: the fact IDs that produced it.<br>
Export to <strong>Obsidian</strong> with one command — entities become notes,<br>
connections become wikilinks, and the whole graph renders natively.
</p>

```bash
graymatter daemon run --kg    # that's it — the graph builds itself
```

The graph as one self-contained page — inline force-directed SVG, zero
external assets, works offline. Hover any edge to see the fact IDs that
produced it:

```bash
graymatter kg render --out graph.html
graymatter kg render --out graph.dot    # Graphviz, for your own layout
graymatter doctor --graph --html graph.html
graymatter kg inspect --json            # edge provenance and pending reasons
```

Status and graph doctor report complete and pending provenance. Historical
edges with uncertain support stay available to graph navigation. The inventory
can finish with edges still pending review.

Watch it build, one frame per session:

```bash
scripts/kg-timelapse.sh    # deterministic corpus -> frames -> GIF
                           # or anywhere: scripts/Dockerfile.kg-timelapse
```

---

## Observability

You can't improve what you can't see.

<p align="center">
  <img src=".github/assets/tui-workbench.gif" alt="GrayMatter TUI: creating and pinning a memory, activity, usage and system status" width="900px" style="max-width: 100%;">
</p>

`graymatter tui` opens a memory workbench with six views:

| View | Purpose |
|---|---|
| **Memory** | Browse namespaces, filter active/retired/alias facts, inspect provenance, add, revise, retire and pin exact facts |
| **Recall** | Inspect ranking receipts without incrementing access counts or learning aliases |
| **Activity** | Inspect harness runs and checkpoints; confirm before stopping a running session |
| **Graph** | Follow connected entities and open recorded supporting facts |
| **Usage** | Switch between subscription limits and API spend, with separate session context and source status |
| **Status** | Inspect memory aggregates, embedding observations and configured providers |

Press `1–6` to switch views, `/` for the command palette, `n` for namespaces,
`f` to filter, `Tab` to move focus, and `?` for contextual controls. Memory opens
first. Narrow terminals show one pane at a time; larger terminals show the list
and inspector together. `--theme dark|light|terminal` and optional `--mouse`
adapt the workbench to your terminal. `--read-only` prevents memory and session
mutations; it requires an existing store and either a running daemon or explicit
`--no-daemon`.

Usage stays available in the footer as well as its own view. Limits are reported
per account and window; API costs retain currency, period, source and whether
they are reported or estimated. Missing data remains unavailable, and failed
refreshes keep the last observation marked stale. No account is connected
automatically. See the [workbench guide](docs/tui.md) and [Usage setup](docs/usage.md).

`graymatter doctor --graph` reports hubs, articulation points, orphans,
connectivity and provenance in text or JSON. It reads the graph through an
existing daemon or a read-only store and only writes a render when given an
explicit `--html` path.

---

## What GrayMatter gives you

| | |
|---|---|
| **Persistent memory** | Facts survive across sessions. Recall by meaning, not just keyword |
| **90% token reduction** | Top-8 relevant facts instead of full-history injection |
| **Automatic hooks** | Claude Code injects routine recall every turn; MCP remains available for writes and focused searches (`graymatter hooks install`) |
| **Explainable recall** | `recall --explain` shows each fact’s ranking signals, fused score, and provenance |
| **Knowledge graph** | Typed entities and co-mention edges, auto-populated from ordinary use |
| **Self-curation** | `memory_reflect` lets the agent add, update, forget, and link its own memories |
| **Context block** | Projects top facts into CLAUDE.md / AGENTS.md inside a token budget (`context-sync`) |
| **Free auditor** | `doctor --audit` measures tokens, duplicates, staleness, and marker conflicts in any instruction file |
| **Deterministic decay** | Unpinned facts decay with a default 30-day half-life. Pruning can remove live facts and tombstones |
| **Single binary** | ~10 MB static. No Docker, no Redis, no config files, no cloud accounts |

---

## Quick start

Install and see it working in under a minute — no API keys, no Ollama:

```bash
go install github.com/angelnicolasc/graymatter/cmd/graymatter@latest
graymatter demo              # offline sample store, then the workbench opens
graymatter init              # wire YOUR project: MCP config + memory block
graymatter init --hooks      # Claude Code: memory injected every turn
graymatter doctor            # read-only observations of local setup artifacts
```

Standard `doctor` does not write a probe, start a daemon, execute a binary on
PATH, or test whether the data directory is writable. Its config checks find
references in files; they do not prove which settings a client loaded. In JSON,
`ok` means no check failed, while `readiness: not_evaluated` keeps readiness
separate from the observations. The `--health`, `--audit`, and `--embeddings`
modes have separate contracts.

`graymatter init --global` still performs that normal setup in the current
directory. It additionally installs the managed memory instructions in Claude
Code and OpenCode's home-scoped instruction files. It does **not** globalize
project-scoped MCP configs. If Claude's MCP server is already registered at
user scope and the instructions are already available globally, you do not
need to repeat local client setup in each repository. For a new user-scoped
Claude MCP registration, run once:

```sh
claude mcp add --scope user --transport stdio graymatter -- graymatter mcp serve
```

To prepare only the current project's memory directory before a session, use
`graymatter init --store-only` (available since v0.20.0). It creates
`.graymatter/MEMORY.md` if needed and leaves an existing regular
`.graymatter/gray.db` untouched. It does not
write client configs, instructions or hooks, change `PATH`, open the database,
or verify runtime health. If neither leaf is regular, symlink or other
nonregular `MEMORY.md`/`gray.db` entries cause an error; use `--dir` to select
the real data directory. You can repeat it safely:

```sh
graymatter init --store-only --quiet
```

For launchers that find the Git checkout or worktree root before running this
command, see [the Claude Code examples](examples/claude-global/README.md).
Global hooks are optional (`graymatter hooks install --scope global`) and skip
unprepared directories. MCP can itself create `gray.db` when it starts, even
without `init --store-only`; this command does not prevent that behavior.
Project-scoped clients still need their own MCP config. Codex is the exception
in the table below because its MCP config is already home-scoped.

For a **new, opt-in guarded** Claude user registration, use `--no-create` and
prepare each selected checkout before connecting:

```sh
claude mcp add --scope user --transport stdio graymatter -- graymatter mcp serve --no-create
cd /path/to/selected/project
graymatter init --store-only --quiet
```

Reconnect the MCP client after preparation. `--no-create` is not added to
existing entries by `init`; update a custom registration deliberately. It
requires a regular `gray.db`, or a regular `MEMORY.md` when the database is
absent. It is neither a database health check nor a read-only mode: an accepted
server can create and write runtime files. Hooks and MCP reject a symlink,
directory, or other nonregular `gray.db` even in the default eager mode. For a
custom store, use the same absolute `--dir` for preparation, MCP, and hooks.
Before downgrading to a binary without `--no-create`, remove the flag from the
registration; an older binary rejects it instead of retrying with eager
creation.

MCP stdio and hooks now select one project root per invocation. With an
omitted `--dir`, they use that root's `.graymatter` directory; an explicit
relative `--dir` is instead relative to the process working directory. If a
previous process-directory store contains data at a different location,
select the intended store explicitly rather than moving it automatically.
See [project routing and migration](docs/runtime-project-routing.md) for
worktree, hook namespace, custom-store, and HTTP behavior.

`graymatter demo` seeds a scratch store, runs consolidation, and opens the
TUI — then `graymatter kg render --out kg-graph.html` shows the graph it
built. Restart your editor. Seven memory tools are live.

<details>
<summary><strong>Package managers</strong> — Homebrew, Scoop, Nix</summary>

```bash
# Homebrew (macOS / Linux)
brew install angelnicolasc/tap/graymatter

# Scoop (Windows)
scoop bucket add angelnicolasc https://github.com/angelnicolasc/scoop-bucket
scoop install graymatter
```
</details>

<details>
<summary><strong>Pre-built binaries</strong> — Linux, macOS, Windows</summary>

```bash
# Linux (x86_64)
curl -sSL https://github.com/angelnicolasc/graymatter/releases/download/v0.21.0/graymatter_0.21.0_linux_amd64.tar.gz | tar -xz && sudo mv graymatter /usr/local/bin/

# macOS (Apple Silicon)
curl -sSL https://github.com/angelnicolasc/graymatter/releases/download/v0.21.0/graymatter_0.21.0_darwin_arm64.tar.gz | tar -xz && sudo mv graymatter /usr/local/bin/

# Windows (PowerShell)
iwr https://github.com/angelnicolasc/graymatter/releases/download/v0.21.0/graymatter_0.21.0_windows_amd64.zip -OutFile graymatter.zip
Expand-Archive graymatter.zip -DestinationPath .
```
</details>

<details>
<summary><strong>MCP client wiring</strong> — Claude Code, Cursor, Codex, OpenCode, Antigravity, and anything else</summary>

`graymatter init` configures every supported client at once. Existing entries
from other MCP servers and customized GrayMatter entries are preserved.

Normal init preserves an existing GrayMatter MCP entry, including custom
commands, remote endpoints, disabled settings and environment. To replace one
deliberately, select it explicitly:
`graymatter init --only claudecode --replace-mcp`. Invalid config files now
stop setup before any write; a later
partial apply returns nonzero while retaining successful actions for retry.
Scripts that accept a known partial result can opt into `--best-effort`.
`init --json` reports preparation actions with `runtime_verified:false`; it
does not certify a live client's setup. On Windows, interactive init asks
separately before changing user PATH, defaults to No, and honors `--no-path`.
Windows may reject edits to existing setup files with `unsupported_metadata`
when the audit SACL cannot be read; it leaves those files untouched. This also
applies to existing instructions during normal init. Edit that file manually,
use `--skip-instructions` to omit it, or run with permission to read its audit
SACL.

| Client | Config file | Scope |
|--------|-------------|-------|
| Claude Code | `.mcp.json` | project |
| Cursor | `.cursor/mcp.json` | project |
| Codex (OpenAI) | `~/.codex/config.toml` | home |
| OpenCode | `opencode.jsonc` | project |
| Antigravity (Google) | `mcp_config.json` | opt-in |
| Windsurf | `.windsurf/mcp.json` | project |
| VS Code Copilot Agent | `.vscode/mcp.json` | project |

**Also works out of the box:** Pi (reads `.mcp.json` natively), Zed, Cline,
and any MCP-compatible client — point them at `graymatter mcp serve`.
Per-client verified configs for 25 clients, including the ones that need a
different shape (VS Code's `servers` key, Codex TOML, Zed's
`context_servers`), live in [docs/integrations.md](docs/integrations.md).
See [docs/AGENTS.md](docs/AGENTS.md) for tool parameters and query patterns.
</details>

---

## Token efficiency

Numbers produced by `go run ./benchmarks/token_count` — real Recall calls,
keyword embedder, no LLM required:

| Sessions | Full injection | GrayMatter | Reduction |
|----------|---------------|------------|-----------|
| 1        | ~80 tokens    | ~80 tokens | 0% |
| 10       | ~630 tokens   | ~550 tokens | 12% |
| 30       | ~1,880 tokens | ~550 tokens | 71% |
| 100      | ~6,960 tokens | ~670 tokens | **90%** |

### Does it return the *right* facts?

Tokens are only half the question. A second benchmark checks whether the
returned facts actually answer the query, against a real sliding window:

| | sliding window | GrayMatter | + `MinRelevance` |
|---|---|---|---|
| Finds a fact planted 96 sessions ago | 0% | **83%** | 83% |
| Returns a superseded fact | 0% | 0% | 0% |
| Tokens per query | 95 | 114 | **64** |

At equal fact count, relevance-selected facts cost slightly more tokens than a
window's newest-first picks. With `MinRelevance`, GrayMatter uses 64 tokens per
query and retains the observed 83% hit rate on old facts. CI checks the token
and retrieval tables above against their benchmark outputs. [Retrieval methodology and per-query results](benchmarks/RESULTS.md)

### What happens when a fact changes?

A separate keyword-retrieval benchmark made the same 35 queries against 600 facts. Storing corrections as independent facts let retired values appear **35 times** in the top eight. Recording explicit revisions brought that count to **zero**. The current value both reached the top eight and outranked every retired version in **25 of 35** queries, up from **8 of 35**.

[Revision benchmark and per-group results](benchmarks/revision_currency/RESULTS.md) · [How citations are stored and retrieved](docs/citation-evidence.md)

---

## Memory lifecycle

```
Recall(agent, task)          ← hybrid: vector + keyword + recency → top-8 facts
    ↓
Inject into system prompt    ← your 3 lines of code
    ↓
Agent runs
    ↓
Remember(agent, observation) ← store key facts during/after run
    ↓
Consolidate() [async]        ← apply decay, prune, and extract entities when enabled
```

Consolidation runs memory maintenance. Generative compaction is disabled
for Anthropic and Ollama. Configured embeddings and knowledge-graph extraction
continue to operate. Historical summaries and counters remain available
subject to the usual retention rules. Update or restart a running legacy
daemon before using operations that can trigger maintenance.


### Review memory evidence

Use `review analyze` to explicitly send one namespace's eligible facts to a
configured Anthropic or Ollama provider. Review writes versioned evidence,
candidate summaries, and conflict records to a separate journal. Active
memory, its recall eligibility, and routine maintenance are unchanged.

```bash
graymatter review analyze project --provider ollama
graymatter review list project
graymatter review inspect project record-id
graymatter review reject project summary-id --decision "Needs more evidence"
graymatter review resolve project conflict-id --decision "The runbook governs" --reference "runbook/retention"
graymatter review dismiss project conflict-id --decision "Separate environments" --reference "runbook/environments"
graymatter review purge project closed-record-id
```

Frequently Asked Questions

What is graymatter?

graymatter is a Artificial Intelligence library for the Go programming language. Local persistent memory layer and MCP server for AI agents with hybrid search, knowledge graph, and TUI

How do I install graymatter?

Install graymatter with the Go module system using `go get angelnicolasc/graymatter`. Check the repository for the current installation instructions.

What category does graymatter belong to?

graymatter is listed under Artificial Intelligence, specifically Artificial Intelligence.

← Back to Artificial Intelligence