mastra-observational-memory
Skill2 starsChanged 29 days agoApache-2.0View on GitHub
Enable and tune Observational Memory (OM) in Mastra: background Observer and Reflector agents compress old messages into a dense observation log that replaces raw history, keeping the context window small and the prompt prefix cacheable. Use this skill whenever the user has long-running agent threads, tool-heavy sessions that blow the context window, rising token cost from history, prompt cache misses, or asks whether to use OM, message history, or semantic recall. Triggers on observationalMemory, Observational Memory, OM, Observer, Reflector, observation.messageTokens, reflection.observationTokens, bufferTokens, blockAfter, activateAfterIdle, shareTokenBudget, retrieval recall tool, Extractor, manageWorkingMemory, ModelByInputTokens, skillResultRedactor, memory.settled, OM_DEBUG, data-om-status. Also triggers for coding agents, browser agents, or support agents whose conversations run for hours.
- Reads credentials
In this repository46 other files it gives its agents.
- mastra-a2a-acpSkill
- mastra-agent-approval-hitlSkill
- mastra-agentic-uiSkill
- mastra-agent-skillsSkill
- mastra-agentsSkill
- mastra-authSkill
- mastra-browserSkill
- mastra-build-playbookSkill
- mastra-channelsSkill
- mastra-classifierSkill
- mastra-cli-apiSkill
- mastra-client-sdkSkill
- mastra-datasets-experimentsSkill
- mastra-deploymentSkill
- mastra-evalsSkill
- mastra-file-based-agentsSkill
- mastra-framework-integrationSkill
- mastra-guideSkill
- mastra-harnessSkill
- mastra-knowledgeSkill
- mastra-mcpSkill
- mastra-memorySkill
- mastra-migrationsSkill
- mastra-modelsSkill
- mastra-multi-agentSkill
- mastra-observabilitySkill
- mastra-platformSkill
- mastra-processors-guardrailsSkill
- mastra-project-setupSkill
- mastra-ragSkill
- mastra-schedulesSkill
- mastra-semantic-recallSkill
- mastra-serverSkill
- mastra-signalsSkill
- mastra-storageSkill
- mastra-streamingSkill
- mastra-structured-outputSkill
- mastra-studio-editorSkill
- mastra-tool-integrationsSkill
- mastra-toolsSkill
- mastra-troubleshootingSkill
- mastra-vector-storesSkill
- mastra-voiceSkill
- mastra-workflowsSkill
- mastra-workflow-suspend-resumeSkill
- mastra-workspace-sandboxSkill
The file
We split this skill into the rules it gives an agent
9 rules. About 0 are common, 2 are distinctive, and 7 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈2
Distinctive · estimate
This author's own choices. Worth a look.
7
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 14
Keep long agent conversations coherent and cheap by replacing old raw messages with a compressed, append-only observation log.
- Very specific: line 56
Reflections: when observations pass reflection.observationTokens (default 40,000), the Reflector rewrites the whole log into a smaller one.
- Very specific: line 102
Verify the API: If node_modules/@mastra/ exists, read node_modules/@mastra/memory/dist/docs/ and the installed types.
- Very specific: line 103
Confirm storage: Use one of the six supported adapters, set on Mastra or on Memory.
- Very specific: line 105
Pick models: Keep 'auto', or pin a fast model with a 128K+ window.
- Very specific: line 110
Decide failure policy: Default failurePolicy: 'abort'.
- Distinctive: line 143
Huge first turn on an old thread: All stored messages load until the first observation completes.
- Very specific: line 151
Skill instructions re-observed on every use: Add hooks: { beforeObservation: skillResultRedactor() } from @mastra/memory/hooks.
- Very specific: line 162
Call sites that always pass resource and thread
≈ “Common” is an estimate: at least 1 in 5 of the 408,460 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Mastra Observational Memory
Keep long agent conversations coherent and cheap by replacing old raw messages with a compressed, append-only observation log.
When to use
- Threads run long enough to approach the model's context window
- Tool results are large (browser snapshots, file reads) and old ones are noise
- Prompt caching matters and a sliding
lastMessageswindow keeps breaking it - Working memory is being abused to hold growing summaries or event logs
- Several users share a thread and per-user facts must survive history eviction
- Choosing between OM, message history, and semantic recall
- Debugging OM thresholds, buffering, retries, or the
recalltool
When NOT to use
- Short, single-session chats that fit in
lastMessages(usemastra-memory) - Threads, resources, working memory basics, memory APIs (use
mastra-memory) - Searching raw past messages by embedding similarity without OM (use
mastra-semantic-recall) - Storage adapter setup (use
mastra-storage); OM supports only some adapters - Shared facts across all threads of a user as a graph (use
mastra-knowledge) - One-off summaries of a finished thread (use
memory.summarizeThread()inmastra-memory)
Required inputs
- The storage adapter: must be
@mastra/libsql,@mastra/pg,@mastra/mongodb,@mastra/mysql,@mastra/convex, or@mastra/oracledb - Whether every call can pass a stable
thread(required in the default thread scope) - The Observer/Reflector model, or
'auto', and which provider keys exist - Whether the agent relies on prompt caching (sets idle activation)
- Whether the agent needs exact wording later (retrieval mode)
- Values to extract into structured metadata, if any
The framework: observe, reflect, retain
Three tiers live in context:
- Recent messages: raw history for the current task.
- Observations: dated notes the Observer writes when unobserved messages pass
observation.messageTokens(default 30,000). Typical compression is 5x to 40x. - Reflections: when observations pass
reflection.observationTokens(default 40,000), the Reflector rewrites the whole log into a smaller one.
import { Agent } from '@mastra/core/agent'
import { LibSQLStore } from '@mastra/libsql'
import { Memory } from '@mastra/memory'
const memory = new Memory({
storage: new LibSQLStore({ id: 'memory-storage', url: 'file:./memory.db' }),
options: {
observationalMemory: {
model: 'openai/gpt-6-luna',
},
},
})
export const agent = new Agent({
id: 'memory-agent',
name: 'Memory Agent',
instructions: 'You are a helpful assistant.',
model: 'openai/gpt-6-luna',
memory,
})
await agent.generate('Remember that my favorite color is blue.', {
memory: { resource: 'user-123', thread: 'conversation-123' },
})observationalMemory: true uses model: 'auto'. Async buffering is on by default: the Observer pre-computes chunks every ~6k tokens (bufferTokens: 0.2), and at 30k they activate instantly, leaving ~6k tokens of raw history (bufferActivation: 0.8). Raw history oscillates between about 6k and 30k tokens; the log stays near 40k.
Choosing a memory layer
| Need | Use |
| Verbatim record of a short conversation | Message history (lastMessages) |
| Small, structured user facts | Working memory |
| Long-running threads, stable cacheable prompt | Observational memory |
| Find exact old wording by meaning | Semantic recall, or OM with retrieval: { vector: true } |
The docs state OM replaces both working memory and message history for long event logs, with greater accuracy and lower cost than semantic recall.
Workflow
- Verify the API. If
node_modules/@mastra/exists, readnode_modules/@mastra/memory/dist/docs/and the installed types. Otherwise fetchhttps://mastra.ai/docs/memory/observational-memory.mdandhttps://mastra.ai/reference/memory/observational-memory.md. Trust these over memory. OM was added in@mastra/memory@1.1.0. - Confirm storage. Use one of the six supported adapters, set on Mastra or on
Memory. - Enable OM.
observationalMemory: true, or an object withmodel. RemovelastMessagesreliance: it does nothing under OM. - Pick models. Keep
'auto', or pin a fast model with a 128K+ window. Useobservation.modelandreflection.modelto split roles (never with a top-levelmodel). - Pass a thread on every call. Thread scope throws without one. Send only the new message from clients.
- Tune for caching. Set
activateAfterIdle: 'auto', andactivateOnProviderChange: trueif the agent switches models. - Add retrieval if exact details matter.
retrieval: trueregisters arecalltool;{ vector: true }adds semantic search using the Memory's vector store and embedder. - Add extractors or working memory management.
observation.extract: [new Extractor({...})], orobservation.manageWorkingMemory: true. - Decide failure policy. Default
failurePolicy: 'abort'. Use'continue'on both stages if a turn must survive an Observer outage. - Shut down cleanly.
await memory.settled()before closing storage. Run every process against the same storage and PubSub backend with leases. - Observe it. Studio's Memory tab shows token bars and the active log. Debug with
OM_DEBUG=1(writesom-debug.log).
Deep dive: thresholds, buffering, and activation
| Setting | Default | Meaning |
observation.messageTokens | 30_000 | Unobserved tokens that trigger observation |
observation.bufferTokens | 0.2 | Buffer interval (fraction of messageTokens or absolute). false disables all async buffering |
observation.bufferActivation | 0.8 | Fraction removed on activation (ratio) or tokens kept (1000 or more) |
observation.blockAfter | 1.2 | Synchronous observation when buffering falls behind. 1 observes at the threshold |
reflection.observationTokens | 40_000 | Observation tokens that trigger reflection |
reflection.bufferActivation | 0.5 | Start background reflection at this fraction |
reflection.blockAfter | 1.2 | Synchronous reflection safety net |
activateAfterIdle | none | Activate buffered observations after idle time: ms, '5m', 'auto', or { default: 'auto', anthropic: '1h' } |
activateOnProviderChange | false | Activate when the actor model changes |
shareTokenBudget | false | Pool both budgets. Requires observation.bufferTokens: false |
observation.observeOnContextOverflow | true | On provider overflow, observe pending messages and retry once. Keep it on |
With 'auto', idle TTL follows the provider: 5 minutes for Anthropic and OpenRouter, 1 hour for DeepSeek, 24 hours for Gemini, 2 hours for Groq, 1 hour or 5 minutes for OpenAI depending on model and promptCacheRetention. A per-message Anthropic cacheControl.ttl is not read; mirror it in the object form.
Through new Memory(...), only the top-level activateAfterIdle and activateOnProviderChange apply. The nested observation.* and reflection.* variants apply only with the standalone ObservationalMemory class.
Failure patterns
- "threadId required" error. Thread scope needs a thread on every call. Pass
memory: { resource, thread }. - Unsupported adapter. OM fails on adapters outside libSQL, PostgreSQL, MongoDB, MySQL, Convex, OracleDB. Switch, or route the
memorydomain withmastra-storagecomposite storage. - Tuning
lastMessageswith OM on. Ignored: OM replaces history and the MessageHistory processor is skipped. Tuneobservation.messageTokens. - Huge first turn on an old thread. All stored messages load until the first observation completes. Expect a one-time cost.
shareTokenBudget: truefails on first use. Async buffering is on. Setobservation.bufferTokens: false. Some invalid options validate on first memory operation, not at construction.- Lost observations in tests or scripts. Background buffering was cut off.
await memory.settled()beforestore.close(). - Multi-process deployment double-observes. The mutex is per process. Share one PubSub backend with leases and one storage across processes.
scope: 'resource'. Deprecated: worse caching, mixed context, slow. Use thread scope plusretrieval: trueand resource-scoped working memory.ModelByInputTokensthrows on big inputs. Input exceeded the largestupTotier; OM aborts via TripWire and returns empty text. Cover the full range.- Reflections stay above threshold. Detail-preserving Reflector model. Pick a condensing model such as
deepseek/deepseek-flashforreflection.model. - Text-only Observer rejects images. Set
observation.observeAttachments: falseor'auto'. - Skill instructions re-observed on every use. Add
hooks: { beforeObservation: skillResultRedactor() }from@mastra/memory/hooks. - Treating
afterObservationas a redaction boundary. It rewrites only observation text, not extractor results. Redact inbeforeObservation.
Output format
A finished OM delivery contains:
MemorywithobservationalMemoryand a supported storage adapter- Model choice (
'auto'or pinned) with provider keys in.env.example - Call sites that always pass
resourceandthread - Idle activation and failure policy chosen deliberately
memory.settled()in shutdown paths and tests- Evidence: Studio Memory tab or
data-om-*stream parts showing an observation cycle
Reference files
references/api.md- EveryobservationalMemoryoption with defaults, Extractor API, recall tool parameters, stream data parts, standalone class.references/examples.md- Defaults, cache-friendly tuning, retrieval with resource working memory, extractors with hooks, tiered models.references/checklist.md- Pre-production checklist for OM.
Live docs
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

