@seanhogg/builderforce-memory
JavaScript-native AI runtime — SSM execution + Transformer orchestration + online distillation + persistent agent memory.

@seanhogg/builderforce-memory is the runtime layer of BuilderForce Agent Memory — a complete, self-contained AI runtime built directly on top of @seanhogg/builderforce-memory-engine. It includes the full session layer (previously @seanhogg/mambakit) as an internal layer, so you only need one package. (Formerly published as @seanhogg/ssmjs.)
Technical report & peer review. The runtime's design — Write-Through Cognition, hybrid recall, the inference router, and online distillation — is specified in the Evermind technical report (../../publication/evermind/). Its adversarial PEER-REVIEW.md is candid about runtime-level gaps to weigh before production: recall is an O(N) scan with no ANN index and frequently uses the lexical (Jaccard) fallback rather than dense embeddings; the "stable subject key" is caller-supplied and not yet canonicalized (so the single-incumbent guarantee rests on an unenforced precondition); recalled facts are injected unsanitized (memory-poisoning surface); and the online loop has no catastrophic-forgetting guard. Tracked as EVM-1…EVM-8. These have since been resolved in the v2026.6.34 hardening — an HNSW ANN index (src/retrieval/hnsw.ts) gates the exact scan, a subject-key canonicalizer (src/cognition/canonicalize.ts) runs inside commit(), recall is fenced, and the online loop has a forgetting guard — and the engine now ships a benchmarking harness for measured quality. See the resolution addendum in PEER-REVIEW.md.
Overview
@seanhogg/builderforce-memory is a JavaScript-native AI runtime that combines local SSM (State Space Model) inference with optional transformer bridge escalation, persistent semantic memory, and online distillation — all without leaving the browser or Node.js process.
The layered stack:
@seanhogg/builderforce-memory-engine → WebGPU kernels (WGSL, Mamba-1/2/3 SSM math)
@seanhogg/builderforce-memory → Session layer + Runtime orchestration (this package)
├── src/session/ MambaSession, tokenizer, persistence
├── src/runtime/ SSMRuntime, routing
├── src/memory/ MemoryStore
├── src/agent/ SSMAgent
└── src/distillation/ DistillationEngine
| Capability |
@seanhogg/builderforce-memory |
| Simple session API |
✅ |
| WebGPU execution |
✅ |
| SSM variants (1/2/3/hybrid) |
✅ |
| Transformer bridge |
✅ |
| Intelligent routing |
✅ |
| Online distillation |
✅ |
| Persistent semantic memory |
✅ |
| Agent workflows |
✅ |
| Create-an-LLM pipeline + diagnostics |
✅ |
Create an LLM (workflow + diagnostics)
The TRAIN_LLM workflow trains a custom EvermindLM on any corpus and packages
it as a portable .evermind artifact — domain-agnostic (resume tailoring, support
replies, code, prose). Every run is gated by built-in diagnostics so a broken model
never ships:
import { runWorkflow, TRAIN_LLM } from '@seanhogg/builderforce-memory';
const r = await runWorkflow(TRAIN_LLM); // or cloneTemplate('train-llm', { steps: [...] })
const artifact = r.artifacts.evermind; // ArrayBuffer → ship + serve
Generic build step types (compose your own pipeline via the step registry):
| Step |
What it validates |
train-tokenizer |
Learns a BPE vocab from your corpus |
dataset-quality |
Gates corpus size / sequence count / duplicate ratio before spending epochs |
train-model |
Trains the EvermindLM (exposes the loss curve on ctx.bag.trainingHistory) |
convergence |
Asserts training loss actually decreased (the model learned) |
evaluate / generate-check |
Output is non-empty and seed-reproducible |
roundtrip |
Packages the trained model → loads → generates; served output must match trained |
benchmark |
Scores the trained model on a held-out corpus (perplexity, bits-per-token, top-1/top-k accuracy, throughput); optional maxPerplexity / minTop1 gates fail the run |
Evermind recall contract (@seanhogg/builderforce-memory/evermind)
A dependency-free subpath a browser chat client can import without the rest of the runtime:
EvermindRecallItem, EvermindRecallResult — what a project Evermind recall returns.
rankEvermindRecall, hashRecallQuery — the lexical recall ranker.
countReconciledMemories — which recalled memories an answer restates (write-through reconcile).
formatEvermindMemoryBlock — the recalled-memory prompt block, each item neutralised with sanitizeRecalledFact.
EVERMIND_MIN_TEACH_CHARS — the teach floor below which a turn is never contributed.
Working memory and code maps (@seanhogg/builderforce-memory/working)
A run has two memories. Both are pure (no I/O) and run in a Worker, a browser and Node.
Short-term: WorkingMemory.brief() and the volatile tail
WorkingMemory records what this run has read, searched and changed. Record successful tool calls only. brief() restates that record once the run is long enough for compaction to have dropped its own results. Before that it returns null.
The brief changes every turn, so where it goes decides what the prompt cache can reuse. The rule:
- Tag it and put it last. Deliver the brief, and any other per-turn content (affect, budget line, task state), inside ONE trailing
user message built with volatileTail() from /handoff. That message opens with <run-state>. The prompt-cache breakpoint is placed before a tagged block, so the history before it stays cached. packHandoff also never treats a tagged block as "the latest user directive".
- Never persist it into the transcript. Build the tail for each request and throw it away. A brief written into history grows every later turn and moves the cached prefix each time.
- Never put it in the system prompt. The system prompt is the start of the cached prefix, so content that changes per turn there invalidates the cache on every request.
- Hosts that can only insert into the transcript should not use
brief(). Some SDKs only offer insertion points that persist, for example the Claude Agent SDK's PostToolUse additionalContext, which is written into the session transcript. A brief delivered there breaks both rules above. Such a host should skip the brief and still record into WorkingMemory for the run-end code map.
Long-term: code maps
consolidate(snapshot, { root?, at?, minFiles? }) turns a finished run into ONE memory per code area under the key codemap:<area>. The content is a map: changed files first, then reads ranked by how often the run opened them. The area is the deepest directory (2 to 4 segments) holding most of the files.
- Minimum size. A run must touch at least
MIN_CONSOLIDATED_FILES (3) distinct files, counting changed, deleted and read together, or consolidate returns null. This applies to every run, including one that changed files. Pass minFiles to override it.
- Root area. A run whose files all sit at the repository root is filed under
codemap:(root) (CONSOLIDATED_ROOT_AREA). areaOfPath('package.json') resolves to the same area, so the map can be recalled.
- Merging. A keyed store applies
mergeConsolidated(key, prior, next) on write. The new run's entries come first, then the earlier map's entries it did not touch. An earlier changed is restated as changed earlier, files this run deleted leave the map, and the list is capped at 12. Pass prior only when the stored map is still live (not expired or superseded). Any non-codemap: key is stored as sent.
- Reading a stored map.
consolidatedFiles(content) lists the files a map names. A store can anchor the map to them. withoutConsolidatedFiles(content, paths) drops files that changed since the map was written and keeps the rest. It returns null when no file is left.
- Choosing maps for a run.
consolidatedFactsFor(facts, areas) keeps the maps whose area overlaps the areas a run is about, most specific first. areasOfPathsIn(text) gives the areas of the repo-relative paths a request names. areasNamedIn(text, areas) finds stored areas a request names by word ("the run store" matches …/runStore). Generic directory names such as src never match.
Knowledge graph (@seanhogg/builderforce-memory/knowledge)
A directory review turns a folder into a graph of facts connected to each other and to the sources they came from (PRD 38). The subpath is pure TypeScript and runs in a browser, a Worker and Node. A host supplies ports only, never graph logic: a DirectorySource, a KnowledgeStore, an IngestManifest, and optionally a JudgementPort and a similar function.
Store judgement, compute perception. Nodes and edges derived from source text (origin: 'extracted') are recomputed from the sources and cached by content hash through KnowledgeStore.getExtracted / putExtracted. They are never written as knowledge, and assertStoredBatch throws if a batch carries one. Only what a model, a person or an agent judged (model, human, agent) is stored, together with the content hash it was judged from. That judgement goes stale when the hash changes.
What a review is
reviewDirectory(args) walks a DirectorySource, diffs it against the IngestManifest by content hash, and reviews only the changed files:
plan → per changed file: read · parse · extract (cached) · judge · write · markStale
→ analyzers → compare near-duplicate claims → manifest + scope digest