The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(state): finish the #80216 bug class — archive-preserving rewrites at the two remaining sibling sites
kshitijee6d79648a59
diff --git a/acp_adapter/session.py b/acp_adapter/session.pyindex 6e16016a6b3..e0ba0c7cf1e 100644--- a/acp_adapter/session.py+++ b/acp_adapter/session.py@@ -480,16 +480,17 @@ class SessionManager:# fresh agent with _session_db_created=False (so the check above# is False) yet leave the durable archived transcript in place.# A full-history replace would DELETE those archived rows just- # like the owned-agent case. Guard against it: when archived- # rows exist, replace ONLY the live (active=1) set and leave the- # archived turns untouched; otherwise the destructive replace is- # safe (fresh create/fork with no archived history to lose).- try:- has_archived = db.has_archived_messages(state.session_id)- except Exception:- has_archived = False+ # like the owned-agent case. Guard against it by replacing ONLY+ # the live (active=1) set unconditionally: on a fresh+ # create/fork every row is active=1, so active-only replace is+ # behaviorally identical to the full replace — and when archived+ # rows DO exist they survive. An existence probe here+ # (has_archived_messages) would fail OPEN into the destructive+ # replace on any DB error and can race a concurrent+ # archive_and_compact — the same probe failure mode #80216's+ # /retry fix (gateway/slash_commands.py) deliberately avoids.db.replace_messages(- state.session_id, state.history, active_only=has_archived+ state.session_id, state.history, active_only=True)except Exception:logger.warning("Failed to persist ACP session %s", state.session_id, exc_info=True)diff --git a/hermes_state.py b/hermes_state.pyindex cecdc96d9c2..92b238c061f 100644--- a/hermes_state.py+++ b/hermes_state.py@@ -7228,9 +7228,10 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)def has_archived_messages(self, session_id: str) -> bool:"""Return True if the session has any soft-archived (``active = 0``) rows.- Used by callers (e.g. the ACP adapter's ``_persist``) that must decide- whether a full-history :meth:`replace_messages` would destroy durable- compaction-archived turns. Cheap existence probe — does not load rows.+ Cheap existence probe — does not load rows. NOTE: production rewrite+ paths no longer branch on this (they pass ``active_only=True``+ unconditionally — a probe can fail open or race a concurrent+ ``archive_and_compact``, #80216); kept for tests and diagnostics."""with self._lock:cursor = self._conn.execute(diff --git a/tests/hermes_state/test_replace_messages_archive_siblings.py b/tests/hermes_state/test_replace_messages_archive_siblings.pynew file mode 100644index 00000000000..398a6c9cbe1--- /dev/null+++ b/tests/hermes_state/test_replace_messages_archive_siblings.py@@ -0,0 +1,163 @@+"""Sibling-site regression tests for the #80216 bug class.++#80216 fixed /retry destroying soft-archived (``active=0/compacted=1``)+in-place-compaction rows because ``rewrite_transcript`` defaulted to a+destructive full ``replace_messages``. The same class existed at two more+sites, fixed here:++- ``acp_adapter/session.py`` ``_persist`` (non-owned-agent branch): probed+ ``has_archived_messages`` and FAILED OPEN into the destructive replace on+ any probe error (and could race a concurrent ``archive_and_compact``).+ Now passes ``active_only=True`` unconditionally.+- ``tui_gateway/methods_prompt.py`` edit/regenerate truncation: bare+ ``replace_messages`` deleted the archived transcript on every+ edit/regenerate of a compacted session. Now ``active_only=True``.++Behavior contract on a fresh (never-compacted) session: every row is+``active=1``, so the active-only replace is identical to the full replace —+also pinned below.+"""++import os+import sys++import pytest+++def state_db(tmp_path, monkeypatch):+ """A real SessionDB on a temp state.db with one compacted session."""+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))+ os.makedirs(tmp_path / ".hermes", exist_ok=True)+ for mod in [m for m in sys.modules if m.startswith("hermes_state")]:+ del sys.modules[mod]+ import hermes_state++ db = hermes_state.SessionDB(tmp_path / "state.db")+ return db+++def _seed_compacted_session(db, session_id: str) -> None:+ """Create a session with archived (active=0/compacted=1) + live rows."""+ db.create_session(session_id, "test")+ msgs = [+ {"role": "user", "content": "old question"},+ {"role": "assistant", "content": "old answer"},+ {"role": "user", "content": "another old question"},+ {"role": "assistant", "content": "another old answer"},+ ]+ db.append_messages_batch(session_id, msgs)+ db.archive_and_compact(+ session_id,+ [+ {"role": "assistant", "content": "summary of old turns"},+ {"role": "user", "content": "live question"},+ {"role": "assistant", "content": "live answer"},+ ],+ )+++def _archived_count(db, session_id: str) -> int:+ with db._lock:+ cur = db._conn.execute(+ "SELECT COUNT(*) FROM messages WHERE session_id = ? AND active = 0",+ (session_id,),+ )+ return cur.fetchone()[0]+++class TestAcpPersistPreservesArchives:+ def test_persist_nonowned_branch_keeps_archived_rows(self, state_db):+ """The ACP _persist fallback replace must not delete archived rows."""+ sid = "acp-compacted"+ _seed_compacted_session(state_db, sid)+ assert _archived_count(state_db, sid) == 4++ # Drive the exact replace the non-owned-agent branch of _persist now+ # performs (active_only=True unconditionally, no probe).+ new_history = [+ {"role": "user", "content": "rewritten"},+ {"role": "assistant", "content": "rewritten answer"},+ ]+ state_db.replace_messages(sid, new_history, active_only=True)++ assert _archived_count(state_db, sid) == 4+ live = [+ m for m in state_db.get_messages_as_conversation(sid)+ if m.get("role") in ("user", "assistant")+ ]+ assert [m["content"] for m in live] == ["rewritten", "rewritten answer"]++ def test_persist_source_has_no_failopen_probe(self):+ """The fail-open has_archived_messages probe must stay dead in _persist.++ Guards the #80216 bug class at the source level: a probe that fails+ open (``except: has_archived = False``) silently reintroduces the+ destructive replace. ``active_only=True`` must be unconditional.+ """+ import inspect+ import acp_adapter.session as acp_session++ src = inspect.getsource(acp_session.SessionManager._persist)+ assert "has_archived = " not in src, (+ "_persist re-grew a has_archived_messages probe — #80216 class"+ )+ assert "active_only=True" in src++ def test_fresh_session_active_only_equals_full_replace(self, state_db):+ """On a never-compacted session active_only=True must behave exactly+ like the historical full replace (the safety claim the unconditional+ switch rests on)."""+ sid = "acp-fresh"+ state_db.create_session(sid, "test")+ state_db.append_messages_batch(+ sid,+ [+ {"role": "user", "content": "q"},+ {"role": "assistant", "content": "a"},+ ],+ )+ state_db.replace_messages(+ sid, [{"role": "user", "content": "only"}], active_only=True+ )+ rows = [+ m for m in state_db.get_messages_as_conversation(sid)+ if m.get("role") in ("user", "assistant")+ ]+ assert [m["content"] for m in rows] == ["only"]+ assert _archived_count(state_db, sid) == 0+++class TestTuiPromptTruncationPreservesArchives:+ def test_truncation_source_uses_active_only(self):+ """The edit/regenerate persistence call must pass active_only=True."""+ import inspect+ import tui_gateway.methods_prompt as mp++ src = inspect.getsource(mp)+ # The truncation write is the only replace_messages call in the module;+ # it must carry active_only=True.+ import re+ calls = re.findall(r"db\.replace_messages\([^)]*\)", src, re.S)+ assert calls, "expected the truncation replace_messages call"+ for call in calls:+ assert "active_only=True" in call, (+ f"bare replace_messages in methods_prompt — #80216 class: {call}"+ )++ def test_truncation_write_keeps_archived_rows(self, state_db):+ """Drive the exact write shape methods_prompt now performs against a+ compacted session and assert the archive survives."""+ sid = "tui-compacted"+ _seed_compacted_session(state_db, sid)+ assert _archived_count(state_db, sid) == 4++ truncated = [{"role": "user", "content": "kept head"}]+ state_db.replace_messages(sid, truncated, active_only=True)++ assert _archived_count(state_db, sid) == 4+ live = [+ m for m in state_db.get_messages_as_conversation(sid)+ if m.get("role") in ("user", "assistant")+ ]+ assert [m["content"] for m in live] == ["kept head"]diff --git a/tests/test_tui_gateway_server.py b/tests/test_tui_gateway_server.pyindex 87eb31995c6..8f0eb124ac3 100644--- a/tests/test_tui_gateway_server.py+++ b/tests/test_tui_gateway_server.py@@ -4247,7 +4247,7 @@ def test_prompt_submit_rejects_negative_truncate_ordinal(monkeypatch):replaced = []class _FakeDB:- def replace_messages(self, key, messages):+ def replace_messages(self, key, messages, active_only=False):replaced.append((key, list(messages)))history = [@@ -4298,7 +4298,7 @@ def test_prompt_submit_refuses_empty_truncation_without_confirm(monkeypatch):replaced = []class _FakeDB:- def replace_messages(self, key, messages):+ def replace_messages(self, key, messages, active_only=False):replaced.append((key, list(messages)))history = [@@ -4383,7 +4383,7 @@ def test_prompt_submit_empty_truncation_allowed_with_confirm(monkeypatch):self._target()class _FakeDB:- def replace_messages(self, key, messages):+ def replace_messages(self, key, messages, active_only=False):replaced.append((key, list(messages)))history = [@@ -9275,7 +9275,7 @@ def test_prompt_submit_can_truncate_before_user_ordinal(monkeypatch):def __init__(self):self.replaced = []- def replace_messages(self, session_id, messages):+ def replace_messages(self, session_id, messages, active_only=False):self.replaced.append((session_id, list(messages)))stub_db = _StubDb()@@ -9331,7 +9331,7 @@ def test_prompt_submit_refuses_turn_when_truncate_persist_fails(monkeypatch):server._sessions["trunc-fail-sid"] = sessclass _FailDb:- def replace_messages(self, session_id, messages):+ def replace_messages(self, session_id, messages, active_only=False):raise OSError("disk full")monkeypatch.setattr(server, "_get_db", lambda: _FailDb())@@ -9422,7 +9422,7 @@ def test_prompt_submit_truncate_ordinal_skips_display_kind_rows(monkeypatch):def __init__(self):self.replaced = []- def replace_messages(self, session_id, messages):+ def replace_messages(self, session_id, messages, active_only=False):self.replaced.append((session_id, list(messages)))stub_db = _StubDb()diff --git a/tui_gateway/methods_prompt.py b/tui_gateway/methods_prompt.pyindex e662ff2f36b..b25c93a89f0 100644--- a/tui_gateway/methods_prompt.py+++ b/tui_gateway/methods_prompt.py@@ -220,7 +220,17 @@ def _(rid, params: dict) -> dict:# Fail closed: refuse the turn and leave memory/DB unchanged.if (db := _get_db()) is not None:try:- db.replace_messages(session["session_key"], truncated)+ # active_only=True: replace only the live (active=1) rows.+ # In-place compaction (#38763) keeps the pre-compaction+ # transcript as active=0/compacted=1 rows under this same+ # session key; a bare replace_messages() would DELETE that+ # durable archive on every edit/regenerate — the same bug+ # class #80216 fixed for /retry. On an uncompacted session+ # all rows are active=1, so this is behaviorally identical+ # to the full replace.+ db.replace_messages(+ session["session_key"], truncated, active_only=True+ )except Exception as exc:logger.error("prompt.submit: replace_messages failed for session %s "