Skip to content

fix: handle truncated code blocks in removeCodeBlocks function#4421

Merged
whysosaket merged 2 commits intomainfrom
fix/4401-remove-code-blocks-truncation
Mar 19, 2026
Merged

fix: handle truncated code blocks in removeCodeBlocks function#4421
whysosaket merged 2 commits intomainfrom
fix/4401-remove-code-blocks-truncation

Conversation

@kartik-mem0
Copy link
Copy Markdown
Contributor

Description

removeCodeBlocks fails to strip markdown fences from truncated LLM responses. When an LLM returns JSON wrapped in ```json that gets truncated (no closing fence), the regex doesn't match
and raw text with backticks is passed to JSON.parse, causing a SyntaxError. This silently drops all extracted memories.

Fixed by making the closing fence optional in the regex: (?:```|$) matches either the closing fence or end-of-string.

Fixes #4401

Type of change

  • Bug fix (non-breaking change which fixes an issue)

How Has This Been Tested?

  • Unit Test

Added 7 new test cases covering: truncated blocks (missing closing fence), incomplete JSON, orphan trailing fence, bare fence, multi-block + truncated combo, empty input, and CRLF line endings.
All 12 tests pass (5 existing + 7 new).

cd mem0-ts && npx jest --testPathPattern="remove-code-blocks"

Checklist:

  • My code follows the style guidelines of this project
  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • New and existing unit tests pass locally with my changes
  • Any dependent changes have been merged and published in downstream modules
  • I have checked my code and corrected any misspellings

Maintainer Checklist

@kartik-mem0 kartik-mem0 requested a review from whysosaket March 19, 2026 12:33
@whysosaket whysosaket merged commit 88abb29 into main Mar 19, 2026
6 checks passed
@whysosaket whysosaket deleted the fix/4401-remove-code-blocks-truncation branch March 19, 2026 12:48
jamebobob pushed a commit to jamebobob/mem0-vigil-recall that referenced this pull request Mar 29, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

removeCodeBlocks fails to strip markdown fences from truncated LLM responses

2 participants