Skip to content

The agent that grows with you

fix(agent): stop the run-budget wrap-up notice from mutating a persisted tool row

nftpoetrist511633be90ef
diff --git a/agent/conversation_loop.py b/agent/conversation_loop.py
index 6f9eff403c2..72a6be2aed9 100644
--- a/agent/conversation_loop.py
+++ b/agent/conversation_loop.py
@@ -127,8 +127,13 @@ def _maybe_inject_run_budget_wrapup(agent: Any, messages: List[Dict[str, Any]])
(time.time() - started) < 0.8 * float(budget)
):
return False
+ from agent.context_compressor import _DB_PERSISTED_MARKER
for msg in reversed(messages):
if isinstance(msg, dict) and msg.get("role") == "tool":
+ # Only the current tool-result tail is mutable; an older turn may already be
+ # cached (same contract as _maybe_inject_iteration_budget_warning).
+ if msg.get(_DB_PERSISTED_MARKER):
+ return False
existing = msg.get("content", "")
if isinstance(existing, str):
msg["content"] = existing + f"\n\n{RUN_BUDGET_WRAPUP_NOTICE}"
diff --git a/agent/tool_executor.py b/agent/tool_executor.py
index a34d2843123..6b15d2f6372 100644
--- a/agent/tool_executor.py
+++ b/agent/tool_executor.py
@@ -173,10 +173,12 @@ def _resolve_concurrent_tool_timeout() -> float | None:
def _flush_session_db_after_tool_progress(agent, messages: list, *, stage: str) -> bool:
"""Flush tool-call progress to the session DB before projecting it to any UI: tool side
effects can kill/restart the process before turn-end persistence runs."""
+ from agent.conversation_loop import _maybe_inject_run_budget_wrapup
from agent.turn_iteration_prep import _maybe_inject_iteration_budget_warning
# Persist exactly the checkpoint text the next model call will see, before stamping
# this tool result as durable. Already-written rows must never be rewritten later.
+ _maybe_inject_run_budget_wrapup(agent, messages)
_maybe_inject_iteration_budget_warning(agent, messages)
try:
persisted = agent._flush_messages_to_session_db(messages) is not False
diff --git a/tests/agent/test_run_budget.py b/tests/agent/test_run_budget.py
index d602bb3d0d1..a29b3c49648 100644
--- a/tests/agent/test_run_budget.py
+++ b/tests/agent/test_run_budget.py
@@ -285,6 +285,23 @@ def test_wrapup_not_injected_without_turn_clock():
assert _maybe_inject_run_budget_wrapup(agent, messages) is False
+def test_wrapup_skips_already_persisted_tool_row():
+ """An already-flushed tool row is append-only; mutating it would diverge the
+ replayed transcript from the live wire bytes and break the prompt cache (same
+ contract as _maybe_inject_iteration_budget_warning)."""
+ from agent.context_compressor import _DB_PERSISTED_MARKER
+ from agent.conversation_loop import _maybe_inject_run_budget_wrapup
+
+ agent = _StubAgent(budget=900, started=time.time() - 800)
+ messages = _tool_messages()
+ messages[-1][_DB_PERSISTED_MARKER] = True
+ snapshot = [dict(m) for m in messages]
+
+ assert _maybe_inject_run_budget_wrapup(agent, messages) is False
+ assert agent._run_budget_wrapup_injected is False
+ assert messages == snapshot
+
+
def test_wrapup_multimodal_tool_content():
"""Content-blocks tool results get a text block appended, not clobbered."""
from agent.conversation_loop import (
@@ -304,6 +321,32 @@ def test_wrapup_multimodal_tool_content():
assert blocks[-1] == {"type": "text", "text": RUN_BUDGET_WRAPUP_NOTICE}
+# ── pre-flush wiring (the notice must reach durable bytes) ─────────────────
+
+
+def test_wrapup_lands_in_the_persisted_row_via_pre_flush_hook(monkeypatch, tmp_path):
+ """The wrap-up notice must be injected BEFORE the tool row is flushed, or it
+ never reaches SQLite: prepare_iteration's own call always runs on an
+ already-persisted row (the previous iteration's flush already ran)."""
+ from hermes_state import SessionDB
+ from agent.tool_executor import _flush_session_db_after_tool_progress
+ from agent.conversation_loop import RUN_BUDGET_WRAPUP_NOTICE
+
+ session_db = SessionDB(db_path=tmp_path / "proof.db")
+ try:
+ agent = _make_agent(tmp_path, monkeypatch, session_db=session_db, run_budget_seconds=900)
+ agent._run_budget_started_at = time.time() - 800 # 89% elapsed
+ messages = _tool_messages()
+
+ assert _flush_session_db_after_tool_progress(agent, messages, stage="checkpoint")
+
+ persisted = session_db.get_messages(agent.session_id)
+ assert any(RUN_BUDGET_WRAPUP_NOTICE in str(row["content"]) for row in persisted)
+ assert agent._run_budget_wrapup_injected is True
+ finally:
+ session_db.close()
+
+
# ── turn clock stamping ────────────────────────────────────────────────────