Skip to content

The agent that grows with you

feat(cli): add sessions clean-markers to permanently purge stale tool-call markers (#78148)

joaomarcose1a2739692df
diff --git a/hermes_cli/main.py b/hermes_cli/main.py
index cd9966cf8cf..33a751731b1 100644
--- a/hermes_cli/main.py
+++ b/hermes_cli/main.py
@@ -12159,6 +12159,27 @@ def main():
help="Reclaim disk space: merge FTS5 segments + VACUUM (no data change)",
)
+ sessions_clean_markers = sessions_subparsers.add_parser(
+ "clean-markers",
+ help="Permanently clear stale tool-call marker content left by sessions from before #78148",
+ description=(
+ "Before the #78148 fix, a local tool-call template could persist a "
+ "bare bracketed marker (e.g. \"[memory]\") as an assistant turn's "
+ "content instead of real text. This is already repaired in memory "
+ "on every session load, so running this is optional — it rewrites "
+ "the affected rows once, in place, so long-lived sessions stop "
+ "re-scanning/re-repairing the same rows on every resume. Only the "
+ "content column is touched; tool_calls and every other column on "
+ "the row are left untouched."
+ ),
+ )
+ sessions_clean_markers.add_argument(
+ "--dry-run",
+ action="store_true",
+ default=False,
+ help="Report the affected row count without writing",
+ )
+
sessions_optimize_storage = sessions_subparsers.add_parser(
"optimize-storage",
help="Migrate the search index to the compact v23 layout (reclaims disk on large DBs)",
diff --git a/hermes_cli/sessions_cmd.py b/hermes_cli/sessions_cmd.py
index 0338585a688..b8a06e30212 100644
--- a/hermes_cli/sessions_cmd.py
+++ b/hermes_cli/sessions_cmd.py
@@ -1039,6 +1039,22 @@ def cmd_sessions(args, sessions_parser=None):
f"({_size_delta_label(saved)})"
)
+ elif action == "clean-markers":
+ if args.dry_run:
+ print("Dry run — scanning for stale tool-call marker rows (#78148)…")
+ else:
+ print("Scanning for stale tool-call marker rows (#78148)…")
+ report = db.purge_stale_tool_call_markers(dry_run=args.dry_run)
+ if report["rows_affected"] == 0:
+ print("✓ No affected rows found — nothing to clean.")
+ elif args.dry_run:
+ print(
+ f"Would clear {report['rows_affected']} row(s): "
+ f"ids {report['row_ids']}"
+ )
+ else:
+ print(f"✓ Cleared {report['rows_affected']} row(s).")
+
elif action == "optimize-storage":
db_path = db.db_path
if not db.fts_optimize_available():
diff --git a/hermes_state.py b/hermes_state.py
index 2b6f22017e3..c0cba359ecb 100644
--- a/hermes_state.py
+++ b/hermes_state.py
@@ -8443,6 +8443,64 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
self._remove_session_files(sessions_dir, sid)
return count
+ def purge_stale_tool_call_markers(self, *, dry_run: bool = False) -> Dict[str, Any]:
+ """Permanently clear bare tool-call marker content (e.g. "[memory]")
+ left in the ``messages`` table by sessions persisted before the
+ #78148 fix in ``agent.conversation_loop``.
+
+ ``_strip_stale_tool_call_markers`` already repairs this in memory on
+ every session load (see ``_rows_to_conversation``), so running this
+ is optional — but for long-lived sessions the same rows get
+ re-scanned and re-repaired on every resume, which is wasted work
+ and keeps the contaminated bytes sitting in the DB (and in any
+ downstream cache/backup snapshot of it) indefinitely. This rewrites
+ the affected rows once, in place.
+
+ Only the ``content`` column is touched — ``role``, ``tool_calls``,
+ and every other column on the row are left exactly as they are, so
+ provider tool_call/tool_result pairing is unaffected.
+
+ With ``dry_run=True``, reports the affected row count/ids without
+ writing (read-only, no write lock taken).
+
+ Returns ``{"dry_run": bool, "rows_affected": int, "row_ids": [...]}``.
+ """
+
+ def _find_affected(conn) -> List[int]:
+ cursor = conn.execute(
+ "SELECT id, content FROM messages "
+ "WHERE role = 'assistant' AND tool_calls IS NOT NULL AND tool_calls != ''"
+ )
+ affected: List[int] = []
+ for row in cursor.fetchall():
+ content = row["content"]
+ if isinstance(content, str) and _STALE_TOOL_CALL_MARKER_RE.fullmatch(content.strip()):
+ affected.append(row["id"])
+ return affected
+
+ if dry_run:
+ with self._read_ctx() as conn:
+ affected_ids = _find_affected(conn)
+ return {"dry_run": True, "rows_affected": len(affected_ids), "row_ids": affected_ids}
+
+ def _do(conn):
+ affected_ids = _find_affected(conn)
+ if affected_ids:
+ placeholders = ",".join("?" * len(affected_ids))
+ conn.execute(
+ f"UPDATE messages SET content = '' WHERE id IN ({placeholders})",
+ affected_ids,
+ )
+ return affected_ids
+
+ affected_ids = self._execute_write(_do)
+ if affected_ids:
+ logger.info(
+ "Permanently cleared %d stale tool-call marker row(s) in state.db (#78148)",
+ len(affected_ids),
+ )
+ return {"dry_run": False, "rows_affected": len(affected_ids), "row_ids": affected_ids}
+
# ── Meta key/value (for scheduler bookkeeping) ──
def get_meta(self, key: str) -> Optional[str]:
diff --git a/tests/test_stale_tool_call_marker_session_repair.py b/tests/test_stale_tool_call_marker_session_repair.py
index e07bef5ea58..41b5d8f12e9 100644
--- a/tests/test_stale_tool_call_marker_session_repair.py
+++ b/tests/test_stale_tool_call_marker_session_repair.py
@@ -134,3 +134,89 @@ class TestGetMessagesAsConversationStripsStaleMarkers:
assert contents == ["What's the weather?", "It's sunny."]
finally:
db.close()
+
+
+class TestPurgeStaleToolCallMarkers:
+ """SessionDB.purge_stale_tool_call_markers: the permanent, one-time DB
+ rewrite. Complements the load-on-read repair — this variant edits the
+ stored rows in place so long-lived sessions stop re-scanning/re-repairing
+ the same contaminated rows on every resume."""
+
+ def _seed_polluted_db(self, db):
+ db.create_session(session_id="s1", source="cli")
+ db.append_message("s1", role="user", content="do the full task")
+ db.append_message(
+ "s1", role="assistant", content="[memory]",
+ tool_calls=[{"id": "1", "function": {"name": "skill_manage", "arguments": "{}"}}],
+ )
+ db.append_message("s1", role="tool", content="ok", tool_call_id="1")
+ db.append_message("s1", role="assistant", content="Here is the result.")
+
+ def test_dry_run_reports_without_writing(self):
+ import tempfile
+ from pathlib import Path
+ from hermes_state import SessionDB
+
+ with tempfile.TemporaryDirectory() as tmp:
+ db = SessionDB(db_path=Path(tmp) / "t.db")
+ try:
+ self._seed_polluted_db(db)
+
+ report = db.purge_stale_tool_call_markers(dry_run=True)
+ assert report["dry_run"] is True
+ assert report["rows_affected"] == 1
+
+ # Nothing written: the raw row still has the marker.
+ raw = db._conn.execute(
+ "SELECT content FROM messages WHERE role = 'assistant' "
+ "AND tool_calls IS NOT NULL AND tool_calls != ''"
+ ).fetchone()
+ assert raw["content"] == "[memory]"
+ finally:
+ db.close()
+
+ def test_purge_clears_content_keeps_tool_calls(self):
+ import tempfile
+ from pathlib import Path
+ from hermes_state import SessionDB
+
+ with tempfile.TemporaryDirectory() as tmp:
+ db = SessionDB(db_path=Path(tmp) / "t.db")
+ try:
+ self._seed_polluted_db(db)
+
+ report = db.purge_stale_tool_call_markers(dry_run=False)
+ assert report["dry_run"] is False
+ assert report["rows_affected"] == 1
+
+ row = db._conn.execute(
+ "SELECT content, tool_calls FROM messages WHERE role = 'assistant' "
+ "AND tool_calls IS NOT NULL AND tool_calls != ''"
+ ).fetchone()
+ assert row["content"] == ""
+ # tool_calls column itself must survive the rewrite untouched.
+ assert row["tool_calls"]
+
+ # Running again finds nothing left to clean — idempotent.
+ second = db.purge_stale_tool_call_markers(dry_run=False)
+ assert second["rows_affected"] == 0
+ finally:
+ db.close()
+
+ def test_no_affected_rows_on_clean_db(self):
+ import tempfile
+ from pathlib import Path
+ from hermes_state import SessionDB
+
+ with tempfile.TemporaryDirectory() as tmp:
+ db = SessionDB(db_path=Path(tmp) / "t.db")
+ try:
+ db.create_session(session_id="s1", source="cli")
+ db.append_message("s1", role="user", content="What's the weather?")
+ db.append_message("s1", role="assistant", content="It's sunny.")
+
+ report = db.purge_stale_tool_call_markers(dry_run=False)
+ assert report["rows_affected"] == 0
+ assert report["row_ids"] == []
+ finally:
+ db.close()