@mastra/memory 1.41.3-alpha.2 → 1.41.3-alpha.4

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.
@@ -24261,14 +24261,14 @@ function getRetrievalInstructions(scope = "resource", customInstructions, search
24261
24261
  The recall tool works across ALL of this user's conversation threads, not just the current one.
24262
24262
 
24263
24263
  - Use \`mode: "search"\` with a \`query\` to find relevant history, even when you already know the thread. Each result includes its thread ID, observation group ID, and source message range.
24264
- - Use \`mode: "messages"\` for original wording or details behind an observation — pass \`threadId\` to read another thread and a \`cursor\` from the source message range.
24264
+ - Use \`mode: "messages"\` for original wording or details behind an observation \u2014 pass \`threadId\` to read another thread and a \`cursor\` from the source message range.
24265
24265
  - Use \`mode: "threads"\` to list the user's threads (IDs, titles, dates) when you need to discover where something was discussed. Use \`before\`/\`after\` to narrow by date.
24266
24266
 
24267
- **If search results look irrelevant, do not give up.** Search only covers content that has been indexed — a short or recent conversation may exist in raw message history before any observation of it was created. When search returns nothing suitable but the user is clearly referring to a past conversation, call \`mode: "threads"\` to find candidate threads (titles and dates are strong clues), then read them with \`mode: "messages"\`. Use a useful hit as an entry point to the surrounding history rather than treating it as the whole answer.` : `### Choosing a mode
24267
+ **If search results look irrelevant, do not give up.** Search only covers content that has been indexed \u2014 a short or recent conversation may exist in raw message history before any observation of it was created. When search returns nothing suitable but the user is clearly referring to a past conversation, call \`mode: "threads"\` to find candidate threads (titles and dates are strong clues), then read them with \`mode: "messages"\`. Use a useful hit as an entry point to the surrounding history rather than treating it as the whole answer.` : `### Choosing a mode
24268
24268
  The recall tool works across ALL of this user's conversation threads, not just the current one.
24269
24269
 
24270
24270
  - Use \`mode: "threads"\` to list the user's threads (IDs, titles, dates) when you need to discover where something was discussed. Use \`before\`/\`after\` to narrow by date.
24271
- - Use \`mode: "messages"\` when you know the thread — pass \`threadId\` to read another thread, or a \`cursor\` from an observation-group range.
24271
+ - Use \`mode: "messages"\` when you know the thread \u2014 pass \`threadId\` to read another thread, or a \`cursor\` from an observation-group range.
24272
24272
 
24273
24273
  When the user refers to a past conversation you don't have a cursor for, call \`mode: "threads"\` to find candidate threads (titles and dates are strong clues), then read them with \`mode: "messages"\`. Raw history may exist for threads that have no observations yet.` : `### Choosing a mode
24274
24274
  The recall tool is limited to the current conversation thread.
@@ -24293,7 +24293,7 @@ When searches keep returning the same groups, often as already-in-context refere
24293
24293
  "Excerpt already in current context" marks a hit whose text an earlier search result already shows. "Group already in current context" marks a group that is already in your observations or whose source messages are still in the conversation. "Source range overlaps current context" marks a group whose source messages are still in the conversation. Search keeps these references and tries lower-ranked matches to fill the requested number of excerpts. This backfill is bounded: fewer excerpts do not mean history is exhausted. Use the evidence already present rather than repeating the same lookup. You can still ${pagingEnabled ? "page a referenced group" : "read a referenced group's source messages"} when you need all of it, or search again if that context is no longer available.
24294
24294
 
24295
24295
  If search still finds nothing useful, browse raw messages${isResource ? " or discover other threads" : " in this thread"} before concluding the information is unavailable. Raw history may exist for threads that have no observations yet.` : "";
24296
- const base = `## Recall — looking up source messages
24296
+ const base = `## Recall \u2014 looking up source messages
24297
24297
 
24298
24298
  Your memory contains observation groups with IDs and source message ranges, shown as \`## Group\` headings with \`_range: startId:endId\` or as \`<observation-group>\` tags. Use the **recall** tool to recover retained original observations and source messages.
24299
24299
 
@@ -24304,13 +24304,13 @@ Groups marked \`kind="reflection"\` (rendered as \`_kind: reflection_\`) are los
24304
24304
 
24305
24305
  ### When to use recall
24306
24306
  - The user asks you to **repeat, show, or reproduce** something from a past conversation
24307
- - The user asks for **exact content** — code, text, quotes, error messages, URLs, file paths, specific numbers
24307
+ - The user asks for **exact content** \u2014 code, text, quotes, error messages, URLs, file paths, specific numbers
24308
24308
  - Your observations mention something but your memory lacks the detail needed to fully answer (e.g. you know a blog post was shared but only have a summary of it)
24309
24309
  - You want to **verify or expand on** an observation before responding
24310
24310
  - The answer depends on historical dates, order, or duration: verify both event dates and that they refer to the events the user means. Distinguish a plan, an actual start, a later update, and a repeated mention instead of choosing a nearby date from a summary
24311
24311
  - An observation records something the assistant proposed, such as a schedule, date, or plan, and your observations don't show what the user decided. Read the raw messages around it to find the user's decision before treating the proposal as what happened
24312
24312
  - Relevant details are missing, ambiguous, or conflicting in the current observations${isResource ? `
24313
- - The user references another conversation that your observations don't cover — even if you have no observations yet, their other threads may contain it` : ""}
24313
+ - The user references another conversation that your observations don't cover \u2014 even if you have no observations yet, their other threads may contain it` : ""}
24314
24314
 
24315
24315
  **Default to using recall when the user references specific past content.** Your observations capture the gist, not the details. If there's any doubt whether your memory is complete enough, use recall.
24316
24316
 
@@ -24345,17 +24345,17 @@ Each range has the format \`startId:endId\` where both are message IDs separated
24345
24345
  In \`mode: "messages"\`, recall returns **low** detail by default: truncated text and tool names only. Each message shows its ID and each part has a positional index like \`[p0]\`, \`[p1]\`, etc.
24346
24346
 
24347
24347
  - Use \`detail: "high"\` to get full message content including tool arguments and results. This will only return the high detail version of a single message part at a time.
24348
- - Use \`partIndex\` with a cursor to fetch a single part at full detail — for example, to read one specific tool result or code block without loading every part.
24348
+ - Use \`partIndex\` with a cursor to fetch a single part at full detail \u2014 for example, to read one specific tool result or code block without loading every part.
24349
24349
 
24350
24350
  If the result says \`truncated: true\`, the output was cut to fit the token budget. You can paginate or use \`partIndex\` to target specific content. If a single part is itself too large, follow the returned \`nextCharOffset\` as described below.
24351
24351
 
24352
24352
  ### Following up on truncated parts
24353
24353
  Low-detail results may include truncation hints like:
24354
- \`[truncated — call recall cursor="..." partIndex=N detail="high" for full content]\`
24354
+ \`[truncated \u2014 call recall cursor="..." partIndex=N detail="high" for full content]\`
24355
24355
 
24356
24356
  **When you see these hints and need the full content, make the exact call described in the hint.** This is the normal workflow: first recall at low detail to scan, then drill into specific parts at high detail. Do not stop at the low-detail result if the user asked for exact content.
24357
24357
 
24358
- If a single part is larger than the token budget, the \`partIndex\` result is \`truncated: true\` and includes \`nextCharOffset\`. Repeat the same call with \`charOffset\` set to that exact value to read the next chunk from where the previous one ended. Keep following \`nextCharOffset\` until the result no longer includes it — the chunks together contain the full part. Retrying without \`charOffset\` returns the same prefix again.
24358
+ If a single part is larger than the token budget, the \`partIndex\` result is \`truncated: true\` and includes \`nextCharOffset\`. Repeat the same call with \`charOffset\` set to that exact value to read the next chunk from where the previous one ended. Keep following \`nextCharOffset\` until the result no longer includes it \u2014 the chunks together contain the full part. Retrying without \`charOffset\` returns the same prefix again.
24359
24359
 
24360
24360
  ### When recall is NOT needed
24361
24361
  - The user is asking for a high-level summary and your observations already cover it
@@ -24752,6 +24752,15 @@ function buildThreadMetadataFromExtractedValues(extractors, values) {
24752
24752
  async function applyExtractorHooks(opts) {
24753
24753
  const values = normalizeExtractedValues(opts.values) ?? {};
24754
24754
  const failures = [...opts.failures ?? []];
24755
+ let recentMessages;
24756
+ let recentMessagesResolved = false;
24757
+ const resolveRecentMessages = () => {
24758
+ if (!recentMessagesResolved) {
24759
+ recentMessages = typeof opts.recentMessages === "function" ? opts.recentMessages() : opts.recentMessages;
24760
+ recentMessagesResolved = true;
24761
+ }
24762
+ return recentMessages;
24763
+ };
24755
24764
  for (const extractor of opts.extractors) {
24756
24765
  const isHook = extractor.mode === "hook";
24757
24766
  const hasValue = Object.prototype.hasOwnProperty.call(values, extractor.slug);
@@ -24771,7 +24780,9 @@ async function applyExtractorHooks(opts) {
24771
24780
  previous: isHook ? void 0 : opts.previousValues?.[extractor.slug],
24772
24781
  current,
24773
24782
  rawObservations: opts.rawObservations,
24774
- recentMessages: opts.recentMessages,
24783
+ get recentMessages() {
24784
+ return resolveRecentMessages();
24785
+ },
24775
24786
  mainAgent: opts.mainAgent,
24776
24787
  memory: opts.memory,
24777
24788
  sendSignal: opts.sendSignal,
@@ -25530,7 +25541,7 @@ const YEAR = String.raw`(?:19|20|21)\d{2}(?!\d)`;
25530
25541
  const MERIDIEM = String.raw`(?:[AaPp]\.[Mm]\.|[AaPp][Mm]\b)`;
25531
25542
  const TIME = String.raw`(?:,?\s+(?:at\s+)?\d{1,2}:\d{2}(?:\s*${MERIDIEM})?|\s+at\s+\d{1,2}\s*${MERIDIEM})`;
25532
25543
  const QUALIFIER = String.raw`(?:(?:early|mid|late)[- ](?:to[- ](?:early|mid|late)[- ])?)`;
25533
- const RANGE_SEP = String.raw`(?:\s*[–—]\s*|\s*-\s*|\s+(?:to|through|until)\s+)`;
25544
+ const RANGE_SEP = String.raw`(?:\s*[\u2013\u2014]\s*|\s*-\s*|\s+(?:to|through|until)\s+)`;
25534
25545
  /**
25535
25546
  * Dates written into observation text that carry their own year, longest forms first:
25536
25547
  * "Mar 1 - Mar 18, 2025", "May 27-28, 2023", "January 10, 2024 at 3:00 PM",
@@ -25833,15 +25844,15 @@ const SHORT_TOKEN_THRESHOLD = 3;
25833
25844
  const KANA_CHARS_PER_TOKEN = 1.35;
25834
25845
  const DEFAULT_LANGUAGE_CONFIGS = [
25835
25846
  {
25836
- pattern: /[äöüßẞ]/i,
25847
+ pattern: /[\u00E4\u00F6\u00FC\u00DF\u1E9E]/i,
25837
25848
  averageCharsPerToken: 2.6
25838
25849
  },
25839
25850
  {
25840
- pattern: /[éèêëàâîïôûùüÿçœæáíóúñ]/i,
25851
+ pattern: /[\u00E9\u00E8\u00EA\u00EB\u00E0\u00E2\u00EE\u00EF\u00F4\u00FB\u00F9\u00FC\u00FF\u00E7\u0153\u00E6\u00E1\u00ED\u00F3\u00FA\u00F1]/i,
25841
25852
  averageCharsPerToken: 3
25842
25853
  },
25843
25854
  {
25844
- pattern: /[ąćęłńóśźżěščřžýůúďťň]/i,
25855
+ pattern: /[\u0105\u0107\u0119\u0142\u0144\u00F3\u015B\u017A\u017C\u011B\u0161\u010D\u0159\u017E\u00FD\u016F\u00FA\u010F\u0165\u0148]/i,
25845
25856
  averageCharsPerToken: 2.5
25846
25857
  },
25847
25858
  {
@@ -25930,10 +25941,10 @@ function sanitizeSurrogates(value) {
25930
25941
  if (next >= 56320 && next <= 57343) {
25931
25942
  sanitized += value.charAt(index) + value.charAt(index + 1);
25932
25943
  index++;
25933
- } else sanitized += "�";
25944
+ } else sanitized += "\uFFFD";
25934
25945
  continue;
25935
25946
  }
25936
- sanitized += code >= 56320 && code <= 57343 ? "�" : value[index];
25947
+ sanitized += code >= 56320 && code <= 57343 ? "\uFFFD" : value[index];
25937
25948
  }
25938
25949
  return sanitized;
25939
25950
  }
@@ -25955,7 +25966,7 @@ function truncatePath(path) {
25955
25966
  const headLength = 50;
25956
25967
  const tailLength = 60;
25957
25968
  const omitted = path.length - headLength - tailLength;
25958
- return `${safeSlice(path, headLength)}…[${omitted} chars; ${stablePathDigest(path)}]…${safeTail(path, tailLength)}`;
25969
+ return `${safeSlice(path, headLength)}\u2026[${omitted} chars; ${stablePathDigest(path)}]\u2026${safeTail(path, tailLength)}`;
25959
25970
  }
25960
25971
  function formatPath(parent, key, isArray) {
25961
25972
  if (isArray) return truncatePath(`${parent}[${key}]`);
@@ -26064,7 +26075,7 @@ function selectOutlineEntries(entries, limits) {
26064
26075
  const rendered = joinEntries(selected, marker);
26065
26076
  if (fits(rendered, limits)) return rendered;
26066
26077
  if (fits(marker, limits)) return marker;
26067
- return fits("…", limits) ? "…" : "";
26078
+ return fits("\u2026", limits) ? "\u2026" : "";
26068
26079
  }
26069
26080
  function indentPreview(value) {
26070
26081
  return value.split("\n").map((line) => ` | ${line}`).join("\n");
@@ -26107,13 +26118,13 @@ function formatToolArgumentsForObserver(value, options) {
26107
26118
  if (!isObjectLike$1(value)) {
26108
26119
  if (typeof value !== "string" || value.length <= OBSERVER_TOOL_ARGUMENT_INLINE_STRING_MAX_CHARS) {
26109
26120
  const primitive = formatPrimitive(value);
26110
- return fits(primitive, limits) ? primitive : fits("…", limits) ? "…" : "";
26121
+ return fits(primitive, limits) ? primitive : fits("\u2026", limits) ? "\u2026" : "";
26111
26122
  }
26112
26123
  const summary = `<string, ${value.length} characters; preview size-limited>`;
26113
26124
  const rendered = appendWithinBudget(summary, formatPreview("preview", value, limits, summary), limits);
26114
26125
  if (rendered) return rendered;
26115
26126
  if (fits(summary, limits)) return summary;
26116
- return fits("…", limits) ? "…" : "";
26127
+ return fits("\u2026", limits) ? "\u2026" : "";
26117
26128
  }
26118
26129
  const outline = [];
26119
26130
  const previews = [];
@@ -26359,24 +26370,24 @@ function formatToolResultForObserver(value, options) {
26359
26370
  const OBSERVER_EXTRACTION_INSTRUCTIONS = `CRITICAL: DISTINGUISH USER ASSERTIONS FROM QUESTIONS
26360
26371
 
26361
26372
  When the user TELLS you something about themselves, mark it as an assertion:
26362
- - "I have two kids" → 🔴 (14:30) User stated has two kids
26363
- - "I work at Acme Corp" → 🔴 (14:31) User stated works at Acme Corp
26364
- - "I graduated in 2019" → 🔴 (14:32) User stated graduated in 2019
26373
+ - "I have two kids" \u2192 \u{1F534} (14:30) User stated has two kids
26374
+ - "I work at Acme Corp" \u2192 \u{1F534} (14:31) User stated works at Acme Corp
26375
+ - "I graduated in 2019" \u2192 \u{1F534} (14:32) User stated graduated in 2019
26365
26376
 
26366
26377
  When the user ASKS about something, mark it as a question/request:
26367
- - "Can you help me with X?" → 🔴 (15:00) User asked help with X
26368
- - "What's the best way to do Y?" → 🔴 (15:01) User asked best way to do Y
26378
+ - "Can you help me with X?" \u2192 \u{1F534} (15:00) User asked help with X
26379
+ - "What's the best way to do Y?" \u2192 \u{1F534} (15:01) User asked best way to do Y
26369
26380
 
26370
26381
  Distinguish between QUESTIONS and STATEMENTS OF INTENT:
26371
- - "Can you recommend..." → Question (extract as "User asked...")
26372
- - "I'm looking forward to [doing X]" → Statement of intent (extract as "User stated they will [do X] (include estimated/actual date if mentioned)")
26373
- - "I need to [do X]" → Statement of intent (extract as "User stated they need to [do X] (again, add date if mentioned)")
26382
+ - "Can you recommend..." \u2192 Question (extract as "User asked...")
26383
+ - "I'm looking forward to [doing X]" \u2192 Statement of intent (extract as "User stated they will [do X] (include estimated/actual date if mentioned)")
26384
+ - "I need to [do X]" \u2192 Statement of intent (extract as "User stated they need to [do X] (again, add date if mentioned)")
26374
26385
 
26375
26386
  STATE CHANGES AND UPDATES:
26376
26387
  When a user indicates they are changing something, frame it as a state change that supersedes previous information:
26377
- - "I'm going to start doing X instead of Y" → "User will start doing X (changing from Y)"
26378
- - "I'm switching from A to B" → "User is switching from A to B"
26379
- - "I moved my stuff to the new place" → "User moved their stuff to the new place (no longer at previous location)"
26388
+ - "I'm going to start doing X instead of Y" \u2192 "User will start doing X (changing from Y)"
26389
+ - "I'm switching from A to B" \u2192 "User is switching from A to B"
26390
+ - "I moved my stuff to the new place" \u2192 "User moved their stuff to the new place (no longer at previous location)"
26380
26391
 
26381
26392
  If the new state contradicts or updates previous information, make that explicit:
26382
26393
  - BAD: "User plans to use the new method"
@@ -26467,11 +26478,11 @@ BAD: User got something.
26467
26478
  GOOD: User purchased / received / was given something. (be specific)
26468
26479
 
26469
26480
  Common clarifications:
26470
- - "getting" something regularly → "subscribed to" or "enrolled in"
26471
- - "getting" something once → "purchased" or "acquired"
26472
- - "got" → "purchased", "received as gift", "was given", "picked up"
26473
- - "signed up" → "enrolled in", "registered for", "subscribed to"
26474
- - "stopped getting" → "canceled", "unsubscribed from", "discontinued"
26481
+ - "getting" something regularly \u2192 "subscribed to" or "enrolled in"
26482
+ - "getting" something once \u2192 "purchased" or "acquired"
26483
+ - "got" \u2192 "purchased", "received as gift", "was given", "picked up"
26484
+ - "signed up" \u2192 "enrolled in", "registered for", "subscribed to"
26485
+ - "stopped getting" \u2192 "canceled", "unsubscribed from", "discontinued"
26475
26486
 
26476
26487
  When the assistant interprets or confirms the user's vague language, prefer the assistant's precise terminology.
26477
26488
 
@@ -26556,16 +26567,16 @@ AVOIDING REPETITIVE OBSERVATIONS:
26556
26567
  - Do NOT repeat the same observation across multiple turns if there is no new information.
26557
26568
  - When the agent performs repeated similar actions (e.g., browsing files, running the same tool type multiple times), group them into a single parent observation with sub-bullets for each new result.
26558
26569
 
26559
- Example — BAD (repetitive):
26560
- * 🟡 (14:30) Agent used view tool on src/auth.ts
26561
- * 🟡 (14:31) Agent used view tool on src/users.ts
26562
- * 🟡 (14:32) Agent used view tool on src/routes.ts
26570
+ Example \u2014 BAD (repetitive):
26571
+ * \u{1F7E1} (14:30) Agent used view tool on src/auth.ts
26572
+ * \u{1F7E1} (14:31) Agent used view tool on src/users.ts
26573
+ * \u{1F7E1} (14:32) Agent used view tool on src/routes.ts
26563
26574
 
26564
- Example — GOOD (grouped):
26565
- * 🟡 (14:30) Agent browsed source files for auth flow
26566
- * -> viewed src/auth.ts — found token validation logic
26567
- * -> viewed src/users.ts — found user lookup by email
26568
- * -> viewed src/routes.ts — found middleware chain
26575
+ Example \u2014 GOOD (grouped):
26576
+ * \u{1F7E1} (14:30) Agent browsed source files for auth flow
26577
+ * -> viewed src/auth.ts \u2014 found token validation logic
26578
+ * -> viewed src/users.ts \u2014 found user lookup by email
26579
+ * -> viewed src/routes.ts \u2014 found middleware chain
26569
26580
 
26570
26581
  Only add a new observation for a repeated action if the NEW result changes the picture.
26571
26582
 
@@ -26578,29 +26589,29 @@ COMPLETION TRACKING:
26578
26589
  Completion observations are not just summaries. They are explicit memory signals to the assistant that a task, question, or subtask has been resolved.
26579
26590
  Without clear completion markers, the assistant may forget that work is already finished and may repeat, reopen, or continue an already-completed task.
26580
26591
 
26581
- Use ✅ to answer: "What exactly is now done?"
26592
+ Use \u2705 to answer: "What exactly is now done?"
26582
26593
  Choose completion observations that help the assistant know what is finished and should not be reworked unless new information appears.
26583
26594
 
26584
- Use ✅ when:
26595
+ Use \u2705 when:
26585
26596
  - The user explicitly confirms something worked or was answered ("thanks, that fixed it", "got it", "perfect")
26586
26597
  - The assistant provided a definitive, complete answer to a factual question and the user moved on
26587
26598
  - A multi-step task reached its stated goal
26588
26599
  - The user acknowledged receipt of requested information
26589
26600
  - A concrete subtask, fix, deliverable, or implementation step became complete during ongoing work
26590
26601
 
26591
- Do NOT use ✅ when:
26592
- - The assistant merely responded — the user might follow up with corrections
26602
+ Do NOT use \u2705 when:
26603
+ - The assistant merely responded \u2014 the user might follow up with corrections
26593
26604
  - The topic is paused but not resolved ("I'll try that later")
26594
26605
  - The user's reaction is ambiguous
26595
26606
 
26596
26607
  FORMAT:
26597
26608
  As a sub-bullet under the related observation group:
26598
- * 🔴 (14:30) User asked how to configure auth middleware
26609
+ * \u{1F534} (14:30) User asked how to configure auth middleware
26599
26610
  * -> Agent explained JWT setup with code example
26600
- * ✅ User confirmed auth is working
26611
+ * \u2705 User confirmed auth is working
26601
26612
 
26602
26613
  Or as a standalone observation when closing out a broader task:
26603
- * ✅ (14:45) Auth configuration task completed — user confirmed middleware is working
26614
+ * \u2705 (14:45) Auth configuration task completed \u2014 user confirmed middleware is working
26604
26615
 
26605
26616
  Completion observations should be terse but specific about WHAT was completed.
26606
26617
  Prefer concrete resolved outcomes over abstract workflow status so the assistant remembers what is already done.`;
@@ -26617,28 +26628,28 @@ buildObserverOutputFormat();
26617
26628
  */
26618
26629
  function buildObserverOutputFormat(extractors) {
26619
26630
  return `Use priority levels:
26620
- - 🔴 High: explicit user facts, preferences, unresolved goals, critical context
26621
- - 🟡 Medium: project details, learned information, tool results
26622
- - 🟢 Low: minor details, uncertain observations
26623
- - ✅ Completed: concrete task finished, question answered, issue resolved, goal achieved, or subtask completed in a way that helps the assistant know it is done
26631
+ - \u{1F534} High: explicit user facts, preferences, unresolved goals, critical context
26632
+ - \u{1F7E1} Medium: project details, learned information, tool results
26633
+ - \u{1F7E2} Low: minor details, uncertain observations
26634
+ - \u2705 Completed: concrete task finished, question answered, issue resolved, goal achieved, or subtask completed in a way that helps the assistant know it is done
26624
26635
 
26625
26636
  Group related observations (like tool sequences) by indenting:
26626
- * 🔴 (14:33) Agent debugging auth issue
26637
+ * \u{1F534} (14:33) Agent debugging auth issue
26627
26638
  * -> ran git status, found 3 modified files
26628
26639
  * -> viewed auth.ts:45-60, found missing null check
26629
26640
  * -> applied fix, tests now pass
26630
- * ✅ Tests passing, auth issue resolved
26641
+ * \u2705 Tests passing, auth issue resolved
26631
26642
 
26632
26643
  Group observations by date. Within a date, list observations in the order the events happened (not by importance), each with 24-hour time.
26633
26644
 
26634
26645
  <observations>
26635
26646
  Date: Dec 4, 2025
26636
- * 🔴 (14:30) User prefers direct answers
26637
- * 🔴 (14:31) Working on feature X
26638
- * 🟡 (14:32) User might prefer dark mode
26647
+ * \u{1F534} (14:30) User prefers direct answers
26648
+ * \u{1F534} (14:31) Working on feature X
26649
+ * \u{1F7E1} (14:32) User might prefer dark mode
26639
26650
 
26640
26651
  Date: Dec 5, 2025
26641
- * 🔴 (09:15) Continued work on feature X
26652
+ * \u{1F534} (09:15) Continued work on feature X
26642
26653
  </observations>
26643
26654
 
26644
26655
  ${buildExtractorOutputSections(extractors ?? []) || (extractors === void 0 ? `
@@ -26668,9 +26679,9 @@ const OBSERVER_GUIDELINES = `- Be specific enough for the assistant to act on
26668
26679
  - If the agent calls tools, observe what was called, why, and what was learned
26669
26680
  - When observing files with line numbers, include the line number if useful
26670
26681
  - If the agent provides a detailed response, observe the contents so it could be repeated
26671
- - Make sure you start each observation with a priority emoji (🔴, 🟡, 🟢) or a completion marker (✅)
26672
- - Capture the user's words closely — short/medium messages near-verbatim, long messages summarized with key quotes. User confirmations or explicit resolved outcomes should be ✅ when they clearly signal something is done; unresolved or critical user facts remain 🔴
26673
- - Treat ✅ as a memory signal that tells the assistant something is finished and should not be repeated unless new information changes it
26682
+ - Make sure you start each observation with a priority emoji (\u{1F534}, \u{1F7E1}, \u{1F7E2}) or a completion marker (\u2705)
26683
+ - Capture the user's words closely \u2014 short/medium messages near-verbatim, long messages summarized with key quotes. User confirmations or explicit resolved outcomes should be \u2705 when they clearly signal something is done; unresolved or critical user facts remain \u{1F534}
26684
+ - Treat \u2705 as a memory signal that tells the assistant something is finished and should not be repeated unless new information changes it
26674
26685
  - Make completion observations answer "What exactly is now done?"
26675
26686
  - Prefer concrete resolved outcomes over meta-level workflow or bookkeeping updates
26676
26687
  - When multiple concrete things were completed, capture the concrete completed work rather than collapsing it into a vague progress summary
@@ -26724,8 +26735,8 @@ For multi-thread output, wrap each thread's observations like this:
26724
26735
  <observations>
26725
26736
  <thread id="thread_id_1">
26726
26737
  Date: Dec 4, 2025
26727
- * 🔴 (14:30) User prefers direct answers
26728
- * 🔴 (14:31) Working on feature X${currentTaskEnabled ? `
26738
+ * \u{1F534} (14:30) User prefers direct answers
26739
+ * \u{1F534} (14:31) Working on feature X${currentTaskEnabled ? `
26729
26740
 
26730
26741
  <current-task>
26731
26742
  What the agent is currently working on in this thread
@@ -26738,7 +26749,7 @@ Hint for the agent's next message in this thread
26738
26749
 
26739
26750
  <thread id="thread_id_2">
26740
26751
  Date: Dec 5, 2025
26741
- * 🔴 (09:15) User asked about deployment${currentTaskEnabled ? `
26752
+ * \u{1F534} (09:15) User asked about deployment${currentTaskEnabled ? `
26742
26753
 
26743
26754
  <current-task>
26744
26755
  Current task for this thread
@@ -27586,7 +27597,7 @@ function sanitizeObservationLines(observations) {
27586
27597
  const lines = observations.split("\n");
27587
27598
  let changed = false;
27588
27599
  for (let i = 0; i < lines.length; i++) if (lines[i].length > MAX_OBSERVATION_LINE_CHARS) {
27589
- lines[i] = safeSlice(lines[i], MAX_OBSERVATION_LINE_CHARS) + " … [truncated]";
27600
+ lines[i] = safeSlice(lines[i], MAX_OBSERVATION_LINE_CHARS) + " \u2026 [truncated]";
27590
27601
  changed = true;
27591
27602
  }
27592
27603
  return changed ? lines.join("\n") : observations;
@@ -27810,8 +27821,8 @@ function extractCurrentTask(observations) {
27810
27821
  */
27811
27822
  function optimizeObservationsForContext(observations) {
27812
27823
  let optimized = stripEphemeralAnchorIds(observations);
27813
- optimized = optimized.replace(/🟡\s*/g, "");
27814
- optimized = optimized.replace(/🟢\s*/g, "");
27824
+ optimized = optimized.replace(/\uD83D\uDFE1\s*/g, "");
27825
+ optimized = optimized.replace(/\uD83D\uDFE2\s*/g, "");
27815
27826
  optimized = optimized.replace(/\s*->\s*/g, " ");
27816
27827
  optimized = optimized.replace(/ +/g, " ");
27817
27828
  optimized = optimized.replace(/\n{3,}/g, "\n\n");
@@ -30097,8 +30108,8 @@ const updateWorkingMemoryTool = (memoryConfig) => {
30097
30108
  }
30098
30109
  const usesMergeSemantics = Boolean(schema);
30099
30110
  const useStateSignals = memoryConfig?.workingMemory?.useStateSignals === true;
30100
- const stateSignalsPreamble = `The current working memory state is delivered to you each turn by the system inside a <working-memory>...</working-memory> block. That block is system-emitted state, NOT something the user typed — never describe it as the user sharing it. Read from it directly when answering. Only call this tool when the user provides genuinely NEW or CHANGED facts that should be persisted; do NOT call it to re-save unchanged data.`;
30101
- const description = schema ? useStateSignals ? `${stateSignalsPreamble} Data is merged with existing memory — only include fields you want to add or update.` : `Update the working memory with new information. Data is merged with existing memory - only include fields you want to add or update. To preserve existing data, omit the field entirely. Arrays are replaced entirely when provided, so pass the complete array or omit it to keep the existing values.` : useStateSignals ? `${stateSignalsPreamble} Pass the full updated Markdown blob as a string in the memory field.` : `Update the working memory with new information. Any data not included will be overwritten. Always pass data as string to the memory field. Never pass an object.`;
30111
+ const stateSignalsPreamble = `The current working memory state is delivered to you each turn by the system inside a <working-memory>...</working-memory> block. That block is system-emitted state, NOT something the user typed \u2014 never describe it as the user sharing it. Read from it directly when answering. Only call this tool when the user provides genuinely NEW or CHANGED facts that should be persisted; do NOT call it to re-save unchanged data.`;
30112
+ const description = schema ? useStateSignals ? `${stateSignalsPreamble} Data is merged with existing memory \u2014 only include fields you want to add or update.` : `Update the working memory with new information. Data is merged with existing memory - only include fields you want to add or update. To preserve existing data, omit the field entirely. Arrays are replaced entirely when provided, so pass the complete array or omit it to keep the existing values.` : useStateSignals ? `${stateSignalsPreamble} Pass the full updated Markdown blob as a string in the memory field.` : `Update the working memory with new information. Any data not included will be overwritten. Always pass data as string to the memory field. Never pass an object.`;
30102
30113
  return createTool({
30103
30114
  id: "update-working-memory",
30104
30115
  description,
@@ -31129,8 +31140,8 @@ async function pageGroups({ om, threadId, resourceId, groupId, recordId, directi
31129
31140
  })).count > 0;
31130
31141
  const hasLater = direction === "before" || hasMore;
31131
31142
  const newer = hasLater ? null : await newerMessagesNote(page.at(-1).group, countNewerMessages, pagingThreadId);
31132
- text.unshift(hasEarlier ? `— Browse earlier: ${pagingCall(page[0].group.id, "before", pagingThreadId, page[0].record.id)} —` : "— Start of retained observation history for this thread. —");
31133
- text.push(hasLater ? `— Browse later: ${pagingCall(page.at(-1).group.id, "after", pagingThreadId, page.at(-1).record.id)} —` : newer ? `— End of observation history for this thread. ${newer} —` : "— End of retained observation history for this thread. —");
31143
+ text.unshift(hasEarlier ? `\u2014 Browse earlier: ${pagingCall(page[0].group.id, "before", pagingThreadId, page[0].record.id)} \u2014` : "\u2014 Start of retained observation history for this thread. \u2014");
31144
+ text.push(hasLater ? `\u2014 Browse later: ${pagingCall(page.at(-1).group.id, "after", pagingThreadId, page.at(-1).record.id)} \u2014` : newer ? `\u2014 End of observation history for this thread. ${newer} \u2014` : "\u2014 End of retained observation history for this thread. \u2014");
31134
31145
  text.unshift(`### Observation page\nThread: ${threadTitle || "(untitled)"}\nShowing ${page.length} groups ${requestedDirection === void 0 ? "starting at" : `strictly ${direction}`} \`${groupId}\` (oldest first).`);
31135
31146
  return {
31136
31147
  results: text.join("\n\n"),
@@ -31318,7 +31329,7 @@ async function listThreadsForResource({ memory, resourceId, currentThreadId, pag
31318
31329
  const title = thread.title || "(untitled)";
31319
31330
  const updated = formatTimestamp(thread.updatedAt);
31320
31331
  const created = formatTimestamp(thread.createdAt);
31321
- const marker = isCurrent ? " ← current" : "";
31332
+ const marker = isCurrent ? " \u2190 current" : "";
31322
31333
  lines.push(`- **${title}**${marker}`);
31323
31334
  lines.push(` id: ${thread.id}`);
31324
31335
  lines.push(` updated: ${updated} | created: ${created}`);
@@ -31497,7 +31508,7 @@ async function searchMessagesForResource({ memory, om, resourceId, currentThread
31497
31508
  const groupLine = match.groupId ? `- observation group: ${groupCursor(match.groupId, match.recordId)}` : void 0;
31498
31509
  const scoreLine = `- score: ${match.score.toFixed(2)}`;
31499
31510
  const prev = i > 0 ? ordered[i - 1].match : void 0;
31500
- if (om && prev?.groupId && match.groupId && prev.threadId === match.threadId) sections.push(`— Observation groups may be hidden between these results; continue with ${pagingCall(prev.groupId, "after", includeThreadId ? prev.threadId : void 0, prev.recordId)} —`);
31511
+ if (om && prev?.groupId && match.groupId && prev.threadId === match.threadId) sections.push(`\u2014 Observation groups may be hidden between these results; continue with ${pagingCall(prev.groupId, "after", includeThreadId ? prev.threadId : void 0, prev.recordId)} \u2014`);
31501
31512
  if (suppression) {
31502
31513
  sections.push(`${groupLine}\n thread: ${match.threadId}; ${suppression}`);
31503
31514
  continue;
@@ -32052,7 +32063,7 @@ async function recallAttachmentView({ memory, threadId, resourceId, cursor, part
32052
32063
  const partType = rawPart?.type;
32053
32064
  if (!rawPart || partType !== "image" && partType !== "file") return { messages: `Part ${partIndex} of message ${cursor} is ${rawPart ? `a ${partType ?? "unknown"}-type part` : "missing"}, not an attachment. Call recall with the same cursor and partIndex without viewAttachment to read it.` };
32054
32065
  const resolvedAttachment = resolveViewableAttachment(rawPart);
32055
- if ("note" in resolvedAttachment) return { messages: `${formatAttachmentPart(partType, rawPart)} — ${resolvedAttachment.note}` };
32066
+ if ("note" in resolvedAttachment) return { messages: `${formatAttachmentPart(partType, rawPart)} \u2014 ${resolvedAttachment.note}` };
32056
32067
  return { content: [{
32057
32068
  type: "text",
32058
32069
  text: formatAttachmentPart(partType, rawPart)
@@ -32455,7 +32466,7 @@ const recallTool = (_memoryConfig, options) => {
32455
32466
  if (!thread) return { error: "Could not resolve current thread." };
32456
32467
  if (isResourceScope && resourceId && thread.resourceId !== resourceId) throw new Error("Thread does not belong to the active resource");
32457
32468
  return {
32458
- threads: `- **${thread.title || "(untitled)"}** ← current\n id: ${thread.id}\n updated: ${formatTimestamp(thread.updatedAt)} | created: ${formatTimestamp(thread.createdAt)}`,
32469
+ threads: `- **${thread.title || "(untitled)"}** \u2190 current\n id: ${thread.id}\n updated: ${formatTimestamp(thread.updatedAt)} | created: ${formatTimestamp(thread.createdAt)}`,
32459
32470
  count: 1,
32460
32471
  page: 0,
32461
32472
  hasMore: false
@@ -33026,6 +33037,79 @@ var BufferingCoordinator = class BufferingCoordinator {
33026
33037
  * Key format: "refl:{lockKey}"
33027
33038
  */
33028
33039
  static reflectionBufferCycleIds = /* @__PURE__ */ new Map();
33040
+ /**
33041
+ * The buffered-reflection op that set the reflection boundary and cycle, and the generation
33042
+ * it buffers for. Key format: "refl:{lockKey}"
33043
+ */
33044
+ static reflectionBufferOwners = /* @__PURE__ */ new Map();
33045
+ /** Set the reflection boundary for a new buffered-reflection op on generation `recordId`. */
33046
+ static startReflectionBuffer(bufferKey, tokens, recordId) {
33047
+ const owner = {
33048
+ recordId,
33049
+ retired: false
33050
+ };
33051
+ BufferingCoordinator.lastBufferedBoundary.set(bufferKey, tokens);
33052
+ BufferingCoordinator.reflectionBufferOwners.set(bufferKey, owner);
33053
+ return owner;
33054
+ }
33055
+ /** Drop this process's reflection boundary, cycle, and owner. */
33056
+ static clearReflectionBuffer(bufferKey) {
33057
+ BufferingCoordinator.lastBufferedBoundary.delete(bufferKey);
33058
+ BufferingCoordinator.reflectionBufferCycleIds.delete(bufferKey);
33059
+ BufferingCoordinator.reflectionBufferOwners.delete(bufferKey);
33060
+ }
33061
+ /**
33062
+ * Another writer retired generation `recordId`, so a buffer this process prepared for it can
33063
+ * never activate. Its boundary and cycle are dropped now, or, while the op that set them is
33064
+ * still running (it may be awaiting its `onReflectionEnd` hook), when that op finishes. State
33065
+ * owned by a newer generation is kept.
33066
+ */
33067
+ static retireReflectionBuffer(bufferKey, recordId) {
33068
+ const owner = BufferingCoordinator.reflectionBufferOwners.get(bufferKey);
33069
+ if (owner && owner.recordId !== recordId) return;
33070
+ if (owner && BufferingCoordinator.asyncBufferingOps.has(bufferKey)) {
33071
+ owner.retired = true;
33072
+ return;
33073
+ }
33074
+ BufferingCoordinator.clearReflectionBuffer(bufferKey);
33075
+ }
33076
+ /**
33077
+ * Reconcile this process's reflection buffer state against an observed head record.
33078
+ * Whenever `head.id` differs from `owner.recordId`, confirm against a fresh storage read started
33079
+ * after `owner` existed (never trusting `generationCount`, which resets to 0 after `clear()`):
33080
+ * only retire/clear when storage's live head is no longer `owner.recordId`.
33081
+ */
33082
+ static async reconcileReflectionBufferHead(bufferKey, headId, readLiveHead) {
33083
+ const owner = BufferingCoordinator.reflectionBufferOwners.get(bufferKey);
33084
+ if (!owner || owner.recordId === headId) return;
33085
+ const ownerRecordId = owner.recordId;
33086
+ const live = await readLiveHead();
33087
+ if (BufferingCoordinator.reflectionBufferOwners.get(bufferKey) !== owner || owner.recordId !== ownerRecordId) return;
33088
+ if (live?.id === ownerRecordId) return;
33089
+ if (BufferingCoordinator.asyncBufferingOps.has(bufferKey)) {
33090
+ owner.retired = true;
33091
+ return;
33092
+ }
33093
+ BufferingCoordinator.clearReflectionBuffer(bufferKey);
33094
+ }
33095
+ /**
33096
+ * Take the buffered-reflection cycle id for generation `recordId` and release its
33097
+ * coordinator state after its buffer activates. State owned by another generation
33098
+ * is left untouched.
33099
+ */
33100
+ static consumeReflectionBuffer(bufferKey, recordId) {
33101
+ const owner = BufferingCoordinator.reflectionBufferOwners.get(bufferKey);
33102
+ if (owner && owner.recordId !== recordId) return void 0;
33103
+ const cycleId = BufferingCoordinator.reflectionBufferCycleIds.get(bufferKey);
33104
+ if (owner && BufferingCoordinator.asyncBufferingOps.has(bufferKey)) owner.retired = true;
33105
+ else BufferingCoordinator.clearReflectionBuffer(bufferKey);
33106
+ return cycleId;
33107
+ }
33108
+ /** Called when the op that started as `owner` finishes; completes a deferred retirement. */
33109
+ static finishReflectionBuffer(bufferKey, owner) {
33110
+ if (BufferingCoordinator.reflectionBufferOwners.get(bufferKey) !== owner) return;
33111
+ if (owner.retired) BufferingCoordinator.clearReflectionBuffer(bufferKey);
33112
+ }
33029
33113
  constructor(opts) {
33030
33114
  this.observationConfig = opts.observationConfig;
33031
33115
  this.reflectionConfig = opts.reflectionConfig;
@@ -33081,6 +33165,7 @@ var BufferingCoordinator = class BufferingCoordinator {
33081
33165
  BufferingCoordinator.asyncBufferingOps.delete(obsBufKey);
33082
33166
  BufferingCoordinator.asyncBufferingOps.delete(reflBufKey);
33083
33167
  BufferingCoordinator.reflectionBufferCycleIds.delete(reflBufKey);
33168
+ BufferingCoordinator.reflectionBufferOwners.delete(reflBufKey);
33084
33169
  }
33085
33170
  }
33086
33171
  /**
@@ -33141,9 +33226,9 @@ const suggestedResponseInstructions = `Hint for the agent's immediate next messa
33141
33226
  - "The assistant should wait for the user to respond before continuing."
33142
33227
  - Call the view tool on src/example.ts to continue debugging.`;
33143
33228
  const threadTitleInstructions = `A short, noun-phrase title for this conversation (2-5 words). Examples:
33144
- - "Auth bug fix" — not "Fixing the auth bug"
33145
- - "Dark mode toggle" — not "User wants dark mode toggle added"
33146
- - "Deployment pipeline setup" — not "Setting up deployment pipeline for project"
33229
+ - "Auth bug fix" \u2014 not "Fixing the auth bug"
33230
+ - "Dark mode toggle" \u2014 not "User wants dark mode toggle added"
33231
+ - "Deployment pipeline setup" \u2014 not "Setting up deployment pipeline for project"
33147
33232
  Only update when the topic meaningfully changes.`;
33148
33233
  function createCurrentTaskExtractor() {
33149
33234
  return new Extractor({
@@ -34220,7 +34305,7 @@ var SyncObservationStrategy = class extends ObservationStrategy {
34220
34305
  failures: result.extractionFailures,
34221
34306
  previousValues: this.priorExtractedValues,
34222
34307
  rawObservations: result.observations,
34223
- recentMessages: formatMessagesForObserver(this.opts.messages, {
34308
+ recentMessages: () => formatMessagesForObserver(this.opts.messages, {
34224
34309
  maxPartLength: 500,
34225
34310
  timeZone: this.opts.record.observedTimezone
34226
34311
  }),
@@ -34445,7 +34530,7 @@ var AsyncBufferObservationStrategy = class extends ObservationStrategy {
34445
34530
  failures: result.extractionFailures,
34446
34531
  previousValues: this.priorExtractedValues,
34447
34532
  rawObservations: result.observations,
34448
- recentMessages: formatMessagesForObserver(messages, {
34533
+ recentMessages: () => formatMessagesForObserver(messages, {
34449
34534
  maxPartLength: 500,
34450
34535
  timeZone: this.opts.record.observedTimezone
34451
34536
  }),
@@ -34875,7 +34960,7 @@ var ResourceScopedObservationStrategy = class extends ObservationStrategy {
34875
34960
  failures: result.extractionFailures,
34876
34961
  previousValues,
34877
34962
  rawObservations: result.observations,
34878
- recentMessages: formatMessagesForObserver(threadMessages, {
34963
+ recentMessages: () => formatMessagesForObserver(threadMessages, {
34879
34964
  maxPartLength: 500,
34880
34965
  timeZone: this.opts.record.observedTimezone
34881
34966
  }),
@@ -35208,7 +35293,7 @@ var ObservationStep = class {
35208
35293
  }
35209
35294
  /** Step context from prepare(). Throws if prepare() hasn't been called. */
35210
35295
  get context() {
35211
- if (!this._context) throw new Error("Step not prepared yet — call prepare() first");
35296
+ if (!this._context) throw new Error("Step not prepared yet \u2014 call prepare() first");
35212
35297
  return this._context;
35213
35298
  }
35214
35299
  /**
@@ -35628,7 +35713,7 @@ var ObservationStep = class {
35628
35713
  const messagesToSeal = messageToSeal ? [messageToSeal] : [];
35629
35714
  this.turn.abortSignal?.throwIfAborted();
35630
35715
  om.sealMessagesForBuffering(messagesToSeal);
35631
- if (this.seededResponseMessage) omDebug("[OM:observe] skipping response-id rotation — step-0 seeded response message holds the active id");
35716
+ if (this.seededResponseMessage) omDebug("[OM:observe] skipping response-id rotation \u2014 step-0 seeded response message holds the active id");
35632
35717
  else try {
35633
35718
  await this.turn.hooks?.onSyncObservationComplete?.();
35634
35719
  } catch (error) {
@@ -35779,12 +35864,12 @@ var ObservationTurn = class {
35779
35864
  messageList;
35780
35865
  /** The current cached record. Refreshed after mutations (activate/observe/reflect). */
35781
35866
  get record() {
35782
- if (!this._record) throw new Error("Turn not started — call start() first");
35867
+ if (!this._record) throw new Error("Turn not started \u2014 call start() first");
35783
35868
  return this._record;
35784
35869
  }
35785
35870
  /** The context loaded during start(). */
35786
35871
  get context() {
35787
- if (!this._context) throw new Error("Turn not started — call start() first");
35872
+ if (!this._context) throw new Error("Turn not started \u2014 call start() first");
35788
35873
  return this._context;
35789
35874
  }
35790
35875
  /** Whether the turn has been ended and can no longer accept steps. */
@@ -35853,7 +35938,7 @@ var ObservationTurn = class {
35853
35938
  * (its output messages will be saved at the start of the new step's prepare()).
35854
35939
  */
35855
35940
  step(stepNumber) {
35856
- if (!this._started) throw new Error("Turn not started — call start() first");
35941
+ if (!this._started) throw new Error("Turn not started \u2014 call start() first");
35857
35942
  if (this._ended) throw new Error("Turn already ended");
35858
35943
  this._currentStep = new ObservationStep(this, stepNumber);
35859
35944
  return this._currentStep;
@@ -35948,6 +36033,80 @@ var ObservationTurn = class {
35948
36033
  };
35949
36034
  }
35950
36035
  };
36036
+ // src/processors/observational-memory/buffered-reflection-values.ts
36037
+ const pendingValuesBaseSchema = z.object({
36038
+ recordId: z.string(),
36039
+ reflectedObservationLineCount: z.number(),
36040
+ values: z.record(z.string(), z.unknown())
36041
+ });
36042
+ const pendingValuesSchema = z.union([pendingValuesBaseSchema.extend({
36043
+ reflectionDigest: z.string().regex(/^[a-f0-9]{64}$/),
36044
+ reflection: z.never().optional()
36045
+ }), pendingValuesBaseSchema.extend({
36046
+ reflection: z.string(),
36047
+ reflectionDigest: z.never().optional()
36048
+ })]);
36049
+ const metadataSchema = z.record(z.string(), z.unknown());
36050
+ function reflectionDigest(reflection) {
36051
+ return createHash("sha256").update(reflection).digest("hex");
36052
+ }
36053
+ function getMastraMetadata(metadata) {
36054
+ const parsed = metadataSchema.safeParse(metadata?.mastra);
36055
+ return parsed.success ? parsed.data : {};
36056
+ }
36057
+ /** Keep prepared values outside active OM metadata, durable across Memory instances. */
36058
+ async function stageBufferedReflectionValues(storage, record, values) {
36059
+ if (!record.threadId || !record.bufferedReflection) return;
36060
+ const digest = reflectionDigest(record.bufferedReflection);
36061
+ await storage.updateThreadMetadata({
36062
+ id: record.threadId,
36063
+ update: (thread) => ({
36064
+ ...thread.metadata,
36065
+ mastra: {
36066
+ ...getMastraMetadata(thread.metadata),
36067
+ omBufferedReflection: {
36068
+ recordId: record.id,
36069
+ reflectionDigest: digest,
36070
+ reflectedObservationLineCount: record.reflectedObservationLineCount ?? 0,
36071
+ values: values ?? {}
36072
+ }
36073
+ }
36074
+ })
36075
+ });
36076
+ }
36077
+ /** Called under the OM commit lock, only after this exact buffer was activated. */
36078
+ async function publishBufferedReflectionValues(storage, extractors, record) {
36079
+ if (!record.threadId || !record.bufferedReflection) return;
36080
+ const digest = reflectionDigest(record.bufferedReflection);
36081
+ await storage.updateThreadMetadata({
36082
+ id: record.threadId,
36083
+ update: (thread) => {
36084
+ const mastra = getMastraMetadata(thread.metadata);
36085
+ const parsed = pendingValuesSchema.safeParse(mastra.omBufferedReflection);
36086
+ if (!parsed.success) return;
36087
+ const pending = parsed.data;
36088
+ if (pending.recordId !== record.id || (pending.reflectionDigest !== void 0 ? pending.reflectionDigest !== digest : pending.reflection !== record.bufferedReflection) || pending.reflectedObservationLineCount !== (record.reflectedObservationLineCount ?? 0)) return;
36089
+ const update = buildThreadMetadataFromExtractedValues(extractors, pending.values);
36090
+ const previous = getThreadOMMetadata(thread.metadata);
36091
+ const metadata = setThreadOMMetadata(thread.metadata, {
36092
+ currentTask: update.currentTask ?? previous?.currentTask,
36093
+ suggestedResponse: update.suggestedResponse ?? previous?.suggestedResponse,
36094
+ threadTitle: update.threadTitle ?? previous?.threadTitle,
36095
+ extracted: {
36096
+ ...previous?.extracted,
36097
+ ...update.extracted
36098
+ }
36099
+ });
36100
+ return {
36101
+ ...metadata,
36102
+ mastra: {
36103
+ ...getMastraMetadata(metadata),
36104
+ omBufferedReflection: null
36105
+ }
36106
+ };
36107
+ }
36108
+ });
36109
+ }
35951
36110
  // src/processors/observational-memory/reflector-agent.ts
35952
36111
  /**
35953
36112
  * Build the Reflector's system prompt.
@@ -36002,8 +36161,8 @@ When consolidating observations:
36002
36161
  - Keep what the user explicitly said they have never done, do not know, or refused, and keep every stated preference, rule, and instruction with its meaning intact
36003
36162
  - Prefer many short factual lines over prose summaries. Do not replace facts with generalities like "discussed travel plans"
36004
36163
  - Combine related items where it makes sense (e.g., "agent called view tool 5 times on file x")
36005
- - Preserve ✅ completion markers — they are memory signals that tell the assistant what is already resolved and help prevent repeated work
36006
- - Preserve the concrete resolved outcome captured by ✅ markers so the assistant knows what exactly is done
36164
+ - Preserve \u2705 completion markers \u2014 they are memory signals that tell the assistant what is already resolved and help prevent repeated work
36165
+ - Preserve the concrete resolved outcome captured by \u2705 markers so the assistant knows what exactly is done
36007
36166
  - Condense the wording of older observations more than recent ones, but keep their facts
36008
36167
 
36009
36168
  CRITICAL: USER ASSERTIONS vs QUESTIONS
@@ -36025,23 +36184,23 @@ When observations contain <thread id="..."> sections:
36025
36184
  Example input:
36026
36185
  <thread id="thread-1">
36027
36186
  Date: Dec 4, 2025
36028
- * 🔴 (14:30) User prefers TypeScript
36029
- * 🟡 (14:35) Working on auth feature
36187
+ * \u{1F534} (14:30) User prefers TypeScript
36188
+ * \u{1F7E1} (14:35) Working on auth feature
36030
36189
  </thread>
36031
36190
  <thread id="thread-2">
36032
36191
  Date: Dec 4, 2025
36033
- * 🔴 (15:00) User prefers TypeScript
36034
- * 🟡 (15:05) Debugging API endpoint
36192
+ * \u{1F534} (15:00) User prefers TypeScript
36193
+ * \u{1F7E1} (15:05) Debugging API endpoint
36035
36194
  </thread>
36036
36195
 
36037
36196
  Example output (consolidated):
36038
36197
  Date: Dec 4, 2025
36039
- * 🔴 (14:30) User prefers TypeScript
36198
+ * \u{1F534} (14:30) User prefers TypeScript
36040
36199
  <thread id="thread-1">
36041
- * 🟡 (14:35) Working on auth feature
36200
+ * \u{1F7E1} (14:35) Working on auth feature
36042
36201
  </thread>
36043
36202
  <thread id="thread-2">
36044
- * 🟡 (15:05) Debugging API endpoint
36203
+ * \u{1F7E1} (15:05) Debugging API endpoint
36045
36204
  </thread>
36046
36205
 
36047
36206
  === OUTPUT FORMAT ===
@@ -36072,8 +36231,8 @@ Please re-process with slightly more compression:
36072
36231
  - Memory is getting long - use a more condensed style throughout
36073
36232
  - Combine related items more aggressively but do not lose important specific details of names, places, events, and people
36074
36233
  - Combine repeated similar tool calls (e.g. multiple file views, searches, or edits in the same area) into a single summary line describing what was explored/changed and the outcome
36075
- - Preserve ✅ completion markers — they are memory signals that tell the assistant what is already resolved and help prevent repeated work
36076
- - Preserve the concrete resolved outcome captured by ✅ markers so the assistant knows what exactly is done
36234
+ - Preserve \u2705 completion markers \u2014 they are memory signals that tell the assistant what is already resolved and help prevent repeated work
36235
+ - Preserve the concrete resolved outcome captured by \u2705 markers so the assistant knows what exactly is done
36077
36236
 
36078
36237
  Aim for a 8/10 detail level.
36079
36238
  `,
@@ -36089,8 +36248,8 @@ Please re-process with much more aggressive compression:
36089
36248
  - Combine related items aggressively but do not lose important specific details of names, places, events, and people
36090
36249
  - Combine repeated similar tool calls (e.g. multiple file views, searches, or edits in the same area) into a single summary line describing what was explored/changed and the outcome
36091
36250
  - If the same file or module is mentioned across many observations, merge into one entry covering the full arc
36092
- - Preserve ✅ completion markers — they are memory signals that tell the assistant what is already resolved and help prevent repeated work
36093
- - Preserve the concrete resolved outcome captured by ✅ markers so the assistant knows what exactly is done
36251
+ - Preserve \u2705 completion markers \u2014 they are memory signals that tell the assistant what is already resolved and help prevent repeated work
36252
+ - Preserve the concrete resolved outcome captured by \u2705 markers so the assistant knows what exactly is done
36094
36253
  - Remove redundant information and merge overlapping observations
36095
36254
 
36096
36255
  Aim for a 6/10 detail level.
@@ -36101,14 +36260,14 @@ Aim for a 6/10 detail level.
36101
36260
  Your previous reflections have failed to compress sufficiently after multiple attempts.
36102
36261
 
36103
36262
  Please re-process with maximum compression:
36104
- - Summarize the oldest observations (first 50-70%) into brief high-level paragraphs — only key facts, decisions, and outcomes
36263
+ - Summarize the oldest observations (first 50-70%) into brief high-level paragraphs \u2014 only key facts, decisions, and outcomes
36105
36264
  - For the most recent observations (last 30-50%), retain important details but still use a condensed style
36106
- - Ruthlessly merge related observations — if 10 observations are about the same topic, combine into 1-2 lines
36107
- - Combine all tool call sequences (file views, searches, edits, builds) into outcome-only summaries — drop individual steps entirely
36108
- - Drop procedural details (tool calls, retries, intermediate steps) — keep only final outcomes
36265
+ - Ruthlessly merge related observations \u2014 if 10 observations are about the same topic, combine into 1-2 lines
36266
+ - Combine all tool call sequences (file views, searches, edits, builds) into outcome-only summaries \u2014 drop individual steps entirely
36267
+ - Drop procedural details (tool calls, retries, intermediate steps) \u2014 keep only final outcomes
36109
36268
  - Drop observations that are no longer relevant or have been superseded by newer information
36110
- - Preserve ✅ completion markers — they are memory signals that tell the assistant what is already resolved and help prevent repeated work
36111
- - Preserve the concrete resolved outcome captured by ✅ markers so the assistant knows what exactly is done
36269
+ - Preserve \u2705 completion markers \u2014 they are memory signals that tell the assistant what is already resolved and help prevent repeated work
36270
+ - Preserve the concrete resolved outcome captured by \u2705 markers so the assistant knows what exactly is done
36112
36271
  - Preserve: names, dates, decisions, errors, user preferences, and architectural choices
36113
36272
 
36114
36273
  Aim for a 4/10 detail level.
@@ -36119,14 +36278,14 @@ Aim for a 4/10 detail level.
36119
36278
  Multiple compression attempts have failed. The content may already be dense from a prior reflection.
36120
36279
 
36121
36280
  You MUST dramatically reduce the number of observations while keeping the standard observation format (date groups with bullet points and priority emojis):
36122
- - Tool call observations are the biggest source of bloat. Collapse ALL tool call sequences into outcome-only observations — e.g. 10 observations about viewing/searching/editing files become 1 observation about what was actually learned or achieved (e.g. "Investigated auth module and found token validation was skipping expiry check")
36123
- - Never preserve individual tool calls (viewed file X, searched for Y, ran build) — only preserve what was discovered or accomplished
36281
+ - Tool call observations are the biggest source of bloat. Collapse ALL tool call sequences into outcome-only observations \u2014 e.g. 10 observations about viewing/searching/editing files become 1 observation about what was actually learned or achieved (e.g. "Investigated auth module and found token validation was skipping expiry check")
36282
+ - Never preserve individual tool calls (viewed file X, searched for Y, ran build) \u2014 only preserve what was discovered or accomplished
36124
36283
  - Consolidate many related observations into single, more generic observations
36125
36284
  - Merge all same-day date groups into at most 2-3 date groups per day
36126
36285
  - For older content, each topic or task should be at most 1-2 observations capturing the key outcome
36127
36286
  - For recent content, retain more detail but still merge related items aggressively
36128
36287
  - If multiple observations describe incremental progress on the same task, keep only the final state
36129
- - Preserve ✅ completion markers and their outcomes but merge related completions into fewer lines
36288
+ - Preserve \u2705 completion markers and their outcomes but merge related completions into fewer lines
36130
36289
  - Preserve: user preferences, key decisions, architectural choices, and unresolved issues
36131
36290
 
36132
36291
  Aim for a 2/10 detail level. Fewer, more generic observations are better than many specific ones that exceed the budget.
@@ -36307,6 +36466,15 @@ function isReflectionApplied(returned, newRecordId, reflectedRecordId) {
36307
36466
  return returned.supersededBy === void 0 && returned.id !== reflectedRecordId;
36308
36467
  }
36309
36468
  /**
36469
+ * The active observations a buffered-reflection swap writes: the buffered reflection replaces the
36470
+ * first `reflectedLineCount` lines, and the trimmed remainder follows after a blank line. Mirrors
36471
+ * `swapBufferedReflectionToActive` in the storage adapters.
36472
+ */
36473
+ function bufferedActivationText({ bufferedReflection, observations, reflectedLineCount }) {
36474
+ const unreflected = observations.split("\n").slice(reflectedLineCount).join("\n").trim();
36475
+ return unreflected ? `${bufferedReflection}\n\n${unreflected}` : bufferedReflection;
36476
+ }
36477
+ /**
36310
36478
  * Runs the Reflector agent for compressing observations.
36311
36479
  * Handles synchronous reflection, async buffered reflection, and activation.
36312
36480
  */
@@ -36541,7 +36709,7 @@ var ReflectorRunner = class {
36541
36709
  operationType: "reflection",
36542
36710
  startedAt: streamContext.startedAt,
36543
36711
  tokensAttempted: originalTokens,
36544
- error: `Did not compress below threshold (${originalTokens} → ${reflectedTokens}, target: ${targetThreshold}), retrying at level ${currentLevel + 1}`,
36712
+ error: `Did not compress below threshold (${originalTokens} \u2192 ${reflectedTokens}, target: ${targetThreshold}), retrying at level ${currentLevel + 1}`,
36545
36713
  retrying: true,
36546
36714
  recordId: streamContext.recordId,
36547
36715
  threadId: streamContext.threadId
@@ -36571,7 +36739,7 @@ var ReflectorRunner = class {
36571
36739
  }
36572
36740
  currentLevel = Math.min(currentLevel + 1, maxLevel);
36573
36741
  }
36574
- if (observations.trim().length > 0 && parsed.observations.trim().length === 0) throw new Error(`Reflector produced empty output after ${attemptNumber} attempt(s)${parsed.degenerate ? " (degenerate repetition)" : ""} — refusing to commit an empty reflection over ${originalTokens} observation tokens`);
36742
+ if (observations.trim().length > 0 && parsed.observations.trim().length === 0) throw new Error(`Reflector produced empty output after ${attemptNumber} attempt(s)${parsed.degenerate ? " (degenerate repetition)" : ""} \u2014 refusing to commit an empty reflection over ${originalTokens} observation tokens`);
36575
36743
  const structuredExtraction = await extractStructuredValues({
36576
36744
  agent,
36577
36745
  source: "reflector",
@@ -36615,18 +36783,18 @@ var ReflectorRunner = class {
36615
36783
  startAsyncBufferedReflection(record, observationTokens, lockKey, writer, requestContext, observabilityContext, reflectionHooks, priorExtractedValues, mainAgent, sendSignal, trigger, currentModel) {
36616
36784
  const bufferKey = this.buffering.getReflectionBufferKey(lockKey);
36617
36785
  if (this.buffering.isAsyncBufferingInProgress(bufferKey)) return;
36618
- BufferingCoordinator.lastBufferedBoundary.set(bufferKey, observationTokens);
36786
+ const owner = BufferingCoordinator.startReflectionBuffer(bufferKey, observationTokens, record.id);
36619
36787
  registerOp(record.id, "bufferingReflection");
36620
36788
  const flagSet = this.storage.setBufferingReflectionFlag(record.id, true).catch((err) => {
36621
36789
  omError("[OM] Failed to set buffering reflection flag", err);
36622
36790
  });
36623
- const asyncOp = (async () => {
36791
+ const run = async () => {
36624
36792
  await flagSet;
36625
36793
  let outcome;
36626
36794
  let reflectionError;
36627
36795
  try {
36628
36796
  await reflectionHooks?.onReflectionStart?.();
36629
- outcome = await this.doAsyncBufferedReflection(record, bufferKey, writer, requestContext, observabilityContext, priorExtractedValues, mainAgent, sendSignal, trigger, currentModel);
36797
+ outcome = await this.doAsyncBufferedReflection(record, bufferKey, owner, writer, requestContext, observabilityContext, priorExtractedValues, mainAgent, sendSignal, trigger, currentModel);
36630
36798
  } catch (error) {
36631
36799
  reflectionError = error instanceof Error ? error : new Error(String(error));
36632
36800
  if (writer) try {
@@ -36649,7 +36817,7 @@ var ReflectorRunner = class {
36649
36817
  omError("[OM] Failed to persist buffering-failed marker after async buffered reflection failure", markerError);
36650
36818
  }
36651
36819
  omError("[OM] Async buffered reflection failed", error);
36652
- BufferingCoordinator.lastBufferedBoundary.delete(bufferKey);
36820
+ owner.retired = true;
36653
36821
  } finally {
36654
36822
  try {
36655
36823
  await reflectionHooks?.onReflectionEnd?.({
@@ -36660,13 +36828,15 @@ var ReflectorRunner = class {
36660
36828
  } catch (hookError) {
36661
36829
  omError("[OM] onReflectionEnd hook failed after async buffered reflection", hookError);
36662
36830
  }
36663
- BufferingCoordinator.asyncBufferingOps.delete(bufferKey);
36831
+ BufferingCoordinator.finishReflectionBuffer(bufferKey, owner);
36832
+ if (BufferingCoordinator.asyncBufferingOps.get(bufferKey) === asyncOp) BufferingCoordinator.asyncBufferingOps.delete(bufferKey);
36664
36833
  unregisterOp(record.id, "bufferingReflection");
36665
36834
  await this.storage.setBufferingReflectionFlag(record.id, false).catch((err) => {
36666
36835
  omError("[OM] Failed to clear buffering reflection flag", err);
36667
36836
  });
36668
36837
  }
36669
- })();
36838
+ };
36839
+ const asyncOp = run();
36670
36840
  BufferingCoordinator.asyncBufferingOps.set(bufferKey, asyncOp);
36671
36841
  this.trackBackgroundWork?.(asyncOp, lockKey);
36672
36842
  }
@@ -36674,13 +36844,27 @@ var ReflectorRunner = class {
36674
36844
  * Perform async buffered reflection — reflects observations and stores to bufferedReflection.
36675
36845
  * Does NOT create a new generation or update activeObservations.
36676
36846
  */
36677
- async doAsyncBufferedReflection(record, bufferKey, writer, requestContext, observabilityContext, priorExtractedValues, mainAgent, sendSignal, trigger, currentModel) {
36678
- const currentRecord = await this.storage.getObservationalMemory(record.threadId, record.resourceId) ?? record;
36847
+ async doAsyncBufferedReflection(record, bufferKey, owner, writer, requestContext, observabilityContext, priorExtractedValues, mainAgent, sendSignal, trigger, currentModel) {
36848
+ const freshRecord = await this.storage.getObservationalMemory(record.threadId, record.resourceId);
36849
+ if (BufferingCoordinator.reflectionBufferOwners.get(bufferKey) !== owner) {
36850
+ omDebug(`[OM:reflect] doAsyncBufferedReflection: ${bufferKey} was cleared while the op waited; stopping`);
36851
+ return;
36852
+ }
36853
+ const currentRecord = freshRecord ?? record;
36854
+ if (freshRecord?.bufferedReflection) {
36855
+ omDebug(`[OM:reflect] doAsyncBufferedReflection: live head ${freshRecord.id} already has a buffered reflection; skipping duplicate run`);
36856
+ owner.retired = true;
36857
+ return;
36858
+ }
36679
36859
  const observationTokens = currentRecord.observationTokenCount ?? 0;
36680
36860
  const reflectThreshold = getMaxThreshold(this.getEffectiveReflectionTokens(currentRecord));
36681
36861
  const bufferActivation = this.reflectionConfig.bufferActivation ?? .5;
36682
36862
  const startedAt = (/* @__PURE__ */ new Date()).toISOString();
36683
36863
  const cycleId = `reflect-buf-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;
36864
+ if (owner.recordId !== currentRecord.id) {
36865
+ owner.recordId = currentRecord.id;
36866
+ owner.retired = false;
36867
+ }
36684
36868
  BufferingCoordinator.reflectionBufferCycleIds.set(bufferKey, cycleId);
36685
36869
  const allLines = (currentRecord.activeObservations ?? "").split("\n");
36686
36870
  const totalLines = allLines.length;
@@ -36696,7 +36880,7 @@ var ReflectorRunner = class {
36696
36880
  const reflectedObservationLineCount = linesToReflect;
36697
36881
  const sliceTokenEstimate = Math.round(avgTokensPerLine * linesToReflect);
36698
36882
  const compressionTarget = Math.round(sliceTokenEstimate * .75);
36699
- omDebug(`[OM:reflect] doAsyncBufferedReflection: slicing observations for reflection — totalLines=${totalLines}, avgTokPerLine=${avgTokensPerLine.toFixed(1)}, activationPointTokens=${activationPointTokens}, linesToReflect=${linesToReflect}/${totalLines}, sliceTokenEstimate=${sliceTokenEstimate}, compressionTarget=${compressionTarget}`);
36883
+ omDebug(`[OM:reflect] doAsyncBufferedReflection: slicing observations for reflection \u2014 totalLines=${totalLines}, avgTokPerLine=${avgTokensPerLine.toFixed(1)}, activationPointTokens=${activationPointTokens}, linesToReflect=${linesToReflect}/${totalLines}, sliceTokenEstimate=${sliceTokenEstimate}, compressionTarget=${compressionTarget}`);
36700
36884
  omDebug(`[OM:reflect] doAsyncBufferedReflection: starting reflector call, recordId=${currentRecord.id}, observationTokens=${sliceTokenEstimate}, compressionTarget=${compressionTarget} (inputTokens), activeObsLength=${activeObservations.length}, reflectedLineCount=${reflectedObservationLineCount}`);
36701
36885
  if (writer) {
36702
36886
  const startMarker = createBufferingStartMarker({
@@ -36717,10 +36901,18 @@ var ReflectorRunner = class {
36717
36901
  const compressionStartLevel = await this.getCompressionStartLevel(requestContext);
36718
36902
  const reflectResult = await this.call(activeObservations, void 0, void 0, compressionTarget, void 0, true, compressionStartLevel, requestContext, priorExtractedValues, observabilityContext, void 0, mainAgent, sendSignal, currentModel);
36719
36903
  reflectResult.observations = await applyTextTransform(this.hooks, "afterReflection", reflectResult.observations, hookContext);
36904
+ if (!reflectResult.observations.trim()) {
36905
+ omDebug(`[OM:reflect] doAsyncBufferedReflection: reflection for ${currentRecord.id} is empty after afterReflection; discarding it`);
36906
+ owner.retired = true;
36907
+ return {
36908
+ usage: reflectResult.usage,
36909
+ providerMetadata: reflectResult.providerMetadata
36910
+ };
36911
+ }
36720
36912
  const reflectionTokenCount = this.tokenCounter.countObservations(reflectResult.observations);
36721
36913
  omDebug(`[OM:reflect] doAsyncBufferedReflection: reflector returned ${reflectionTokenCount} tokens (${reflectResult.observations?.length} chars), saving to recordId=${currentRecord.id}`);
36722
36914
  if (!await runOMCommit(this.buffering.getLockKey(currentRecord.threadId, currentRecord.resourceId), async () => {
36723
- if ((await this.storage.getObservationalMemory(currentRecord.threadId, currentRecord.resourceId))?.id !== currentRecord.id) return false;
36915
+ if ((await this.storage.getObservationalMemory(currentRecord.threadId, currentRecord.resourceId))?.id !== currentRecord.id || BufferingCoordinator.reflectionBufferOwners.get(bufferKey) !== owner) return false;
36724
36916
  await this.storage.updateBufferedReflection({
36725
36917
  id: currentRecord.id,
36726
36918
  reflection: reflectResult.observations,
@@ -36728,17 +36920,18 @@ var ReflectorRunner = class {
36728
36920
  inputTokenCount: sliceTokenEstimate,
36729
36921
  reflectedObservationLineCount
36730
36922
  });
36923
+ const buffered = await this.storage.getObservationalMemory(currentRecord.threadId, currentRecord.resourceId);
36924
+ if (buffered?.id === currentRecord.id && buffered.bufferedReflection === reflectResult.observations) await stageBufferedReflectionValues(this.storage, buffered, reflectResult.extractedValues);
36731
36925
  return true;
36732
36926
  })) {
36733
36927
  omDebug(`[OM:reflect] doAsyncBufferedReflection: record ${currentRecord.id} is no longer the head; discarding the buffered reflection`);
36734
- BufferingCoordinator.lastBufferedBoundary.delete(bufferKey);
36928
+ owner.retired = true;
36735
36929
  return {
36736
36930
  usage: reflectResult.usage,
36737
36931
  providerMetadata: reflectResult.providerMetadata
36738
36932
  };
36739
36933
  }
36740
36934
  omDebug(`[OM:reflect] doAsyncBufferedReflection: bufferedReflection saved with lineCount=${reflectedObservationLineCount}`);
36741
- await persistThreadExtractedValues(this.storage, this.reflectionConfig.extractors, currentRecord.threadId ?? void 0, reflectResult.extractedValues);
36742
36935
  if (writer) {
36743
36936
  const endMarker = createBufferingEndMarker({
36744
36937
  cycleId,
@@ -36764,6 +36957,57 @@ var ReflectorRunner = class {
36764
36957
  };
36765
36958
  }
36766
36959
  /**
36960
+ * Decide what a buffered-reflection swap did. Built-in adapters only swap the buffer and line
36961
+ * count in the snapshot, return the stored record (no new generation) when another writer
36962
+ * extended them after the head check, and mark a generation they created after that check with
36963
+ * `bufferedReflectionVerified`. Adapters without that check build the new generation from
36964
+ * whatever is stored. Either way the swap must also produce what the snapshot's buffer and line
36965
+ * count give from the text the swap retired (retired records are never written again, so that
36966
+ * text is exactly what the swap read).
36967
+ *
36968
+ * Staged values are published only with the adapter's proof. Without it an extension that
36969
+ * repeats the unreflected tail produces the same text as the snapshot's buffer, so the values
36970
+ * fail closed: the activation still applies, but the staged values stay unpublished.
36971
+ */
36972
+ async classifyBufferedReflectionSwap({ result, newRecordId, snapshot, bufferedReflection, reflectedLineCount }) {
36973
+ if (result.id === snapshot.id) return {
36974
+ kind: "not-applied",
36975
+ headId: result.id
36976
+ };
36977
+ const createdByThisSwap = result.id === newRecordId;
36978
+ if (!createdByThisSwap && result.supersededBy !== void 0) return {
36979
+ kind: "not-applied",
36980
+ headId: result.id
36981
+ };
36982
+ const swapActiveObservations = result.activeObservations;
36983
+ const bufferedReflectionVerified = result.bufferedReflectionVerified === true;
36984
+ let matchesSnapshotBuffer = false;
36985
+ try {
36986
+ const retired = (await this.storage.getObservationalMemoryHistory(snapshot.threadId, snapshot.resourceId, 5, { recordId: snapshot.id })).find((candidate) => candidate.id === snapshot.id);
36987
+ matchesSnapshotBuffer = retired !== void 0 && swapActiveObservations === bufferedActivationText({
36988
+ bufferedReflection,
36989
+ observations: retired.activeObservations,
36990
+ reflectedLineCount
36991
+ });
36992
+ } catch (error) {
36993
+ omError("[OM] Failed to read the generation retired by buffered reflection activation", error);
36994
+ }
36995
+ const snapshotBufferActivated = matchesSnapshotBuffer && bufferedReflectionVerified;
36996
+ if (createdByThisSwap) return {
36997
+ kind: "applied",
36998
+ record: result,
36999
+ snapshotBufferActivated
37000
+ };
37001
+ return matchesSnapshotBuffer ? {
37002
+ kind: "applied",
37003
+ record: result,
37004
+ snapshotBufferActivated
37005
+ } : {
37006
+ kind: "not-applied",
37007
+ headId: result.id
37008
+ };
37009
+ }
37010
+ /**
36767
37011
  * Try to activate buffered reflection when threshold is reached.
36768
37012
  * Returns a discriminated result so the caller can distinguish between
36769
37013
  * "activated", "no buffer present", and "suppressed by overshoot guard"
@@ -36783,24 +37027,32 @@ var ReflectorRunner = class {
36783
37027
  }
36784
37028
  }
36785
37029
  }
36786
- const freshRecord = await this.storage.getObservationalMemory(record.threadId, record.resourceId);
37030
+ const storedRecord = await this.storage.getObservationalMemory(record.threadId, record.resourceId);
37031
+ const freshRecord = storedRecord ? { ...storedRecord } : void 0;
36787
37032
  omDebug(`[OM:reflect] tryActivateBufferedReflection: recordId=${record.id}, hasBufferedReflection=${!!freshRecord?.bufferedReflection}, bufferedReflectionLen=${freshRecord?.bufferedReflection?.length ?? 0}`);
36788
37033
  omDebug(`[OM:reflect] tryActivateBufferedReflection: freshRecord.id=${freshRecord?.id}, freshBufferedReflection=${freshRecord?.bufferedReflection ? "present (" + freshRecord.bufferedReflection.length + " chars)" : "empty"}, freshObsTokens=${freshRecord?.observationTokenCount}`);
37034
+ if (freshRecord) await BufferingCoordinator.reconcileReflectionBufferHead(bufferKey, freshRecord.id, () => this.storage.getObservationalMemory(record.threadId, record.resourceId));
36789
37035
  if (!freshRecord?.bufferedReflection) {
36790
37036
  omDebug(`[OM:reflect] tryActivateBufferedReflection: no buffered reflection after re-fetch`);
36791
37037
  return { status: "no-buffer" };
36792
37038
  }
36793
37039
  const beforeTokens = freshRecord.observationTokenCount ?? 0;
36794
37040
  const reflectedLineCount = freshRecord.reflectedObservationLineCount ?? 0;
36795
- const unreflectedLines = (freshRecord.activeObservations ?? "").split("\n").slice(reflectedLineCount);
37041
+ const currentObservations = freshRecord.activeObservations ?? "";
37042
+ const unreflectedLines = currentObservations.split("\n").slice(reflectedLineCount);
36796
37043
  const unreflectedContent = unreflectedLines.join("\n").trim();
36797
- const combinedObservations = unreflectedContent ? `${freshRecord.bufferedReflection}\n\n${unreflectedContent}` : freshRecord.bufferedReflection;
37044
+ const bufferedReflection = freshRecord.bufferedReflection;
37045
+ const combinedObservations = bufferedActivationText({
37046
+ bufferedReflection,
37047
+ observations: currentObservations,
37048
+ reflectedLineCount
37049
+ });
36798
37050
  const combinedTokenCount = this.tokenCounter.countObservations(combinedObservations);
36799
37051
  if (activationMetadata?.triggeredBy === "ttl" || activationMetadata?.triggeredBy === "provider_change") {
36800
37052
  const unreflectedTailTokens = unreflectedContent ? this.tokenCounter.countObservations(unreflectedContent) : 0;
36801
37053
  const bufferedReflectionTokens = freshRecord.bufferedReflectionTokens ?? 0;
36802
37054
  if (unreflectedTailTokens < bufferedReflectionTokens) {
36803
- omDebug(`[OM:reflect] tryActivateBufferedReflection: suppressing early ${activationMetadata.triggeredBy} activation — unreflectedTailTokens=${unreflectedTailTokens} < bufferedReflectionTokens=${bufferedReflectionTokens}; keeping buffer for threshold activation`);
37055
+ omDebug(`[OM:reflect] tryActivateBufferedReflection: suppressing early ${activationMetadata.triggeredBy} activation \u2014 unreflectedTailTokens=${unreflectedTailTokens} < bufferedReflectionTokens=${bufferedReflectionTokens}; keeping buffer for threshold activation`);
36804
37056
  return {
36805
37057
  status: "suppressed",
36806
37058
  reason: "composition"
@@ -36811,7 +37063,7 @@ var ReflectorRunner = class {
36811
37063
  const regularActivationTarget = reflectThreshold * (1 - bufferActivation);
36812
37064
  const minCombinedTokens = Math.round(regularActivationTarget * EARLY_ACTIVATION_SIZE_FLOOR_RATIO);
36813
37065
  if (combinedTokenCount < minCombinedTokens) {
36814
- omDebug(`[OM:reflect] tryActivateBufferedReflection: suppressing early ${activationMetadata.triggeredBy} activation — combinedTokenCount=${combinedTokenCount} < minCombinedTokens=${minCombinedTokens} (${EARLY_ACTIVATION_SIZE_FLOOR_RATIO * 100}% of regular activation target ${Math.round(regularActivationTarget)}, threshold=${reflectThreshold}, bufferActivation=${bufferActivation}); keeping buffer for threshold activation`);
37066
+ omDebug(`[OM:reflect] tryActivateBufferedReflection: suppressing early ${activationMetadata.triggeredBy} activation \u2014 combinedTokenCount=${combinedTokenCount} < minCombinedTokens=${minCombinedTokens} (${EARLY_ACTIVATION_SIZE_FLOOR_RATIO * 100}% of regular activation target ${Math.round(regularActivationTarget)}, threshold=${reflectThreshold}, bufferActivation=${bufferActivation}); keeping buffer for threshold activation`);
36815
37067
  return {
36816
37068
  status: "suppressed",
36817
37069
  reason: "size"
@@ -36820,28 +37072,48 @@ var ReflectorRunner = class {
36820
37072
  }
36821
37073
  omDebug(`[OM:reflect] tryActivateBufferedReflection: activating, beforeTokens=${beforeTokens}, combinedTokenCount=${combinedTokenCount}, reflectedLineCount=${reflectedLineCount}, unreflectedLines=${unreflectedLines.length}`);
36822
37074
  const newRecordId = crypto.randomUUID();
36823
- const swapped = await runOMCommit(lockKey, () => {
37075
+ const commit = await runOMCommit(lockKey, async () => {
36824
37076
  abortSignal?.throwIfAborted();
36825
- return this.storage.swapBufferedReflectionToActive({
37077
+ const head = await this.storage.getObservationalMemory(record.threadId, record.resourceId);
37078
+ if (head && (head.id !== freshRecord.id || head.bufferedReflection !== freshRecord.bufferedReflection || head.reflectedObservationLineCount !== freshRecord.reflectedObservationLineCount)) return {
37079
+ kind: "not-applied",
37080
+ headId: head.id
37081
+ };
37082
+ const result = await this.storage.swapBufferedReflectionToActive({
36826
37083
  currentRecord: freshRecord,
36827
37084
  tokenCount: combinedTokenCount,
36828
37085
  newRecordId
36829
37086
  });
37087
+ const outcome = await this.classifyBufferedReflectionSwap({
37088
+ result,
37089
+ newRecordId,
37090
+ snapshot: freshRecord,
37091
+ bufferedReflection,
37092
+ reflectedLineCount
37093
+ });
37094
+ if (outcome.kind === "applied" && outcome.snapshotBufferActivated) try {
37095
+ await publishBufferedReflectionValues(this.storage, this.reflectionConfig.extractors, freshRecord);
37096
+ } catch (error) {
37097
+ omError("[OM] Failed to publish buffered reflection values after activation", error);
37098
+ }
37099
+ return outcome;
36830
37100
  }, {
36831
37101
  priority: "reflection",
36832
37102
  abortSignal
36833
37103
  });
36834
- if (!isReflectionApplied(swapped, newRecordId, freshRecord.id)) {
36835
- omDebug(`[OM:reflect] tryActivateBufferedReflection: buffered reflection on ${freshRecord.id} not applied (head is ${swapped.id})`);
37104
+ if (commit.kind === "not-applied") {
37105
+ omDebug(`[OM:reflect] tryActivateBufferedReflection: buffered reflection on ${freshRecord.id} not applied (head is ${commit.headId})`);
37106
+ if (commit.headId !== freshRecord.id) BufferingCoordinator.retireReflectionBuffer(bufferKey, freshRecord.id);
36836
37107
  return { status: "not-applied" };
36837
37108
  }
36838
- BufferingCoordinator.lastBufferedBoundary.delete(bufferKey);
37109
+ if (!commit.snapshotBufferActivated) omDebug(`[OM:reflect] tryActivateBufferedReflection: ${commit.record.id} does not hold exactly the snapshot's buffered reflection (extended by another writer, or unverifiable); staged values stay unpublished`);
37110
+ const originalCycleId = BufferingCoordinator.consumeReflectionBuffer(bufferKey, freshRecord.id);
36839
37111
  const afterRecord = await this.storage.getObservationalMemory(record.threadId, record.resourceId);
36840
37112
  const afterTokens = afterRecord?.observationTokenCount ?? 0;
36841
37113
  omDebug(`[OM:reflect] tryActivateBufferedReflection: activation complete! beforeTokens=${beforeTokens}, afterTokens=${afterTokens}, newRecordId=${afterRecord?.id}, newGenCount=${afterRecord?.generationCount}`);
36842
37114
  if (writer) {
36843
37115
  const activationMarker = createActivationMarker({
36844
- cycleId: BufferingCoordinator.reflectionBufferCycleIds.get(bufferKey) ?? `reflect-act-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`,
37116
+ cycleId: originalCycleId ?? `reflect-act-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`,
36845
37117
  operationType: "reflection",
36846
37118
  chunksActivated: 1,
36847
37119
  tokensActivated: beforeTokens,
@@ -36867,7 +37139,6 @@ var ReflectorRunner = class {
36867
37139
  }).catch(() => {});
36868
37140
  await this.persistMarkerToMessage(activationMarker, messageList, freshRecord.threadId ?? "", freshRecord.resourceId ?? void 0, abortSignal);
36869
37141
  }
36870
- BufferingCoordinator.reflectionBufferCycleIds.delete(bufferKey);
36871
37142
  return { status: "activated" };
36872
37143
  }
36873
37144
  /**
@@ -36884,7 +37155,7 @@ var ReflectorRunner = class {
36884
37155
  const priorExtractedValues = await getThreadExtractedValues(this.storage, this.reflectionConfig.extractors, requestedThreadId ?? record.threadId);
36885
37156
  abortSignal?.throwIfAborted();
36886
37157
  if (this.buffering.isAsyncReflectionEnabled() && observationTokens < reflectThreshold) {
36887
- if ((() => {
37158
+ if (await (async () => {
36888
37159
  if (!this.buffering.isAsyncReflectionEnabled()) return false;
36889
37160
  if (record.isBufferingReflection) {
36890
37161
  if (isOpActiveInProcess(record.id, "bufferingReflection")) return false;
@@ -36892,6 +37163,7 @@ var ReflectorRunner = class {
36892
37163
  this.storage.setBufferingReflectionFlag(record.id, false).catch(() => {});
36893
37164
  }
36894
37165
  const bufferKey = this.buffering.getReflectionBufferKey(lockKey);
37166
+ await BufferingCoordinator.reconcileReflectionBufferHead(bufferKey, record.id, () => this.storage.getObservationalMemory(record.threadId, record.resourceId));
36895
37167
  if (this.buffering.isAsyncBufferingInProgress(bufferKey)) return false;
36896
37168
  if (BufferingCoordinator.lastBufferedBoundary.has(bufferKey)) return false;
36897
37169
  if (record.bufferedReflection) return false;
@@ -36920,7 +37192,7 @@ var ReflectorRunner = class {
36920
37192
  omDebug(`[OM:reflect] isReflecting=true and active in this process, skipping`);
36921
37193
  return;
36922
37194
  }
36923
- omDebug(`[OM:reflect] isReflecting=true but NOT active in this process — stale flag from dead process, clearing`);
37195
+ omDebug(`[OM:reflect] isReflecting=true but NOT active in this process \u2014 stale flag from dead process, clearing`);
36924
37196
  await this.storage.setReflectingFlag(record.id, false);
36925
37197
  }
36926
37198
  if (this.buffering.isAsyncReflectionEnabled()) {
@@ -36934,10 +37206,15 @@ var ReflectorRunner = class {
36934
37206
  else {
36935
37207
  const activationPoint = reflectThreshold * this.reflectionConfig.bufferActivation;
36936
37208
  if (observationTokens < activationPoint) {
36937
- omDebug(`[OM:reflect] skipping async reflection — observationTokens (${observationTokens}) below activation point (${activationPoint}), triggered by ${activationTriggeredBy}`);
37209
+ omDebug(`[OM:reflect] skipping async reflection \u2014 observationTokens (${observationTokens}) below activation point (${activationPoint}), triggered by ${activationTriggeredBy}`);
37210
+ return;
37211
+ }
37212
+ const bufferKey = this.buffering.getReflectionBufferKey(lockKey);
37213
+ if (this.buffering.isAsyncBufferingInProgress(bufferKey) || BufferingCoordinator.lastBufferedBoundary.has(bufferKey)) {
37214
+ omDebug(`[OM:reflect] skipping async reflection \u2014 reflection buffer already active or present for ${bufferKey}`);
36938
37215
  return;
36939
37216
  }
36940
- omDebug(`[OM:reflect] async activation failed, no blockAfter or below it (obsTokens=${observationTokens}, blockAfter=${this.reflectionConfig.blockAfter}) — starting background reflection`);
37217
+ omDebug(`[OM:reflect] async activation failed, no blockAfter or below it (obsTokens=${observationTokens}, blockAfter=${this.reflectionConfig.blockAfter}) \u2014 starting background reflection`);
36941
37218
  this.startAsyncBufferedReflection(record, observationTokens, lockKey, writer, requestContext, observabilityContext, reflectionHooks, priorExtractedValues, mainAgent, sendSignal, trigger, currentModel);
36942
37219
  return;
36943
37220
  }
@@ -36945,7 +37222,7 @@ var ReflectorRunner = class {
36945
37222
  if (activationTriggeredBy === "threshold") {
36946
37223
  const suppressedAtTokens = this.syncReflectionSuppression.get(lockKey);
36947
37224
  if (suppressedAtTokens !== void 0 && observationTokens === suppressedAtTokens) {
36948
- omDebug(`[OM:reflect] skipping sync reflection — observations unchanged at ${observationTokens} tokens since the last unproductive attempt; retrying once they change`);
37225
+ omDebug(`[OM:reflect] skipping sync reflection \u2014 observations unchanged at ${observationTokens} tokens since the last unproductive attempt; retrying once they change`);
36949
37226
  return;
36950
37227
  }
36951
37228
  }
@@ -37788,7 +38065,7 @@ var ObservationalMemory = class ObservationalMemory {
37788
38065
  const asyncBufferingDisabled = config.observation?.bufferTokens === false || config.scope === "resource" && !userExplicitlyConfiguredAsync;
37789
38066
  if (isSharedBudget && !asyncBufferingDisabled) {
37790
38067
  if (userExplicitlyConfiguredAsync) throw new Error("shareTokenBudget requires async buffering to be disabled (this is a temporary limitation). Add observation: { bufferTokens: false } to your config:\n\n observationalMemory: {\n shareTokenBudget: true,\n observation: { bufferTokens: false },\n }\n\nRemove any other async buffering settings (bufferTokens, bufferActivation, blockAfter).");
37791
- else throw new Error("shareTokenBudget requires async buffering to be disabled (this is a temporary limitation). Add observation: { bufferTokens: false } to your config:\n\n observationalMemory: {\n shareTokenBudget: true,\n observation: { bufferTokens: false },\n }\n\nAsync buffering is enabled by default — this opt-out is only needed when using shareTokenBudget.");
38068
+ else throw new Error("shareTokenBudget requires async buffering to be disabled (this is a temporary limitation). Add observation: { bufferTokens: false } to your config:\n\n observationalMemory: {\n shareTokenBudget: true,\n observation: { bufferTokens: false },\n }\n\nAsync buffering is enabled by default \u2014 this opt-out is only needed when using shareTokenBudget.");
37792
38069
  }
37793
38070
  const observationActivateAfterIdle = config.observation?.activateAfterIdle ?? config.activateAfterIdle;
37794
38071
  const observationActivateAfterIdlePath = config.observation?.activateAfterIdle !== void 0 ? "observation.activateAfterIdle" : "activateAfterIdle";
@@ -37885,7 +38162,7 @@ var ObservationalMemory = class ObservationalMemory {
37885
38162
  hasWarnedResourceScopeDeprecation = true;
37886
38163
  console.warn("[Mastra] Observational memory `scope: 'resource'` is deprecated and will be removed in a future release because it works much worse than thread scope for prompt caching and agent understanding. Remove `scope` to use the default thread scope, and enable `retrieval` for cross-thread recall. See https://mastra.ai/docs/memory/observational-memory#resource-scope-deprecated");
37887
38164
  }
37888
- omDebug(`[OM:init] new ObservationalMemory instance created — scope=${this.scope}, messageTokens=${JSON.stringify(this.observationConfig.messageTokens)}, obsAsyncEnabled=${this.buffering.isAsyncObservationEnabled()}, bufferTokens=${this.observationConfig.bufferTokens}, bufferActivation=${this.observationConfig.bufferActivation}, blockAfter=${this.observationConfig.blockAfter}, reflectionTokens=${this.reflectionConfig.observationTokens}, refAsyncEnabled=${this.buffering.isAsyncReflectionEnabled()}, refAsyncActivation=${this.reflectionConfig.bufferActivation}, refBlockAfter=${this.reflectionConfig.blockAfter}`);
38165
+ omDebug(`[OM:init] new ObservationalMemory instance created \u2014 scope=${this.scope}, messageTokens=${JSON.stringify(this.observationConfig.messageTokens)}, obsAsyncEnabled=${this.buffering.isAsyncObservationEnabled()}, bufferTokens=${this.observationConfig.bufferTokens}, bufferActivation=${this.observationConfig.bufferActivation}, blockAfter=${this.observationConfig.blockAfter}, reflectionTokens=${this.reflectionConfig.observationTokens}, refAsyncEnabled=${this.buffering.isAsyncReflectionEnabled()}, refAsyncActivation=${this.reflectionConfig.bufferActivation}, refBlockAfter=${this.reflectionConfig.blockAfter}`);
37889
38166
  }
37890
38167
  __registerMastra(mastra) {
37891
38168
  this.mastra = mastra;
@@ -38166,7 +38443,7 @@ var ObservationalMemory = class ObservationalMemory {
38166
38443
  threadId: null,
38167
38444
  resourceId: resourceId ?? threadId
38168
38445
  };
38169
- if (!threadId) throw new Error("ObservationalMemory (scope: 'thread') requires a threadId, but received an empty value. This is a bug — getThreadContext should have caught this earlier.");
38446
+ if (!threadId) throw new Error("ObservationalMemory (scope: 'thread') requires a threadId, but received an empty value. This is a bug \u2014 getThreadContext should have caught this earlier.");
38170
38447
  return {
38171
38448
  threadId,
38172
38449
  resourceId: resourceId ?? threadId
@@ -38477,7 +38754,7 @@ var ObservationalMemory = class ObservationalMemory {
38477
38754
  const isImportant = new Array(totalCount);
38478
38755
  for (let i = 0; i < totalCount; i++) {
38479
38756
  lineTokens[i] = this.tokenCounter.countString(lines[i]);
38480
- isImportant[i] = lines[i].includes("🔴") || lines[i].includes("✅");
38757
+ isImportant[i] = lines[i].includes("\u{1F534}") || lines[i].includes("\u2705");
38481
38758
  }
38482
38759
  const suffixTokens = new Array(totalCount + 1);
38483
38760
  suffixTokens[totalCount] = 0;
@@ -38810,7 +39087,7 @@ ${formattedMessages}
38810
39087
  resourceId: freshRecord.resourceId ?? void 0
38811
39088
  });
38812
39089
  } catch (err) {
38813
- omError("[OM] Failed to persist sealed messages before buffering — skipping observation cycle", err);
39090
+ omError("[OM] Failed to persist sealed messages before buffering \u2014 skipping observation cycle", err);
38814
39091
  return;
38815
39092
  }
38816
39093
  const cycleId = `buffer-obs-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;
@@ -39960,7 +40237,7 @@ ${formattedMessages}
39960
40237
  usage: void 0
39961
40238
  };
39962
40239
  }
39963
- omDebug(`[OM:reflect] isReflecting=true but NOT active in this process — stale flag from dead process, clearing`);
40240
+ omDebug(`[OM:reflect] isReflecting=true but NOT active in this process \u2014 stale flag from dead process, clearing`);
39964
40241
  await this.storage.setReflectingFlag(record.id, false);
39965
40242
  }
39966
40243
  await this.storage.setReflectingFlag(record.id, true);
@@ -40195,7 +40472,7 @@ ${formattedMessages}
40195
40472
  // src/processors/observational-memory/temporal-markers.ts
40196
40473
  const TEMPORAL_GAP_REMINDER_TYPE = "temporal-gap";
40197
40474
  function getTemporalGapReminderText(gapText, timestamp) {
40198
- return `${gapText} — ${formatTemporalTimestamp(new Date(timestamp))}`;
40475
+ return `${gapText} \u2014 ${formatTemporalTimestamp(new Date(timestamp))}`;
40199
40476
  }
40200
40477
  function getTemporalGapReminderMetadata(message, gapText, gapMs, timestamp) {
40201
40478
  const formattedTimestamp = formatTemporalTimestamp(new Date(timestamp));
@@ -40417,14 +40694,14 @@ var ObservationalMemoryProcessor = class {
40417
40694
  omDebug(`[OM:processInputStep:ENTER] step=${stepNumber}, hasMastraMemory=${!!requestContext?.get("MastraMemory")}, hasMemoryInfo=${!!messageList?.serialize()?.memoryInfo?.threadId}`);
40418
40695
  const context = this.engine.getThreadContext(requestContext, messageList);
40419
40696
  if (!context) {
40420
- omDebug(`[OM:processInputStep:NO-CONTEXT] getThreadContext returned null — returning early`);
40697
+ omDebug(`[OM:processInputStep:NO-CONTEXT] getThreadContext returned null \u2014 returning early`);
40421
40698
  return messageList;
40422
40699
  }
40423
40700
  const gatewayMemoryManaged = await isGatewayMemoryManaged(model);
40424
40701
  state[GATEWAY_STATE_KEY] = gatewayMemoryManaged;
40425
40702
  if (gatewayMemoryManaged) {
40426
40703
  await this.endActiveTurn(state);
40427
- omDebug(`[OM:processInputStep:GATEWAY] gateway manages memory — skipping local processing`);
40704
+ omDebug(`[OM:processInputStep:GATEWAY] gateway manages memory \u2014 skipping local processing`);
40428
40705
  return messageList;
40429
40706
  }
40430
40707
  const { threadId, resourceId } = context;
@@ -40645,7 +40922,7 @@ var ObservationalMemoryProcessor = class {
40645
40922
  if (!context) return;
40646
40923
  if (parseMemoryRequestContext(requestContext)?.memoryConfig?.readOnly) return;
40647
40924
  state[CONTEXT_OVERFLOW_STEP_KEY] = stepNumber;
40648
- omDebug(`[OM:processAPIError] context overflow at step ${stepNumber} — observing pending messages`);
40925
+ omDebug(`[OM:processAPIError] context overflow at step ${stepNumber} \u2014 observing pending messages`);
40649
40926
  const { threadId, resourceId } = context;
40650
40927
  await this.engine.waitForBuffering(threadId, resourceId, void 0, args.abortSignal);
40651
40928
  const messages = getObservableMessages(messageList);