Skip to main content
Glama
Agent Memory Engine
by ululazmi18

๐Ÿง  Agent Memory Engine

CI / Quality Gate Python Version MCP Protocol License: MIT Zero Cloud Leak Token Reduction

Deterministic High-Density Memory Engine & Autonomous Model Context Protocol (MCP) Server for AI Coding Agents.
Eliminate raw code scanning token waste through instant SQLite FTS5 search, exact line referencing (#Lstart-Lend), AST code mapping, and the 6-Pillar High-Density Knowledge Contract.

โšก 60-Second Quickstart โ€ข ๐Ÿ“Š Executive Pitch & ROI โ€ข ๐Ÿ—๏ธ Architecture โ€ข ๐Ÿ”Œ MCP Integrations โ€ข ๐Ÿ’ก Python API โ€ข โ“ FAQ โ€ข ๐Ÿ‡ฎ๐Ÿ‡ฉ Panduan Bahasa Indonesia


๐Ÿ“Š Executive Summary & ROI (Why CEOs & CTOs Care)

Every modern software engineering team is deploying AI coding agents (Google Antigravity, Claude Code, Cursor, Windsurf, Roo Code). However, context window bloat is crippling agent velocity and inflating LLM API budgets:

Traditional AI Coding Agents:
  Prompt -> Broad directory scan -> Read 20+ raw files -> 45,000+ tokens consumed ($0.45 - $1.50 / query)
  Latency: 35s - 60s | Accuracy: Vulnerable to hallucinated line numbers & lost-in-the-middle context

With Agent Memory Engine:
  Prompt -> Instant SQLite FTS5 + AST Card -> Exact #Lstart-Lend -> 850 tokens consumed ($0.008 / query)
  Latency: < 0.8s | Accuracy: 100% deterministic, zero hallucinations, zero cloud leaks

๐Ÿ† Empirical Benchmark Comparison

Metric

Traditional File Scraping (cat / view_file)

Cloud Vector RAG (Embeddings / Pinecone)

๐Ÿง  Agent Memory Engine (SQLite + AST)

Token Consumption

30,000 โ€“ 80,000 tokens / prompt

4,000 โ€“ 12,000 tokens / prompt

400 โ€“ 1,200 tokens / prompt (85-95% savings)

Retrieval Latency

15s โ€“ 45s (disk I/O + buffer limits)

1.5s โ€“ 4.0s (network + embedding calls)

< 0.01s (Local SQLite FTS5 index)

Line-Level Precision

Low (dumps full files or broad chunks)

Fuzzy (approximate similarity chunks)

100% Deterministic (#Lstart-Lend exact lines)

Hallucination Risk

High (context overflow / lost in middle)

Medium (semantic drift / false positive)

Zero (grounded directly in static AST)

Cloud Privacy

Depends on LLM provider

โš ๏ธ Code sent to external embedding APIs

๐Ÿ”’ 100% Local (Zero Cloud Leak Guarantee)

Infrastructure Cost

$0 (High LLM API token bills)

$50 - $500 / month (Vector DB + API)

$0 (Embedded SQLite WAL, pure standard lib)


Related MCP server: CodeGraph MCP

โšก 60-Second Quickstart

Step 1: Install Package

# Direct install via pip from GitHub
python -m pip install git+https://github.com/ululazmi18/agent-memory.git

# Or clone and install locally:
git clone https://github.com/ululazmi18/agent-memory.git
cd agent-memory
python -m pip install -e .

Step 2: One-Command Autonomous Setup

Run the autonomous installer inside your target project workspace:

python -m agent_memory --install

What --install automatically does:

  1. Dynamic Python Discovery: Detects the active Python binary (sys.executable) without hardcoded path assumptions.

  2. Registers MCP Server: Automatically provisions agent-memory into ~/.gemini/config/mcp_config.json with UTF-8 encoding.

  3. Deploys Agent Skill: Installs SKILL.md to ~/.gemini/config/skills/agent-memory/SKILL.md.

  4. Applies Gatekeeping Rule: Copies workflow-memory-first.md into your workspace .agents/rules/.

  5. Initializes AST Codebase: Builds .agents/memory/memory.db and maps every symbol, function, class, and SHA-256 hash in seconds.


๐Ÿ—๏ธ System Architecture

flowchart TD
    Client["๐Ÿค– AI Coding Agent<br/>(Antigravity / Claude Code / Cursor / Windsurf)"]
    
    subgraph Engine ["๐Ÿง  Agent Memory Engine Core"]
        MCP["Model Context Protocol (MCP 2.0+)"]
        CLI["Universal Multi-Query CLI"]
        Validator["Quality Gate Validator<br/>(6-Pillar High-Density Model)"]
        AST["Static AST Parser<br/>(Function, Class, Line #Lstart-Lend)"]
        CRMW["Cognitive Read-Merge-Write<br/>(Bullet Consolidation & Set Union)"]
    end
    
    subgraph Storage ["๐Ÿ”’ Embedded Local Storage"]
        DB[("SQLite WAL Database<br/>.agents/memory/memory.db")]
        FTS["FTS5 Full-Text Index<br/>(Unicode & Colloquial Slang)"]
        Seed["knowledge_seed.json<br/>(Version-Controlled Knowledge Backup)"]
    end

    Client <-->|MCP Protocol / JSON-RPC| MCP
    Client <-->|CLI Commands| CLI
    MCP --> Validator
    CLI --> Validator
    Validator --> AST
    AST --> DB
    Validator --> CRMW
    CRMW --> DB
    DB <--> FTS
    DB -.->|Export / Hydrate| Seed

Key Technical Pillars

  1. Deterministic Static AST Parser: Extracts signatures, docstrings, decorators, and internal call graphs without executing untrusted code.

  2. SQLite FTS5 Full-Text Search: Supports colloquial query terms, user slang, command habits, and typo-tolerant search in < 0.01s.

  3. The 6-Pillar High-Density Knowledge Contract: Prevents shallow AI memory notes:

    • Pillar 1: Physical Metadata & Size Profile.

    • Pillar 2: Upstream Dependencies & Downstream Artifacts.

    • Pillar 3: Exact Symbol Contracts (#Lstart-Lend), Call Graphs, and Data Schemas.

    • Pillar 4: Colloquial Human Aliases (Natural conversational search hooks).

    • Pillar 5: Hierarchical Progressive Depth (Level 0 Root to Level 4+ Binary Aggregations).

    • Pillar 6: Critical Guardrails, Gotchas & Strict Constraints.

  4. Cognitive Read-Merge-Write (Anti-Knowledge Regression): Smart bullet consolidation and set union preserve all previous engineering discoveries during live updates (merge_mode="merge").


๐Ÿ”Œ Universal MCP Integration

Agent Memory Engine complies with the Model Context Protocol (MCP 2.0+). It seamlessly integrates with any MCP-compatible coding tool.

1. Google Antigravity

The one-liner python -m agent_memory --install automatically registers the server. Manual configuration in ~/.gemini/config/mcp_config.json:

{
  "mcpServers": {
    "agent-memory": {
      "command": "python",
      "args": ["-m", "agent_memory.mcp_server"],
      "env": {
        "PYTHONIOENCODING": "utf-8"
      }
    }
  }
}

2. Claude Code (Anthropic CLI)

Register the server in Claude Code with a single command:

claude mcp add agent-memory python -m agent_memory.mcp_server

3. Cursor & Windsurf (mcp.json)

Add to your project's .cursor/mcp.json or .codeium/windsurf/mcp_config.json:

{
  "mcpServers": {
    "agent-memory": {
      "command": "python",
      "args": ["-m", "agent_memory.mcp_server"]
    }
  }
}

4. Roo Code / VS Code Cline

Add to your Extension MCP settings:

{
  "mcpServers": {
    "agent-memory": {
      "command": "python",
      "args": ["-m", "agent_memory.mcp_server"]
    }
  }
}

๐Ÿ› ๏ธ MCP Toolset Reference

Tool Name

Parameters

Purpose

memory_batch_inspect

targets: list[str]

Multi-query complete High-Density Identity Cards for multiple files/directories in a single turn.

memory_find_by_intent

terms: list[str]

Instant FTS5 search by colloquial human intent, command slang, or natural query habits.

memory_get_phase_map

file_path: str

Retrieves 16+ sequential execution sub-blocks of complex scripts without reading raw code.

memory_enrich_knowledge

entity_path, purpose, colloquial_aliases, ...

Records deep architectural insights. Automatically enforced by the 6-Pillar Quality Gate.

memory_sync_codebase

None

Runs incremental AST parsing and SHA-256 line drift detection across all files.


๐Ÿ’ป CLI Usage & Terminal Output

Multi-Query Composite Command (One-Shot):

python -m agent_memory \
  -q src/auth_service.py src/database.py \
  -f "login flow" "reset password" "verify jwt" \
  -i authenticate_user hash_token \
  -b src/pipeline_worker.py

Terminal Output Preview:

=== [IDENTITY CARD] src/auth_service.py (Type: FILE_PY | Level: 1 | Size: 4.2 KB) ===
[Pillar 1: Purpose] Manages OAuth2 token lifecycle, JWT verification, and user authentication.
[Pillar 2: Architecture] Upstream: api/routes.py | Downstream: db/users.py, cache/redis.py
[Pillar 6: Guardrails & Gotchas] Never log raw bearer tokens or expose private signing keys.
[Pillar 3: Technical Symbols & Contracts (2 functions detected)]
โ€ข [authenticate_user] [src/auth_service.py#L24-L68] `def authenticate_user(token: str) -> UserSession`
  Contracts: Calls: verify_jwt, db.get_user | Side-effects: Redis TTL refresh | Error-hnd: Raises AuthError
โ€ข [hash_token] [src/auth_service.py#L72-L95] `def hash_token(raw_key: str) -> str`
  Contracts: Calls: hashlib.sha256 | Error-hnd: None (pure)
--- [END OF CARD: src/auth_service.py] ---

[USER INTENT SEARCH] Query: 'login flow' (2 matches found)
โ€ข [Score: 1.0] src/auth_service.py -> authenticate_user | Context: Matches 'login flow'

๐Ÿ’ก Python Programmatic API

You can use Agent Memory directly within your Python scripts, CI bots, or custom AI agent orchestrations:

from agent_memory.config import resolve_workspace_root, get_database_path
from agent_memory.core.database import Database
from agent_memory.core.scanner import Scanner

# 1. Connect to workspace memory
workspace = resolve_workspace_root()
db = Database(get_database_path(workspace))

# 2. Synchronize AST & Codebase
scanner = Scanner(workspace)
cards = scanner.scan_all()
db.upsert_entities_batch(cards)

# 3. Retrieve Identity Card
card = db.get_entity_card("src/auth_service.py")
print(f"File Purpose: {card.purpose}")
for sym in card.symbols:
    print(f"  โ€ข {sym.name} [#L{sym.start_line}-L{sym.end_line}] -> {sym.signature}")

# 4. Instant FTS5 Search by Natural Human Slang
matches = db.find_by_intent("login token")
for match in matches:
    print(f"Match: {match['path']} -> {match.get('target_name', '')}")

(See examples/basic_usage.py for a runnable demonstration).


โ“ Frequently Asked Questions (FAQ)


๐Ÿงช Automated Testing & Quality Gate

Agent Memory Engine includes a comprehensive, zero-dependency unit test suite using Python's native unittest framework:

# Run all unit tests
python -m unittest discover tests -v

# Or using pytest (if installed)
pytest

Quality Status: 30/30 unit tests passing (100% pass rate). Tested across Windows, Linux, and macOS on Python 3.10, 3.11, and 3.12.


๐Ÿ”’ Privacy & Security (Zero Cloud Leak)

  • Local Embedded Storage: All indices are stored locally in .agents/memory/memory.db.

  • Zero Third-Party Telemetry: Your proprietary code never leaves your developer workstation.

  • Git Governance: Binary SQLite databases (*.db, *.db-wal, *.db-shm) are strictly excluded via .gitignore, preventing accidental repository bloat.


๐Ÿ‡ฎ๐Ÿ‡ฉ Panduan Eksekutif Bahasa Indonesia

Mengapa Repositori Ini Wajib Digunakan?

Bagi Software Architect, Tech Lead, dan Engineering Manager:

  1. Pemberantasan Pemborosan Token (Token Bloat): AI Coding Agent konvensional menghabiskan 30.000โ€“80.000 token hanya untuk membaca file mentah (view_file, cat, grep). Agent Memory Engine memangkasnya menjadi < 1.000 token per interaksi (hemat hingga 95%).

  2. Akurasi Baris Deterministik 100%: Dilengkapi navigasi baris eksak (#Lstart-Lend), AST parser bawaan, dan call graph internal untuk mencegah halusinasi kode.

  3. Pencarian Intent Bahasa Santai Pengguna: Berkat SQLite FTS5 berkecepatan 0.01 detik, AI dapat menemukan letak fungsi berdasarkan kebiasaan perintah, typo, atau bahasa santai pengguna (misal: "cek login", "sambung audio", "potong ayat", "hitung pajak").

Cara Pasang Cepat 1-Baris:

python -m pip install -e .
python -m agent_memory --install

๐Ÿ“œ Lisensi & Kontribusi

Didistribusikan di bawah lisensi MIT License. Bebas digunakan, dimodifikasi, dan didistribusikan untuk proyek komersial maupun open-source.

Available Tools

5 tools
memory_batch_inspectB

Fetch complete High-Density Identity Cards for multiple folders and files in a single call (Multi-Query).

Inputs: targets (required). Returns: result

memory_enrich_knowledgeC

Save deep understanding of a file/folder or function/symbol. MANDATORY: Write technical specs (purpose, logic_phases, upstream, downstream, guardrails, side_effects, error_handling) in High-Density Technical English (saves 40% tokens). MANDATORY: Write colloquial_aliases in natural Indonesian user habits/slang for instant FTS5 matching.

Inputs: entity_path (required), purpose, upstream, downstream, +8 more. Returns: result

memory_find_by_intentA

Search symbols, files, or exact code blocks using natural human language, Indonesian colloquial slang, command habits, or typos.

Inputs: terms (required). Returns: result

memory_get_phase_mapB

Retrieve detailed internal logic execution phase map for a script from start to finish without reading raw code.

Inputs: file_path (required). Returns: result

memory_sync_codebaseB

Automatically sync codebase via AST parsing and SHA-256 hashing to detect exact line and symbol changes.

Inputs: no named parameters. Returns: result

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelogโ€ฆ

    TDQS

    B3.3/5.0

    Scored across 5 tools

    Disambiguation4/5

    Each tool has a fairly distinct role: bulk read (batch_inspect), search (find_by_intent), deep read of one script's logic (get_phase_map), sync/index (sync_codebase), and write (enrich_knowledge). The only mild overlap is between batch_inspect and get_phase_map, since both return stored knowledge about code, but the granularity difference (identity cards vs. execution phases) is stated clearly enough to choose correctly.

    Naming Consistency4/5

    All five tools share a clear `memory_` prefix and use snake_case, giving a predictable namespace. The verb ordering varies slightly (adjective+verb in batch_inspect, verb+preposition in find_by_intent, verb+noun elsewhere), but each name remains self-descriptive and readable.

    Tool Count4/5

    Five tools is lean but each covers a distinct stage of the memory lifecycle (sync, search, bulk read, deep read, write). It stays well under the heavy-tool threshold and no tool feels redundant, though the surface is minimal for a full memory engine.

    Completeness3/5

    The read/create/sync path is covered, but there is no delete or invalidate operation for stale knowledge, no explicit update/amend for existing entries, and no listing/index tool to discover what folders are stored. Agents can work around some of this via search and re-enrich, but lifecycle coverage has notable holes.

    Related MCP Connectors

    Related MCP Servers

    • F
      license
      Not graded
      quality
      B
      maintenance
      Provides graph-native code intelligence for coding agents, enabling them to navigate repositories through compact SQLite-backed symbol graphs and retrieve full source only for relevant symbols.
      -
    • F
      license
      Not graded
      quality
      B
      maintenance
      Enables AI coding agents to interrogate a local repository deterministically for symbols, dependencies, call paths, routes, tests, and Git impact, returning verified structured evidence with exact line citations instead of requiring the whole codebase to be read.
      56 PyPI
      4
      -
    • A
      license
      A
      quality
      B
      maintenance
      Enables semantic and keyword search over a local codebase by chunking source files along function and class boundaries, embedding them offline, and fusing vector and BM25 results. Runs entirely on your machine in a single SQLite file, so AI coding agents can find relevant code with no API keys, telemetry, or cloud calls.
      7
      11 npm
      MIT
    • A
      license
      Not graded
      quality
      B
      maintenance
      Enables AI coding agents to query a local semantic code graph for surgical context, cross-file resolution, framework-aware routes, and code intelligence while keeping indexes automatically up to date.
      168,951 npm
      MIT