Skip to main content

SPINE: Hierarchical Graph Memory for Long-Horizon AI Agents

Read this in: English · Русский

CI PyPI Python License

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

  1. 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.
  2. 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.
  3. Multi-dimensional navigation & Hebbian salience.
    • Chronological chains: roots → after with typed relations (:continuation, :genesis, :contrast, …).
    • Typed semantic_links + a compiled reverse_index.json for bidirectional traversal without mutating existing YAML.
    • strategic_weight (0.0–1.0), access_count, last_accessed keep active memories hot while dormant ones cool without dead links.
  4. Zero-token deterministic guardrails. _critic_check.py and _quality_audit.py enforce structure, length caps (IMPULSE <= 2 lines, SUMMARY <= 5 sentences), anchor canon compliance, and SOURCE_BASE >= 70% byte retention via instant bash/Python checks — no LLM-vs-LLM critic loops.
  5. 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 file
  • spine_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% (6/6 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.py 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)
├── 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.py
    ├── _check_anchors.py
    ├── _crosslink.py
    ├── _wander.py
    ├── _quality_audit.py
    ├── _build_index.py        # rebuild reverse_index + anchor canon (recursive + cache.json)
    ├── _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..006) is written in Russian to verify Cyrillic tokenization and semantic anchors. All tools and the schema are language-agnostic. The full story is told as a longread in docs/longread.md — each chapter maps to one SPINE mechanic.

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)
python tools/_critic_check.py 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
#    (recursive node walk; cache.json skips the rebuild when inputs are unchanged)
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).


Ecosystem: agent cartridges on Agensi.io

SPINE-Memory is the free, git-native core. Companion agent cartridges are distributed on Agensi.io:

Cartridge What it adds
repo-immune-system write-hook gotcha / dead-end guard + Circuit Breaker
memory-janitor recursive index / crosslink / audit + shared cache.json
token-diet-context KV-prefix-stable compaction + token budget + scan/pipe
epistemic-code-critic Popperian / Bayesian code-review gates + blast_radius.py
anti-lobotomy persona-lock drift detection + 4 ready presets

Each cartridge is autonomous (stdlib-only, no imports between them) and talks through two text contracts: the node YAML frontmatter and the CLI JSON output.

Metadata

Release files for spine-memory 0.2.7

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for spine-memory 0.2.7
File Size Uploaded Provenance Actions
spine_memory-0.2.7.tar.gz 43.1 kB With provenance Details for spine_memory-0.2.7.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for spine-memory 0.2.7
File Interpreter ABI Platform Actions
spine_memory-0.2.7-py3-none-any.whl Python 3 none any Details for spine_memory-0.2.7-py3-none-any.whl

Total release size: 92.9 kB

Release files / spine_memory-0.2.7.tar.gz

Download URL spine_memory-0.2.7.tar.gz
Size 43.1 kB
Tags Source
SHA-256 checksum
How to use checksums
1e1f69cea6815319eee038134c0cf65dad93845c3e3485a7633bbd61fe266bc6
BLAKE2b-256 checksum
How to use checksums
b1781baa48efc042d9f77d7905304e99d7259103d59befdc525a6a3051409d6c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

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.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 1, 2026.

Transparency log

Release files / spine_memory-0.2.7-py3-none-any.whl

Download URL spine_memory-0.2.7-py3-none-any.whl
Size 49.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
f4b1d2add17f9c5d531e5a911333ce23c91db82d4ab4af5ae7d0e854b37af077
BLAKE2b-256 checksum
How to use checksums
3c659c54555c58cd42905e9d0f072f4c7c539342e4806874ab8e5b966977e45b
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

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.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 1, 2026.

Transparency log

Security for spine-memory 0.2.7

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.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for spine_memory-0.2.7.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 1, 2026.

Transparency log

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.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page