SPINE: Hierarchical Graph Memory for Long-Horizon AI Agents
SPINE is a lightweight Markdown- and YAML-based cognitive memory framework that gives LLM agents persistent, scalable, low-latency long-term memory without heavy vector-database overhead.
Battle-tested on a real-world personal knowledge graph of 532 structured memory nodes (~2.6M+ chars indexed) and 460+ typed semantic links, with schema integrity enforced by deterministic, zero-token CI checks.
Your IDE remembers WHAT is in the file. SPINE remembers WHY it's there — with receipts.
SPINE in 60 seconds
Dev / IDE. Your coding agent spots a sleep(200) in a retry loop and reaches
to "clean it up". It runs git blame, finds the commit, then asks SPINE. SPINE
returns a post-mortem node: "2026-03 rate-limit incident — the API returns 429
if we retry faster than 200 ms." The agent leaves the line alone. No 3 AM page.
Long-horizon agent. An agent running 500+ sessions across months, with 2.6M+
chars of accumulated context, needs a decision from three months ago. It walks
the funnel — impulse (2 lines) → summary (5 sentences) → cleaned_data →
source_base — spending 60 tokens on the first hop instead of loading the whole
corpus. Marginal cost: **$0.01/node**.
The Problem
Standard flat RAG degrades as a knowledge base grows past a few hundred documents:
- Context bloat & token cost — full raw chunks exhaust context windows with logs, formatting noise, and boilerplate.
- Loss of causality & chronology — vector similarity misses temporal order
(
roots -> after) and high-level thematic grouping. - Destructive compression — summarization discards original data, blocking forensic lookups and future fine-tuning.
- Memory rot & hallucination — without periodic consolidation and schema validation, agent memory accumulates noise.
Core Architecture
SPINE organizes memory into a 3-tier cognitive topology modeled after biological neural organization:
[ Tier 1: Domains — macro-areas ]
│
▼
[ Tier 2: Constellations — thematic clusters, 5–20 nodes ]
│
▼
[ Tier 3: SPINE Nodes — atomic memory units, ~5k chars each ]
Key mechanisms
- Deterministic ingestion & chunking. Raw logs are pre-processed by deterministic Python scripts into ~5,000-char Markdown chunks before touching an LLM — cutting ingestion token cost and semantic load.
- Multi-layer progressive disclosure (
Constellation→Impulse→Summary→Cleaned→Raw). The agent walks a relevance funnel instead of loading raw chunks upfront:- Routing & scent — filter by domain/constellation, scan 1–2-line impulses and anchors inside candidate clusters.
- Synthesis — read the 3–5-sentence summary to confirm relevance.
- Precision context — load artifact-free cleaned data.
- Lossless basement — preserve the untouched original in source_base (≥70% byte ratio) for forensic drill-down and future LoRA/QLoRA fine-tuning.
- Multi-dimensional navigation & Hebbian salience.
- Chronological chains:
roots→afterwith typed relations (:continuation,:genesis,:contrast, …). - Typed
semantic_links+ a compiledreverse_index.jsonfor bidirectional traversal without mutating existing YAML. strategic_weight(0.0–1.0),access_count,last_accessedkeep active memories hot while dormant ones cool without dead links.
- Chronological chains:
- Zero-token deterministic guardrails.
_critic_check.shand_quality_audit.pyenforce structure, length caps (IMPULSE <= 2 lines,SUMMARY <= 5 sentences), anchor canon compliance, andSOURCE_BASE >= 70%byte retention via instant bash/Python checks — no LLM-vs-LLM critic loops. - Hybrid compute routing. Designed for constrained edge hardware: local embeddings on a Linux GPU, lightweight API models for routine extraction, frontier models reserved strictly for deep synthesis.
Dev Overlay: memory around code
SPINE is not a symbol index — LSP, Tree-sitter and ripgrep already own that.
SPINE stores intent: why a decision was made, what broke, what traps exist.
One node type, four kinds, bound to code with a pointer to Git (not a copy of
the source):
kind: adr | postmortem | gotcha | contract
repo_ref: {path, commit, lines}
code_refs: ["src/auth/jwt.py::verify_token@a1b2c3d"]
status: active | superseded | historical # facts don't decay, they get superseded
Dev tools:
spine_for_file(filepath)— ADR / post-mortem / gotcha for a code filespine_preflight --files ...— what you might break before you change it_git_hook.py --kind ...— scaffold a memory node from a merged PR (memory fills itself as a byproduct of normal work)
Graph scale & metrics
| Metric | Value |
|---|---|
| Production graph scale | 532 nodes (~2.6M+ chars indexed) |
| Typed semantic links | 460+ edges |
| Embedding links | 1496 (top-5, threshold 0.88) |
| YAML validity — production | 100% (532/532), enforced by critic_check |
| YAML validity — demo corpus | 100% (3/3 PASS) |
| Chunk granularity | ~5,000 chars |
| Retrieval strategy | progressive disclosure |
Human-Readable & Obsidian-Ready
Memory is plain Markdown in Git — open it in Obsidian, grep it, diff it,
read it with your own eyes. No black box, no "trust me, the vector said so".
Batch Ingestion & Staging Workflow
flowchart LR
A[Raw Chunk] --> B[Temp Staging]
B --> C{Zero-Token Critic}
C -- PASS --> D[Atomic Commit]
C -- FAIL --> B
D --> E[Context Compaction<br/>every 5 nodes]
E --> F[Next Chunk]
The agent writes each node draft into a temporary buffer (TEMP), runs
_critic_check.sh on it, resolves boundary cases on its own with bounded
discretion (e.g. a short source chunk, or a decimal point miscounted as a
sentence terminator) without looping in self-criticism, and only then atomically
commits the valid node into the production graph. Every 5 nodes the heavy
context is compacted into lightweight snapshots.
This staging discipline enables ingesting 40+ raw nodes in a row (500k+ tokens) in a single session without degradation, at a marginal cost of ~$0.01/node (deterministic validation is token-free; only the final write consumes model tokens).
Repository structure
.
├── pyproject.toml # pip package (zero required deps)
├── README.md
├── README_RU.md
├── SKILL.md # agent skill (Pi, Claude Code, Cursor)
├── requirements.txt # optional deps (fastmcp, tiktoken)
├── assets/
│ └── graph_dark.png # Obsidian graph screenshot
├── methodology/
│ ├── SPINE_METHODOLOGY.md # format spec (RU)
│ └── SPINE_METHODOLOGY_EN.md # format spec (EN)
├── raw/
│ ├── U001.md # raw chunk #1
│ ├── U002.md # raw chunk #2
│ └── U003.md # raw chunk #3
├── nodes/
│ ├── KEDR_001.md # processed node (domain «Связь»)
│ ├── KEDR_002.md # processed node (domain «Карта»)
│ └── KEDR_003.md # processed node (domain «Тайны_Груза»)
├── anchors/
│ └── anchor_dump.json # anchor canon for the demo graph
└── tools/ # validation & traversal utilities
├── cli.py # spine CLI entry point
├── _node_io.py # canonical node reader/writer
├── _critic_check.sh
├── _check_anchors.py
├── _crosslink.py
├── _wander.py
├── _quality_audit.py
├── _build_index.py # rebuild reverse_index + anchor canon
├── _embed_links.py # import precomputed embedding links
├── spine_preflight.py # context radar for changed files
├── _git_hook.py # PR -> node scaffold
├── night_daemon.py # nightly consolidation + self-audit
├── mcp_server.py # MCP server (FastMCP)
└── benchmark_tokens.py # token savings benchmark
The demo corpus (KEDR_001..003) is written in Russian to verify Cyrillic
tokenization and semantic anchors. All tools and the schema are
language-agnostic.
Raw chunks are named U<number>.md and paired with nodes/<ID>.md by the
trailing number (U001 ↔ KEDR_001).
Quickstart
Install and try it in 60 seconds:
pip install spine-memory # core (zero required deps)
pip install spine-memory[mcp] # + MCP server (fastmcp)
spine init --preset dev # scaffold .spine/ inside your repo
spine index # rebuild reverse_index.json
spine wander --from ADR_001 # walk the graph
spine mcp # start the MCP server
Or run directly from a checkout (no install):
# 1. Auto-audit nodes (clean PASS expected)
bash tools/_critic_check.sh nodes raw anchors/anchor_dump.json
# 2. Validate anchors against the canon
python tools/_check_anchors.py nodes/KEDR_001.md --dump anchors/anchor_dump.json --quiet
# 3. Walk the graph (forward and backlinks)
python tools/_wander.py --from KEDR_001 --hops 2 --folder nodes
# 4. Global quality audit
python tools/_quality_audit.py --nodes nodes --raw raw
# 5. Crosslink generation (dry run / apply)
python tools/_crosslink.py --folder nodes
python tools/_crosslink.py --folder nodes --apply
# 6. MCP server (stdio, for Claude Desktop / Cursor / Windsurf)
pip install -r requirements.txt
python tools/mcp_server.py
# 7. Token savings benchmark
python tools/benchmark_tokens.py
# 8. Rebuild reverse index + refresh anchor canon
python tools/_build_index.py
# 9. Nightly consolidation + self-audit
python tools/night_daemon.py --folder nodes
# 10. Import precomputed embedding links (from an external GPU worker)
python tools/_embed_links.py --input embed_links.json --folder nodes
Node format (v2.1)
--- # YAML frontmatter
id: KEDR_001
type: spine_node
domain: Связь
hub: "[[Кедр_Связь]]"
constellation: Кедр-9 Expedition
vectors:
- "связь::трёхслойный_архив" # comment required
search_anchors:
- трёхслойный_архив
chronology:
roots: "[[U001]]"
after: "[[KEDR_002]]:continuation"
semantic_links:
- "[[KEDR_002]]::продолжение"
---
# IMPULSE — 1–2 lines
# SUMMARY — 3–5 sentences
# CLEANED_DATA — ~25 lines of facts
# IMPACT — strategic_weight + key_insight
# SOURCE_BASE — ≥70% of the raw source
---
Full specification: methodology/SPINE_METHODOLOGY_EN.md (RU: methodology/SPINE_METHODOLOGY.md).
Metadata
Release files for spine-memory 0.2.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| spine_memory-0.2.0.tar.gz | 32.4 kB | Without provenance | Details for spine_memory-0.2.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| spine_memory-0.2.0-py3-none-any.whl | Python 3 | none | any | Details for spine_memory-0.2.0-py3-none-any.whl |
Total release size: 69.8 kB
Release files / spine_memory-0.2.0.tar.gz
| Download URL | spine_memory-0.2.0.tar.gz |
|---|---|
| Size | 32.4 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
c01884f796378e676567b0b073000270dbcb80ac183124cc60abbab224d7c747
|
|
BLAKE2b-256 checksum How to use checksums |
18c8ea9177d64389777d0e45e242cc790c59397aa1fd12d559e7d9b512ff7769
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.11.9
|
Release files / spine_memory-0.2.0-py3-none-any.whl
| Download URL | spine_memory-0.2.0-py3-none-any.whl |
|---|---|
| Size | 37.5 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
ea9ff6b4e12d1f85a9b99c12467e3a98f450aede7d8b71eb3af53cfb8eae78c1
|
|
BLAKE2b-256 checksum How to use checksums |
925d19e254fd25aa1d305a2e54fad16f98cf5442850395c25007671ad2eb56b5
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.11.9
|
Security for spine-memory 0.2.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.