convez.ai
MCP Server
hugfeature

engram

hugfeature/engram

Ver no GitHub
InicialPluginScore · de 0 a 100

Runtime continuity and interruption recovery for AI coding agents — auto-checkpoint on SIGTERM, semantic recall with decay, structured task/handoff/failure tracking. MCP server. pip install mcp-engram

Instalação

$npx convez-ai hugfeature/engram

1 comando no terminal: detecta o formato do repositório (marketplace ou plugin avulso) e instala via Claude Code. Requer Node 18+ e o Claude Code instalado.

Métricas

Estrelas
1
Forks
0
Acompanhando
0
Saúde
42%
Último commit
há 5 meses
Versão
V0.19.0
Issues abertas
0
Contribuidores
1

README

A tradução para o português deste README ainda está na fila.

Engram

Runtime continuity and interruption recovery for AI coding agents

PyPI License: MIT Python 3.11+ Tests engram MCP server

Engram gives Claude Code, Cursor, and OpenHands resumable execution — recover agent working state after context collapse, interruption, or session termination. Agents continue from where they stopped, not from zero.

中文文档 · PyPI · Glama


The Problem

Every AI agent session is an island:

SituationWithout EngramWith Engram
Context window fullAgent loses history, starts guessingCheckpoint restored, constraints preserved
Process killed / server restartAll working state lostAuto-checkpoint on SIGTERM, resume on next recall
Switch agents (Claude → Cursor)Start from scratchStructured handoff with task state
Same bug hits twiceNo memory of previous fixFailure record surfaces automatically
3-session taskNo one knows overall progressTask state + continuity metrics available

Why Engram

Most memory systems focus on conversation recall.

Engram focuses on runtime continuity:

  • What the agent was doing — task state, working set, modified files
  • Where execution stopped — checkpoint with goal, progress, blockers
  • How to resume safely — negative memory (must_not_redo) + invariants (must_preserve)

Quick Start

pip install mcp-engram
engram-setup          # downloads embedding model + initializes DB (~500MB, one-time)

Add to your Claude Code / Cursor config:

{
  "mcpServers": {
    "engram": {
      "command": "engram",
      "env": { "HF_ENDPOINT": "https://huggingface.co" }
    }
  }
}

That's it. Engram runs fully locally — no cloud, no API keys, no telemetry.


Interruption Recovery

When a session ends unexpectedly — context overflow, process kill, IDE crash — Engram automatically captures a structured working state on shutdown:

SIGTERM / context collapse
        ↓
Engram auto-checkpoint
  goal · completed · in_progress · blocked
  modified_files (git diff) · last_tool_called · last_failure
        ↓
Agent restarts → recall_memory()
        ↓
interrupt_recovery injected into response
  → "Call restore_checkpoint(task_id=X) to resume"

No manual intervention. The next agent session picks up the hint automatically on first recall_memory call.

Generate a CLAUDE.md snippet from current state:

engram-prompt

Output (paste into your project's CLAUDE.md):

## Engram Runtime State

**Active task:** 10 — Fix the auth bug in login.py
**Checkpoint:** v3 (confidence: 0.71)

**Already completed (do not redo):**

- Reproduced the bug in test_auth.py

**In progress:**

- Tracing the JWT validation path

**Files modified in last session:**

- `src/auth/validator.py`
- `tests/test_auth.py`

## Engram Session Rules

- Session start: recall_memory(query) — interrupt state auto-pinned
- Resume task: restore_checkpoint(task_id=10)
- Context filling up: report_interruption(reason="overflow") then session_handoff(...)

How It Works

Engram is a local MCP server providing 18 tools across three areas:

Memory

Hybrid semantic search (BM25 + vector + graph) with Ebbinghaus decay so important memories stay longer.

ToolWhat it does
store_memorySave a fact, decision, or lesson (auto-deduplicates)
recall_memoryHybrid search — call at the start of every task
update_memoryCorrect a specific memory by ID
consolidate_memoryMerge similar memories, prune weak ones
memory_statsHealth overview: counts, strength, last maintenance
get_runtime_healthRead-only backend health report

Task Tracking

Tasks are first-class entities that survive session boundaries.

ToolWhat it does
create_taskStart a tracked multi-session task
get_taskFull task context + latest checkpoint
update_taskUpdate status, goal, or metadata
list_tasksSee all tasks, filter by status
track_progressSnapshot feature/task progress
track_failureRecord structured failure with root cause + fix

Continuity

Checkpoint-based recovery so a new agent can pick up exactly where the previous one left off.

ToolWhat it does
session_handoffEnd-of-session structured summary
session_outcomeMark session success/failure (adjusts memory weights)
restore_checkpointConstrained continuation package for takeover
list_checkpointsCheckpoint history for a task
report_interruptionSignal overflow/rate-limit before exit
evaluate_continuityScore recovery quality across checkpoint versions

Checkpoint Recovery Flow

Agent A (Claude Code)                  Agent B (Cursor)
  │                                        │
  ├─ create_task(name, goal)               │
  ├─ track_progress / track_failure        │
  ├─ ⚡ Interrupted (SIGTERM / overflow)   │
  ├─ [auto] interrupt checkpoint saved     │
  │        │                               │
  │   ┌────▼────────────────┐              │
  │   │  Engram Checkpoint  │              │
  │   │  goal               │              │
  │   │  completed          │              │
  │   │  must_not_redo  ────┼──────────▶   │
  │   │  must_preserve      │             ├─ recall_memory() → interrupt_recovery pinned
  │   │  modified_files     │             ├─ restore_checkpoint(task_id)
  │   │  working_set        │             ├─ continue, not from zero
  │   └─────────────────────┘             └─ session_handoff → next agent...

Continuation package fields: goal · completed · in_progress · blocked · preferred_next · must_not_redo (negative memory) · must_preserve (invariants) · working_set · continuation_confidence


Recommended CLAUDE.md Instructions

Run engram-prompt to auto-generate this from your current state, or paste manually:

## Engram Session Rules

- Task start: create_task(name, goal) → save the task_id
- Session begin: recall_memory(query) — latest handoff + interrupt state auto-pinned
- Task takeover: restore_checkpoint(task_id, memory_restore_mode="SELECTIVE")
- Progress update: track_progress(feature, status, task_id=<id>)
- On error: track_failure(error, component, root_cause, task_id=<id>)
- Context filling up: report_interruption(reason="overflow") then session_handoff(...)
- Session end: session_handoff(summary, completed, in_progress, blocked, next_steps, task_id=<id>)

Architecture

Tier 1 — Event Journal (immutable, append-only)
  source of truth · snapshot compaction · incremental replay
  → ~/.engram/events/*.jsonl  (fsync, gzip-rotated)
  → periodic snapshots for fast startup

Tier 2 — Runtime State Store (operationally durable)
  tasks · checkpoints · executions · sessions
  → SQLite WAL  ~/.engram/*.state.sqlite
  → concurrent reads, fast restore, recovery-critical
  → controlled by ENGRAM_SQLITE_TIER2=1 (fallback: DuckDB)

Tier 3 — Runtime Intelligence Cache (rebuildable)
  memories · embeddings · FTS · vector index
  future: drift vectors · recovery metrics · tool stats · continuity history
  → DuckDB (can be dropped and rebuilt without data loss)
  → rebuild with: engram-setup rebuild-cache

Two Laws:

  1. The event log is the only durability primitive.
  2. If it cannot be replayed, it is not critical state.

DB corruption enters readonly degraded mode — never silently resets. Recover with engram-setup recover.


Benchmark

Evaluated on LoCoMo (Snap Research long-term conversation memory benchmark):

SystemOverall F1Hit@5LLMDeployment
MemMachine0.8487—GPT-4o-miniCloud
Memobase0.7578—GPT-4o-miniCloud
Zep0.7514—GPT-4o-miniCloud
Mem00.6688—GPT-4o-miniCloud
Engram0.438377.7%DeepSeek-V3.2Local

Zero cloud dependency. Four optimization rounds: F1 +50.3%, Hit@5 +26.2pp.

Engram also tracks runtime continuity metrics via evaluate_continuity: Goal Retention · Action Consistency · Failure Recall · Working Set Stability · Replanning Rate · Redundant Exploration.

Category Scores

CategoryCountF1Hit@5
Single-Hop1140.512176.3%
Temporal630.450195.2%
Multi-Hop430.318160.5%
Open-Domain130.132461.5%
Overall2330.438377.7%

Memory Algorithm

  • Ebbinghaus Decay: strength = importance × e^(−λ × days) × (1 + recall_count × 0.2)
    • failure: λ=0.35, ~11d half-life · strategy: λ=0.10, ~38d half-life
  • Deduplication: ≥0.85 → reinforce · 0.65–0.84 → merge/replace contradiction · <0.65 → new
  • Hybrid Retrieval: 0.3 × BM25 + 0.7 × (semantic × decay strength) + graph boost
  • Auto-maintenance: consolidate every 12h + prune (strength < 0.05) + FTS rebuild

Importance Guide

RangeUse for
0.9–1.0Core identity, permanent facts
0.7–0.8Architecture decisions, strong preferences
0.5Regular project facts
0.2–0.3Transient session context

Key Environment Variables

VariableDefaultDescription
HF_ENDPOINThttps://hf-mirror.comHuggingFace mirror (change to https://huggingface.co outside China)
ENGRAM_MODELall-mpnet-base-v2Embedding model
ENGRAM_DEDUP_THRESHOLD0.65Dedup similarity lower bound
ENGRAM_REINFORCE_THRESHOLD0.85Reinforce similarity threshold
ENGRAM_W_BM25 / ENGRAM_W_VECTOR0.30 / 0.70Retrieval weights
ENGRAM_PRUNE_THRESHOLD0.05Prune strength threshold
ENGRAM_SQLITE_TIER2(disabled)Set to 1 to enable SQLite WAL Runtime State Store (Tier 2)

Full variable list: src/engram/config.py


What Engram Is Not

  • ❌ Guaranteed identical LLM behavior after recovery (LLM non-determinism is a physical constraint)
  • ❌ Custom agent loop or prompt orchestration (handled by the MCP client)
  • ❌ Multi-agent coordination or shared team memory (single-user, local-first)

Requirements

  • macOS / Linux / WSL2
  • Python 3.11+
  • ~500MB disk for embedding model cache (one-time download)

Contributing

git clone https://github.com/hugfeature/engram.git
cd engram
pip install -e ".[dev]"
pytest tests/ -v

Issues and PRs welcome.

License

MIT · Maintained by @hugfeature


Engram restores an agent's working state, not just its memories.

Ver o original no GitHub

Bom para

Relacionados