Skip to main content
Glama
Bhaskar-GameDev

context-manager

README.md
# context-manager

Local-first, cross-session context store **built to reduce token usage**. Save facts, decisions,
preferences, todos, and session handoffs once — recall them in any later session or a different AI
conversation, ranked and token-budgeted so they cost the model as little as possible.

- **Token-efficient.** Recall is ranked (pinned > importance > recent) and capped by a token
  budget. The model restores context instead of re-reading files / re-deriving it.
- **Squeeze rendering (v0.3).** Default recall is lossy-compressed — filler words dropped,
  safe abbreviations applied — while code, paths, identifiers and URLs are left intact.
  Typically ~40-50% fewer tokens than the full bodies, still LLM-readable.
- **Focus rerank (v0.3).** `--focus "<task>"` blends full-text relevance into ranking so only
  on-topic context surfaces — load what the current task needs, not the whole store.
- **Delta recall (v0.3).** Each recall prints a `cursor=`. Pass it back as `--since` next time
  to skip entries unchanged since then — never re-pay tokens for context already seen (pinned
  always kept).
- **Savings accounting (v0.3).** Recall reports `saved N% vs Mt full dump` so the win is measurable.
- **Zero external services.** Single SQLite file at `~/.context-manager/context.db`.
- **Two interfaces.** An MCP server (Claude Code / Cursor / any MCP client) and a `ctx` CLI.
- **Namespaced by project.** Default namespace = current folder name; override with `--project`.
- **Full-text search** via SQLite FTS5. No embeddings, no API keys.

## Why it saves tokens

AI sessions forget everything when they end; a new session re-reads files and re-derives context —
expensive. This stores the durable stuff (decisions + the *why*, where you left off). Next session
calls `context_recall` (or a SessionStart hook injects it automatically) and is up to speed in a few
hundred tokens instead of thousands of re-exploration tokens. Compact rendering + a token budget keep
the injected context small; ranking ensures the few tokens spent are the highest-value ones.

## Install

```bash
npm install
npm run build
npm link        # optional: global `ctx` command
```

## CLI

```bash
ctx save "use Gemini Flash" -t decision -b "budget choice" -i 5 --pin --tags ai,budget
ctx append "build log" "phase 2 done"     # accumulate without overwriting
ctx recall                                 # ranked, squeezed (max savings), current folder
ctx recall --budget 400                    # cap output to ~400 tokens
ctx recall --focus "cold email sending"    # rerank to the current task
ctx recall --since 2026-06-27T07:23:58Z    # delta: only what changed since the cursor
ctx recall -f full                         # full detail (no compression)
ctx recall -f compact                      # one-line, no lossy squeeze
ctx search gemini                          # full-text search
ctx list                                   # titles-only index
ctx handoff "built MCP server" -n "wire into lead-gen project"
ctx pin 1 / ctx unpin 1                     # pin critical entries
ctx forget 3                                # delete entry #3
ctx export -p demo > demo.md                # backup / git / portable
ctx import demo.md -p demo                  # restore
ctx prune --days 30 -t session              # drop stale entries (keeps pinned)
```

Flags: `-p/--project`, `-t/--type <fact|decision|preference|todo|session>`, `-b/--body`,
`-i/--importance <1-5>`, `--pin`, `--tags a,b,c`, `-n/--limit`, `-f/--format <compact|full|squeeze>`,
`--budget <tokens>`, `--focus <task>`, `--since <iso>`. Override DB location with `CONTEXT_DB` env.

## Claude Code (MCP)

Register once, available in every project (user scope):

```bash
claude mcp add --scope user context-manager -- node "F:/Tools/context-manager/dist/mcp.js"
```

Tools: `context_recall`, `context_save`, `context_append`, `context_search`, `context_list`,
`context_handoff`, `context_pin`, `context_forget`, `context_prune`.

After rebuilding (`npm run build`), restart Claude Code so the new `dist/` is loaded by the MCP
server.

## Auto-recall on session start (biggest token win)

Make recall automatic instead of relying on the model to ask. Add a `SessionStart` hook to your
Claude Code `settings.json` that injects a small, budgeted context snapshot:

```jsonc
// in "hooks" -> "SessionStart" -> a "hooks" array
{
  "type": "command",
  "command": "\"C:\\Program Files\\nodejs\\node.exe\" \"F:\\Tools\\context-manager\\dist\\cli.js\" hook-recall --budget 400",
  "timeout": 10,
  "statusMessage": "Recalling saved context..."
}
```

`hook-recall` prints a compact, budget-capped snapshot (silent if the project has none). Its stdout
is injected as session context — every session boots warm for a few hundred tokens.

End sessions with `context_handoff` (or `ctx handoff`) so the next start has "where we left off".

## Data model

One table, `entries(project, type, title, body, tags, pinned, importance, source, created_at,
updated_at)`, unique on `(project, type, title)` so re-saving the same title updates in place.
An FTS5 virtual table mirrors title/body/tags via triggers for search. Recall ranks by
`pinned DESC, importance DESC, updated_at DESC`.

## Develop

```bash
npm test          # vitest: store + format (28 tests)
npm run cli -- recall      # run CLI from source (tsx)
npm run mcp                # run MCP server from source (tsx)
```