From f1a9b1f4cf4259f24954c6629ef77fcd99472162 Mon Sep 17 00:00:00 2001 From: kvpratama Date: Wed, 22 Apr 2026 19:59:15 +0900 Subject: [PATCH] fix(history_text): preserve recent entries when truncating transcript --- mini_coding_agent.py | 9 ++++++++- tests/test_mini_coding_agent.py | 35 +++++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 1 deletion(-) diff --git a/mini_coding_agent.py b/mini_coding_agent.py index 1bf2403..b783edb 100644 --- a/mini_coding_agent.py +++ b/mini_coding_agent.py @@ -58,6 +58,13 @@ def clip(text, limit=MAX_TOOL_OUTPUT): return text[:limit] + f"\n...[truncated {len(text) - limit} chars]" +def tail_clip(text, limit=MAX_HISTORY): + text = str(text) + if len(text) <= limit: + return text + return f"...[truncated {len(text) - limit} chars]\n" + text[-limit:] + + def middle(text, limit): text = str(text).replace("\n", " ") if len(text) <= limit: @@ -414,7 +421,7 @@ def history_text(self): limit = 900 if recent else 220 lines.append(f"[{item['role']}] {clip(item['content'], limit)}") - return clip("\n".join(lines), MAX_HISTORY) + return tail_clip("\n".join(lines), MAX_HISTORY) ######################################################## #### 2) Prompt Shape And Cache Reuse (Continued) ####### diff --git a/tests/test_mini_coding_agent.py b/tests/test_mini_coding_agent.py index 5c62693..fcae548 100644 --- a/tests/test_mini_coding_agent.py +++ b/tests/test_mini_coding_agent.py @@ -397,3 +397,38 @@ def fake_urlopen(request, timeout): assert captured["body"]["raw"] is False assert captured["body"]["think"] is False assert captured["body"]["options"]["num_predict"] == 42 + + +def test_history_text_preserves_recent_when_truncating(tmp_path): + """When history exceeds MAX_HISTORY, recent items should be preserved.""" + from mini_coding_agent import MAX_HISTORY + + agent = build_agent(tmp_path, []) + + # Create history that exceeds MAX_HISTORY + for i in range(70): + agent.record({ + "role": "tool", + "name": "read_file", + "args": {"path": f"file{i}.txt"}, + "content": "x" * 500, # 500 chars of content + "created_at": str(i), + }) + + history = agent.history_text() + + # Verify truncation message is at the TOP (indicating oldest was cut) + assert history.startswith("...[truncated") + + # Verify recent entries are present (last 6 are "recent") + assert "file69.txt" in history # most recent + assert "file68.txt" in history + assert "file67.txt" in history + + # Verify oldest entries are NOT present + assert "file0.txt" not in history + assert "file1.txt" not in history + + # Verify the length is strictly controlled + # It should be roughly MAX_HISTORY + length of the truncation message + assert len(history) <= MAX_HISTORY + 100