@mastra/mongodb 1.6.0 → 1.6.1-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,97 @@
1
1
  # @mastra/mongodb
2
2
 
3
+ ## 1.6.1-alpha.0
4
+
5
+ ### Patch Changes
6
+
7
+ - **Refactored Observational Memory into modular architecture** ([#14453](https://github.com/mastra-ai/mastra/pull/14453))
8
+
9
+ Restructured the Observational Memory (OM) engine from a single ~3,800-line monolithic class into a modular, strategy-based architecture. The public API and behavior are unchanged — this is a purely internal refactor that improves maintainability, testability, and separation of concerns.
10
+
11
+ **Why** — The original `ObservationalMemory` class handled everything: orchestration, LLM calling, observation logic for three different scopes, reflection, buffering coordination, turn lifecycle, and message processing. This made it difficult to reason about individual behaviors, test them in isolation, or extend the system. The refactor separates these responsibilities into focused modules.
12
+
13
+ **Observation strategies** — Extracted three duplicated observation code paths (~650 lines of conditionals) into pluggable strategy classes sharing a common `prepare → process → persist` lifecycle via an abstract base class. The correct strategy is selected automatically based on scope and buffering configuration.
14
+
15
+ ```
16
+ observation-strategies/
17
+ base.ts — abstract ObservationStrategy + StrategyDeps interface
18
+ sync.ts — SyncObservationStrategy (thread-scoped synchronous)
19
+ async-buffer.ts — AsyncBufferObservationStrategy (background buffered)
20
+ resource-scoped.ts — ResourceScopedObservationStrategy (multi-thread)
21
+ index.ts — static factory: ObservationStrategy.create(om, opts)
22
+ ```
23
+
24
+ ```ts
25
+ // Internal usage — strategies are selected and run automatically:
26
+ const strategy = ObservationStrategy.create(om, {
27
+ record,
28
+ threadId,
29
+ resourceId,
30
+ messages,
31
+ cycleId,
32
+ startedAt,
33
+ });
34
+ const result = await strategy.run();
35
+ ```
36
+
37
+ **Turn/Step abstraction** — Introduced `ObservationTurn` and `StepContext` to model the lifecycle of a single agent interaction. A Turn manages message loading, system message injection, record caching, and cleanup. A Step handles per-generation observation, activation, and reflection decisions. This replaced ~580 lines of inline orchestration in the processor with ~170 lines of structured calls.
38
+
39
+ ```ts
40
+ // Internal lifecycle managed by the processor:
41
+ const turn = new ObservationTurn(om, memory, { threadId, resourceId });
42
+ await turn.start(messageList, writer); // loads history, injects OM system message
43
+
44
+ const step = turn.step(0);
45
+ await step.prepare(messageList, writer); // activate buffered, maybe reflect
46
+ // ... agent generates response ...
47
+ await step.complete(messageList, writer); // observe new messages, buffer if needed
48
+
49
+ await turn.end(messageList, writer); // persist, cleanup
50
+ ```
51
+
52
+ **Dedicated runners** — Moved observer and reflector LLM-calling logic into `ObserverRunner` (194 lines) and `ReflectorRunner` (710 lines), separating prompt construction, degenerate output detection, retry logic, and compression level escalation from orchestration. `BufferingCoordinator` (175 lines) extracts the static buffering state machine and async operation tracking.
53
+
54
+ **Processor** — Added `ObservationalMemoryProcessor` implementing the `Processor` interface, bridging the OM engine with the AI SDK message pipeline. It owns the decision of _when_ to buffer, activate, observe, and reflect — while the OM engine owns _how_ to do each operation.
55
+
56
+ ```ts
57
+ // The processor is created automatically by Memory when OM is enabled.
58
+ // It plugs into the AI SDK message pipeline:
59
+ const memory = new Memory({
60
+ storage: new InMemoryStore(),
61
+ options: {
62
+ observationalMemory: {
63
+ enabled: true,
64
+ observation: { model, messageTokens: 500 },
65
+ reflection: { model, observationTokens: 10_000 },
66
+ },
67
+ },
68
+ });
69
+
70
+ // For direct access to the OM engine (e.g. for manual observe/buffer/activate):
71
+ const om = await memory.omEngine;
72
+ ```
73
+
74
+ **Unified OM engine instantiation** — Replaced the duplicated `getOMEngine()` singleton and per-call `createOMProcessor()` engine creation with a single lazy `omEngine` property on the `Memory` class. This eliminates config drift between the legacy `getContext()` API and the processor pipeline — both now share the same `ObservationalMemory` instance with the full configuration.
75
+
76
+ ```ts
77
+ // Before (casting required, config could drift):
78
+ const om = (await (memory as any).getOMEngine()) as ObservationalMemory;
79
+
80
+ // After (typed, single shared engine):
81
+ const om = await memory.omEngine;
82
+ ```
83
+
84
+ **Improved observation activation atomicity** — Added conditional WHERE clauses to `activateBufferedObservations` in all storage adapters (pg, libsql, mongodb) to prevent duplicate chunk swaps when concurrent processes attempt activation simultaneously. If chunks have already been cleared by another process, the operation returns early with zero counts instead of corrupting state.
85
+
86
+ **Compression start level from model context** — Integrated model-aware compression start levels into the `ReflectorRunner`. Models like `gemini-2.5-flash` that struggle with light compression now start at compression level 2 instead of 1, reducing wasted reflection retries.
87
+
88
+ **Pure function extraction** — Moved reusable helpers into `message-utils.ts`: `filterObservedMessages`, `getBufferedChunks`, `sortThreadsByOldestMessage`, `stripThreadTags`. Eliminated dead code including `isObserving` DB flag, `countMessageTokens`, `acquireObservingLock`/`releaseObservingLock`, and ~10 cascading dead private methods.
89
+
90
+ **Cleanup** — Dropped `threadIdCache` (pointless memoization), removed `as any` casts for private method access (made methods properly public with `@internal` tsdoc), replaced sealed-ID-based tracking with message-level `metadata.mastra.sealed` flag checks.
91
+
92
+ - Updated dependencies [[`7302e5c`](https://github.com/mastra-ai/mastra/commit/7302e5ce0f52d769d3d63fb0faa8a7d4089cda6d)]:
93
+ - @mastra/core@1.16.1-alpha.1
94
+
3
95
  ## 1.6.0
4
96
 
5
97
  ### Minor Changes
@@ -3,7 +3,7 @@ name: mastra-mongodb
3
3
  description: Documentation for @mastra/mongodb. Use when working with @mastra/mongodb APIs, configuration, or implementation.
4
4
  metadata:
5
5
  package: "@mastra/mongodb"
6
- version: "1.6.0"
6
+ version: "1.6.1-alpha.0"
7
7
  ---
8
8
 
9
9
  ## When to use
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "1.6.0",
2
+ "version": "1.6.1-alpha.0",
3
3
  "package": "@mastra/mongodb",
4
4
  "exports": {},
5
5
  "modules": {}
package/dist/index.cjs CHANGED
@@ -14,7 +14,7 @@ var evals = require('@mastra/core/evals');
14
14
 
15
15
  // package.json
16
16
  var package_default = {
17
- version: "1.6.0"};
17
+ version: "1.6.1-alpha.0"};
18
18
  var MongoDBFilterTranslator = class extends filter.BaseFilterTranslator {
19
19
  getSupportedOperators() {
20
20
  return {
@@ -5786,8 +5786,11 @@ var MemoryStorageMongoDB = class _MemoryStorageMongoDB extends storage.MemorySto
5786
5786
  const newTokenCount = existingTokenCount + activatedTokens;
5787
5787
  const existingPending = Number(doc.pendingMessageTokens || 0);
5788
5788
  const newPending = Math.max(0, existingPending - activatedMessageTokens);
5789
- await collection.updateOne(
5790
- { id: input.id },
5789
+ const updateResult = await collection.updateOne(
5790
+ {
5791
+ id: input.id,
5792
+ bufferedObservationChunks: { $exists: true, $ne: null, $not: { $size: 0 } }
5793
+ },
5791
5794
  {
5792
5795
  $set: {
5793
5796
  activeObservations: newActive,
@@ -5799,6 +5802,16 @@ var MemoryStorageMongoDB = class _MemoryStorageMongoDB extends storage.MemorySto
5799
5802
  }
5800
5803
  }
5801
5804
  );
5805
+ if (updateResult.modifiedCount === 0) {
5806
+ return {
5807
+ chunksActivated: 0,
5808
+ messageTokensActivated: 0,
5809
+ observationTokensActivated: 0,
5810
+ messagesActivated: 0,
5811
+ activatedCycleIds: [],
5812
+ activatedMessageIds: []
5813
+ };
5814
+ }
5802
5815
  const latestChunkHints = activatedChunks[activatedChunks.length - 1];
5803
5816
  return {
5804
5817
  chunksActivated: activatedChunks.length,