BuilderForce Agent Memory
Part of Builderforce open source: the MIT projects Builderforce.ai is built on.
A framework for giving any AI agent persistent, browser-trainable SSM memory. It is provider-neutral — swappable LLM bridges (Anthropic / OpenAI / Fetch), an inference router, online distillation, and a persistent memory store — so any agent or app can depend on it, not just BuilderForce.
BuilderForce.ai is the flagship deployment, not the boundary: it trains a custom SSM in the browser, exports a model, and pushes it to an agent runtime where it runs as Evermind — the model itself, not just memory bolted onto someone else's LLM. Evermind is the whole brain: its own shared-expert generator (the cortex that does reasoning and language), a write-through knowledge memory (the hippocampus), and a trainable affective layer (the limbic system). A request can be served by Evermind directly — evermind/<ref> traffic is generated on-device, not forwarded to Claude/GPT — and external frontier models stay an optional routing choice rather than a hard dependency. The same framework is reusable by other agents off the shelf.
This monorepo consolidates two packages that previously lived in separate repos (mambacode.js and ssmjs) whose names described the technique rather than the role. They are renamed and unified here so that "what they do" is legible: they are Agent Memory.
Packages
| Package |
Layer |
Was |
Responsibility |
@seanhogg/builderforce-memory-engine |
Engine |
@seanhogg/mambacode.js |
WGSL/WebGPU Mamba SSM kernels, model blocks (Mamba1/2/3 + attention), autograd, trainer, BPE tokenizer, quantization. Zero runtime deps. |
@seanhogg/builderforce-memory |
Runtime |
@seanhogg/ssmjs |
SSM execution, Transformer orchestration (Anthropic/OpenAI/Fetch bridges), online distillation, inference router, sessions, the persistent MemoryStore, and Write-Through Cognition (EvermindCognition). Depends on memory-engine. |
The two-package split is deliberate: the engine is zero-dep and WebGPU-pure and can be consumed standalone; the runtime pulls in LLM-vendor bridges. Flattening them would force engine-only consumers to drag in vendor code and vice versa. They release in lockstep from one pipeline, which kills the publish-drift bug class that the separate-repo setup suffered (bumping one version without publishing + regenerating the consumer lockfile).
Cutting token cost
Agent Memory ships three layers that reduce LLM spend, in increasing power. All are portable — the same code runs in the browser (WebGPU SSM) and in Node (the agent's @webgpu/node SSM) because the embedder and storage are injected, never hard-wired.
| Layer |
What it does |
Saves |
Prompt caching (AnthropicBridge cacheSystem) |
Marks the stable system prompt as an Anthropic cache_control block |
~90% on the cached input prefix (cost, not count) |
Exact-match cache (CachingBridge + ResponseCache) |
Reuses byte-identical completions |
Eliminates duplicate calls (retries, identical fan-out) |
Semantic cache (SemanticCache + SemanticCachingBridge) |
Reuses a prior answer when the new prompt is within a cosine threshold of one already answered — catches paraphrases |
Avoids frontier calls entirely on semantically-repeated prompts |
The semantic cache is the real lever. It is read-through with two tiers, mirroring an L1-Map / L2-KV cache:
- L1 — an in-process vector list, scanned locally with on-device SSM embeddings (free, offline-capable).
- L2 — an optional shared backend (
FetchSemanticCacheBackend → the BuilderForce.ai gateway), so a paraphrase answered by the web app is reusable by an agent and vice-versa.
import { SemanticCache, FetchSemanticCacheBackend, AnthropicBridge } from '@seanhogg/builderforce-memory';
const cache = new SemanticCache({
embed: (t) => runtime.embed(t), // on-device SSM (free)
l2: new FetchSemanticCacheBackend({ baseUrl, apiKey }), // shared via the gateway
threshold: 0.92,
});
const { response, cached, tier } = await cache.getOrGenerate(
prompt,
() => bridge.generate(prompt), // only runs on a miss
);
Memory-backed fact injection is semantic too: SSMAgent defaults to factSelection: 'semantic', injecting only the top-maxFacts embedding-relevant facts each turn (paraphrase-robust, smaller prompts) instead of an exact key-substring match.
Agent runs: code maps and a cache-safe working memory
Two more levers sit in the /working subpath, for agent loops rather than single prompts. Details and the full API are in the runtime README.
| Lever |
What it does |
Saves |
Code maps (consolidate / mergeConsolidated) |
At run end, turns the files a run changed and opened (≥ 3, successful calls only) into one codemap:<area> memory. The next question on that area recalls the map and opens those files first. |
Repeat search / glob / read turns on areas the agent has already worked in |
Working memory brief (WorkingMemory.brief() + volatileTail()) |
Restates what the run already read and changed once compaction has dropped those results, so the model stops re-reading them |
Re-read turns on long runs |
Chunked windowing (buildWorkingTranscript) |
Drops old turns a chunk at a time, so the start of the history stays fixed for many turns |
Keeps provider prompt-cache hits on long runs |
The cache rule. Per-turn content goes in ONE trailing <run-state> message (volatileTail()), built fresh for each request and never written into the transcript or the system prompt. Anywhere else it moves the cached prefix every turn and raises cost instead of cutting it. A host whose SDK can only insert into the persisted transcript (for example the Claude Agent SDK's PostToolUse additionalContext) should skip brief() and keep the code maps.
Compaction is lossless
memory_compact (in memory-mcp) shrinks a fact the local Evermind has absorbed to a one-line [absorbed→Evermind vN] <first line> stub — but never at the cost of the fact:
- Probe first. A cloze question generated from the fact is put to the configured Evermind (
BUILDERFORCE_MEMORY_MODEL). If the model cannot answer it, or no model is loaded, the fact stays uncompacted and the tool says why.
- Archive before stub. The full original is written to
memory.archive.json beside the snapshot before the body becomes a stub. The archive is merged into, never pruned, so it survives the snapshot being rebuilt or rewritten by another process and the 10,000-entry cap's eviction. memory_recall / memory_get resolve a stub to its archived original.
- Backups. Every overwrite of a shared store file rotates the previous version into
.bak.1 … .bak.3.
- Lost content is labelled, then recoverable. A stub with no archived original (compacted before archiving existed) is flagged
contentLost: the boot log counts them, and recall plus the Claude Code SessionStart / UserPromptSubmit hooks inject them importance-demoted with the label "(content lost — re-verify before relying on it)". memory_restore brings the text back from a [{key, content}] export or the Evermind coordinator's [{id, text}] mem: dump (matched by key, else uniquely by first line), archiving it beside the stub.
One memory file: the installer, both server bins and the hook script share resolveMemoryFile() — BUILDERFORCE_MEMORY_FILE, else whichever of ~/.builderforce-memory/memory.json / the legacy ~/.claude/builderforce-memory/memory.json holds the live store (the most recently written when both do, logged; neither is deleted), else the canonical path.
Write-Through Cognition (Evermind)
Caching keeps answers fresh; cognition keeps knowledge fresh. A frozen model — or an append-only memory — drifts: stale and current facts pile up under different keys until something reconciles them by hand. EvermindCognition closes that gap. It is the model-knowledge analogue of a write-through cache with a conflict resolver, so a belief is replaced on write, never appended into a reconciliation backlog. This is what lets Evermind's knowledge stay current without a manual reconcile step.
Every candidate fact flows through one pipeline:
Canonicalize (stable subject key) → recall incumbent → evaluate evidence → reconcile (augment | confirm | supersede | reject) → write-through
- Stable subject key — facts about the same subject collide and replace, instead of accumulating under per-run ids. This is the anti-drift fix.
- Evidence-gated — a conflicting fact only supersedes the incumbent when ground-truth evidence favours it. The
EvidenceGatherer is injected, so the evidence source is surface-specific (IDE file tools, a DB probe, an HTTP check); workspacePresenceGatherer ships for the common "is it still on disk?" case.
- Write-through recall —
recall() is served from a version-token cache that invalidates the instant knowledge changes — the same invalidate-on-write rule as the semantic cache, applied to beliefs.
import { EvermindCognition, workspacePresenceGatherer, MemoryStore } from '@seanhogg/builderforce-memory';
const cog = new EvermindCognition({ store: new MemoryStore() });
// Seed a (soon-to-be) stale belief.
await cog.commit({ subjectKey: 'pkg:ssm-stack', content: 'SSM stack = MambaKit + SSMjs' });
// Re-observe: evidence from the real workspace decides the conflict.
const r = await cog.commit(
{ subjectKey: 'pkg:ssm-stack', content: 'SSM stack = builderforce-memory monorepo' },
workspacePresenceGatherer({
list: () => listWorkspace(), // e.g. the IDE `list_files` control tool
mustExist: ['builderforce-memory/'],
mustBeAbsent: ['MambaKit/', 'SSMjs/'],
}),
);
// r.verdict === 'supersede' → exactly one belief held, the stale one retired (replace, not append)
EvermindCognition is store- and surface-agnostic — the CognitionFactStore interface is satisfied structurally by MemoryStore (no adapter) — so the same loop runs in the IDE, on-prem, cloud, and the browser.
Enterprise architecture
Caching cuts the bill and cognition keeps knowledge current, but neither answers the questions an enterprise buyer actually asks before signing: can it read our data, will it leak across tenants, what did that answer cost, and how do we know it got better? Those four questions are what this layer exists to answer. Each is a port with adapters behind it, so a customer's existing stack is an adapter choice rather than a rewrite.
| Layer |
Entry point |
Subpath export |
Answers |
| Ingestion |
IngestionPipeline |
@seanhogg/builderforce-memory/ingest |
Can it read our data — structured and unstructured — and stay current? |
| Vector store |
VectorStore port + adapters |
…/vectorstore |
Can it run against the database we already have, with our tenancy rules? |
| Retrieval |
EnterpriseRetriever |
…/rag |
Are the answers grounded, scoped, and citable? |
| Orchestration |
AgentGraph + patterns |
…/orchestration |
Can agents coordinate, pause for a human, and resume after a crash? |
| Telemetry |
Tracer + MetricsRegistry |
…/telemetry |
What did it cost, how fast was it, and where did it go wrong? |
| Evaluation |
EvalHarness |
…/eval |
How do we know it is good enough to launch — and still is? |
Ingestion — structured and unstructured through one path
A support-ticket export (rows, typed columns) and a policy document (prose) reach the index through the same pipeline; the difference is which parser ran, not which system was built. Structure that survives parsing becomes filterable metadata, which is what makes "summarise open P1 tickets about billing" answerable — status and priority are database predicates rather than something the embedding has to imply.
import { IngestionPipeline, InMemoryIngestManifest } from '@seanhogg/builderforce-memory/ingest';
import { MemoryVectorStore } from '@seanhogg/builderforce-memory/vectorstore';
const pipeline = new IngestionPipeline({
store : new MemoryVectorStore(),
embed : (texts) => embedder.embedBatch(texts),
manifest: new InMemoryIngestManifest(), // enables `diff` sync
tracer,
});
await pipeline.ingest([
{ id: 'policy.md', tenantId: 'acme', title: 'Retention Policy',
content: { kind: 'text', text: markdown, mediaType: 'text/markdown' } },
{ id: 'tickets', tenantId: 'acme', acl: ['support'],
content: { kind: 'rows', rows: ticketRows, rowIdField: 'id' } },
]);
What makes it a pipeline rather than a loader script is everything that happens on the second run: chunk ids are deterministic (a re-run overwrites instead of duplicating), content hashes mean only changed chunks are re-embedded, vanished chunks are deleted, one malformed document fails alone and is reported by id, and forget(sourceId) erases a source completely. Builtin parsers cover markdown (keeping the full heading breadcrumb), HTML, JSON, CSV/TSV and typed rows; a new format is a ParserRegistry entry, not a branch.
Vector store — a port, not a vendor