New:Microsoft Teams Notifications Are Now Available in Socket.Learn more
Get Started

engramx

Package Overview
Dependencies
Maintainers
1
Versions
35
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

engramx

The context spine for AI coding agents. 9 built-in providers + mcpConfig plugin contract (wrap any MCP server in 10 lines), generic MCP-client aggregator (stdio), pre-mortem mistake-guard, bi-temporal mistake memory, Anthropic Auto-Memory bridge, SSE stre

Source
npmnpm
Version
3.3.0
Version published
Weekly downloads
118
-1.67%
Maintainers
1
Weekly downloads
 
Created
Source

EngramX — the memory layer for AI coding agents

The memory layer that stretches every Claude session.

CI npm version npm downloads License Node Tests 9 Providers + plugins Zero native deps Discord Stars

Why · Install · Per-agent setup · engram remembers · How it works · Architecture · Discord

Anthropic capped your week. engram extends it.

In November 2025, Anthropic tightened weekly limits on Claude Pro and Max. Heavy Claude Code users now hit caps mid-week. Some by Wednesday. The honest reality nobody is naming out loud:

Most of your weekly tokens are spent re-introducing yourself to an agent that forgets.

Every Monday starts from zero. The agent re-reads the codebase. Re-asks setup questions. Repeats last week's wrong fix. Re-decides architecture you already locked in. By Friday you're rate-limited. Not because you built a lot. Because the agent never got smarter.

engram is the memory layer that fixes that. A persistent knowledge graph, plus a mistake replay buffer, plus a provider mesh that wires in mempalace, obsidian, context7, MCP servers, and Anthropic's own auto-memory. The agent stops being single-shot. It learns from its own history.

What changes when your agent has memory

Without engramWith engram
MondayAgent re-reads codebase from scratch (~40K tokens)Reads structural graph (~3K tokens)
TuesdayRepeats Monday's wrong fix⚠️ Warned: "You tried this Monday, broke parser.rs:42"
WednesdayRe-decides architecture you already lockedSurfaces Monday's decision: "We chose Saga over 2PC because…"
ThursdayAsks the same 5 setup questionsPulls config from mempalace, obsidian, context7 providers
FridayCap hit by 3pmCap hit Sunday, if at all

Token savings (89.1% measured per Read interception, reproducible benchmark below) are the side-effect. Compounding agent intelligence is the product.

Install

brew install engramx

Cross-platform fallback

npm install -g engramx

Zero-dep one-liner

curl -fsSL engramx.dev/install | sh

Verify: engram --version should show 3.x or later. Requires Node.js 20+. Zero native deps. No build tools, no Rust, no Python, no system libs.

Note: "engram" the audio plugin and "engram" the neuroscience term are different things. We're engramx on npm, engram on the CLI. Also not Go-Engram (a salience-gated chat memory in Go) and not DeepSeek's January 2026 "Engram" paper (research artifact, not a product).

Per-agent setup

One command for your stack:

engram init --agent claude          # Claude Code (default)
engram init --agent cursor          # Cursor
engram init --agent windsurf        # Windsurf
engram init --agent codex           # OpenAI Codex
engram init --agent gemini          # Gemini CLI
engram init --agent cline           # Cline / Roo Code
engram init --agent copilot         # GitHub Copilot CLI
engram init --agent kilocode        # Kilo Code
engram init --agent antigravity     # Google Antigravity

One run wires the right hooks, settings, and per-agent config files. Restart your AI tool. engram is live.

Prefer the all-in-one bootstrap? engram setup runs engram init + engram install-hook + IDE detection + dual-emits AGENTS.md and CLAUDE.md + engram doctor. Under 30 seconds on most projects.

See what your agent has remembered

$ engram remembers

  43 mistakes avoided     ⚠️  surfaced before the agent could repeat them
 127 decisions surfaced   📜  prior architectural choices recalled in context
  18 cross-session bridges 🔗 sessions that picked up where the last one ended
  86K tokens saved        🎟️  ~ 4.3 hours of weekly cap, reclaimed
   7 days indexed         📅  since engram init

Your subscription, stretched.

Cumulative since engram init. Run it weekly. Share the screenshot.

How it works

  Without engram:                              With engram:

  Claude → reads file.rs (8,000 tokens)        Claude → reads file.rs
                                                          ↓
                                               engram intercepts → graph context (800 tokens)
                                                          ↓
                                               Claude sees: structure
                                                         + last week's mistakes (⚠️ pre-mortem)
                                                         + relevant decisions
                                                         + git co-changes
                                                         + cross-session memory

Nine providers ship by default and every one is pluggable:

ProviderSurfaces
structureAST-derived class/function/import graph of the project
mistakesWhat broke last week. Pre-mortem warnings before the agent re-makes the error. Bi-temporal: refactored-away mistakes stop firing.
gitHot files, co-change pairs, authorship signals
mempalaceYour local semantic memory (mempalace MCP / ChromaDB)
context7Up-to-date library docs (Context7 MCP)
obsidianYour knowledge vault, queried at agent-time
anthropic-memoryAnthropic's auto-memory bridge
mcp-clientAny MCP server. engram talks to all of them.
lspLive language-server symbols (Serena, etc.)

Add your own: drop a 10-line .mjs into ~/.engram/plugins/. Validated before install.

Why this exists

Stateless agents are amnesiacs with PhDs. They solve the problem in front of them, then never get smarter at your codebase. Multiply that by Anthropic's weekly caps and every session burns tokens re-learning what last session already learned.

engram is the spine that connects sessions. It does what stateless tools physically can't:

  • Persistence. .engram/graph.db survives every restart, every cap reset, every laptop reboot. Your agent gets a brain that remembers.
  • Mistake memory. Pre-mortem warnings before the agent repeats last week's error. Surfaced at the top of context, automatically.
  • Provider mesh. Runtime composition across knowledge sources you already use. mempalace, obsidian, context7, MCP servers, all wired in.

Token compression is downstream of those.

Proof, not promises

Everything above is measured. bench/real-world.ts runs the full resolver against real files in this repo and compares the rich-packet token cost to the raw-file-read cost. Reproducible in one command on any project.

Latest run (2026-04-24, 87 source files, full report at bench/results/real-world-2026-04-24.md):

MetricValue
Baseline tokens (87 files read raw)163,122
engramx tokens (rich packets)17,722
Aggregate savings89.1%
Median per-file savings84.2%
Files where engramx saved tokens85 of 87
Best case (src/cli.ts)98.4% (18,820 → 306)

Reproduce on your own code:

cd your-project
engram init
npx tsx /path/to/engram/bench/real-world.ts --project . --files 50

Small projects score lower. Dense structural projects score higher. It's real arithmetic on your files. You can audit every number.

Companion tools

engram compresses what the codebase is (file contents into graph context). For compressing what the system is doing (shell command output) pair it with rtk:

brew install rtk           # 60-90% savings on git/npm/cargo/grep/etc. (Bash)
brew install engramx       # 89% savings + memory + mistake-guard (Read)

Both register PreToolUse hooks. They don't conflict. rtk owns Bash, engram owns Read. Run both for a 3-5x weekly cap stretch end to end.

Clean uninstall

One command:

npm uninstall -g engramx     # 3.0.1+ auto-runs preuninstall hook-cleanup

If you installed 3.0.0 and ran npm uninstall before the 3.0.1 patch shipped, your Claude Code hooks may be orphaned. Run engram repair-hooks --scope user (install 3.0.1 first) or see the CHANGELOG.md for the manual jq-based recovery one-liner.

Dashboard

A zero-dependency web dashboard ships built-in. One command, opens in your browser:

engram ui

engram dashboard — Overview tab

The Overview tab: real metrics from your sessions — tokens saved, cost saved at $3/M rate, session-level hit rate, cache performance, graph health.

engram dashboard — Activity tab

Activity — live hook events streamed via Server-Sent Events. See every Read / Edit / Write decision (deny = intercepted, passthrough = engram couldn't help). Per-tool breakdown on the right shows where the savings come from.

engram dashboard — Files heatmap

Files — the heatmap ranks your hot files by interception count. Cursor knows this view.

engram dashboard — Knowledge graph visualization

Graph — Canvas 2D force-directed visualization of the knowledge graph. God nodes are larger and labeled. Drag to pan, scroll to zoom, click for details. 300+ nodes at 60fps.

engram dashboard — Providers + cache health

Providers — component health (HTTP / LSP / AST / IDE count) and per-layer cache stats (entries + cross-session hit counts).

Design

  • 35KB total — one HTTP response, zero external CDN calls, works offline and on air-gapped machines.
  • Zero runtime dependencies — all CSS and JS inlined as TypeScript template literals; SVG charts and Canvas 2D graph hand-rolled (~400 LOC total).
  • CSP-hardeneddefault-src 'self'; connect-src 'self' meta tag plus esc() at every data-to-HTML boundary. Defends against attacker-controlled file paths and labels mined from untrusted repos.
  • Live-updating — SSE stream pushes new hook events to the Activity tab within 1 second.

See also the Sessions tab (cumulative breakdown + sparkline) in assets/screenshots/02-sessions.png.

Benchmark

engramx ships with two benchmarks — use whichever fits your workflow.

Real-world bench (new in v3.0, preferred)

npx tsx bench/real-world.ts --project . --files 50 runs the full resolver against real files in any project and outputs exact token numbers. See the Proof section above for the reproducible 89.1% result on engramx itself.

Structured task bench (CI regression)

Measured across 10 structured coding tasks against a baseline of reading the relevant files directly. No synthetic data. No cherry-picked queries.

TaskBaseline (tokens)engram (tokens)Savings
task-01-find-caller4,50065085.6%
task-02-parent-class2,80040085.7%
task-03-file-for-class3,20030090.6%
task-04-import-graph6,80090086.8%
task-05-exported-api5,50070087.3%
task-06-landmine-check8,20085089.6%
task-07-architecture-sketch14,5001,60089.0%
task-08-refactor-scope9,2001,10088.0%
task-09-hot-files3,80055085.5%
task-10-cross-file-flow12,8001,40089.1%
Aggregate7,13084588.1%

Run it yourself: npx tsx bench/runner.ts (structured fixtures) or npx tsx bench/real-world.ts (live resolver on real files).

Plugins multiply the savings

The 89.1% number is engramx with its 9 built-in providers. Every MCP server you plug in closes another context gap the agent would otherwise burn tokens researching. And because every provider is budget-capped and the resolver is budget-weighted + mistakes-boost reranked, more plugins = more relevant context without packet bloat.

PluginCloses this gapInstall
Serena (LSP symbols, 20+ languages)Cross-file references engramx's AST can't resolve precisely — kills the grep-then-read loopcp docs/plugins/examples/serena-plugin.mjs ~/.engram/plugins/
GitHub MCP (issues, PRs, commits)Recent PR discussion & issue history for the file being editedengram plugin install github
Sentry MCP (production errors)"What broke in prod for this file" — cuts the open-dashboard → paste-trace loopengram plugin install sentry
Supabase / Neon (schema, RLS)Database schema context when editing queries / migrations / ORM modelsengram plugin install supabase
Context7 (library docs)Always-current API surface for your actual importsshipped as a built-in
Anthropic Auto-MemoryClaude Code's own consolidated project memoryshipped — auto-detected when ~/.claude/projects/…/memory/MEMORY.md exists

Writing a plugin is ~10 lines — see docs/plugins/README.md for the full spec + examples.

What It Does

engram sits between your AI agent and the filesystem. When the agent reads a file, engram checks its knowledge graph. If the file is covered with sufficient confidence, it blocks the read and injects a compact context packet instead. The packet is assembled from up to 9 built-in providers plus any plugins you've added, all pre-cached at session start.

The 9 built-in providers (v3.0):

ProviderSourceConfidenceLatency
engram:astTree-sitter parse (10 languages)1.0<50ms
engram:structureRegex heuristics (fallback)0.85<50ms
engram:mistakesPast failure nodes (bi-temporal — stale mistakes filtered out)<10ms
anthropic:memoryClaude Code's auto-managed MEMORY.md index (v3.0)0.85<10ms
engram:gitCo-change patterns, churn, authorship<100ms
mempalaceDecisions, learnings, project context<5ms cached
context7Library API docs for detected imports<5ms cached
obsidianProject notes, architecture docs<5ms cached
engram:lspLive diagnostics captured as mistake nodeson-event

External providers cache into SQLite at SessionStart. Per-read resolution is a cache lookup, not a live call. If a provider is unavailable it is skipped silently — you always get at least the structural summary. Plus: any MCP server becomes a provider via a 10-line plugin file — see Plugins multiply the savings above.

The 9 hook handlers:

HookWhat it does
PreToolUse:ReadBlocks the read if file is covered. Delivers structural summary as the block reason.
PreToolUse:EditPasses through. Injects known mistakes as landmine warnings alongside the edit.
PreToolUse:WriteSame as Edit — advisory injection only, never blocks writes.
PreToolUse:BashCatches cat | head | tail | less | more <single-file> and delegates to the Read handler.
SessionStartInjects a compact project brief (god nodes, graph stats, top landmines, git branch). Bundles MemPalace context in parallel.
UserPromptSubmitExtracts keywords from the prompt, runs a budget-capped pre-query, injects results before the agent responds.
PostToolUseObserver only. Writes to .engram/hook-log.jsonl for hook-stats.
PreCompactRe-injects god nodes and active landmines right before Claude compresses the conversation. Survives compaction.
CwdChangedAuto-switches project context when you navigate to a different repo mid-session.

Ten safety invariants enforced at runtime:

  • Any handler error → passthrough (Claude Code is never blocked)
  • 2-second per-handler timeout
  • Kill switch (.engram/hook-disabled) respected by every handler
  • Atomic settings.json writes with timestamped backups
  • Never intercept outside the project root
  • Never intercept binary files or secrets (.env, .pem, .key, id_rsa, etc.)
  • Never log user prompt content (privacy invariant, asserted in tests)
  • Never inject more than 8,000 chars per hook response
  • Stale graph detection — file mtime newer than graph mtime → passthrough
  • Partial-read bypass — explicit offset or limit on Read → passthrough

Quickstart

One command, zero friction:

cd ~/my-project
engram setup                     # init + install-hook + adapter detect + doctor

engram setup runs the whole first-run flow interactively (or pass -y for defaults, --dry-run to preview). It is idempotent — safe to re-run, and skips any step already done.

Prefer the individual commands?

cd ~/my-project
engram init                      # scan codebase → .engram/graph.db (~40ms, 0 tokens)
engram install-hook              # wire the Sentinel into Claude Code
engram ui                        # open the web dashboard in your browser

Diagnostics + self-update:

engram doctor                    # component health + remediation hints (0=ok, 1=warn, 2=fail)
engram update                    # check + upgrade via detected pkg manager (no telemetry)
engram update --check            # check only, dry-probe the registry

Set ENGRAM_NO_UPDATE_CHECK=1 to disable the passive "newer version available" hint on every CLI invocation. $CI does the same automatically.

Open a Claude Code session. When the agent reads a well-covered file you will see a system-reminder with the structural summary instead of file contents. After the session:

engram hook-stats                # what was intercepted, tokens saved (CLI)
engram ui                        # same data, richer view, real-time updates
engram hook-preview src/auth.ts  # dry-run: see what the hook would inject for one file

Full recommended setup (one-time per project):

npm install -g engramx
cd ~/my-project
engram init --with-skills        # also index ~/.claude/skills/ into the graph
engram install-hook              # wire Sentinel into Claude Code
engram hooks install             # auto-rebuild graph on every git commit

Experience tiers — each works standalone:

TierWhat you runWhat you get
Graph onlyengram initCLI queries, MCP server, engram gen for CLAUDE.md
+ Sentinelengram install-hookAutomatic Read interception, Edit warnings, session briefs, HUD
+ Context SpineConfigure providers.jsonRich packets from 9 built-ins + any MCP plugin per read
+ Skills indexengram init --with-skillsGraph includes your ~/.claude/skills/
+ Git hooksengram hooks installGraph rebuilds on every commit, stays current
+ HTTP serverengram server --httpREST API on port 7337 for external tooling

IDE Integrations

IDEIntegrationSetup
Claude CodeHook-based interception (native, automatic)engram install-hook
CursorMDC snapshot + native MCPengram gen-mdc · docs/integrations/cursor-mcp.md
Continue.dev@engram context providerdocs/integrations/continue.md
ZedContext server (/engram)engram context-server
AiderContext file generationengram gen-aider
Windsurf (Codeium).windsurfrules snapshot + MCPengram gen-windsurfrules
NeovimMCP via codecompanion / avantedocs/integrations/neovim.md
EmacsMCP via gptel-mcpdocs/integrations/emacs.md

Per-IDE setup guides are in docs/integrations/.

How It Compares

engramContinue @RepoMapCursor .cursorrulesAider repo-map@199-bio/engram
Interception modelHook-based, automatic on every ReadFetched at @-mention timeStatic file, manualPer-session mapMCP server, called explicitly
Cache strategySQLite at SessionStart, <5ms per readNo cache — live fetchNo cachePer-session onlyNo cache
Persistent memoryDecisions, mistakes, patterns across sessionsNoManual text fileNoNo
Multiple providers8 (AST, git, mistakes, MemPalace, Context7, Obsidian, LSP)Repo structure onlyNoRepo structure onlyGraph query only
Mistake trackingLSP diagnostics → mistake nodes, ⚠️ on EditNoNoNoNo
Survives compactionYes (PreCompact hook)NoYes (static file)NoNo
LLM cost$0$0$0$0$0
Native depsZeroNoNoNoNo

Install + Configuration

npm install -g engramx

providers.json (optional — auto-detection works for most setups):

{
  "providers": {
    "mempalace": { "enabled": true },
    "context7": { "enabled": true },
    "obsidian": { "enabled": true, "vault": "~/vault" },
    "lsp": { "enabled": true }
  }
}

Hook scope options:

engram install-hook                  # default: .claude/settings.local.json (gitignored)
engram install-hook --scope project  # .claude/settings.json (committed)
engram install-hook --scope user     # ~/.claude/settings.json (global)
engram install-hook --dry-run        # preview changes without writing
engram install-hook --auto-reindex   # also keep the graph fresh after every Edit/Write/MultiEdit (#8)

Kill switch (if anything goes wrong):

engram hook-disable    # touches .engram/hook-disabled — all handlers pass through
engram hook-enable     # removes the kill switch
engram uninstall-hook  # surgical removal, preserves other hooks in settings.json

CLI Reference

Core:

engram init [path]               # scan codebase, build knowledge graph
engram init --with-skills        # also index ~/.claude/skills/
engram query "how does auth"     # query the graph (BFS, token-budgeted)
engram query "auth" --dfs        # DFS traversal
engram gods                      # most connected entities
engram stats                     # node/edge counts, confidence breakdown
engram bench                     # token reduction benchmark (10 tasks)
engram stress-test               # full stress test suite
engram path "auth" "database"    # shortest path between concepts
engram learn "chose JWT..."      # add a decision or pattern to the graph
engram mistakes                  # list known landmines

Code generation:

engram gen                       # auto-detect target (CLAUDE.md / .cursorrules / AGENTS.md)
engram gen --target claude       # write to CLAUDE.md
engram gen --target cursor       # write to .cursorrules
engram gen --target agents       # write to AGENTS.md
engram gen --task bug-fix        # task-aware view (general | bug-fix | feature | refactor)
engram gen --memory-md           # write structural facts to Claude's native MEMORY.md
engram gen-mdc                   # generate Cursor MDC rules
engram gen-aider                 # generate Aider context file
engram gen-ccs                   # generate CCS-compatible output

Sentinel:

engram intercept                 # hook entry point (called by Claude Code, reads stdin)
engram install-hook              # install hooks into Claude Code settings
engram uninstall-hook            # remove engram entries
engram hook-stats                # summarize .engram/hook-log.jsonl
engram hook-stats --json         # machine-readable output
engram hook-preview <file>       # dry-run Read handler for a specific file
engram hook-disable              # kill switch
engram hook-enable               # remove kill switch

Infrastructure:

engram watch [path]              # live file watcher — incremental re-index on save
engram reindex <file>            # re-index one file (editor/hook/CI primitive, issue #8)
engram reindex-hook              # PostToolUse hook entry point (reads JSON from stdin, always exits 0)
engram dashboard [path]          # live terminal dashboard
engram hud-label [path]          # JSON label for Claude HUD --extra-cmd integration
engram hooks install             # install post-commit + post-checkout git hooks
engram hooks status              # check git hook installation
engram hooks uninstall           # remove git hooks
engram server --http             # start HTTP REST server on port 7337
engram context-server            # start Zed context server
engram tune --dry-run            # auto-tune provider weights (preview mode)
engram db status                 # schema version, migration state
engram init --from-ccs           # import from CCS-format context file

Claude HUD integration:

Add --extra-cmd="engram hud-label" to your statusLine command to see live savings:

engram 48.5K saved 75%

HTTP API

Start the server with engram server --http (default port 7337).

MethodEndpointDescription
GET/healthServer health + graph stats
POST/queryQuery the knowledge graph
GET/godsMost connected entities
GET/statsNode/edge counts, confidence breakdown
POST/pathShortest path between two concepts
GET/mistakesKnown failure nodes
POST/learnAdd a decision or pattern
POST/initTrigger a graph rebuild
GET/hook-statsHook interception log summary

All responses are JSON. The server is local-only by default — bind address is 127.0.0.1.

MCP Server

{
  "mcpServers": {
    "engram": {
      "command": "npx",
      "args": ["-y", "engramx", "serve", "/path/to/your/project"]
    }
  }
}

MCP Tools (6):

  • query_graph — search the knowledge graph with natural language
  • god_nodes — core abstractions (most connected entities)
  • graph_stats — node/edge counts, confidence breakdown
  • shortest_path — trace connections between two concepts
  • benchmark — token reduction measurement
  • list_mistakes — known failure modes from past sessions

Shell wrapper (for Bash-based agents):

cp scripts/mcp-engram ~/bin/mcp-engram && chmod +x ~/bin/mcp-engram
mcp-engram query "how does auth work" -p ~/myrepo

ECP Spec

engram v1.0 ships the first draft of the Engram Context Protocol (ECP v0.1) — an open specification for how AI coding tools should package and exchange structured context packets.

The spec defines the wire format, provider negotiation, budget constraints, and confidence scoring used by engram internally. Any tool can implement the spec to produce or consume engram-compatible context packets.

License: CC-BY 4.0
Spec: docs/specs/ecp-v0.1.md

Programmatic API

import { init, query, godNodes, stats } from "engramx";

const result = await init("./my-project");
console.log(`${result.nodes} nodes, ${result.edges} edges`);

const answer = await query("./my-project", "how does auth work");
console.log(answer.text);

const gods = await godNodes("./my-project");
for (const g of gods) {
  console.log(`${g.label}${g.degree} connections`);
}

Architecture

src/
├── cli.ts                 CLI entry point
├── core.ts                API surface (init, query, stats, learn)
├── serve.ts               MCP server (6 tools, JSON-RPC stdio)
├── server.ts              HTTP REST server (port 7337)
├── hooks.ts               Git hook install/uninstall
├── autogen.ts             CLAUDE.md / .cursorrules / MDC generation
├── graph/
│   ├── schema.ts          Types: nodes, edges, confidence, schema versioning
│   ├── store.ts           SQLite persistence (sql.js WASM, zero native deps)
│   └── query.ts           BFS/DFS traversal, shortest path
├── miners/
│   ├── ast-miner.ts       Tree-sitter AST extraction (10 languages, confidence 1.0)
│   ├── git-miner.ts       Change patterns from git history
│   ├── session-miner.ts   Decisions/patterns from AI session docs
│   └── skills-miner.ts    ~/.claude/skills/ indexer (opt-in)
├── providers/
│   ├── context-spine.ts   Provider assembly + budget management
│   ├── mempalace.ts       MemPalace integration
│   ├── context7.ts        Context7 library docs
│   ├── obsidian.ts        Obsidian vault
│   └── lsp.ts             LSP diagnostic capture
└── intelligence/
    └── token-tracker.ts   Cumulative token savings measurement

Supported languages (AST): TypeScript, JavaScript, Python, Go, Rust, Java, C, C++, Ruby, PHP.

Privacy

Everything runs locally. No data leaves your machine. No telemetry. No cloud dependency. The only network call is npm install. Prompt content is never logged (asserted in 579 tests).

Contributing

Issues and PRs welcome at github.com/NickCirv/engram.

Run engram init on a real codebase and share what it got right and wrong. The benchmark suite (engram bench) is the fastest way to see the difference on your own code.

License

Apache 2.0

Keywords

structural-code-graph

FAQs

Package last updated on 02 May 2026

Related posts