Merge pull request #645 from santhreal/fix/line-doc-raw-decode-edits-dev

fix(memory): parse line-edit JSON with raw_decode
This commit is contained in:
Bingxi Zhao
2026-07-23 22:26:47 +08:00
committed by GitHub
2 changed files with 17 additions and 6 deletions

View File

@@ -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__ = [

View File

@@ -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"