Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(runtime): preserve Unicode records and handoff summaries

Haozhe Wuaba6b2cf2519
diff --git a/agent/src/agent/context_budget.py b/agent/src/agent/context_budget.py
index 22334d5ce..d07d17a46 100644
--- a/agent/src/agent/context_budget.py
+++ b/agent/src/agent/context_budget.py
@@ -85,8 +85,10 @@ def resolve_window(
if learned_window:
return int(learned_window), "learned:context_length_error"
catalog = _catalog()
- provider = (provider or "").strip().lower()
- model = (model or "").strip()
+ # Provider/model labels arrive from different adapters with either hyphens
+ # or underscores. Catalog patterns use the canonical hyphenated spelling.
+ provider = (provider or "").strip().lower().replace("_", "-")
+ model = (model or "").strip().replace("_", "-")
for entry in catalog["models"]:
if entry.get("provider") and entry["provider"] != provider:
continue
diff --git a/agent/src/agent/context_compact.py b/agent/src/agent/context_compact.py
index 9ee81bc04..f2a2d59e3 100644
--- a/agent/src/agent/context_compact.py
+++ b/agent/src/agent/context_compact.py
@@ -27,6 +27,7 @@ COLLAPSE_TAIL = 500
# which is not a constant — it embeds the original payload length, so it is
# built by ``_cleared_text`` and matched by ``_is_cleared``.
_STUB_RESULT_CONTENT = "[Result from earlier context — see summary above]"
+_HANDOFF_SUMMARY_PREFIX = "[Conversation compressed — handoff summary."
TAIL_TOKEN_BUDGET = 20_000
SUMMARY_CHUNK_CHARS = 80_000
@@ -305,6 +306,10 @@ def _context_collapse(messages: list, *, preserve_tool_call_ids: Optional[set[st
content = msg.get("content")
if not isinstance(content, str) or len(content) <= COLLAPSE_TEXT_MIN:
continue
+ # The handoff summary is the only surviving copy of older context
+ # after layer 3. Layer 2 must leave it intact for the next turn.
+ if content.startswith(_HANDOFF_SUMMARY_PREFIX):
+ continue
if _result_data_gone(content):
continue
head = content[:COLLAPSE_HEAD]
diff --git a/agent/src/agent/trace.py b/agent/src/agent/trace.py
index 1f04ad54f..2854c46f1 100644
--- a/agent/src/agent/trace.py
+++ b/agent/src/agent/trace.py
@@ -322,7 +322,10 @@ class TraceWriter:
return []
fields = set(resolve_fields) if resolve_fields is not None else None
entries: List[Dict[str, Any]] = []
- for line in path.read_text(encoding="utf-8").splitlines():
+ # JSONL records are separated by LF. ``str.splitlines()`` also treats
+ # U+2028/U+2029 as delimiters, but those characters are valid JSON
+ # string data and must remain inside the record.
+ for line in path.read_text(encoding="utf-8").split("\n"):
line = line.strip()
if not line:
continue
diff --git a/agent/src/governance/ledger.py b/agent/src/governance/ledger.py
index 420af028e..d294a3fd0 100644
--- a/agent/src/governance/ledger.py
+++ b/agent/src/governance/ledger.py
@@ -433,7 +433,9 @@ def append_record(
start_prev = str(tail[-1]["record_hash"])
verification, last_seq, last_hash = _walk_chain(
- _iter_parsed_lines(existing_text.splitlines()),
+ # JSONL records are separated by LF; Unicode line separators
+ # may occur inside a JSON string and are not record breaks.
+ _iter_parsed_lines(existing_text.split("\n")),
start_seq=start_seq,
start_prev_hash=start_prev,
)
@@ -480,7 +482,8 @@ def _read_raw_records(path: Path) -> list[dict[str, Any]]:
if not path.exists():
return []
records: list[dict[str, Any]] = []
- for line in path.read_text(encoding="utf-8").splitlines():
+ # Keep U+2028/U+2029 inside JSON string values; only LF terminates JSONL.
+ for line in path.read_text(encoding="utf-8").split("\n"):
stripped = line.strip()
if not stripped:
continue
@@ -696,7 +699,7 @@ def _iter_all_segment_lines(
for segment in [*archive_segments(path), path]:
if not segment.exists():
continue
- lines = segment.read_text(encoding="utf-8").splitlines()
+ lines = segment.read_text(encoding="utf-8").split("\n")
for local_index, record, parse_error in _iter_parsed_lines(lines):
yield offset + local_index, record, parse_error
if parse_error is not None:
diff --git a/agent/src/session/search.py b/agent/src/session/search.py
index a5b803a18..dc66bd2f3 100644
--- a/agent/src/session/search.py
+++ b/agent/src/session/search.py
@@ -441,9 +441,10 @@ class SessionSearchIndex:
self.index_session(sid, title, ts=ts)
if messages_file.exists():
- for line in (
- messages_file.read_text(encoding="utf-8").strip().splitlines()
- ):
+ # JSONL uses LF as its record separator. ``splitlines``
+ # incorrectly treats U+2028/U+2029 inside message text as
+ # separators and drops the affected record during rebuild.
+ for line in messages_file.read_text(encoding="utf-8").strip().split("\n"):
if not line.strip():
continue
try:
diff --git a/agent/tests/test_context_budget.py b/agent/tests/test_context_budget.py
index 85dc2e5e0..624416214 100644
--- a/agent/tests/test_context_budget.py
+++ b/agent/tests/test_context_budget.py
@@ -54,6 +54,11 @@ def test_window_comes_from_the_catalog_for_the_reported_models() -> None:
assert resolve_window("openrouter", "deepseek/deepseek-v4-pro")[0] == 1_000_000
+def test_window_resolution_normalizes_underscore_labels() -> None:
+ assert resolve_window("deep_seek", "deepseek_v4_pro")[0] == 1_000_000
+ assert resolve_window("openai_codex", "openai_codex/gpt_6_sol")[0] == 272_000
+
+
def test_provider_scoped_entries_do_not_leak_to_other_providers() -> None:
# The 272K is what the Codex backend publishes; another provider serving a
# model of the same name is not covered by that source.
diff --git a/agent/tests/test_governance.py b/agent/tests/test_governance.py
index cbacbdcb9..9784b3018 100644
--- a/agent/tests/test_governance.py
+++ b/agent/tests/test_governance.py
@@ -396,6 +396,17 @@ def test_only_asserting_untampered_pass_would_be_insufficient_so_also_assert_ok_
assert verify_chain(path) == ChainVerificationResult(ok=True, record_count=5, first_break=None)
+def test_append_record_keeps_unicode_line_separator_in_payload(tmp_path: Path) -> None:
+ path = tmp_path / "chain.jsonl"
+ append_record(path, {"note": "before\u2028after\u2029end"})
+ append_record(path, {"note": "second"})
+
+ result = verify_chain(path)
+ assert result == ChainVerificationResult(ok=True, record_count=2, first_break=None)
+ records = [json.loads(line) for line in path.read_text(encoding="utf-8").split("\n") if line.strip()]
+ assert records[0]["note"] == "before\u2028after\u2029end"
+
+
def test_append_record_refuses_to_extend_an_already_broken_chain(tmp_path: Path) -> None:
path = tmp_path / "chain.jsonl"
_write_five_records(path)
diff --git a/agent/tests/test_loop_helpers.py b/agent/tests/test_loop_helpers.py
index fa6988dde..0df8d435f 100644
--- a/agent/tests/test_loop_helpers.py
+++ b/agent/tests/test_loop_helpers.py
@@ -286,6 +286,22 @@ class TestContextCollapse:
assert "TAIL_MARKER" in collapsed_msg
assert "collapsed" in collapsed_msg
+ def test_preserves_handoff_summary(self) -> None:
+ handoff = (
+ "[Conversation compressed — handoff summary. Transcript: run/trace.jsonl]\n\n"
+ + "critical handoff context "
+ + ("x" * (COLLAPSE_TEXT_MIN + 500))
+ )
+ messages = [{"role": "system", "content": "sys"}, {"role": "user", "content": handoff}]
+ messages.extend(
+ {"role": "user", "content": f"older {i} " + ("z" * (COLLAPSE_TEXT_MIN + 500))}
+ for i in range(COLLAPSE_PRESERVE_RECENT + 2)
+ )
+
+ _context_collapse(messages)
+
+ assert messages[1]["content"] == handoff
+
# ---------------------------------------------------------------------------
# _fix_tool_pairs
diff --git a/agent/tests/test_session_search.py b/agent/tests/test_session_search.py
index ed2402c08..4232a0616 100644
--- a/agent/tests/test_session_search.py
+++ b/agent/tests/test_session_search.py
@@ -237,3 +237,29 @@ class TestReindex:
results = index.search("reindex probe")
assert len(results) >= 1
assert results[0].session_id == "session-001"
+
+ def test_reindex_keeps_unicode_line_separator_inside_message(self, index: SessionSearchIndex, tmp_path: Path) -> None:
+ import json
+
+ store_dir = tmp_path / "sessions"
+ store_dir.mkdir()
+ s_dir = store_dir / "session-unicode"
+ s_dir.mkdir()
+ (s_dir / "session.json").write_text(
+ json.dumps({
+ "session_id": "session-unicode",
+ "title": "Unicode message",
+ "created_at": "2026-01-01T00:00:00",
+ }),
+ encoding="utf-8",
+ )
+ (s_dir / "messages.jsonl").write_text(
+ json.dumps({"role": "user", "content": "before\u2028searchable\u2029after"}, ensure_ascii=False)
+ + "\n",
+ encoding="utf-8",
+ )
+
+ assert index.reindex_from_store(store_dir) == 1
+ results = index.search("searchable")
+ assert len(results) == 1
+ assert results[0].snippet.replace(">>>", "").replace("<<<", "") == "before\u2028searchable\u2029after"
diff --git a/agent/tests/test_trace_writer.py b/agent/tests/test_trace_writer.py
index 5643b98ec..c87c01c3f 100644
--- a/agent/tests/test_trace_writer.py
+++ b/agent/tests/test_trace_writer.py
@@ -84,6 +84,15 @@ def test_trace_reader_refuses_offload_path_escape(tmp_path: Path) -> None:
assert "result" not in entry
+def test_trace_reader_keeps_unicode_line_separator_inside_json_record(tmp_path: Path) -> None:
+ trace = TraceWriter(tmp_path)
+ trace.write({"type": "note", "content": "before\u2028after\u2029end"})
+ trace.close()
+
+ [entry] = TraceWriter.read(tmp_path)
+ assert entry["content"] == "before\u2028after\u2029end"
+
+
def test_text_field_offload_round_trips_selected_fields(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,