Skip to content

The agent that grows with you

Merge remote-tracking branch 'origin/main' into codex/81234-live-main-final

poisdahl3f075d41dd59
diff --cc gateway/session.py
index 21228473e6f,cd62db5048f..123deaf0f0f
--- a/gateway/session.py
+++ b/gateway/session.py
@@@ -3793,6 -3816,6 +3816,7 @@@ class SessionStore
session_id: str,
messages: List[Dict[str, Any]],
active_only: bool = False,
++ reject_active_turn_lease: bool = False,
) -> bool:
"""Replace the entire transcript for a session with new messages.
@@@ -3813,12 -3836,12 +3837,21 @@@
change on top of a failed write — e.g. /compress repointing the live
session onto a fresh session_id — must check it so they can surface an
error instead of silently dropping the conversation.
++
++ ``reject_active_turn_lease`` is for user-initiated rewrites that do not
++ own the cross-process turn lease. It leaves internal rewrite policy
++ unchanged for existing callers unless they opt in explicitly.
"""
if not self._db:
return True
self._clear_dirty_transcript(session_id)
try:
-- self._db.replace_messages(session_id, messages, active_only=active_only)
++ self._db.replace_messages(
++ session_id,
++ messages,
++ active_only=active_only,
++ reject_active_turn_lease=reject_active_turn_lease,
++ )
return True
except Exception as e:
logger.debug("Failed to rewrite transcript in DB: %s", e)
diff --cc gateway/slash_commands.py
index 7f72f0df1f1,523af310e97..b91f91b50e1
--- a/gateway/slash_commands.py
+++ b/gateway/slash_commands.py
@@@ -2609,51 -2610,24 +2612,54 @@@ class GatewaySlashCommandsMixin
for i in range(len(history) - 1, -1, -1):
msg = history[i]
- if is_user_originated_turn(msg):
- last_user_msg = msg.get("content", "")
+ if user_originated_turn_view(msg) is not None:
last_user_idx = i
break
-
- if not last_user_msg:
+
+ if last_user_idx is None:
return t("gateway.retry.no_previous")
-
- # Truncate history to before the last user message and persist only the
- # live view. After in-place compaction the pre-compaction transcript
- # lives on as active=0/compacted=1 rows under this same session id, and
- # a bare rewrite (active_only=False) would DELETE them (same class as
- # #61145). /retry never intends to purge archived history, so avoid a
- # separate existence probe: it could fail open or race with the write.
- truncated = history[:last_user_idx]
- await self.async_session_store.rewrite_transcript(
- session_entry.session_id, truncated, active_only=True
- )
+
+ # Resolve the live text and the scaffold-preserving prefix before any
+ # transcript write. Messaging retries cannot reconstruct attachments;
+ # reject media/unknown content without truncating the session.
+ try:
+ truncated, live_view = history_before_user_originated_turn(
+ history, last_user_idx
+ )
+ last_user_msg = retryable_user_text(live_view.get("content"))
+ handoff, _ = split_user_originated_turn(history[last_user_idx])
+ except ValueError as exc:
+ return f"Cannot retry that message safely: {exc}"
+
+ if handoff is not None:
+ # A composite carrier is one physical row containing both the
+ # retained summary and the live ask. Let the carrier-aware rewind
+ # archive that row/tail and insert its pure scaffold atomically.
+ # Plain turns keep the existing rewrite path below; #84078 owns
+ # its separate archive_dropped/prefix-CAS semantics.
+ rewind_result = await self.async_session_store.rewind_session(
+ session_entry.session_id,
+ 1,
+ require_retryable_composite=True,
+ )
+ if rewind_result is None:
+ return "Retry failed; transcript was not changed."
+ # The store reselects and validates the latest carrier on the same
+ # snapshot used by the atomic rewind. A concurrent newer turn can
+ # therefore never be removed while this handler resends stale text.
+ last_user_msg = rewind_result["target_text"]
+ else:
+ # After in-place compaction the pre-compaction transcript lives on
+ # as active=0/compacted=1 rows under this session id. active_only
+ # preserves that archive; a separate existence probe could fail
+ # open or race with the write.
+ if not await self.async_session_store.rewrite_transcript(
- session_entry.session_id, truncated, active_only=True
++ session_entry.session_id,
++ truncated,
++ active_only=True,
++ reject_active_turn_lease=True,
+ ):
+ return "Retry failed; transcript was not changed."
# Reset stored token count — transcript was truncated
session_entry.last_prompt_tokens = 0
diff --cc hermes_state.py
index 9891014d6f5,d229bfcb1b9..5ad8753343f
--- a/hermes_state.py
+++ b/hermes_state.py
@@@ -7948,14 -8862,19 +8862,21 @@@ class SessionDB(SessionSearchMixin, Ses
return None
def _check_transcript_write_guards(
- self, conn, session_id: str, compression_lock_holder: Optional[str]
+ self,
+ conn,
+ session_id: str,
+ compression_lock_holder: Optional[str],
+ turn_lease_holder: Optional[str] = None,
+ turn_lease_ttl_seconds: float = 300.0,
++ reject_active_turn_lease: bool = False,
) -> None:
-- """Transcript-append admission checks, run INSIDE the write txn.
++ """Transcript-write admission checks, run INSIDE the write txn.
Shared by :meth:`append_message` and :meth:`append_messages_batch` so
the two writers can never diverge on these correctness invariants
-- (this guard has already needed targeted fixes — see the #74478
-- patience note below).
++ (this guard has already needed targeted fixes — see the #74478 patience
++ note below). User-initiated transcript mutations may opt in to rejecting
++ an active unowned turn lease in that same transaction.
"""
active_lock = conn.execute(
"SELECT holder FROM compression_locks "
@@@ -7969,6 -8888,33 +8890,53 @@@
raise SessionCompressionInProgressError(
f"Session {session_id!r} is being compressed by another writer"
)
- if turn_lease_holder:
++ if turn_lease_holder or reject_active_turn_lease:
+ conversation_id = self._session_turn_lease_key_on_conn(conn, session_id)
+ lease = conn.execute(
+ "SELECT holder, expires_at FROM session_turn_leases "
+ "WHERE conversation_id = ?",
+ (conversation_id,),
+ ).fetchone()
- if lease is None or lease["holder"] != turn_lease_holder:
- raise SessionTurnLeaseLostError(
- f"Session turn lease lost; refusing transcript write "
- f"for {session_id!r}"
- )
+ now = time.time()
- if float(lease["expires_at"]) <= now:
- # Expiry makes the row reclaimable; it does not prove that a
- # takeover occurred. BEGIN IMMEDIATE serializes this renewal
- # with acquisition, so a still-matching owner can recover from
- # a starved refresher without weakening the foreign-holder fence.
- conn.execute(
- "UPDATE session_turn_leases SET expires_at = ? "
- "WHERE conversation_id = ? AND holder = ?",
- (
- now + max(0.1, float(turn_lease_ttl_seconds)),
- conversation_id,
- turn_lease_holder,
- ),
- )
++ if turn_lease_holder:
++ if lease is None or lease["holder"] != turn_lease_holder:
++ raise SessionTurnLeaseLostError(
++ f"Session turn lease lost; refusing transcript write "
++ f"for {session_id!r}"
++ )
++ if float(lease["expires_at"]) <= now:
++ # Expiry makes the row reclaimable; it does not prove that a
++ # takeover occurred. BEGIN IMMEDIATE serializes this renewal
++ # with acquisition, so a still-matching owner can recover from
++ # a starved refresher without weakening the foreign-holder fence.
++ conn.execute(
++ "UPDATE session_turn_leases SET expires_at = ? "
++ "WHERE conversation_id = ? AND holder = ?",
++ (
++ now + max(0.1, float(turn_lease_ttl_seconds)),
++ conversation_id,
++ turn_lease_holder,
++ ),
++ )
++ elif lease is not None:
++ current_holder = lease["holder"]
++ if (
++ float(lease["expires_at"]) <= now
++ or _compression_lock_holder_process_is_dead(current_holder)
++ ):
++ # Match acquisition semantics: an expired or provably dead
++ # owner is reclaimable. Deleting it inside this BEGIN IMMEDIATE
++ # transaction also fences a stale late flush after the mutation.
++ conn.execute(
++ "DELETE FROM session_turn_leases "
++ "WHERE conversation_id = ? AND holder = ?",
++ (conversation_id, current_holder),
++ )
++ else:
++ raise SessionTurnLeaseLostError(
++ f"Session has an active turn lease; refusing transcript "
++ f"mutation for {session_id!r}"
++ )
session = conn.execute(
"SELECT ended_at, end_reason FROM sessions WHERE id = ?",
(session_id,),
@@@ -8577,6 -9537,6 +9559,7 @@@
messages: List[Dict[str, Any]],
active_only: bool = False,
archive_dropped: bool = False,
++ reject_active_turn_lease: bool = False,
) -> None:
"""Atomically replace the stored messages for a session.
@@@ -8611,21 -9571,21 +9594,34 @@@
fresh active rows exactly as in the destructive path, so the live view
is identical either way; only the durability of the dropped turns
differs.
++
++ Pass ``reject_active_turn_lease=True`` for user-initiated rewrites that
++ do not already own the cross-process turn lease. The lease check and
++ transcript mutation then share one write transaction, so a second
++ process cannot archive or replace a turn that is still being produced.
"""
active_clause = " AND active = 1" if active_only else ""
def _do(conn):
-- session = conn.execute(
-- "SELECT ended_at, end_reason FROM sessions WHERE id = ?",
-- (session_id,),
-- ).fetchone()
-- if (
-- session is not None
-- and session["ended_at"] is not None
-- and session["end_reason"] == "compression"
-- ):
-- raise CompressionSessionClosedError(session_id)
++ if reject_active_turn_lease:
++ self._check_transcript_write_guards(
++ conn,
++ session_id,
++ None,
++ reject_active_turn_lease=True,
++ )
++ else:
++ session = conn.execute(
++ "SELECT ended_at, end_reason FROM sessions WHERE id = ?",
++ (session_id,),
++ ).fetchone()
++ if (
++ session is not None
++ and session["ended_at"] is not None
++ and session["end_reason"] == "compression"
++ ):
++ raise CompressionSessionClosedError(session_id)
if archive_dropped:
# Content-preserving UPDATE: the rows keep their FTS entries
# (the messages_fts triggers fire on INSERT / DELETE / UPDATE
@@@ -9522,17 -10551,7 +10616,19 @@@
}
Raises ``ValueError`` if the target message does not exist in
- *session_id* or if its role is not ``"user"``.
+ *session_id* or if its role is not ``"user"``. With
+ ``preserve_compaction_handoff=True``, a composite summary carrier is
+ split inside the same write transaction: its original row is archived
+ and its canonical hidden handoff scaffold is inserted as the new head.
+ That opt-in result also contains ``replacement_message_id``.
+
+ ``expected_active_ids`` optionally pins the ordered active row set.
+ ``expected_target_content`` additionally pins the selected canonical
+ live-user payload. Both checks run inside the write transaction before
+ any row or counter mutation. Presentation-only metadata changes (for
+ example Desktop reactions) deliberately do not invalidate a rewind.
++ A live cross-process turn lease always refuses the rewind; expired or
++ provably dead holders are reclaimed inside the mutation transaction.
Always increments ``sessions.rewind_count`` — even when the
target is already inactive — so the counter accurately reflects
@@@ -9541,24 -10560,9 +10637,30 @@@
target is a no-op on row state but still bumps the counter.
"""
- # 1) Validate target up-front (read-only, outside the write txn).
- with self._lock:
- row = self._conn.execute(
+ def _do(conn):
+ # Rewind changes the active transcript and must honor the same
- # compression ownership/closed-parent guards as append writers.
- self._check_transcript_write_guards(conn, session_id, None)
++ # compression/closed-parent and cross-process turn guards as
++ # append writers.
++ self._check_transcript_write_guards(
++ conn,
++ session_id,
++ None,
++ reject_active_turn_lease=True,
++ )
+
+ if expected_active_ids is not None:
+ active_rows = conn.execute(
+ "SELECT id FROM messages "
+ "WHERE session_id = ? AND active = 1 ORDER BY id",
+ (session_id,),
+ ).fetchall()
+ active_ids = [int(active_row[0]) for active_row in active_rows]
+ if active_ids != expected_active_ids:
+ raise RuntimeError(
+ "active transcript changed before the rewind could be persisted"
+ )
+
+ row = conn.execute(
"SELECT * FROM messages WHERE id = ? AND session_id = ?",
(target_message_id, session_id),
).fetchone()
diff --cc tests/gateway/test_retry_replacement.py
index 657c89d3763,c83fafbe46d..35394cc688f
--- a/tests/gateway/test_retry_replacement.py
+++ b/tests/gateway/test_retry_replacement.py
@@@ -83,191 -67,6 +83,195 @@@ async def test_gateway_retry_replaces_l
]
+async def test_gateway_retry_redispatches_live_carrier_text_and_keeps_scaffold(
+ tmp_path, monkeypatch
+):
+ import hermes_state
+ monkeypatch.setattr(hermes_state, "DEFAULT_DB_PATH", tmp_path / "state.db")
+
+ config = GatewayConfig()
+ store = SessionStore(sessions_dir=tmp_path, config=config)
+ session_id = "retry-carrier-session"
+ store._db.create_session(session_id=session_id, source="test")
+ store._db.append_message(session_id, "user", "older ask")
+ store._db.append_message(session_id, "assistant", "older answer")
+ store._db.append_message(session_id, "user", _composite_carrier()["content"])
+ store._db.append_message(session_id, "assistant", "failed answer")
+
+ gw = GatewayRunner.__new__(GatewayRunner)
+ gw.config = config
+ gw.session_store = store
+ session_entry = MagicMock(session_id=session_id, last_prompt_tokens=123)
+ gw.session_store.get_or_create_session = MagicMock(return_value=session_entry)
+
+ async def fake_handle_message(event):
+ assert event.text == "REAL ASK"
+ active = store.load_transcript(session_id)
+ assert [m.get("content") for m in active[:2]] == ["older ask", "older answer"]
+ scaffold = active[2]
+ assert scaffold["display_kind"] == "hidden"
+ assert "REAL ASK" not in scaffold["content"]
+ return "new answer"
+
+ gw._handle_message = AsyncMock(side_effect=fake_handle_message)
+
+ result = await gw._handle_retry_command(
+ MessageEvent(text="/retry", message_type=MessageType.TEXT, source=MagicMock())
+ )
+
+ assert result == "new answer"
+ assert session_entry.last_prompt_tokens == 0
+ gw._handle_message.assert_awaited_once()
+ archived = [
+ row
+ for row in store._db.get_messages(session_id, include_inactive=True)
+ if not row["active"]
+ ]
+ assert [row["content"] for row in archived] == [
+ _composite_carrier()["content"],
+ "failed answer",
+ ]
+
+
+async def test_gateway_retry_does_not_rewind_a_newer_plain_turn(
+ tmp_path, monkeypatch
+):
+ """The carrier selected for retry must still be latest at commit time."""
+ import hermes_state
+ monkeypatch.setattr(hermes_state, "DEFAULT_DB_PATH", tmp_path / "state.db")
+
+ config = GatewayConfig()
+ store = SessionStore(sessions_dir=tmp_path, config=config)
+ session_id = "retry-carrier-race-session"
+ store._db.create_session(session_id=session_id, source="test")
+ store._db.append_message(session_id, "user", _composite_carrier()["content"])
+ store._db.append_message(session_id, "assistant", "failed answer")
+
+ gw = GatewayRunner.__new__(GatewayRunner)
+ gw.config = config
+ gw.session_store = store
+ session_entry = MagicMock(session_id=session_id, last_prompt_tokens=123)
+ gw.session_store.get_or_create_session = MagicMock(return_value=session_entry)
+ original_rewind = store.rewind_session
+
+ def append_newer_turn_then_rewind(*args, **kwargs):
+ store._db.append_message(session_id, "user", "newer ask")
+ store._db.append_message(session_id, "assistant", "newer answer")
+ return original_rewind(*args, **kwargs)
+
+ monkeypatch.setattr(store, "rewind_session", append_newer_turn_then_rewind)
+ gw._handle_message = AsyncMock()
+
+ result = await gw._handle_retry_command(
+ MessageEvent(text="/retry", message_type=MessageType.TEXT, source=MagicMock())
+ )
+
+ assert result.startswith("Retry failed;")
+ assert session_entry.last_prompt_tokens == 123
+ gw._handle_message.assert_not_awaited()
+ assert [
+ message.get("content")
+ for message in store.load_transcript(session_id)
+ if message.get("role") == "user"
+ ] == [_composite_carrier()["content"], "newer ask"]
+
+
+async def test_gateway_retry_rejects_media_before_redispatch_or_token_reset():
+ gw = GatewayRunner.__new__(GatewayRunner)
+ backing_store = MagicMock()
+ gw.session_store = backing_store
+ session_entry = SimpleNamespace(session_id="sid", last_prompt_tokens=123)
+ facade = SimpleNamespace(
+ _store=backing_store,
+ get_or_create_session=AsyncMock(return_value=session_entry),
+ load_transcript=AsyncMock(
+ return_value=[
+ {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": "look again"},
+ {"type": "image_url", "image_url": {"url": "image"}},
+ ],
+ },
+ {"role": "assistant", "content": "old answer"},
+ ]
+ ),
+ rewrite_transcript=AsyncMock(return_value=True),
+ )
+ gw._async_session_store = facade
+ gw._handle_message = AsyncMock()
+
+ result = await gw._handle_retry_command(
+ MessageEvent(text="/retry", message_type=MessageType.TEXT, source=MagicMock())
+ )
+
+ assert result.startswith("Cannot retry that message safely:")
+ assert session_entry.last_prompt_tokens == 123
+ gw._handle_message.assert_not_awaited()
+ facade.rewrite_transcript.assert_not_awaited()
+
+
+async def test_gateway_retry_stops_when_transcript_rewrite_fails():
+ gw = GatewayRunner.__new__(GatewayRunner)
+ backing_store = MagicMock()
+ gw.session_store = backing_store
+ session_entry = SimpleNamespace(session_id="sid", last_prompt_tokens=123)
+ facade = SimpleNamespace(
+ _store=backing_store,
+ get_or_create_session=AsyncMock(return_value=session_entry),
+ load_transcript=AsyncMock(
+ return_value=[
+ {"role": "user", "content": "retry me"},
+ {"role": "assistant", "content": "old answer"},
+ ]
+ ),
+ rewrite_transcript=AsyncMock(return_value=False),
+ )
+ gw._async_session_store = facade
+ gw._handle_message = AsyncMock()
+
+ result = await gw._handle_retry_command(
+ MessageEvent(text="/retry", message_type=MessageType.TEXT, source=MagicMock())
+ )
+
+ assert result.startswith("Retry failed;")
+ assert session_entry.last_prompt_tokens == 123
+ gw._handle_message.assert_not_awaited()
+ facade.rewrite_transcript.assert_awaited_once()
++ assert (
++ facade.rewrite_transcript.await_args.kwargs["reject_active_turn_lease"]
++ is True
++ )
+
+
+def test_gateway_undo_prefills_live_carrier_text_and_keeps_scaffold(
+ tmp_path, monkeypatch
+):
+ import hermes_state
+ monkeypatch.setattr(hermes_state, "DEFAULT_DB_PATH", tmp_path / "state.db")
+
+ store = SessionStore(sessions_dir=tmp_path, config=GatewayConfig())
+ session_id = "undo-carrier-session"
+ store._db.create_session(session_id=session_id, source="test")
+ store._db.append_message(session_id, "user", _composite_carrier()["content"])
+ store._db.append_message(session_id, "assistant", "failed answer")
+
+ result = store.rewind_session(session_id)
+
+ assert result["target_text"] == "REAL ASK"
+ assert result["rewound_count"] == 2
+ active = store._db.get_messages_as_conversation(
+ session_id, include_row_ids=True
+ )
+ assert len(active) == 1
+ assert active[0]["display_kind"] == "hidden"
+ assert "REAL ASK" not in active[0]["content"]
+
+
@pytest.mark.asyncio
async def test_gateway_retry_preserves_archived_compaction_rows_when_probe_fails(
tmp_path, monkeypatch
diff --cc tests/hermes_state/test_composite_carrier_rewind.py
index 444f58495f9,00000000000..09ab7c97ffc
mode 100644,000000..100644
--- a/tests/hermes_state/test_composite_carrier_rewind.py
+++ b/tests/hermes_state/test_composite_carrier_rewind.py
@@@ -1,238 -1,0 +1,306 @@@
+"""Transactional persistence contracts for composite compaction carriers."""
+
+from __future__ import annotations
+
++import os
++
+import pytest
+
+from agent.context_compressor import (
+ HISTORICAL_TASK_HEADING,
+ SUMMARY_PREFIX,
+ _MERGED_SUMMARY_DELIMITER,
+ _SUMMARY_END_MARKER,
+)
+from hermes_state import (
+ CompressionSessionClosedError,
+ SessionCompressionInProgressError,
+ SessionDB,
++ SessionTurnLeaseLostError,
+)
+
+
+def _carrier(ask: str = "REAL ASK") -> str:
+ return (
+ f"{SUMMARY_PREFIX}\n{HISTORICAL_TASK_HEADING}\nold task\n\n"
+ f"{_SUMMARY_END_MARKER}\n\n{ask}"
+ )
+
+
+def db(tmp_path):
+ state = SessionDB(db_path=tmp_path / "state.db")
+ yield state
+ state.close()
+
+
+def _session_counts(db: SessionDB, session_id: str) -> tuple[int, int, int]:
+ row = db._conn.execute(
+ "SELECT message_count, tool_call_count, rewind_count "
+ "FROM sessions WHERE id = ?",
+ (session_id,),
+ ).fetchone()
+ return row["message_count"], row["tool_call_count"], row["rewind_count"]
+
+
+def _row_state(db: SessionDB, session_id: str) -> list[tuple]:
+ return [
+ tuple(row)
+ for row in db._conn.execute(
+ "SELECT id, role, content, active, display_kind "
+ "FROM messages WHERE session_id = ? ORDER BY id",
+ (session_id,),
+ ).fetchall()
+ ]
+
+
+def _active_ids(db: SessionDB, session_id: str) -> list[int]:
+ return [
+ int(message["_row_id"])
+ for message in db.get_messages_as_conversation(
+ session_id, include_row_ids=True
+ )
+ ]
+
+
+def test_composite_rewind_archives_tail_and_inserts_its_hidden_scaffold(db):
+ sid = "carrier-rewind"
+ db.create_session(sid, source="tui")
+ db.append_message(sid, "user", "older ask")
+ db.append_message(
+ sid,
+ "assistant",
+ None,
+ tool_calls=[{"id": "call-1", "function": {"name": "terminal"}}],
+ )
+ db.append_message(sid, "tool", "ok", tool_call_id="call-1")
+ target_id = db.append_message(sid, "user", _carrier())
+ db.append_message(sid, "assistant", "failed")
+ expected_active_ids = _active_ids(db, sid)
+
+ result = db.rewind_to_message(
+ sid,
+ target_id,
+ preserve_compaction_handoff=True,
+ expected_active_ids=expected_active_ids,
+ expected_target_content="REAL ASK",
+ )
+
+ assert result["rewound_count"] == 2
+ assert result["replacement_message_id"] == result["new_head_id"]
+ active = db.get_messages_as_conversation(sid, include_row_ids=True)
+ assert len(active) == 4
+ assert active[-1]["_row_id"] == result["replacement_message_id"]
+ assert active[-1]["display_kind"] == "hidden"
+ assert SUMMARY_PREFIX in active[-1]["content"]
+ assert "REAL ASK" not in active[-1]["content"]
+ archived = db._conn.execute(
+ "SELECT active FROM messages WHERE id IN (?, ?) ORDER BY id",
+ (target_id, target_id + 1),
+ ).fetchall()
+ assert [row[0] for row in archived] == [0, 0]
+ assert _session_counts(db, sid) == (4, 1, 1)
+
+
+def test_default_rewind_return_shape_and_active_counters_remain_compatible(db):
+ sid = "default-rewind"
+ db.create_session(sid, source="cli")
+ db.append_message(sid, "user", "first")
+ db.append_message(sid, "assistant", "answer")
+ target_id = db.append_message(sid, "user", "second")
+ db.append_message(
+ sid,
+ "assistant",
+ None,
+ tool_calls=[{"id": "call-2", "function": {"name": "terminal"}}],
+ )
+
+ result = db.rewind_to_message(sid, target_id)
+
+ assert set(result) == {"rewound_count", "target_message", "new_head_id"}
+ assert result["rewound_count"] == 2
+ assert _session_counts(db, sid) == (2, 0, 1)
+
+
+def test_guarded_composite_rewind_rejects_append_without_inserting_scaffold(db):
+ sid = "guarded-rewind-append"
+ db.create_session(sid, source="cli")
+ db.append_message(sid, "user", "first")
+ db.append_message(sid, "assistant", "answer")
+ target_id = db.append_message(sid, "user", _carrier())
+ db.append_message(sid, "assistant", "failed")
+ snapshot = db.get_messages_as_conversation(sid, include_row_ids=True)
+ expected_active_ids = [int(message["_row_id"]) for message in snapshot]
+ assert snapshot[-2]["_row_id"] == target_id
+
+ # Deterministic validation -> write race: a sibling writer commits after
+ # the snapshot but before rewind_to_message begins its write transaction.
+ sibling = SessionDB(db_path=db.db_path)
+ sibling.append_message(sid, "assistant", "concurrent append")
+ sibling.close()
+ before_rows = _row_state(db, sid)
+ before_counts = _session_counts(db, sid)
+
+ with pytest.raises(RuntimeError, match="active transcript changed"):
+ db.rewind_to_message(
+ sid,
+ target_id,
+ preserve_compaction_handoff=True,
+ expected_active_ids=expected_active_ids,
+ expected_target_content=_carrier(),
+ )
+
+ assert _row_state(db, sid) == before_rows
+ assert _session_counts(db, sid) == before_counts
+
+def test_guarded_rewind_rejects_selected_target_content_change(db):
+ sid = "guarded-rewind-in-place"
+ db.create_session(sid, source="cli")
+ db.append_message(sid, "user", "first")
+ db.append_message(sid, "assistant", "answer")
+ target_id = db.append_message(sid, "user", "second")
+ db.append_message(sid, "assistant", "failed")
+ expected_active_ids = _active_ids(db, sid)
+
+ sibling = SessionDB(db_path=db.db_path)
+ sibling._execute_write(
+ lambda conn: conn.execute(
+ "UPDATE messages SET content = ? WHERE id = ?",
+ ("changed second", target_id),
+ )
+ )
+ sibling.close()
+ before_rows = _row_state(db, sid)
+ before_counts = _session_counts(db, sid)
+
+ with pytest.raises(RuntimeError, match="rewind target changed"):
+ db.rewind_to_message(
+ sid,
+ target_id,
+ expected_active_ids=expected_active_ids,
+ expected_target_content="second",
+ )
+
+ assert _row_state(db, sid) == before_rows
+ assert _session_counts(db, sid) == before_counts
+
+
+def test_guarded_rewind_ignores_reaction_metadata_change(db):
+ sid = "guarded-rewind-reaction"
+ db.create_session(sid, source="cli")
+ target_id = db.append_message(sid, "user", "second")
+ db.append_message(sid, "assistant", "failed")
+ expected_active_ids = _active_ids(db, sid)
+
+ assert db.set_message_reaction(sid, target_id + 1, "👍", author="user")
+
+ result = db.rewind_to_message(
+ sid,
+ target_id,
+ expected_active_ids=expected_active_ids,
+ expected_target_content="second",
+ )
+
+ assert result["rewound_count"] == 2
+ assert db.get_messages_as_conversation(sid) == []
+
+
+def test_rewind_guard_rejects_foreign_live_compression_without_any_change(db):
+ sid = "locked-rewind"
+ db.create_session(sid, source="tui")
+ target_id = db.append_message(sid, "user", _carrier())
+ db.append_message(sid, "assistant", "failed")
+ assert db.try_acquire_compression_lock(sid, "foreign-writer", ttl_seconds=60)
+ before_rows = _row_state(db, sid)
+ before_counts = _session_counts(db, sid)
+
+ with pytest.raises(SessionCompressionInProgressError):
+ db.rewind_to_message(
+ sid, target_id, preserve_compaction_handoff=True
+ )
+
+ assert _row_state(db, sid) == before_rows
+ assert _session_counts(db, sid) == before_counts
+
+
++def test_rewind_guard_rejects_foreign_turn_lease_without_any_change(db):
++ sid = "leased-rewind"
++ db.create_session(sid, source="tui")
++ target_id = db.append_message(sid, "user", _carrier())
++ expected_active_ids = _active_ids(db, sid)
++ holder = f"pid={os.getpid()}:turn=active"
++ assert db.try_acquire_session_turn_lease(sid, holder, ttl_seconds=60)
++ before_rows = _row_state(db, sid)
++ before_counts = _session_counts(db, sid)
++
++ with pytest.raises(SessionTurnLeaseLostError, match="active turn lease"):
++ db.rewind_to_message(
++ sid,
++ target_id,
++ preserve_compaction_handoff=True,
++ expected_active_ids=expected_active_ids,
++ expected_target_content="REAL ASK",
++ )
++
++ assert _row_state(db, sid) == before_rows
++ assert _session_counts(db, sid) == before_counts
++
++ db.release_session_turn_lease(sid, holder)
++ result = db.rewind_to_message(
++ sid,
++ target_id,
++ preserve_compaction_handoff=True,
++ expected_active_ids=expected_active_ids,
++ expected_target_content="REAL ASK",
++ )
++ assert result["rewound_count"] == 1
++
++
++def test_guarded_replace_rejects_foreign_turn_lease_without_any_change(db):
++ sid = "leased-replace"
++ db.create_session(sid, source="tui")
++ db.append_message(sid, "user", "old ask")
++ holder = f"pid={os.getpid()}:turn=active"
++ assert db.try_acquire_session_turn_lease(sid, holder, ttl_seconds=60)
++ before_rows = _row_state(db, sid)
++ before_counts = _session_counts(db, sid)
++
++ with pytest.raises(SessionTurnLeaseLostError, match="active turn lease"):
++ db.replace_messages(
++ sid,
++ [{"role": "user", "content": "replacement"}],
++ active_only=True,
++ archive_dropped=True,
++ reject_active_turn_lease=True,
++ )
++
++ assert _row_state(db, sid) == before_rows
++ assert _session_counts(db, sid) == before_counts
++
++ db.release_session_turn_lease(sid, holder)
++ db.replace_messages(
++ sid,
++ [{"role": "user", "content": "replacement"}],
++ active_only=True,
++ archive_dropped=True,
++ reject_active_turn_lease=True,
++ )
++ assert [m[2] for m in _row_state(db, sid) if m[3] == 1] == ["replacement"]
++
++
+def test_rewind_guard_rejects_compression_ended_parent_without_any_change(db):
+ sid = "closed-rewind"
+ db.create_session(sid, source="tui")
+ target_id = db.append_message(sid, "user", _carrier())
+ db.append_message(sid, "assistant", "failed")
+ db.end_session(sid, "compression")
+ before_rows = _row_state(db, sid)
+ before_counts = _session_counts(db, sid)
+
+ with pytest.raises(CompressionSessionClosedError):
+ db.rewind_to_message(
+ sid, target_id, preserve_compaction_handoff=True
+ )
+
+ assert _row_state(db, sid) == before_rows
+ assert _session_counts(db, sid) == before_counts
diff --cc tests/test_tui_gateway_server.py
index 384abd04a0d,bfd1bfd66f8..3f870cc0ec1
--- a/tests/test_tui_gateway_server.py
+++ b/tests/test_tui_gateway_server.py
@@@ -4370,7 -4820,7 +4820,14 @@@ def test_prompt_submit_rejects_negative
replaced = []
class _FakeDB:
-- def replace_messages(self, key, messages, active_only=False, archive_dropped=False):
++ def replace_messages(
++ self,
++ key,
++ messages,
++ active_only=False,
++ archive_dropped=False,
++ reject_active_turn_lease=False,
++ ):
replaced.append((key, list(messages)))
history = [
@@@ -4507,7 -4957,7 +4964,14 @@@ def test_prompt_submit_refuses_unconfir
replaced = []
class _FakeDB:
-- def replace_messages(self, key, messages, active_only=False, archive_dropped=False):
++ def replace_messages(
++ self,
++ key,
++ messages,
++ active_only=False,
++ archive_dropped=False,
++ reject_active_turn_lease=False,
++ ):
replaced.append((key, list(messages)))
history = [
@@@ -4565,7 -5015,7 +5029,14 @@@ def test_prompt_submit_truncates_by_mes
replaced = []
class _FakeDB:
-- def replace_messages(self, key, messages, active_only=False, archive_dropped=False):
++ def replace_messages(
++ self,
++ key,
++ messages,
++ active_only=False,
++ archive_dropped=False,
++ reject_active_turn_lease=False,
++ ):
replaced.append((key, list(messages)))
history = [
@@@ -4603,6 -5053,56 +5074,63 @@@
server._sessions.pop("msg-id-trunc-sid", None)
+ def test_prompt_submit_truncation_falls_back_to_sid_when_session_key_null(monkeypatch):
+ """#81904: a NULL session_key must not FK-fail the truncation persist.
+
+ CLI-origin sessions resumed in the Desktop have no session_key; the
+ truncation path used to call replace_messages(None, ...), whose reinsert
+ violated the messages.session_id FK ("FOREIGN KEY constraint failed" →
+ "Restore failed"). The persist must key off the session id instead —
+ for CLI-origin rows the durable sessions.id IS the requested sid.
+ """
+ replaced = []
+
+ class _FakeDB:
- def replace_messages(self, key, messages, active_only=False, archive_dropped=False):
++ def replace_messages(
++ self,
++ key,
++ messages,
++ active_only=False,
++ archive_dropped=False,
++ reject_active_turn_lease=False,
++ ):
+ replaced.append((key, list(messages)))
+
+ history = [
+ {"role": "user", "content": "first"},
+ {"role": "assistant", "content": "reply 1"},
+ {"role": "user", "content": "second"},
+ {"role": "assistant", "content": "reply 2"},
+ ]
+ server._sessions["null-key-trunc-sid"] = _session(
+ history=list(history), session_key=None
+ )
+ monkeypatch.setattr(server, "_get_db", lambda: _FakeDB())
+ monkeypatch.setattr(server, "_start_agent_build", lambda *a, **k: None)
+ monkeypatch.setattr(server, "_start_inflight_turn", lambda *a, **k: None)
+
+ try:
+ resp = server.handle_request(
+ {
+ "id": "1",
+ "method": "prompt.submit",
+ "params": {
+ "session_id": "null-key-trunc-sid",
+ "text": "new turn",
+ "truncate_before_user_ordinal": 1,
+ "confirm_truncate": True,
+ },
+ }
+ )
+ assert resp.get("result") is not None
+ assert len(replaced) == 1
+ # Keyed by the session id, never None (the FK-violating value).
+ assert replaced[0][0] == "null-key-trunc-sid"
+ assert replaced[0][1] == history[:2]
+ finally:
+ server._sessions.pop("null-key-trunc-sid", None)
+
+
def test_prompt_submit_refuses_ordinal_and_message_id_mismatch(monkeypatch):
"""#82756: A mismatch between truncate_before_user_ordinal and truncate_before_message_id must return 4030."""
history = [
@@@ -4640,12 -5140,58 +5168,72 @@@
server._sessions.pop("mismatch-trunc-sid", None)
+ def test_prompt_submit_refuses_ordinal_only_when_history_has_row_ids(monkeypatch):
+ """A durable session must not trust an ordinal without a row-id target."""
+ replaced = []
+
+ class _FakeDB:
- def replace_messages(self, key, messages, active_only=False, archive_dropped=False):
++ def replace_messages(
++ self,
++ key,
++ messages,
++ active_only=False,
++ archive_dropped=False,
++ reject_active_turn_lease=False,
++ ):
+ replaced.append((key, list(messages)))
+
+ history = [
+ {"_row_id": 101, "role": "user", "content": "first"},
+ {"_row_id": 102, "role": "assistant", "content": "reply 1"},
+ {"_row_id": 103, "role": "user", "content": "second"},
+ {"_row_id": 104, "role": "assistant", "content": "reply 2"},
+ ]
+ server._sessions["ordinal-only-durable-sid"] = _session(history=list(history))
+ monkeypatch.setattr(server, "_get_db", lambda: _FakeDB())
+ monkeypatch.setattr(
+ server, "_start_agent_build", lambda *a, **k: pytest.fail("must not start a turn")
+ )
+ monkeypatch.setattr(
+ server, "_start_inflight_turn", lambda *a, **k: pytest.fail("must not start a turn")
+ )
+
+ try:
+ resp = server.handle_request(
+ {
+ "id": "1",
+ "method": "prompt.submit",
+ "params": {
+ "session_id": "ordinal-only-durable-sid",
+ "text": "retry",
+ "truncate_before_user_ordinal": 1,
+ "confirm_truncate": True,
+ },
+ }
+ )
+
+ assert resp["error"]["code"] == 4004
+ assert "truncate_before_row_id" in resp["error"]["message"]
+ assert server._sessions["ordinal-only-durable-sid"]["history"] == history
+ assert server._sessions["ordinal-only-durable-sid"]["running"] is False
+ assert replaced == []
+ finally:
+ server._sessions.pop("ordinal-only-durable-sid", None)
+
+
def test_prompt_submit_truncates_by_row_id(monkeypatch):
"""#82959: prompt.submit with truncate_before_row_id must cut at the target row id."""
replaced = []
class _FakeDB:
-- def replace_messages(self, key, messages, active_only=False, archive_dropped=False):
++ def replace_messages(
++ self,
++ key,
++ messages,
++ active_only=False,
++ archive_dropped=False,
++ reject_active_turn_lease=False,
++ ):
replaced.append((key, list(messages)))
history = [
@@@ -4690,7 -5236,7 +5278,14 @@@ def test_prompt_submit_truncates_by_str
replaced = []
class _FakeDB:
-- def replace_messages(self, key, messages, active_only=False, archive_dropped=False):
++ def replace_messages(
++ self,
++ key,
++ messages,
++ active_only=False,
++ archive_dropped=False,
++ reject_active_turn_lease=False,
++ ):
replaced.append((key, list(messages)))
history = [
@@@ -4844,7 -5390,7 +5439,14 @@@ def test_prompt_submit_refuses_empty_tr
replaced = []
class _FakeDB:
-- def replace_messages(self, key, messages, active_only=False, archive_dropped=False):
++ def replace_messages(
++ self,
++ key,
++ messages,
++ active_only=False,
++ archive_dropped=False,
++ reject_active_turn_lease=False,
++ ):
replaced.append((key, list(messages)))
history = [
@@@ -4931,7 -5477,7 +5533,14 @@@ def test_prompt_submit_empty_truncation
self._target()
class _FakeDB:
-- def replace_messages(self, key, messages, active_only=False, archive_dropped=False):
++ def replace_messages(
++ self,
++ key,
++ messages,
++ active_only=False,
++ archive_dropped=False,
++ reject_active_turn_lease=False,
++ ):
replaced.append((key, list(messages)))
history = [
@@@ -9992,7 -10739,7 +10884,14 @@@ def test_prompt_submit_can_truncate_bef
def __init__(self):
self.replaced = []
-- def replace_messages(self, session_id, messages, active_only=False, archive_dropped=False):
++ def replace_messages(
++ self,
++ session_id,
++ messages,
++ active_only=False,
++ archive_dropped=False,
++ reject_active_turn_lease=False,
++ ):
self.replaced.append((session_id, list(messages)))
stub_db = _StubDb()
@@@ -10049,7 -10796,7 +10948,14 @@@ def test_prompt_submit_refuses_turn_whe
server._sessions["trunc-fail-sid"] = sess
class _FailDb:
-- def replace_messages(self, session_id, messages, active_only=False, archive_dropped=False):
++ def replace_messages(
++ self,
++ session_id,
++ messages,
++ active_only=False,
++ archive_dropped=False,
++ reject_active_turn_lease=False,
++ ):
raise OSError("disk full")
monkeypatch.setattr(server, "_get_db", lambda: _FailDb())
@@@ -10141,7 -10888,7 +11047,14 @@@ def test_prompt_submit_truncate_ordinal
def __init__(self):
self.replaced = []
-- def replace_messages(self, session_id, messages, active_only=False, archive_dropped=False):
++ def replace_messages(
++ self,
++ session_id,
++ messages,
++ active_only=False,
++ archive_dropped=False,
++ reject_active_turn_lease=False,
++ ):
self.replaced.append((session_id, list(messages)))
stub_db = _StubDb()
@@@ -17283,7 -18154,7 +18320,14 @@@ def test_personality_marker_does_not_sh
def __init__(self):
self.replaced = []
-- def replace_messages(self, session_id, messages, active_only=False, archive_dropped=False):
++ def replace_messages(
++ self,
++ session_id,
++ messages,
++ active_only=False,
++ archive_dropped=False,
++ reject_active_turn_lease=False,
++ ):
self.replaced.append((session_id, list(messages)))
session = _session(
@@@ -17391,10 -18262,10 +18435,16 @@@ def test_prompt_submit_truncation_archi
class _StubDb:
def replace_messages(
-- self, session_id, messages, active_only=False, archive_dropped=False
++ self,
++ session_id,
++ messages,
++ active_only=False,
++ archive_dropped=False,
++ reject_active_turn_lease=False,
):
captured["active_only"] = active_only
captured["archive_dropped"] = archive_dropped
++ captured["reject_active_turn_lease"] = reject_active_turn_lease
server._sessions["archive-trunc-sid"] = _session(
agent=_Agent(),
@@@ -17433,6 -18304,6 +18483,7 @@@
)
# #80216: still must not touch rows archived by an earlier compaction.
assert captured.get("active_only") is True
++ assert captured.get("reject_active_turn_lease") is True
finally:
server._sessions.pop("archive-trunc-sid", None)
@@@ -17454,7 -18325,7 +18505,14 @@@ def test_prompt_submit_unmatched_row_id
replaced = []
class _FakeDB:
-- def replace_messages(self, key, messages, active_only=False, archive_dropped=False):
++ def replace_messages(
++ self,
++ key,
++ messages,
++ active_only=False,
++ archive_dropped=False,
++ reject_active_turn_lease=False,
++ ):
replaced.append((key, list(messages)))
history = [
@@@ -17498,7 -18369,7 +18556,14 @@@ def test_prompt_submit_unmatched_messag
replaced = []
class _FakeDB:
-- def replace_messages(self, key, messages, active_only=False, archive_dropped=False):
++ def replace_messages(
++ self,
++ key,
++ messages,
++ active_only=False,
++ archive_dropped=False,
++ reject_active_turn_lease=False,
++ ):
replaced.append((key, list(messages)))
# Production-shaped history: no renderer "id" keys on user dicts.
@@@ -17556,7 -18427,7 +18621,14 @@@ def test_prompt_submit_row_id_resolves_
]
class _FakeDB:
-- def replace_messages(self, key, messages, active_only=False, archive_dropped=False):
++ def replace_messages(
++ self,
++ key,
++ messages,
++ active_only=False,
++ archive_dropped=False,
++ reject_active_turn_lease=False,
++ ):
replaced.append((key, list(messages)))
def get_messages_as_conversation(self, key, repair_alternation=False, include_row_ids=False):
@@@ -17882,7 -18753,7 +18954,14 @@@ def test_prompt_submit_row_id_db_fallba
]
class _FakeDB:
-- def replace_messages(self, key, messages, active_only=False, archive_dropped=False):
++ def replace_messages(
++ self,
++ key,
++ messages,
++ active_only=False,
++ archive_dropped=False,
++ reject_active_turn_lease=False,
++ ):
replaced.append((key, list(messages)))
def get_messages_as_conversation(self, key, repair_alternation=False, include_row_ids=False):
diff --cc tui_gateway/methods_prompt.py
index ee8d93a6b02,fd2feabd452..6c79512a3df
--- a/tui_gateway/methods_prompt.py
+++ b/tui_gateway/methods_prompt.py
@@@ -561,36 -565,48 +579,50 @@@ def _(rid, params: dict) -> dict
# new exchange is appended on top of the "undone" turns — durable
# zombie history on resume, and the edit/regenerate never sticks.
# Fail closed: refuse the turn and leave memory/DB unchanged.
- if (db := _get_db()) is not None:
- try:
- # 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.
- # archive_dropped: a rewind overwrites turns the user may
- # not have meant to drop, and this write is the last step
- # before they are gone — three reported incidents ended
- # here with nothing to restore from (#70516, #80763,
- # #82756). Soft-archiving keeps them on disk (active=0) and
- # in the FTS index, so a mis-aimed cut is recoverable
- # instead of terminal. The live transcript is unchanged.
- # Fall back to session id when session_key is NULL — CLI-origin
- # sessions created before the session_key default fix have no
- # key, and replace_messages(None) triggers an FK violation.
- truncation_key = session.get("session_key") or sid
- db.replace_messages(
- truncation_key,
- truncated,
- active_only=True,
- archive_dropped=True,
- )
- except Exception as exc:
- logger.error(
- "prompt.submit: replace_messages failed for session %s "
- "(ordinal=%d); refusing turn so memory and DB stay "
- "aligned: %s",
- sid,
- ordinal,
- exc,
- exc_info=True,
- )
- return _err(
- rid,
- 5008,
- f"failed to persist history truncation: {exc}",
- )
+ try:
+ with _session_db(session) as db:
+ if db is not None:
- # Keep main's durable row-id contract: this rewrite
- # stamps fresh row ids onto the same surviving dicts,
- # and the response below lets Desktop rebind them.
- # ``truncated`` is carrier-aware, so a composite target
- # becomes its pure hidden scaffold in the same atomic
- # replace that archives the selected row and tail.
++ # 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.
++ # archive_dropped: a rewind overwrites turns the user may
++ # not have meant to drop, and this write is the last step
++ # before they are gone — three reported incidents ended
++ # here with nothing to restore from (#70516, #80763,
++ # #82756). Soft-archiving keeps them on disk (active=0) and
++ # in the FTS index, so a mis-aimed cut is recoverable
++ # instead of terminal. The live transcript is unchanged.
++ # Fall back to session id when session_key is NULL — CLI-origin
++ # sessions created before the session_key default fix have no
++ # key, and replace_messages(None) triggers an FK violation.
++ truncation_key = session.get("session_key") or sid
+ db.replace_messages(
- session["session_key"],
++ truncation_key,
+ truncated,
+ active_only=True,
+ archive_dropped=True,
++ reject_active_turn_lease=True,
+ )
+ except Exception as exc:
+ logger.error(
+ "prompt.submit: replace_messages failed for session %s "
+ "(ordinal=%d); refusing turn so memory and DB stay "
+ "aligned: %s",
+ sid,
+ ordinal,
+ exc,
+ exc_info=True,
+ )
+ return _err(
+ rid,
+ 5008,
+ f"failed to persist history truncation: {exc}",
+ )
session["history"] = truncated
session["history_version"] = int(session.get("history_version", 0)) + 1
if db is not None:
diff --cc tui_gateway/server.py
index 179ed6ca881,c34e42fc646..24ad5760254
--- a/tui_gateway/server.py
+++ b/tui_gateway/server.py
@@@ -2980,141 -3079,7 +3079,141 @@@ def _session_db(session: dict)
db.close()
+def _rewind_active_session_history(
+ session: dict, user_ordinal: int
+) -> tuple[list[dict], dict, int]:
+ """Rewind one canonical user turn while retaining carrier scaffolding.
+
+ The caller holds ``history_lock``. Persistent sessions archive the target
+ and tail; a composite carrier's own hidden handoff is inserted in that same
+ transaction. Memory is installed only after the durable commit and is
+ built from the already-validated prefix plus the returned scaffold row id,
+ so there is no fallible post-commit reload.
+ """
+ from agent.context_compressor import (
+ history_before_user_originated_turn,
+ split_user_originated_turn,
+ user_originated_turn_view,
+ )
+ from agent.memory_manager import sanitize_context
+ from agent.tool_dispatch_helpers import (
+ _is_multimodal_tool_result,
+ _multimodal_text_summary,
+ )
+
+ def _comparison_content(message: dict) -> Any:
+ content = message.get("content")
+ if _is_multimodal_tool_result(content):
+ content = _multimodal_text_summary(content)
+ elif isinstance(content, list):
+ text_parts = []
+ for part in content:
+ if isinstance(part, dict) and part.get("type") == "text":
+ text_parts.append(str(part.get("text", "")))
+ elif (
+ isinstance(part, dict)
+ and part.get("type") in {"image", "image_url", "input_image"}
+ ):
+ text_parts.append("[screenshot]")
+ content = "\n".join(text_parts) if text_parts else None
+ if message.get("role") in {"user", "assistant"} and isinstance(content, str):
+ return sanitize_context(content).strip()
+ return content
+
+ history = _history_without_ephemeral_scaffolding(session.get("history", []))
+ user_indices = [
+ index
+ for index, message in enumerate(history)
+ if user_originated_turn_view(message) is not None
+ ]
+ if user_ordinal < 0 or user_ordinal >= len(user_indices):
+ raise ValueError("target user message is no longer in session history")
+ target_index = user_indices[user_ordinal]
+ installed, live_view = history_before_user_originated_turn(history, target_index)
+ rewound_count = len(history) - target_index
+
+ session_key = str(session.get("session_key") or "").strip()
+ persisted = False
+ if session_key:
+ with _session_db(session) as db:
+ if db is None:
+ raise RuntimeError("session database is unavailable")
+ durable = db.get_messages_as_conversation(
+ session_key,
+ include_row_ids=True,
+ )
+ durable_user_indices = [
+ index
+ for index, message in enumerate(durable)
+ if user_originated_turn_view(message) is not None
+ ]
+ if len(durable_user_indices) != len(user_indices):
+ raise RuntimeError(
+ "session history changed before the rewind could be persisted"
+ )
+ durable_target_index = durable_user_indices[user_ordinal]
+ durable_target = durable[durable_target_index]
+ durable_prefix, durable_live_view = history_before_user_originated_turn(
+ durable, durable_target_index
+ )
+ if _comparison_content(durable_live_view) != _comparison_content(live_view):
+ raise RuntimeError(
+ "session history changed before the rewind could be persisted"
+ )
+ target_row_id = durable_target.get("_row_id")
+ if not isinstance(target_row_id, int):
+ raise RuntimeError("rewind target has no durable row identity")
+ expected_active_ids = [
+ int(message["_row_id"])
+ for message in durable
+ if isinstance(message.get("_row_id"), int)
+ ]
+ scaffold, _ = split_user_originated_turn(durable_target)
+ result = db.rewind_to_message(
+ session_key,
+ target_row_id,
+ preserve_compaction_handoff=scaffold is not None,
+ expected_active_ids=expected_active_ids,
+ expected_target_content=durable_live_view.get("content"),
+ )
+ if scaffold is not None:
+ replacement_id = result.get("replacement_message_id")
+ if not isinstance(replacement_id, int):
+ raise RuntimeError(
+ "rewind commit did not return the replacement scaffold id"
+ )
+ durable_prefix[-1]["_row_id"] = replacement_id
+ durable_prefix[-1]["_db_persisted"] = True
+ installed[-1] = durable_prefix[-1]
+ live_view = durable_live_view
+ rewound_count = int(result.get("rewound_count", 0))
+ persisted = True
+
+ installed = [message.copy() for message in installed]
+ session["history"] = installed
+ session["history_version"] = int(session.get("history_version", 0)) + 1
+ agent = session.get("agent")
+ if agent is not None:
+ agent._session_messages = installed
+ if hasattr(agent, "_last_flushed_db_idx"):
+ agent._last_flushed_db_idx = len(installed) if persisted else 0
+ if hasattr(agent, "_db_flush_scan_prefix"):
+ agent._db_flush_scan_prefix = installed[:] if persisted else None
+ return installed, live_view, rewound_count
+
+
+def _history_without_ephemeral_scaffolding(history: list[dict]) -> list[dict]:
+ """Return the durable transcript shape without transient recovery rows."""
+ from run_agent import _is_ephemeral_scaffolding
+
+ return [
+ message.copy()
+ for message in history
+ if not _is_ephemeral_scaffolding(message)
+ ]
+
+
- def _persist_session_git_meta(session: dict, cwd: str) -> None:
+ def _persist_session_git_meta(session: dict, cwd: str, generation: int) -> None:
"""Resolve + persist a session's git branch / repo root WITHOUT blocking.
Branch and root come from ``git`` subprocess probes; running them inline on