Skip to content

The agent that grows with you

fix(state): a Todo plan undone in a compression child stays gone on an omitted resume

Tekniumb8dbdcda2271
diff --git a/hermes_state_todo.py b/hermes_state_todo.py
index 007d28f25c3..9c752025bf4 100644
--- a/hermes_state_todo.py
+++ b/hermes_state_todo.py
@@ -5,7 +5,9 @@ on its _resume_lineage_ids/_read_ctx primitives."""
from __future__ import annotations
import json
-from typing import Optional
+from typing import Any, Optional
+
+_TODO_TOOLS = "tool_name IN ('todo_list', 'todo')"
class SessionTodoResultMixin:
@@ -16,7 +18,9 @@ class SessionTodoResultMixin:
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.
+ are skipped just as the model's Todo hydration does, and explicit empty results are retained. A result
+ whose newest copy was removed (an undo in a compression child) is skipped too, as the display read
+ hides it: its ancestor's copy must not bring the undone plan back.
"""
if not session_id:
return None
@@ -25,13 +29,14 @@ class SessionTodoResultMixin:
max_chars = MAX_TODO_RESULT_CHARS
session_ids = self._resume_lineage_ids(session_id)
with self._read_ctx() as conn:
+ removed = self._removed_todo_copies(conn, session_ids)
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) "
+ "SELECT id, role, content, timestamp, tool_call_id, tool_calls, tool_name, message_uid, "
+ "absorbed_message_uids FROM messages INDEXED BY idx_messages_session_id "
+ f"WHERE session_id = ? AND id < ? AND role = 'tool' AND {_TODO_TOOLS} AND (active = 1 OR compacted = 1) "
"AND length(content) <= ? ORDER BY id DESC LIMIT 100",
(sid, before_id, max_chars),
).fetchall()
@@ -39,7 +44,7 @@ class SessionTodoResultMixin:
break
for row in rows:
call_id = row["tool_call_id"]
- if not call_id:
+ if not call_id or self._todo_copy_removed(row, removed):
continue
prior = conn.execute(
"SELECT role, tool_calls FROM messages INDEXED BY idx_messages_session_id "
@@ -83,3 +88,25 @@ class SessionTodoResultMixin:
return row["content"]
before_id = rows[-1]["id"]
return None
+
+ def _todo_copies(self, row, identity: Any = None) -> list[Any]:
+ """The copy identities ``_dedupe_display_generations(drop_removed=True)`` gives a Todo result row."""
+ from hermes_state_identity import _uid_list
+ hashed = identity or self._display_identity(self._display_dedupe_key(row))
+ return [hashed, *(("uid", uid) for uid in (row["message_uid"], *_uid_list(row["absorbed_message_uids"])) if uid)]
+
+ def _removed_todo_copies(self, conn, session_ids: list[str]) -> dict[Any, int]:
+ """Copy identity -> newest removed (``active=0, compacted=0``) Todo result row id in the lineage."""
+ removed: dict[Any, int] = {}
+ for row in conn.execute(
+ "SELECT id, role, timestamp, tool_call_id, tool_calls, tool_name, message_uid, absorbed_message_uids, "
+ "display_identity, CASE WHEN display_identity IS NULL THEN content END AS content "
+ f"FROM messages WHERE session_id IN ({','.join('?' * len(session_ids))}) AND active = 0 "
+ f"AND compacted = 0 AND role = 'tool' AND {_TODO_TOOLS}", tuple(session_ids)):
+ for copy in self._todo_copies(row, row["display_identity"]):
+ removed[copy] = max(removed.get(copy, 0), row["id"])
+ return removed
+
+ def _todo_copy_removed(self, row, removed: dict[Any, int]) -> bool:
+ """A newer copy of *row* was removed: the display read hides it, so the resume must not restore it."""
+ return bool(removed) and any(removed.get(copy, 0) > row["id"] for copy in self._todo_copies(row))
diff --git a/tests/gateway/test_resume_omit_messages.py b/tests/gateway/test_resume_omit_messages.py
index 46e37428897..8c187d817a9 100644
--- a/tests/gateway/test_resume_omit_messages.py
+++ b/tests/gateway/test_resume_omit_messages.py
@@ -74,3 +74,36 @@ async def test_omit_messages_resume_reads_no_transcript(tmp_path, monkeypatch):
assert omitted['message_count'] == authority.db.get_session(physical)['message_count']
# Both paths report the same plan: the omitted one reads it from the store's bounded todo lookup.
assert omitted['todo_state'] == full['todo_state'] and omitted['todo_state']
+
+
+async def test_omitted_resume_keeps_an_undone_plan_gone_after_a_rotated_compression(tmp_path, monkeypatch):
+ """The rewind removes the child's copy of the Todo turn; the parent's copy must not restore its plan."""
+ from gateway.session_mutations import mutate_session
+ authority, actor, ref, physical = await _local_session(tmp_path, monkeypatch)
+ db = authority.db
+ call = {'id': 'todo-1', 'type': 'function', 'function': {'name': 'todo', 'arguments': '{}'}}
+ tail = [{'role': 'user', 'content': 'TAIL_Q'}, {'role': 'assistant', 'content': None, 'tool_calls': [call]},
+ {'role': 'tool', 'content': json.dumps(TODOS), 'tool_name': 'todo', 'tool_call_id': 'todo-1'},
+ {'role': 'assistant', 'content': 'TAIL_A'}]
+ db.append_message(physical, 'user', 'OLD_Q')
+ db.append_message(physical, 'assistant', 'OLD_A')
+ for row in tail:
+ db.append_message(physical, row['role'], row['content'], tool_calls=row.get('tool_calls'),
+ tool_name=row.get('tool_name'), tool_call_id=row.get('tool_call_id'))
+ assert db.try_acquire_compression_lock(physical, 'fixture')
+ try:
+ db.publish_compression_child(parent_session_id=physical, child_session_id='child', source='gui',
+ messages=[{'role': 'user', 'content': SUMMARY_PREFIX + '\nsummary'}, *tail],
+ compression_lock_holder='fixture')
+ finally:
+ db.release_compression_lock(physical, 'fixture')
+ handle = authority._handle(ref)
+ await mutate_session(authority, actor, ref, {
+ 'session_id': ref.session_id, 'request_id': 'undo', 'operation': 'rewind',
+ 'expected_revision': handle.revision, 'expected_generation': handle.execution_generation,
+ 'payload': {'target_message_id': next(m['id'] for m in db.get_messages('child') if m['content'] == 'TAIL_Q')}})
+ full = await _resume(authority, actor, ref)
+ assert full['todo_state'] is None
+ omitted = await _resume(authority, actor, ref, omit_messages=True)
+ assert omitted['todo_state'] == full['todo_state']