Skip to content

The agent that grows with you

refactor(state): move get_latest_todo_result into hermes_state_todo

Teknium91d331196e5b
diff --git a/hermes_state_messages.py b/hermes_state_messages.py
index 5e7b20fc2e3..62c999dcff1 100644
--- a/hermes_state_messages.py
+++ b/hermes_state_messages.py
@@ -23,6 +23,7 @@ from hermes_state_common import (
_COMPRESSION_LOCK_ROW_SQL, _ENDED_ROW_SQL, _RESET_END_REASONS, _RESET_END_REASONS_SQL, _ended_by_compression,
_json_or, _legacy_reset_child_sql, _placeholders, _sql_json_extract)
from hermes_state_detached_results import SessionDetachedResultsMixin
+from hermes_state_todo import SessionTodoResultMixin
from hermes_state_identity import (
_absorbed_uids_json, _restore_identity_columns, _stable_tool_key, _tool_call_uid_map, _tool_call_uid_or_none, _tool_call_uids_json, _uid_list)
@@ -118,7 +119,7 @@ def _stale_holder(row, now: float) -> bool:
return float(row["expires_at"]) <= now or _compression_lock_holder_process_is_dead(row["holder"])
-class SessionMessagesMixin(SessionDetachedResultsMixin):
+class SessionMessagesMixin(SessionDetachedResultsMixin, SessionTodoResultMixin):
"""Message append/replace/rewind, reactions, resume conversations, replay dedupe (detached results: the base)."""
def _bump_conversation_generation(self, conn, session_id: str, end_reason: str) -> None:
@@ -589,79 +590,6 @@ class SessionMessagesMixin(SessionDetachedResultsMixin):
return pending
return self._execute_write(_do)
- def get_latest_todo_result(self, session_id: str, *, max_chars: Optional[int] = None) -> Optional[str]:
- """Newest visible, paired and valid Todo result in the resume display scope.
-
- Search indexed, bounded pages rather than loading a potentially long transcript. A branch owns its
- copied history; compression continuations also show their ancestors' archived rows. Invalid results
- are skipped just as the model's Todo hydration does, and explicit empty results are retained.
- """
- if not session_id:
- return None
- if max_chars is None:
- from tools.todo_tool import MAX_TODO_RESULT_CHARS
- max_chars = MAX_TODO_RESULT_CHARS
- session_ids = self._resume_lineage_ids(session_id)
- with self._read_ctx() as conn:
- for sid in reversed(session_ids):
- before_id = 2**63 - 1
- while True:
- rows = conn.execute(
- "SELECT id, content, tool_call_id FROM messages INDEXED BY idx_messages_session_id "
- "WHERE session_id = ? AND id < ? AND role = 'tool' "
- "AND tool_name IN ('todo_list', 'todo') AND (active = 1 OR compacted = 1) "
- "AND length(content) <= ? ORDER BY id DESC LIMIT 100",
- (sid, before_id, max_chars),
- ).fetchall()
- if not rows:
- break
- for row in rows:
- call_id = row["tool_call_id"]
- if not call_id:
- continue
- prior = conn.execute(
- "SELECT role, tool_calls FROM messages INDEXED BY idx_messages_session_id "
- "WHERE session_id = ? AND id < ? AND role IN ('assistant', 'user', 'system') "
- "AND (active = 1 OR compacted = 1) ORDER BY id DESC LIMIT 1",
- (sid, row["id"]),
- ).fetchone()
- if prior is None or prior["role"] != "assistant":
- continue
- try:
- calls = json.loads(prior["tool_calls"]) if prior["tool_calls"] else []
- def is_todo_call(call):
- if not isinstance(call, dict) or call.get("id") != call_id:
- return False
- function = call.get("function")
- if not isinstance(function, dict):
- return False
- if function.get("name") in ("todo_list", "todo"):
- return True
- if function.get("name") != "tool_call":
- return False
- arguments = function.get("arguments")
- if isinstance(arguments, str):
- arguments = json.loads(arguments)
- if not isinstance(arguments, dict):
- return False
- inner_calls = arguments.get("calls")
- return isinstance(inner_calls, list) and any(
- isinstance(inner, dict) and inner.get("name") in ("todo_list", "todo")
- for inner in inner_calls)
-
- paired = isinstance(calls, list) and any(is_todo_call(call) for call in calls)
- if not paired:
- continue
- data = json.loads(row["content"])
- if not isinstance(data, dict) or not isinstance(data.get("todos"), list):
- continue
- int(data.get("revision") or 0)
- except (ValueError, TypeError):
- continue
- return row["content"]
- before_id = rows[-1]["id"]
- return None
-
def latest_message_row_id(self, session_id: str, *, role: str = "user", offset: int = 0,
require_text: bool = True) -> Optional[int]:
"""Row id of the most recent active *role* message, or ``None``. ``offset`` steps back; ``require_text``
diff --git a/hermes_state_todo.py b/hermes_state_todo.py
new file mode 100644
index 00000000000..007d28f25c3
--- /dev/null
+++ b/hermes_state_todo.py
@@ -0,0 +1,85 @@
+"""The newest Todo result a resume restores: an indexed, bounded search of the resume display scope.
+Split out of ``hermes_state_messages`` and bound onto SessionDB through ``SessionMessagesMixin``; built
+on its _resume_lineage_ids/_read_ctx primitives."""
+
+from __future__ import annotations
+
+import json
+from typing import Optional
+
+
+class SessionTodoResultMixin:
+ """Latest visible, paired and valid Todo tool result of a session's lineage."""
+
+ def get_latest_todo_result(self, session_id: str, *, max_chars: Optional[int] = None) -> Optional[str]:
+ """Newest visible, paired and valid Todo result in the resume display scope.
+
+ Search indexed, bounded pages rather than loading a potentially long transcript. A branch owns its
+ copied history; compression continuations also show their ancestors' archived rows. Invalid results
+ are skipped just as the model's Todo hydration does, and explicit empty results are retained.
+ """
+ if not session_id:
+ return None
+ if max_chars is None:
+ from tools.todo_tool import MAX_TODO_RESULT_CHARS
+ max_chars = MAX_TODO_RESULT_CHARS
+ session_ids = self._resume_lineage_ids(session_id)
+ with self._read_ctx() as conn:
+ for sid in reversed(session_ids):
+ before_id = 2**63 - 1
+ while True:
+ rows = conn.execute(
+ "SELECT id, content, tool_call_id FROM messages INDEXED BY idx_messages_session_id "
+ "WHERE session_id = ? AND id < ? AND role = 'tool' "
+ "AND tool_name IN ('todo_list', 'todo') AND (active = 1 OR compacted = 1) "
+ "AND length(content) <= ? ORDER BY id DESC LIMIT 100",
+ (sid, before_id, max_chars),
+ ).fetchall()
+ if not rows:
+ break
+ for row in rows:
+ call_id = row["tool_call_id"]
+ if not call_id:
+ continue
+ prior = conn.execute(
+ "SELECT role, tool_calls FROM messages INDEXED BY idx_messages_session_id "
+ "WHERE session_id = ? AND id < ? AND role IN ('assistant', 'user', 'system') "
+ "AND (active = 1 OR compacted = 1) ORDER BY id DESC LIMIT 1",
+ (sid, row["id"]),
+ ).fetchone()
+ if prior is None or prior["role"] != "assistant":
+ continue
+ try:
+ calls = json.loads(prior["tool_calls"]) if prior["tool_calls"] else []
+ def is_todo_call(call):
+ if not isinstance(call, dict) or call.get("id") != call_id:
+ return False
+ function = call.get("function")
+ if not isinstance(function, dict):
+ return False
+ if function.get("name") in ("todo_list", "todo"):
+ return True
+ if function.get("name") != "tool_call":
+ return False
+ arguments = function.get("arguments")
+ if isinstance(arguments, str):
+ arguments = json.loads(arguments)
+ if not isinstance(arguments, dict):
+ return False
+ inner_calls = arguments.get("calls")
+ return isinstance(inner_calls, list) and any(
+ isinstance(inner, dict) and inner.get("name") in ("todo_list", "todo")
+ for inner in inner_calls)
+
+ paired = isinstance(calls, list) and any(is_todo_call(call) for call in calls)
+ if not paired:
+ continue
+ data = json.loads(row["content"])
+ if not isinstance(data, dict) or not isinstance(data.get("todos"), list):
+ continue
+ int(data.get("revision") or 0)
+ except (ValueError, TypeError):
+ continue
+ return row["content"]
+ before_id = rows[-1]["id"]
+ return None