Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

fix(memory): parse line-edit JSON with raw_decode

santhreal69582220ef02
diff --git a/deeptutor/services/memory/consolidator/line_doc.py b/deeptutor/services/memory/consolidator/line_doc.py
index cb55cca85..a14d1051e 100644
--- a/deeptutor/services/memory/consolidator/line_doc.py
+++ b/deeptutor/services/memory/consolidator/line_doc.py
@@ -448,7 +448,8 @@ _FENCE_RE = re.compile(r"^```[a-zA-Z]*\s*|\s*```$")
def _extract_json(raw: str) -> str | None:
text = _FENCE_RE.sub("", raw.strip())
- # Find the outermost {...} or [...].
+ # First {...} or [...] via raw_decode so trailing prose braces cannot
+ # extend the slice past the real JSON value.
obj_start = text.find("{")
arr_start = text.find("[")
if obj_start == -1 and arr_start == -1:
@@ -459,12 +460,11 @@ def _extract_json(raw: str) -> str | None:
start = obj_start
else:
start = min(obj_start, arr_start)
- end_obj = text.rfind("}")
- end_arr = text.rfind("]")
- end = max(end_obj, end_arr)
- if end <= start:
+ try:
+ _parsed, end = json.JSONDecoder().raw_decode(text[start:])
+ except json.JSONDecodeError:
return None
- return text[start : end + 1]
+ return text[start : start + end]
__all__ = [
diff --git a/tests/services/memory/test_line_doc.py b/tests/services/memory/test_line_doc.py
index afe6fcba4..d8fd69271 100644
--- a/tests/services/memory/test_line_doc.py
+++ b/tests/services/memory/test_line_doc.py
@@ -214,3 +214,14 @@ def test_serialize_roundtrip_after_edits_keeps_footnotes_consistent() -> None:
assert "notebook:r1-new" in md
# The old ref text is gone from footnotes (replaced, not appended).
assert "notebook:r1," not in md and "notebook:r1\n" not in md
+
+
+def test_parse_edits_payload_tolerates_trailing_brace_prose() -> None:
+ raw = (
+ '{"edits":[{"op":"replace","line":1,"new_text":"ok",'
+ '"refs":["a:b"],"reason":"y"}]} trailing {brace}'
+ )
+ edits = parse_edits_payload(raw)
+ assert len(edits) == 1
+ assert isinstance(edits[0], ReplaceLineOp)
+ assert edits[0].new_text == "ok"