Skip to main content
Glama
README.md
<div align="center">

# 🧠 grok-memory

**Long-term memory for Grok. Ingest a whole book or codebase once, then ask anything with cited answers.**

[![CI](https://github.com/myn4ki/grok-memory/actions/workflows/ci.yml/badge.svg)](https://github.com/myn4ki/grok-memory/actions/workflows/ci.yml)
[![License: MIT](https://img.shields.io/badge/License-MIT-black.svg)](LICENSE)
[![Node.js](https://img.shields.io/badge/node-%3E%3D20-brightgreen.svg)](https://nodejs.org)
[![Dependencies](https://img.shields.io/badge/dependencies-0-blue.svg)](package.json)
[![MCP](https://img.shields.io/badge/MCP-server-purple.svg)](#use-it-from-any-mcp-client)
[![Powered by Grok](https://img.shields.io/badge/powered%20by-Grok-000000.svg)](https://x.ai/api)

[Why](#why) ·
[Quick start](#quick-start) ·
[How it works](#how-it-works) ·
[Commands](#commands) ·
[MCP](#use-it-from-any-mcp-client) ·
[Cost](#cost-and-caching) ·
[FAQ](#faq)

</div>

---

*Example session (illustrative output):*

```console
$ grok-memory ingest ./three-kingdoms.epub --name tamquoc
Ingesting ./three-kingdoms.epub as "tamquoc" with grok-4.7...
  level 0/3: summarising 412 item(s)...
  level 1/3: summarising 120 item(s)...
  extracting key entities...
✓ Memory "tamquoc" ready: 412 passages, 132 sections, 58 entities

$ grok-memory ask tamquoc "Which stratagems did Zhuge Liang use before the Battle of Red Cliffs?"
… navigating
… answering

Before Red Cliffs, Zhuge Liang "borrowed" about 100,000 arrows by sending straw-lined
boats into Cao Cao's fog-covered camp [P2], then persuaded Sun Quan to ally with Liu Bei
by provoking Zhou Yu's pride [P1] ...

Sources:
  [P1] Chapter 43 › Zhuge Liang debates the scholars  (OEBPS/ch043.xhtml:12-58)
  [P2] Chapter 46 › Borrowing arrows with straw boats  (OEBPS/ch046.xhtml:1-44)

48,210 input tokens (41,902 cached), 612 output
```

## Why

Grok has a large context window, but that alone doesn't make it remember a large source:

| Problem | What grok-memory does |
|---|---|
| A book series or monorepo is **larger than any context window** | Builds a navigable **memory tree** with summaries at every level, so any size works |
| Stuffing 400k tokens into every question is **slow and expensive** | Sends a compact map plus only the passages that matter, typically 20–50k tokens |
| Facts in the middle of very long prompts get **missed** | Grok picks the exact passages to read, and keyword search adds a safety net |
| Every new session **starts from zero** | Memories persist on disk, and notes from conversations are kept for next time |
| Answers are **hard to verify** | Every answer cites passages with chapter or `file:line` locations |

## Quick start

```bash
npm install -g github:myn4ki/grok-memory
export XAI_API_KEY="xai-..."            # from https://console.x.ai   (PowerShell: $env:XAI_API_KEY="xai-...")

grok-memory ingest ./my-book.md --estimate     # preview size and cost, no API call
grok-memory ingest ./my-book.md                # build the memory once
grok-memory ask my-book "How does the main character change between part 1 and part 3?"
grok-memory chat my-book                       # multi-turn conversation with memory
```

Works with:

- **Books and documents:** `.md`, `.txt`, `.rst`, `.adoc`, `.org` and **`.epub`**. Chapters are detected from Markdown headings and lines like *Chapter 12*, *CHƯƠNG IV* or *Part II*.
- **Code:** a single file or a whole directory. `.gitignore` is respected, and dependencies, build output, binaries, dotfiles and likely secrets (`.env`, `*.pem`, keys) are skipped automatically.

## How it works

```
                    ┌──────────────────────────────────────────┐
                    │  MAP (always sent, prompt-cached)        │
                    │  overview · outline with [ids] ·         │
                    │  key entities · your notes               │
                    └──────────────────────────────────────────┘
                                       │
            ┌──────────────────────────┼──────────────────────────┐
       [n1] Part I               [n57] Part II              [n120] Part III      ← section summaries
       /     |     \
 [n2] Ch.1 [n9] Ch.2 ...                                                         ← chapter / file summaries
    /   \
 [n3]  [n4]   ← passages: original text with line ranges, opened only when needed
```

**1. Ingest (one time).**
The source is split along its natural structure (parts, chapters and headings for books;
directories, files and line ranges for code). Grok summarises every passage, then every
section from its children's summaries, up to a whole-source overview. A sheet of
**key entities** (characters, places, modules, APIs, decisions) is extracted at the end.

**2. Ask.**
- **Navigate:** Grok reads the map plus keyword-search hits, then chooses which nodes to
  open. If a chosen section is too large, it drills down one level.
- **Read:** the passages under those nodes are gathered within a token budget, keeping keyword-relevant ones first and then document order.
- **Answer:** Grok answers from the passages and cites them as `[P1]`, `[P2]` and so on, each with its location.

**3. Remember.**
`grok-memory remember <name> "<fact>"` or `/remember` in chat adds durable notes, and every
later answer takes them into account. Run `/remember` with no text and Grok extracts the
facts worth keeping from the conversation itself.

**4. Update incrementally.**
Each summary is keyed by a content hash. `grok-memory update <name>` re-reads the source
and only re-summarises passages that changed, plus their ancestors. That keeps a memory of
an active codebase cheap to refresh.

## Commands

| Command | What it does | API calls |
|---|---|---|
| `ingest <path> [--name n] [--estimate]` | Build a memory from a file or directory | ✅ (none with `--estimate`) |
| `update <name>` | Refresh from the original source, paying only for changes | ✅ |
| `ask <name> "<question>" [--json]` | One-shot question with cited sources | ✅ |
| `chat <name>` | Conversation with `/remember`, `/sources`, `/map` and `/exit` | ✅ |
| `search <name> "<terms>"` | BM25 keyword search over passages | ❌ |
| `map <name>` | Show overview and outline | ❌ |
| `entities <name>` | Show the key entities sheet | ❌ |
| `remember <name> "<note>"` / `notes <name>` | Add or list notes | ❌ |
| `list` / `stats <name>` | List memories, show size and token usage (incl. cache hit %) | ❌ |
| `delete <name> --yes` | Delete a memory | ❌ |
| `mcp` | Run as an MCP server on stdio | — |

Options: `--budget <tokens>` (passage budget per answer, default 40000), `--chunk-tokens`,
`--concurrency`, `--dir` (store location, default `~/.grok-memory` or `$GROK_MEMORY_DIR`),
`-m, --model` (default `grok-4.7` or `$GROK_MODEL`).

## Use it from any MCP client

grok-memory is also a [Model Context Protocol](https://modelcontextprotocol.io) server, so
agents and IDEs can query your books and codebases:

```json
{
  "mcpServers": {
    "grok-memory": {
      "command": "npx",
      "args": ["-y", "github:myn4ki/grok-memory", "mcp"],
      "env": { "XAI_API_KEY": "xai-..." }
    }
  }
}
```

| Tool | Description |
|---|---|
| `memory_list` | List available memories |
| `memory_map` | Overview, outline and entities (no model call) |
| `memory_search` | Keyword search returning raw passages with locators (no model call) |
| `memory_ask` | Navigate and answer with citations |
| `memory_remember` | Add a durable note |

Ingestion stays in the CLI because it is long-running and costs tokens; build memories
first, then share them with every agent.

## Use it as a library

```js
import { createGrok, ingest, loadMemory, ask } from 'grok-memory';

const grok = createGrok(); // reads XAI_API_KEY / GROK_MODEL
await ingest('./docs', { name: 'handbook', grok });

const mem = loadMemory('handbook');
const { answer, sources } = await ask(mem, 'What is our on-call escalation policy?', { grok });
```

## Cost and caching

- **Ingest is a one-time cost**, roughly the size of the source in input tokens plus short
  summaries as output. Run `--estimate` first: it prints passages, sections, token counts and a
  dollar estimate without calling the API. Prices can be overridden with
  `GROK_PRICE_INPUT` and `GROK_PRICE_OUTPUT` (USD per 1M tokens).
- **Questions are cheap.** Each question makes two calls, navigate and answer (three when it
  drills down), over a compact map and the selected passages.
- **Prompt caching by design.** The instructions, map, entities and notes form a stable
  prefix that is byte-identical across questions, and requests carry a per-memory
  `prompt_cache_key`. xAI bills cached input tokens at a discount. `grok-memory stats` shows
  your cache hit rate.
- Requests are sent with `store: false`.

## How does this compare?

| Approach | Good at | Trade-off |
|---|---|---|
| Paste everything into the prompt | Small sources, one-off questions | Cost and latency on every question, and an upper size limit |
| Vector-database RAG | Huge, flat corpora | Needs an embedding model and a database; loses document structure |
| xAI Collections (hosted search) | Managed retrieval inside the xAI platform | Documents live in the cloud collection |
| **grok-memory** | Structured sources (books, docs, code); local, inspectable, incremental | One-time summarisation cost at ingest |

grok-memory runs locally and stores plain JSON in `~/.grok-memory/<name>/`
(`meta.json`, `nodes.json`, `entities.json` and `notes.json`). You can read, diff, back up or delete it.

## FAQ

<details>
<summary><b>How big a source can it handle?</b></summary>

There is no hard limit. Sections with more than 20 children are grouped automatically, so the
tree stays navigable, and the map shows as many outline levels as fit in its budget.
Ingest time and cost grow roughly linearly with source size.
</details>

<details>
<summary><b>Does it work for non-English text?</b></summary>

Yes. Summaries are written in the source's language, answers follow the question's
language, and keyword search is Unicode-aware. Vietnamese queries also match without
diacritics (*gia cat luong* finds *Gia Cát Lượng*), and CJK text is indexed per character.
</details>

<details>
<summary><b>What about PDFs?</b></summary>

PDF parsing is not built in yet, to keep the project dependency-free. Convert first, for example
`pdftotext book.pdf book.txt`, then ingest the text file.
</details>

<details>
<summary><b>What is sent to the xAI API?</b></summary>

During ingest, the passages being summarised. During questions, the map, entities, notes
and the selected passages. Dotfiles, `.env` files, keys and certificates are never read
when ingesting a directory. See [SECURITY.md](SECURITY.md).
</details>

## Roadmap

- [ ] PDF input via an optional converter
- [ ] Watch mode that re-ingests on file changes
- [ ] Export a memory as a single Markdown "study guide"
- [ ] Optional live web and X search for questions that go beyond the source

## Development

```bash
git clone https://github.com/myn4ki/grok-memory.git
cd grok-memory
npm test          # 30 tests, fake Grok client, no network
```

```
bin/grok-memory.js   CLI
src/sources.js       Files, directories (.gitignore aware) and EPUB → outline
src/chunk.js         Chunking and chapter/heading detection
src/epub.js          Dependency-free EPUB (ZIP + OPF) reader
src/tree.js          Memory tree: node building, bottom-up summarisation, map rendering
src/search.js        BM25 keyword index
src/memory.js        Storage, ingest/update, entities, notes
src/ask.js           Navigation, passage gathering, cited answers
src/mcp.js           MCP server
src/grok.js          xAI Responses API client (retries, JSON schema, cache key, usage)
```

## Contributing

Contributions are welcome. Please read [CONTRIBUTING.md](CONTRIBUTING.md) and our
[Code of Conduct](CODE_OF_CONDUCT.md). To report a vulnerability, see [SECURITY.md](SECURITY.md).

## License

Released under the [MIT License](LICENSE).