octoflow-brain
v1.0.1
Published
Memory, recall, consolidation, and feedback runtime for OctoFlow agents.
Maintainers
Readme
octoflow-brain
Local-first cognitive memory for OctoFlow agents. It stores useful facts, recalls context, tracks trust, quarantines risky memories, resolves contradictions, consolidates stable knowledge, replays outcomes, and audits memory health.
Install
npm install octoflow-brainNode.js >=20 is required. The built-in durable store uses SQLite plus FTS and optional vector recall helpers.
The better-sqlite3 and sqlite-vec dependencies ship prebuilt binaries for common Node/arch pairs. If a prebuild is unavailable for your platform (uncommon Node versions, musl libc, etc.) npm will fall back to building from source — install Python 3, a C++ toolchain (build-essential on Linux, Xcode Command Line Tools on macOS), and re-run npm install.
Use It When
- Your agent should remember preferences, decisions, failures, wins, hunches, or procedural knowledge across tasks.
- You need transparent local memory governance instead of opaque long-term prompt stuffing.
- You want trust tiers for
user,tool,model, andexternalsources. - You need quarantine, contradiction handling, replay queues, consolidation, feedback, and audit metrics.
- You want a memory implementation that satisfies the
octoflow-protocolsCognitiveMemorycontract.
30-Second Start
import { createMemoryBrain } from 'octoflow-brain';
async function main() {
const brain = createMemoryBrain();
await brain.remember({
text: 'The billing worker retries transient Stripe failures three times.',
kind: 'fact',
source: 'tool',
scope: 'global',
});
const recall = await brain.recall({
query: 'How do billing retries work?',
topK: 3,
});
console.log(recall.items.map((item) => item.text));
await brain.close();
}
main();This quick start uses the default InMemoryBrainStore, which is intentionally ephemeral. Use it for tests, demos, and short-lived local runs only. Production or restart-safe agents should pass a durable SQLiteBrainStore or custom BrainStore.
Attach it to OctoFlow through createAgent() when agent tasks need memory-backed context. brain: { enabled: true } wires the runtime with default-on pre-turn recall and guarded post-turn memory capture. Tune brain.autoRecall / brain.autoRemember, and expose createCognitiveMemoryTool() when the model should decide when to recall, remember, or ask for advisory.
Agent Integration
For the OOTB path, let createAgent() build and attach the brain runtime, then expose the unified memory tool:
import { createAgent } from 'octoflow-core';
import { createCognitiveMemoryTool } from 'octoflow-tools';
const agent = await createAgent({
brain: {
enabled: true,
autoRecall: { scope: 'global', topK: 5 }, // optional tune; default is on
defaultScope: 'global',
scopeIdSource: 'none',
},
tools: createCognitiveMemoryTool(),
});Automatic writes are also on by default for config-managed brains. Disable with brain: { enabled: true, autoRemember: false }, or tune minChars, maxChars, and duplicateThreshold when output capture needs tighter policy.
Use brainPlugin({ brain, memoryTool }) when you already created the brain yourself or are adapting a full custom backend. For HTTP/shared memory, use createRemoteBrain() from octoflow-core; keep this package's layers on local MemoryBrain instances and put remote layers server-side for now. If your backend only implements remember() and recall(), use memoryCorePlugin({ memory, memoryTool }) from octoflow-core and upgrade to the full contract only when you need digest, consolidation, feedback, replay, audit, or pruning.
What You Get
| Capability | What it does |
| ---------------------- | ---------------------------------------------------------------------------------------------- |
| remember | Stores memory records with kind, source, scope, trust tier, confidence, metadata, and tier. |
| recall | Retrieves memories with lexical, FTS, Bloom-filter, score, and optional vector signals. |
| digest | Promotes candidate observations into hunches. |
| consolidate | Promotes, reinforces, marks stale, or quarantines records within a budget. |
| feedback | Links task outcomes to memories and queues replay entries. |
| replay | Re-examines queued wins/failures and exploration candidates. |
| resolveContradiction | Resolves conflicting memories by preference, merge, or quarantine. |
| audit | Reports contradiction rate, quarantine count, poisoning alerts, stale rate, and total records. |
| prune | Removes archived or stale records on demand, scoped by tenant/context and status filters. |
| close | Closes stores, layers, and embedders owned by the brain. |
Memory Model
| Dimension | Values |
| ------------ | ---------------------------------------------------------------------------------------------- |
| Scope | global, context, tenant. |
| Kind | fact, preference, decision, failure, success, hunch, observation, noise. |
| Status | working, candidate, long_term, reinforced, hunch, quarantine, stale, archived. |
| Tier | working, episodic, semantic, procedural. |
| Source trust | user, tool, model, external mapped to trust tiers 1 through 4. |
Tier promotion is one-way: working memories can become episodic, and episodic memories can become semantic. Records lose value through status changes instead of tier demotion.
Configuration Sketch
import { createMemoryBrain, SQLiteBrainStore } from 'octoflow-brain';
const brain = createMemoryBrain({
store: new SQLiteBrainStore({
path: '.octoflow/brain.sqlite',
maxReplayQueueLength: 10_000,
}),
promoteThreshold: 0.7,
hunchThreshold: 0.45,
weights: {
importance: 0.35,
novelty: 0.2,
reuse: 0.2,
outcome: 0.15,
confidence: 0.1,
},
});The full option surface lives in MemoryBrainOptions. See docs/brain-production.md for the production checklist, error catalog, and the canonical option reference.
Layer Stack
| Layer | Purpose | Notes |
| -------------------------------------- | ----------------------------------- | ---------------------------------------------------------------------------------------------- |
| lexicalLayer() | Declares lexical recall capability. | Core recall already performs keyword/Bloom matching; the layer is a visible capability marker. |
| vectorLayer({ embedder }) | Declares vector recall capability. | Pass the same embedder to createMemoryBrain({ embedder }); the marker alone does not embed. |
| contextualChunkingLayer({ context }) | Adds stable context before storage. | Preserves original text in metadata.originalText. |
| mmrLayer() | Diversifies recall results. | Applies MMR after recall to reduce near-duplicate results. |
| productionSafetyLayer() | Hardens production memory. | Redacts/rejects sensitive data, requires scope IDs, and downgrades weak external evidence. |
| createRerankerLayer() | Custom post-recall ranking. | Use for domain rerankers, recency boosts, or business-specific priority. |
Presets
Every preset starts with lexical. The vector layer is added on any preset whenever you pass an embedder in the preset options — it is not gated by preset name. The differences between presets are the additional layers and the replay budget:
| Preset | Use case | Adds on top of lexical + (optional) vector |
| ------------ | --------------------------------------- | -------------------------------------------------------------------------------------------------------------- |
| local | Tests, demos, ephemeral brains. | Nothing. No storage requirement. |
| hybrid | Single-process app with on-disk SQLite. | Nothing extra — just a sane storage default. |
| quality | Tuned for recall quality. | contextual-chunking (when context is provided) and mmr (unless mmr: false). |
| production | Multi-tenant deployments. | Everything quality adds, plus production-safety and a replay budget biased toward failures (fails: 0.6). |
All non-local presets require either a sqlitePath or skipStorage: true (when storage is configured separately). These presets apply to local/OOTB MemoryBrain; remote shared brains should expose equivalent behavior in the service implementation.
Learn More
../../docs/brain.md- full cognitive memory guide.../../docs/configuration.md- enabling brain-backed memory from config.../octoflow-examples/src/brain- runnable memory examples.../octoflow-protocols- memory contract types.
Validate
npm run -w octoflow-brain lint
npm run -w octoflow-brain typecheck
npm run -w octoflow-brain test
npm run -w octoflow-brain pack:smokeSQLite-backed tests must stay isolated from real user databases. Prefer :memory: for behavior tests; use createSqliteTestPath() from src/__tests__/test-fixtures.ts when a test must verify file-backed persistence or migrations. External vector and embedder adapters should be tested with injected fetch fixtures rather than live Qdrant, Chroma, Ollama, or hosted embedding services.
Status
The npm package is versioned as 1.0.0, but the memory policies, scoring heuristics, and production presets are still marked beta while real-world recall patterns settle. Pin exact versions, run the package benchmarks against your own corpus, and read ../../CHANGELOG.md before depending on it in production.
