Files
el/engram
bigmerge bacaf3d39c
El SDK CI - dev / build-and-test (pull_request) Failing after 4m49s
engram: reconcile M8 HNSW vindex (#109) onto current dev, restore 3 fixes the branch predated
Lands feat/reframe-region-setop (PR #109: native set-based reframe_region,
decorator-as-seam @route port, teacher-summon, and the M8.1 activate-latency
work — lazy-memoized cosq via eg_cosq_at + engram_vindex HNSW-accelerated
seed discovery + vindex_harvest_from_store/vindex_bench oracle) onto dev's
actual current HEAD, plus engram-tiered-storage's still-unique test suite.

RECONCILING #109 WITH engram-tiered-storage (M4-M10 HNSW/geometry/reason/
verify work): not a two-way merge. engram_vindex.c's HNSW core (search_layer/
select_neighbors/prune_links/insert) is BYTE-IDENTICAL between the two
branches; #109's copy is a strict superset (adds vindex_harvest_from_store,
used by vindex_bench.c's brute-force-vs-HNSW oracle). engram_reason.c and
engram_verify.c are also byte-identical. #109's own branch point already
carried engram-tiered-storage's M4-M10 lineage forward, so there was nothing
left to merge into #109 for those files. The one thing engram-tiered-storage
had that #109's tree dropped: its full test suite (test_vindex.c,
test_geometry.c, test_reason.c, test_verify.c, test_m7_traversal.c, the
interoception P0-P5 tests, bufpool/compaction tests, and their run_*.sh
harnesses) — ported over here unchanged.

WHY THIS NEEDED HAND RECONCILIATION, NOT A MECHANICAL MERGE: #109's branch
forked from dev on 2026-08-14 15:40 (before restructure-adjacent history
diverged the file's merge-base for `git merge` — it presented as an add/add
conflict). A straight two-dot diff (dev tip -> PR tip) applied cleanly, but
it silently reverted THREE dev fixes landed on 2026-08-14/15, after the
branch point, that the PR's diff had no way to know about:

  1. qgate rescale (2026-08-14 self-review): PR's lazy eg_cosq_at rewrite of
     the query-aware propagation gate dropped the shift-and-floor rescale
     about ENGRAM_EMBED_S0 (measured: unrelated-pair median 0.562->raw gate
     0.67, i.e. "a small tax, not a gate"). Restored the rescale, wrapped
     around the lazy accessor -- the PR's actual improvement (WHEN cosq[oi]
     is computed) is orthogonal to WHAT it gates on and both are kept.
  2. Eviction cause decomposition (2026-08-14 self-review): dev decomposes
     wm_evicted into evict_floor/evict_cap/evict_bll so WM churn is
     diagnosable (identity: evicted == floor+cap+bll+dup_wm+dup_wm_global).
     PR's tree predates this and dropped all three counters + their JSON
     stats fields. Restored declarations, all 4 direct increment sites, the
     eg_wm_carry_over bll increment, and the act-stats JSON fields --
     alongside (not instead of) the PR's own P4 afferent / API-reshape
     counters already in that same struct/JSON.
  3. Hebbian link-formation selection (2026-08-15 self-review, TODAY): dev
     selects the STRONGEST qualifying candidate for consolidation each call;
     PR's tree predates this and reverted to hash-slot order (arbitrary wrt
     association strength) for edge formation -- the one path that writes
     PERMANENT structure. Restored the strongest-candidate while-loop,
     keeping the PR's own genuine improvement at that site
     (engram_adj_on_edge_added incremental-index append instead of a bare
     adj_dirty=1 full-rebuild flag).

engram/src/server.el's 3-way conflicts (autoconnect_on/ise_offgraph_on env
flags, /api/nodes connected-count in responses) were pure additive: dev's
side was empty, PR's side added the feature. Took PR's side whole.

VERIFIED (nsbx sandbox only, live :8742/:7770 never touched):
  - cc -std=c11 -O2, clean link against the real engram/src/server.el via
    elc, zero errors.
  - vindex_bench (built standalone, read-only harvest) against the real
    production store clone (13,671 embedded nodes, 768-dim nomic-embed-text):
    recall@10 = 1.0000 at ef 64/128/200; HNSW search 0.28-0.79ms/query vs
    2.03ms/query brute-force oracle (2.6x-7.2x). HNSW build itself: 46.5s
    for the full 13,671-node set -- see the flagged risk below.
  - Booted the reconciled binary in an isolated nsbx sandbox (:8905, cloned
    snapshot of the live store, 13,424 nodes / 37,656 edges) and called
    /api/activate for real: first call after boot 41.5s (pays the one-time
    HNSW build inline -- matches the standalone bench), second/third calls
    356ms/605ms, no crash, correct results, act-stats JSON (including the
    restored evict_floor/cap/bll fields) reads correctly.

KNOWN RISK TO FLAG BEFORE ANY LIVE CUTOVER (not fixed here; out of scope for
this dev-only land per instructions not to touch :8742/:7770): eg_vindex_sync
builds the HNSW index synchronously, inline, on the first engram_activate()
call after every process start (or index invalidation). On the real node
count that is a ~46s blocking stall on a single-threaded server -- the first
request after every restart (or its concurrent siblings) waits the full
build. Recommend a background/incremental build (or a bounded per-call build
budget) before this ever reaches the live daemon. See PR description / final
report for the fuller writeup.
2026-08-15 16:46:44 -05:00
..
2026-04-30 13:49:28 -05:00

Engram

A local-first memory substrate for accumulating intelligence.

An engram is the physical trace of a memory in the brain — the actual encoded substrate, not an abstraction above it. That's what this is.


Why existing databases are wrong for this use case

Relational databases store rows and retrieve them by predicate. Key-value stores retrieve by exact key. Vector databases retrieve by geometric proximity. All of them share the same fundamental model: you store data in, you query it out. Storage and retrieval are separate systems.

The brain doesn't work this way.

When you remember something, you don't query your hippocampus. You activate a memory trace and the pattern propagates. Long-term potentiation — the strengthening of synaptic connections through co-activation — is simultaneously the storage mechanism and the retrieval mechanism. The structure that holds the memory is the same structure that surfaces it.

No existing database models this. Engram does.


The Spreading Activation Model

Engram retrieval works through spreading activation:

  1. Seeds — you name one or more nodes you know are relevant (e.g. the current task, recent context, a concept you're reasoning about)

  2. Query embedding — you provide a semantic vector representing the direction of your current thought

  3. Propagation — activation flows outward from seeds through weighted edges. At each hop, strength attenuates multiplicatively:

    strength = parent_strength × edge_weight × target_salience × cosine_sim(query, target)
    
  4. Pruning — paths weaker than a threshold are cut (the attention filter)

  5. Return — the top-N nodes by activation strength

This is not a query. It is a pattern completion. The system surfaces what is most associatively relevant to the current context, weighted by how strongly those things have been reinforced over time.


The Four Memory Tiers

Tier Analogy Contents
Working Prefrontal working memory K most recently activated nodes — hot, fast
Episodic Hippocampus Time-ordered events and experiences
Semantic Neocortex Concept graph — long-term structural knowledge
Procedural Cerebellum / basal ganglia Patterns, workflows, habits

Nodes migrate between tiers based on salience decay and reinforcement. A frequently activated semantic node stays semantic. A rarely-touched episodic memory decays toward procedural background.


Salience — Forgetting as Adaptation

Salience is not stored permanently. It decays:

fn compute_salience(importance: f32, last_activated_ms: i64, activation_count: u64) -> f32 {
    let days_since = (now_ms() - last_activated_ms) as f32 / 86_400_000.0;
    importance * (1.0 / (1.0 + days_since)) * (activation_count as f32 + 1.0).ln()
}

Three signals:

  • Importance (0.01.0): set at creation, stable
  • Recency: decays toward zero as days pass without activation
  • Frequency: log-compressed count of activations

Forgetting in Engram is not a bug. It is adaptive pruning. Memories that are never activated again become less likely to surface during retrieval. They are not deleted — they remain in storage — but they stop competing for attention. This is exactly how biological memory works, and why it is adaptive rather than pathological.


Quick Start

use engram_core::{EngramDb, Node, Edge, NodeType, MemoryTier, RelationType};
use std::path::Path;

// Open or create a database
let db = EngramDb::open(Path::new("/var/lib/my-agent/memory"))?;

// Create a node with a semantic embedding
let node = Node::new(
    NodeType::Concept,
    vec![0.9, 0.1, 0.3, 0.7, 0.8, 0.2],   // embedding from your LLM
    b"Spreading activation surfaces relevant memories by pattern completion".to_vec(),
    MemoryTier::Semantic,
    0.9,   // importance
);
let id = db.put_node(node)?;

// Link it to related concepts
let related = db.put_node(Node::new(
    NodeType::Concept,
    vec![0.8, 0.2, 0.4, 0.6, 0.7, 0.3],
    b"Long-term potentiation: co-activation strengthens synaptic weight".to_vec(),
    MemoryTier::Semantic,
    0.85,
))?;
db.put_edge(Edge::new(id, related, RelationType::Causes, 0.9))?;

// Retrieve by spreading activation
let results = db.activate(
    &[id],                                     // seeds
    &[0.85, 0.15, 0.35, 0.65, 0.75, 0.25],   // query embedding
    3,                                         // max hops
    10,                                        // top-N results
)?;

for r in results {
    println!(
        "strength={:.4} hops={}{}",
        r.activation_strength,
        r.hops,
        String::from_utf8_lossy(&r.node.content)
    );
}

Project Structure

engram/
  crates/
    engram-core/        # The memory engine — storage, graph, activation, salience
    engram-ffi/         # C FFI stubs for cross-language bindings
  bindings/
    kotlin/             # Android / JVM binding notes
    typescript/         # WASM / Node binding notes
    go/                 # CGo binding notes
  examples/
    basic.rs            # Full walkthrough: insert, activate, search, decay

Public API

impl EngramDb {
    fn open(path: &Path) -> EngramResult<Self>;
    fn put_node(&self, node: Node) -> EngramResult<Uuid>;
    fn get_node(&self, id: Uuid) -> EngramResult<Option<Node>>;
    fn put_edge(&self, edge: Edge) -> EngramResult<()>;
    fn get_edges_from(&self, from_id: Uuid) -> EngramResult<Vec<Edge>>;
    fn get_edges_to(&self, to_id: Uuid) -> EngramResult<Vec<Edge>>;
    fn search_embedding(&self, embedding: &[f32], limit: usize) -> EngramResult<Vec<ScoredNode>>;
    fn activate(&self, seeds: &[Uuid], query_embedding: &[f32], max_depth: u8, limit: usize) -> EngramResult<Vec<ActivatedNode>>;
    fn traverse(&self, from: Uuid, relation: Option<RelationType>, max_depth: u8) -> EngramResult<Vec<Node>>;
    fn touch(&self, id: Uuid) -> EngramResult<()>;
    fn decay(&self, factor: f32) -> EngramResult<usize>;
    fn node_count(&self) -> EngramResult<usize>;
    fn edge_count(&self) -> EngramResult<usize>;
}

Dependencies

  • sled — embedded persistent B-tree (no daemon, no network, local-first)
  • bincode — compact binary serialization
  • uuid — stable node identity
  • serde — derive support
  • thiserror / anyhow — error handling

Design Decisions

Why sled? Local-first. No daemon. Transactional. Fast enough for the node counts Engram targets (< 1M nodes). When the right HNSW index is needed, it will layer on top of sled, not replace it.

Why flat cosine scan? Correct and simple. The graph structure itself is the primary retrieval mechanism. Vector search is a secondary signal. HNSW adds complexity and a compile dependency that isn't justified until retrieval quality at scale demands it.

Why multiplicative activation? Because memory is conjunctive. A path requires all of its links to be strong to carry signal. Addition would allow many weak associations to accumulate into false relevance. Multiplication enforces that every factor matters.

Why salience decay? Because not everything that was once important remains important. Adaptive forgetting is not failure — it is the mechanism that keeps attention on what's current. A memory system that never forgets is one that can never focus.