Borrowing it
Nothing to install: this file belongs to 20alexl/claude-engram. Take a copy, put it at the same path in your own repository, and replace the rules that are about this project with yours.
curl -O https://raw.githubusercontent.com/20alexl/claude-engram/main/CLAUDE.mdgit clone --depth 1 https://github.com/20alexl/claude-engramWrote this? Show the measurements
A badge with what this costs and how it scanned, read live from this page, so it follows the numbers instead of freezing them. Markdown for a README, HTML for a documentation site or a project page.
[](https://agentmods.dev/instructions/20alexl/claude-engram/claude-md)<a href="https://agentmods.dev/instructions/20alexl/claude-engram/claude-md"><img src="https://agentmods.dev/badge/instructions/20alexl/claude-engram/claude-md/github.svg" alt="Measured on agentmods" height="20"></a>Or the 80×15 button, for a site that already has a row of RSS and ATOM ones. Only the verdict fits; the numbers stay here.
<a href="https://agentmods.dev/instructions/20alexl/claude-engram/claude-md"><img src="https://agentmods.dev/badge/instructions/20alexl/claude-engram/claude-md.svg" alt="Reviewed on agentmods" width="80" height="20"></a>What it costs to keep this loaded
Counted locally with the o200k_base tokenizer, which is exact for GPT models; Claude uses its own tokenizer and its counts differ. Treat this as one consistent yardstick across the catalogue rather than a bill. Prices are per million input tokens.
| Model | Per session | Once invoked |
|---|---|---|
| Fable 5.1 | $0.09931 | $0.09931 |
| Opus 5.5 | $0.03972 | $0.03972 |
| Sonnet 5.5 | $0.01986 | $0.01986 |
| Haiku 4.5 | $0.00993 | $0.00993 |
Grade B, and why
claude-engram CLAUDE.md scanned grade B with 1 finding against 26 rules in 11 categories — prompt injection, anti-refusal, data exfiltration, privilege escalation, supply chain, agent snooping, system-prompt leakage, SSRF and excessive agency — measured 1mo ago.
A static scan of the body, not an audit. Every finding is printed with the line that produced it so you can judge whether it matters here. A mod is markdown that instructs an agent; that is exactly why what it instructs is worth reading.
Reads agent configuration directoriesmediumAgent snooping
.claude/, .codex/, .gemini/ hold keys, settings and other credentials a mod has no legitimate need for.
- Hook installation merges into existing `~/.claude/settings.json` without destroying other hooks. How it starts
The opening of the file, as written. The whole thing — 279 lines — stays where its author put it; the contents beside it link to each section on GitHub.
Claude Engram - Persistent Memory for Claude Code
How It Works
Claude Engram intercepts your tool calls via Claude Code hooks and automatically tracks what you do. Most features require zero invocations - they fire through hooks on every edit, bash command, error, and session event.
You also have MCP tools for things that need semantic judgment (saving discoveries, declaring rules, managing archives).
What's Fully Automatic
These happen via hooks. You don't call anything:
| What | When It Fires | What You See |
|---|---|---|
| Session restore | SessionStart hook | Rules, mistakes, checkpoint, handoff. Every hook scopes by session_project(project_dir, state) (the transcript's Edit/Write calls via autorun.recent_edit_files, then the hook state, then the cwd mapped to its repo; cached against the transcript size), never by the cwd. The recurring-errors block (_recurring_lines) prints at start on resume/compact and is deferred to the first pre-edit on a fresh start (patterns_deferred); engram's own .claude_engram failures never listed as a project's |
| Edit tracking | PostToolUse Edit/Write | Nothing printed; the count feeds the loop warning before the next edit (files under node_modules/, venvs, or a non_project_dirs name from ~/.claude_engram/config.json never warn) |
| Loop warnings | PreToolUse Edit/Write | Warning when same file edited 3+ times (state lives in per-session hook state, so concurrent sessions don't cross-contaminate) |
| Scored memory injection | PreToolUse Edit/Write | Top 3 file-relevant memories; a rule rides along only when it names the file; an entry older than 30 days (STALE_CONTEXT_DAYS) only with a full-path match; ERRORS.md / LEARNINGS.md / plan.md are generic basenames |
| Test tracking | PostToolUse Bash | "PASS/FAIL Test tracked" on the first run and on each flip only (the status is one per session and survives every Stop); output markers are trusted when the command names a test runner (_is_test_invocation) or when no segment of the chain merely reads (_segment_kind: run / read / noise, wrappers peeled; cat log; bash count.sh is never a test run), and the output must read as a verdict (_output_has_test_markers; a bare "N errors" is not one). A failure's mistake attaches to the traceback's files, else the session's edited code files |
| Error auto-logging | PostToolUseFailure (all tools) | Mistakes auto-saved from any failed tool. The miner's error→fix extractor skips a message that is a source line or a grep line ("141:def ...") and one under four words unless it is a single quoted token |
| Decision capture | UserPromptSubmit | "let's use X" judged by ONE function, hooks/intent.capture_decision: semantic + regex scoring, the 0.6 threshold, then the shape gate (mining/decision_gate.py): one declarative sentence of four or more words (a line break inside is a paste unless the lines are a list under one lead), no question, not an acknowledgement, count, table row, commit report or hash-led line, no markup (tags with attributes included), not a request, not a one-off instruction (step numbers, an ordinal pick, "yet", "go ahead with"), not a status assessment ("should be fine now"), not an approval verdict with no other deciding word ("the plan is approved"), not a question typed without its mark ("would it be better to split it"), no email or key-like token, with a deciding word; hedges (including "probably", "I guess", "up to you", a trailing "or not"), history and third parties excluded; an edit verb only with a transition or a scope; a preference needs four words. The miner mines only typed prompts (extractors._typed_prompt: under 500 chars, one paragraph, no relayed teammate/agent message, no markup), stores the sentence the pattern matched, sends every correction it finds through the same function (server_only=True) before storing a USER PREFERENCE, applies the gate to its structural decisions, and stores a bare sentence once across the hook's "(from user)" copy, its own decision and preference copies, the destination store and its ancestors; migrations 0.8.46–0.8.48:prune_junk_decisions*, 0.8.49:rejudge_preferences (heavy) and 0.8.56:rejudge_mined_decisions archived what was stored before. Tuned and pinned on the neutral 220-prompt corpus by tests/bench_correction_gate.py (decision 1.00 / 0.93, correction 0.97 / 0.80, shared capture 1.00 / 0.95 with or without the daemon), never on a session's own sentences. The regex tier's typo corrector only fixes a swap or a dropped/doubled letter on words of five letters or more, and the stored text is the typed words, never the corrected working text |
| Checkpoint on compact | PreCompact | Task state saved before context compaction |
| Context re-injection | SessionStart(compact, resume) | Rules + mistakes + THIS SESSION's newest deliberate checkpoint (the ring record's session_id), shown whole (task, current step, every completed and pending step, files, warnings, context notes, handoff note, goal, movement since), plus the compaction rhythm (where the next heads-up / checkpoint / compaction sit). The project's newest deliberate checkpoint is the fallback for a session that has banked nothing yet. A checkpoint this session saved on a branch the user then rewound past (transcript_chain: the live chain is the walk from the transcript's last record up its parent links; a rewind fires no hook and leaves only a fork) is skipped and named. context(checkpoint_restore) with no arguments picks the same way. PostCompact does bookkeeping only: Claude Code's hook output schema has no PostCompact channel |
| Context-pressure nudges | UserPromptSubmit / PreToolUse / PostToolUse | <engram-context> heads-up ~10% of the window before the compaction point, CHECKPOINT NOW 20K above the auto-compaction trigger (the setting minus a 32K output reserve, measured; 10K on a 200K window), once each per cycle; fallback after 60 turns with neither a checkpoint nor a completed step. Needs a statusline that records the mirror; announced at session start when there is none |
| Default pack | SessionStart (fresh start only) | Scaffold pieces created where missing (headered CLAUDE.md, .learnings/*.md, session-logs/; per-person layouts left alone) and ten working rules seeded once, skipping any the project or an ancestor already has. .engram/config.json: "structure": false, "default_rules": false |
| Rotation | SessionEnd plans, SessionStart announces; session_mine(rotate) |
Dailies > 30 d → session-logs/archive/<month>/ + digest; dated learnings > 90 d (or over 500 lines) → .learnings/archive/; nothing deleted; note under the title. "rotation": "auto" applies at session end |
| Run report | SessionEnd (auto, substantial sessions) or session_mine(run_report) |
<project>/.engram/runs/<date>-<session>.md + .json: commits, turns, files with edit counts, tests, errors (grouped, known-before), compactions with sizes and what each restored, checkpoints deliberate vs auto, goal text, and an explicit not-measured list. Hook-captured facts only |
| Milestone nudges | Stop (read) → next injection point (deliver); PostToolUse ExitPlanMode / TaskUpdate | The model's own "step done" in its final message, with no deliberate checkpoint that turn, gets one nudge quoting the claim, only when the turn also had an effect (edit, commit, delegated agent; _turn_corroborates_a_close), never for a list bullet or a table row, a sentence still in motion (waiting, running, queued, a percentage through), reported speech, a rule or definition, a number beside "passed"/"closed", or a participle used as an adjective, at most one prose nudge an hour (MILESTONE_NUDGE_GAP_SECS). A turn that banked state with memory(remember) and no checkpoint_save (stall.note_tool records name:op per turn) gets the claim_remember variant: a remember is a fact, the restore reads checkpoints only, both together are fine. A plan approval asks for the plan to be banked with its steps pending. Never written for you, never from commits |
| Session handoff on stop | Stop | Saves last_assistant_message + files for next session |
| Session summary on end | SessionEnd | Files edited, memory counts |
| Stall detection | PostToolBatch (account) + PostToolUse Edit/Bash fallback; Stop (judge); next injection point (deliver) | <engram-stall> after 3 consecutive turns with tool use and no effect (no file change, no test-status flip, no commit, no delegation); strike 2 re-injects the checkpoint + rules and forces a bearings check; strike 3 is the cap (the halt in autonomy mode). Turns with no tools or parked on Monitor/ScheduleWakeup/cron are neutral. Strikes decay: 5 good turns remove one. Events with turn numbers in the run report |
| Usage budget | same injection points as context pressure; StopFailure (record) | Subscription 5-hour / 7-day windows mirrored from the statusline (rate_limits); at 90% / 95% one <engram-context> per window with the reset time: checkpoint and park on a wakeup until the reset. stop_failure_json records every API failure (error_type, message, the window's reset) into run.failures for the run report; a limit hit is never retried by Claude Code and no Stop hook sees it |
| Autonomy halt | Stop (arm at the strike cap when CLAUDE_ENGRAM_AUTONOMY=1); PreToolUse "" (pre_tool_json, deny) |
Every tool denied with a reason naming python -m claude_engram.hooks.stall release <session>; PushNotification, ToolSearch, SendMessage and context(checkpoint_save) stay open; a call carrying agent_id (a subagent, which shares the session id) is never denied; <engram-halt> once at the next injection point; turns after the halt are neutral. Engram never blocks Stop: with no tool use, /goal's stall rule closes the loop |
| Alerts | Stop (halt), StopFailure, Notification (notification_json: needs input / permission prompt / idle), the launcher |
One line under 200 chars through the owner's alert_command ({message} or stdin); recorded in state["alerts"] and the run report whether sent or not. PushNotification is model-only (verified), so the command is the headless channel |
| The /goal bracket | Stop, UserPromptSubmit, SessionEnd (observe); session_mine(run_status) |
hooks/autorun.py: scan_goal() reads the transcript tail for the verified records (sentinel on set, verdicts, /goal clear command); observe() keeps run.auto in step: running from the sentinel, met/failed/cleared from the transcript, halted from the strike cap, capped from goal_turn_cap (150; arms the same halt, since engram cannot end a /goal loop). A met or failed record ends the goal whatever its sentinel flag (2.1.268 writes the met record with both), and a running record whose goal no longer appears in the transcript tail ends as cleared before it can count toward the cap. Autonomy mode is on while running (autonomy_on(state)). A start writes the manifest and stages one directive (park hint, checkpoint rhythm, deny note); an end = one alert + the run report's "Goal run" section. Engram never blocks a Stop of its own; a goal is set only by typing /goal |
| Launcher (cron only) | python -m claude_engram.run --headless |
Manifest, --session-id, CLAUDE_CODE_AUTO_COMPACT_WINDOW at 75% of the model's window, --max-turns, park hint, claude -p --output-format json; a rate_limit exit with a known reset sleeps and --resumes the same session (max 3); run report + closing alert |
| Rules compliance | PreToolUse Bash/PowerShell (match + inject); PostToolBatch (other tools) | A rule with a hand-written detector (tools / command regex / path globs / input regex) has every matching call recorded with turn, input excerpt and verdict (unattended = bypass/auto/dontAsk, prompted = a permission prompt stood between); <engram-rule> injected before a matching shell command runs. Rules without one are advisory, said per rule; detector health shown. Pack rules ship theirs; "compliance": false opts out |
| Search spiral detection | PostToolUse Bash | Warns after 3+ failed search commands |
| Memory archiving | cleanup / session_start | Old inactive memories archived, not deleted |
| Sub-project scoping | PreToolUse / PostToolUse | Memories scoped to the right sub-project |
| Data migrations | SessionStart (upgrade) | Cheap inline check; full migration in background |
| Pre-edit import check | PreToolUse Edit/Write | <engram-precheck> when a proposed import won't resolve against the code index (closest-name suggestion) |
| Blast-radius alert | PreToolUse Edit/Write | <engram-blast-radius> listing modules that import the file being edited |
| Outcome feedback loop | PreToolUse + PostToolUse Bash | Injection kinds correlated with test pass/fail; surfaced via session_mine(reflect) |
| Schema canary | SessionStart | Warning when Claude Code's log format stops being recognized (mining would otherwise degrade silently) |
| Read context | PreToolUse Read | <engram-read-context>: code-index orientation + the file's most relevant memories, once per file per session |
| Error deja-vu | PostToolUseFailure | "Deja vu: TypeError hit in 3 past session(s) - fix: ..." when a fresh failure matches a mined recurring error or stored mistake (identifier-guarded, so an unrelated class never inherits someone else's fix) |
| Known-good test commands | SessionStart | The project's top tracked test commands that currently pass — verification starts from what worked, not a guess |
| Mistake hygiene | Background miner | Stale auto-captured one-off mistakes (3+ weeks, never recurred, away from current work) move to the archive — banners keep their signal; restorable via memory(restore) |
| Live mining tick | Stop (per turn, debounced) | Session index, extractions, search embeddings, and the active code indexes refresh DURING the session — session_mine(search) sees this session's earlier work, not just past sessions. Interval CLAUDE_ENGRAM_LIVE_MINE (default 300s) |
| Curated-lessons bridge | Background miner (opt-in) | Dated entries in lesson files sync as protected lesson memories with code-index-joined triggers — a lesson mentioning a module surfaces when editing files that import it. The file stays the source of truth (edits update, removals retire). Off unless lessons_globs is set in ~/.claude_engram/config.json (e.g. ["docs/lessons/*.md"]) — no default path |
| Project-scoped patterns | SessionStart | Recurring errors/struggles are attributed to sub-projects and filtered by what the last session touched — a vzip session no longer sees CORTEX errors. A recurring error is the same CONCRETE error (directories, hashes and numbers templated; identifiers and file names kept) seen in two or more sessions, shown with its latest sighting's example and fix. Errors unseen for 30 days drop out |
What this file has done since we first saw it
Hashed on every crawl. A supply-chain change to an agent config is a question of when, not whether, so the history is kept rather than the latest state alone.
- 1mo ago Changed · +3 lines · +1,173 tokens per session 5679c10efc32
- 1mo ago Changed · +181 tokens per session 04e0e1a0a98d
- 1mo ago Changed · +25 lines · +3,875 tokens per session b3cf5cb7ed58
- 1mo ago First seen · 251 lines · 4,702 tokens per session scan B 3f0d27e4734b
claude-engram CLAUDE.md is an instructions file published in the GitHub repository 20alexl/claude-engram (16 stars, last pushed 1mo ago), licensed MIT. It adds 9,931 tokens to every session, about $0.0397 per session on Opus 5.5. A static security scan graded it B with 1 finding (reads agent configuration directories). No closer match exists in the catalogue, so it is treated as the original; first seen 2026-08-30.
Other instructions, from other repositories
repobrain copilot-instructions.md
Copilot instructions for study8677/repobrain, covering github copilot bootstrap instructions and hard rule — query the repobrain hub first.
vscode buildNext.instructions.md
Working notes and architecture documentation for the new esbuild-based build system in build/next. Use when making changes to the new build pipeline (transpile/bundle commands, NLS plugin, source-map handling, resource copying, or self-hosting watch tasks).
next.js AGENTS.md
AGENTS.md instructions for vercel/next.js, covering next.js development guide, codebase structure, monorepo overview, core package: packages/next and other important packages.
vscode oss-third-party-notices.instructions.md
Instructions for microsoft/vscode, covering vs code oss third-party-notices pipeline, architecture, pipeline flow in ci, cache eligibility and rollout and applying the notice (cutover).
langchain AGENTS.md
AGENTS.md instructions for langchain-ai/langchain, covering global development guidelines for the langchain monorepo, corridor security analysis, project architecture and context, monorepo structure and development tools & commands.
vscode copilot-instructions.md
Copilot instructions for microsoft/vscode, covering vs code copilot instructions, project overview, root folders, core architecture (src/ folder) and built-in extensions (extensions/ folder).