npm / @mastra/memory
@mastra/memory
What changed in @mastra/memory 1, from its official release notes, upgrade guides and advisories. Sources checked 2026-11-30.
23 breaking3 security3 deprecations38 new APIs and options5 performance27 behavior and defaults1 tooling65 fixes and other
See which of these apply to your code, ranked, in your agent:
npx @unstale/cli init@mastra/memory 1165 changes
Breaking changes 23
When observational memory manages working memory, the observer must write the section or UNCHANGED; a missing section is recorded as an extraction failure.
Setting experimental_subconscious now throws and directs developers to attach Knowledge to the agent instead.
The Memory knowledge option is removed and throws when set, except that knowledge: false remains accepted.
Knowledge requires scope declarations; runs holding undeclared scopes fail, and an empty declaration declares none.
KnowledgeSemanticIndexCoordinator remains exported for older code to load, but constructing it throws.
Queue and steering APIs accept scopes; queued or steering messages with different scopes start their own run after the current run instead of joining it.
Messages with scopes cannot be queued to a thread owner running in another process; sendMessage rejects, while messages without scopes still join that owner's run.
Subconscious remains exported for older code to load, but constructing it throws.
Knowledge tools are off by default; tools: true enables read and write tools, while tools: { read: true } enables read tools only.
Deleting a thread now also deletes its live event stream from Mastra pubsub, instead of leaving it until expiry or indefinitely.
@mastra/memory now requires @mastra/core 1.80.0 or newer; upgrade core first if your package manager reports a peer conflict.
memory.summarizeThread() now throws when retries are exhausted on empty Observer output instead of returning an empty summary.
Synchronous observation and reflection stop with a cancelled run and leave its messages unobserved for a later cycle; async buffering and background reflection continue, and settled() still waits for them.
Text-only Observer replies, including refusals, are retried like empty replies; after retries run out, failurePolicy decides the turn. Replies containing only other Observer sections remain accepted.
summarizeConversation() now throws when retries are exhausted on empty Observer output instead of returning an empty summary.
Curator messages no longer appear in the parent conversation because the curator keeps its messages on its own thread.
A multiplier blockAfter now scales a per-thread messageTokens override instead of the instance threshold.
Merges are rejected with HTTP 400 when the storage adapter does not support atomic merges, rather than silently replacing the record.
Observational memory no longer sends Observer attachments that the agent recorded as unavailable, while retaining their transcript lines.
On existing threads, memory filters input to new trailing user messages and outcomes for still-pending stored tool calls; unstored messages before the last assistant message are removed.
The observer receives instructions after the conversation, and system reminders and signals are labeled by tag instead of being treated as user statements.
When observeAttachments is omitted, Observational Memory now forwards only images and PDFs; set it to true to forward every attachment type.
The tool now returns immediately with a reply ID and pending status, then delivers answers later as correlated partial and terminal replies.
Security 3
Explains whether a run can reach a scope or page and why; it is host-only and should not be exposed through agent tools or unauthenticated routes.
The dependency was bumped to pick up a fix for a quadratic-time denial of service in its SVG parser.
recall with partIndex now respects retrieval scope and rejects out-of-scope cursors, preventing access to message content outside the configured scope.
Deprecations 3
The 'resource' scope is deprecated and logs a one-time warning; remove scope for the default thread scope and use retrieval or resource-scoped working memory for cross-thread continuity.
Soft-deprecated in favour of messageHistory; remains supported and can be combined with it.
The legacy recall option is deprecated; explicit signal visibility settings take precedence, while omitted exclusions preserve existing history defaults.
New APIs and options 38
Knowledge provides keyword search by default; configuring a vector store and embedder blends keyword and semantic results, with semantic hits checked against run read access before ranking.
Knowledge and its option and result types are exported from @mastra/core/knowledge; attach it to an Agent with knowledge and scopes.
Observations using MongoDB Automated Embedding are indexed under memory_observations_selfembed.
Reports each committed write made through knowledge.getStorage(), including tool writes, by ID for live UIs; pages should be re-read under the viewer's read scope before display.
Returns what holders of specified scopes can read, for host code that reads the store directly.
Scope declarations can include a displayLabel for UIs, and scopeDeclaration returns a declaration's display fields.
Messages can carry scopes; a message with scopes different from the running run waits for it to end, then starts its own run in the same conversation.
Failure markers in streams and persisted messages, and tripwire metadata, now include observer span references and failure classifications when Observational Memory interrupts an agent.
Observational memory's auto model can use request credentials to decide whether to prefer Gemini instead of relying on the server's Google API key.
Core exports embedV4, and Memory and RAG support AI SDK v7 v4 embedding models while preserving v1, v2, and v3 behavior.
Accepts an optional threadId and resourceId scope to wait only for that thread's observational memory background work; without a scope it still waits for all work.
Set observationalMemory.observation.observeOnContextOverflow to false to turn off automatic recovery from context overflow.
Pass force: true to observe pending messages regardless of the threshold for that call only.
getStatus() now returns observationBlockAfter and inAsyncObservationBand to expose the observation blocking threshold and async observation band.
Lets applications override the model selected by automatic model resolution for a provider.
Adds a method to merge partial working-memory updates from application code; PostgreSQL performs deep merges in a row-locked transaction when scope is resource.
Previews the model ID that automatic model selection would pick, for uses such as settings UIs.
Turns the automatically picked model ID into a model, allowing auto resolution to use application credentials and routing.
Accepts mode: 'merge' for HTTP working-memory updates, merging partial updates rather than replacing the record.
Pass an object with provider-specific TTLs and a default to set observational memory idle activation delays for providers whose prompt cache TTL 'auto' can't detect.
Recall can page through original observation groups around a search hit, including groups condensed by reflection and buffered groups not yet activated; existing records need no re-indexing.
Added viewAttachment to the observational memory recall tool. When passed with cursor and partIndex, it shows the attachment itself to the model instead of only describing it.
Allows the agent turn to finish after observation still fails after retries when set to 'continue'; the default is 'abort'.
Sets how many times a failed Observer call is retried; the default is 8.
Allows the agent turn to finish after reflection still fails after retries when set to 'continue'; the default is 'abort'.
Sets how many times a failed Reflector call is retried; the default is 8.
Integrations that build the observations context themselves can use this function to get the context prompt for a scope.
Opt out of filtering by setting this memory option per call on memory.options or agent-wide in the memory constructor options; input is processed as supplied and unstored messages are saved.
Adds token-budgeted conversation history that counts the complete prompt and drops the oldest remembered messages in chunks, while preserving the current turn and persisting a per-thread boundary.
Adds a ready-made beforeObservation hook that replaces Agent Skills tool results with a placeholder while retaining tool calls for Observational Memory.
Copies a thread without returning message content, avoiding loading every message payload into the Node heap.
Callers can hide all recognized stored signal types, include all signals, or select types to omit without changing saved messages or model context.
Transfers a thread and its messages to a different resourceId while preserving the thread's createdAt timestamp; semantic recall vectors are migrated when enabled.
A default storage implementation backs thread resource reassignment for memory storage adapters.
Add an optional flag to skip counting matching messages when totals are unnecessary; it defaults to true, and paginated reads fetch one extra row to determine hasMore.
Add awaited transform hooks before and after observation and reflection to filter or rewrite data before model calls or persistence. Errors fail the cycle before transformed text is committed.
Enable the experimental reminder sidekick on observational memory by configuring experimental_subconscious with a Subconscious instance.
Knowledge nodes across storage adapters can now have an optional bounded description, written through a dedicated curator tool.
Performance 5
PostgreSQL observation tables now receive resource_id and thread_id metadata indexes to prevent observational memory search from scanning the whole vector table; with PgVector disableInit, create the indexes yourself.
Each cycle now embeds and stores only the observation group it adds, rather than re-embedding every earlier group.
Creating observational memory per request no longer causes growing CPU usage and gradual slowdown on Node.js versions before 24.
Thread copying now happens in the database first, with messages read back afterward because the caller requested them; the existing signature and return value remain.
CHANGELOG.md is no longer included in distributed npm files, reducing package size.
Behavior and default changes 27
Messages embedded during an agent run now carry thread metadata, so recall filters on thread attributes can find them.
Observational Memory labels user signals with the sender's name when messages include attributes.name; messages without attributes retain the plain User label.
Enable pinnedContext to deliver pinned pages every turn and add knowledge_pin; it accepts true or maxPins and maxTokens settings.
Agent scopes are plain type:value strings identifying who a run is; what it may read or write is determined by the consumer of those scopes.
When message scopes differ from the running run, sendSignal reports a blocked action with reason scope-mismatch and the run ID.
Observational Memory semantic search works with a vector store that generates embeddings itself, so an embedder is not required; configurations that pass an embedder continue working.
If storing a group's vector fails, the cycle still completes and logs a warning; the group is not retried.
When working memory uses agentManaged: false, instructions now tell agents that memory updates automatically after each response; only readOnly: true indicates they cannot update it.
Empty or whitespace-only Observer replies are retried with backoff up to the configured retry limit; after exhaustion, lastObservedAt stays unchanged and failurePolicy decides how the turn proceeds.
Observer, Reflector, or extraction model calls that produce no output for five minutes are aborted and retried; streaming replies are not cut off by total duration.
Moving a thread to another resource now also moves its observational memory recall entries, so searches under the new resource can find past observations.
When a provider rejects a request for exceeding its context window, Observational Memory observes pending messages and retries once with smaller context. Requires a compatible @mastra/core version.
With async buffering, unobserved messages can grow beyond messageTokens before a step blocks; the default is 1.2, and setting it to 1 preserves synchronous observation at the threshold.
The token budget now limits previous observations on every observation path; zero omits them, and the default false sends the full previous observations.
Buffering, activation, observation, reflection, and config-override writes for a thread or resource run one at a time within a process; due reflections take priority, and stuck writes stop blocking later writes after 60 seconds.
Default Reflector instructions now preserve concrete facts, changes of mind, and explicit statements of not knowing, refusing, or never having done something; custom instructions are still appended.
The model, observation.model, and reflection.model defaults change to 'auto'. Observer and Reflector models resolve independently from the agent's main model on every call; set a concrete model ID to keep a fixed model.
When context remains above the messageTokens threshold, observational memory activates buffered observations and synchronously observes remaining messages to avoid oversized prompts.
With retrieval enabled, agents receive recall guidance from the first turn, including in read-only runs, covering search, paging, source-message confirmation, and how to interpret user statements and reflected groups.
Search results are dated and oldest-first, mark possible gaps between hits, use short references for hits already in agent context, and choose query-relevant excerpts for shortened groups.
Annotates additional date formats with relative time, including dates with times, ranges, month or year dates, and dates with a year inside observations; dates without a year remain unchanged.
Messages that were not observed are retried on a later turn, while a cancelled turn always stops regardless of failure policy.
Retry a temporary provider failure once, independently of maxRetries; a failed extraction does not block the turn.
Thread-scoped observations are described as memory of the current conversation, helping agents reuse IDs, artifacts, and tool results as belonging to that session.
Token-routed models selected with ModelByInputTokens now receive the 100,000-token output default.
Observers retain completed tool-call arguments and outcomes, use bounded structure-aware previews for large arguments, and include arguments in token accounting; the default non-multimodal result-text cap is 5,000 tokens.
Observer and reflector passes now trace as memory operations, appearing as memory: observe and memory: reflect.
Tooling 1
The shipped map now lists public exports by name and points to their type definition and implementation when resolvable, helping tools look up exports.
Fixes and other changes 65
When retrieval is on, reflection now reflects or keeps each observation group whole, preventing stray context markers and observations that cannot be traced to source messages.
Concurrent updates from different threads no longer overwrite each other when working memory uses the default resource scope; the lock is held per Memory instance.
When a run is stopped during observation, the abort now includes its reason instead of only the generic abort message.
Each message now has one vector row per chunk, keyed by message id; saving it again replaces its rows, avoiding duplicate rows that reduce distinct recall results.
Recall now returns visible message content while preserving text and tool part indices, and paging no longer stops early on messages containing only reasoning.
The observations block now closes immediately after the last observation, preventing current-task and suggested-response hints from being read as observations.
With vector retrieval enabled, new observations are now indexed in the vector store.
Recovery moves the rest of a run's response to a new message so a later context overflow in the same run can also be observed and retried.
The continuation hint is now added only after observations have actually replaced messages, preventing it from appearing on threads with no observations.
When a durable turn resumes on another worker, the current user request and delayed tool results remain in the prompt, and completed live background results are preserved when reconciling stored messages.
Token counting and the observer now handle structured errors in failed tool calls stored in conversation history, allowing Observational Memory to continue on later turns.
@mastra/memory now loads in Node ESM without failing to resolve probe-image-size/sync.
Per-request false and { enabled: false } overrides now disable observational memory for that request while preserving message history and subsequent enabled runs.
After the model answers a request that memory has observed, the request leaves the prompt and observations stand in for it for the rest of the run.
Observer sections written on one line are now parsed instead of ignored.
In resource scope, omitted threads no longer have their cursor advanced; their messages can be observed later, and replies naming none of the requested threads are retried.
Working-memory data no longer leaks into recalled history after raw message writes or partial edits; message edits index the visible text retained after the edit.
Gemini 3 turns with working memory no longer fail when continuing after a client tool result; saved tool-call history now replays with the required signature.
Threshold-triggered observations use the step's main model rather than unexpectedly falling back to Gemini; with canUseProvider set and no main model, auto returns a clear error.
Assistant message identity is preserved during observational memory feedback continuations.
The current turn's input messages and latest step output stay in the prompt until the turn ends, preventing observation between steps from removing unread user input or tool results.
A recovering worker starts a new message instead of merging the rest of an agent reply into an already-observed message; malformed observed-message lists no longer crash the turn.
Now waits for buffered reflections to finish writing before it resolves.
In AgentController sessions, reminder checks, memory questions, and follow-ups run on the reminder's own thread so reminders reach the main agent.
Long numbers are now counted accurately, so memory and token limits trigger at the right time. Estimates saved on existing messages are recalculated.
The end marker is written to the message carrying the cycle's start marker, preventing it from disappearing on save or overwriting the agent's streamed response.
Observer, reflector and fallback model lists no longer cause type checking complexity to grow with the number of model IDs.
Concurrent buffering, activation, observation, and reflection no longer lose or duplicate context across processes and durable agent steps; stale work after memory clearing or thread deletion is discarded.
Observations are kept in event order so outdated state is not recorded as newer than later user instructions.
Live scorers now receive every response message across suspend and resume segments under the original runId, including tool calls removed from agent context by observational memory.
Semantic recall no longer misses a turn's new user message when background buffering picks it up on the first step.
An empty working-memory result no longer replaces stored working memory; Mastra retries extraction while preserving other extracted values such as the thread title.
When an observational memory error stops a run, the user message and tool results from completed steps are saved first.
Persistence and idle buffering now use the terminal message list accepted by the processor pipeline rather than the list captured by the observation turn.
When a stored model output is null, observational memory falls back to the actual completed tool result so the Observer, token counting, and recall see it.
Very long lines are truncated and retained, repeated short lines share a bounded budget, and genuinely repetitive output remains rejected.
Failed or partial observer and reflector calls retry from the original prompt, so only complete replies are saved.
Reflection retry attempts are marked as retrying, preventing the agent controller from cancelling a run before a stronger-compression retry finishes.
recall({ vectorSearchString }) and its message writes work with vector stores that generate embeddings themselves, without a configured embedder; thread cloning and resource transfers also preserve semantic-recall vectors.
The recall tool now preserves attachment references, including media type and stored URL or provider file ID, so agents can reuse earlier attachments.
Saving messages no longer leaves a thinking-only step behind after hiding updateWorkingMemory, and the hidden call no longer reappears in later prompts.
Returns 'No working memory data available.' instead of working memory instructions containing 'null' when no working memory has been saved.
Include the Mastra error ID so storage failures identify which operation failed instead of showing only the raw driver message.
A later observation group is parsed and shown in reflections with its own ID and range when an earlier truncated group quoted an observation-group tag inline.
Fixes relative dates being off by a day across time zones and daylight-saving changes, and avoids marking an action dated for the current day as likely already happened.
When observation.manageWorkingMemory is enabled, updates that do not match the configured schema are skipped and the previous working memory is kept.
CommonJS consumers can use memory token counting without ESM loading errors.
Thread deletion waits for in-flight observational-memory work, and completed cycles no longer recreate memory records or leave searchable vectors.
Observer and Reflector agents use the logger configured on the Mastra instance instead of the default ConsoleLogger.
Ended turns are discarded so the next step starts a fresh one, and finalization persists remaining messages instead of failing the agentic loop.
Observer and Reflector temperature defaults are applied only to models known to support temperature; explicit modelSettings.temperature values remain preserved.
Reflected observation ranges are no longer saved in reverse order, and every source range used by a reflected section is preserved.
Observational Memory no longer replaces manually renamed thread titles; explicitly regenerating a title or writing a title with pin false enables automatic title updates.
Idle observation buffers safe completed messages even when the newest unobserved message has an incomplete tool call, avoiding overwriting incoming client tool results with older history.
Errors no longer hide provider diagnostics returned in a string detail field, including Codex rejection messages.
Traces preserve caller thread identity without assigning a session ID for other observability integrations.
Failure events preserve provider error messages, HTTP status codes, and nested causes instead of showing only generic errors.
Fixed a memory tool reliability issue.
Temporary connection errors during observation indexing now recover without duplicating stored observations.
Transient database connection timeouts are retried instead of failing the buffer operation.
Observer and reflector passes no longer report an output-step-processor entity type, avoiding their runtimes being counted as processor overhead in mastra_processor_duration_ms.
Observational memory prompts no longer appear in stored conversation history.
Tool schemas are more compatible with providers that validate tool definitions server-side.
Experimental memory processing has improved reliability and capacity.
The curator tool now accepts name and kind as optional properties, fixing curation failures with Gemini models.