The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(state): compact messages docstrings (WHY kept); append_message builds msg from its own kwargs
Teknium388fe39f5535
diff --git a/hermes_state_messages.py b/hermes_state_messages.pyindex 0d801db9359..8e6d75f9ba0 100644--- a/hermes_state_messages.py+++ b/hermes_state_messages.py@@ -112,14 +112,10 @@ class SessionMessagesMixin:"""Message append/replace/rewind, reactions, resume conversations, replay dedupe."""def _bump_conversation_generation(self, conn, session_id: str, end_reason: str) -> None:- """Advance this peer's conversation generation past a boundary, inside the- transaction that writes the boundary.-- Only ``_RESET_END_REASONS`` count (``compression`` continues one conversation).- The counter never reads the session rows: an aggregate over them could re-emit a- pair once ``delete_session()``/pruning removes an ended row and hand a new- conversation a retired affinity identity. It only ever increments.- """+ """Advance this peer's conversation generation past a boundary, inside the txn that+ writes it. Only ``_RESET_END_REASONS`` count (``compression`` continues one+ conversation). Never derived from session rows (deletes/prunes could re-emit a+ retired affinity identity); it only ever increments."""if end_reason not in _RESET_END_REASONS:returnrow = conn.execute("SELECT source, session_key FROM sessions WHERE id = ?", (session_id,)).fetchone()@@ -143,8 +139,7 @@ class SessionMessagesMixin:def _encode_content(cls, content: Any) -> Any:"""Serialize list/dict content (multimodal parts) as a sentinel-prefixed JSONstring; sqlite3 can only bind str/bytes/int/float/None. Lone surrogates are- scrubbed from text so persistence never fails. Paired with :meth:`_decode_content`.- """+ scrubbed from text so persistence never fails. Paired with :meth:`_decode_content`."""if isinstance(content, str):return _sanitize_surrogates(content)if content is None or isinstance(content, (bytes, int, float)):@@ -222,16 +217,12 @@ class SessionMessagesMixin:reject_active_turn_lease: bool = False, reject_active_compression_lock: bool = False,allow_closed_compression_parent: bool = False,) -> None:- """Transcript-write admission checks, run INSIDE the write txn.-- Shared by every transcript writer so they cannot diverge. Ordinary appends do- NOT check compression_locks: the lock only stops two COMPRESSIONS colliding, and- archive_and_compact() commits against a watermark and clones later rows, so- concurrent appends are safe by construction (blocking them killed turns while a- slow summary held the lease). Destructive user mutations opt in via- ``reject_active_compression_lock`` / ``reject_active_turn_lease`` so a compressor- that captured its watermark cannot resurrect the removed turn.- """+ """Transcript-write admission checks, run INSIDE the write txn (shared by every+ writer). Ordinary appends do NOT check compression_locks: the lock only stops two+ COMPRESSIONS colliding and archive_and_compact() commits against a watermark, so+ concurrent appends are safe (blocking them killed turns during slow summaries).+ Destructive user mutations opt in via ``reject_active_*`` so a compressor that+ captured its watermark cannot resurrect the removed turn."""from hermes_state import CompressionSessionClosedError, SessionCompressionInProgressError, SessionTurnLeaseLostErrorif reject_active_compression_lock:active_lock = conn.execute(_COMPRESSION_LOCK_ROW_SQL, (session_id,)).fetchone()@@ -282,8 +273,7 @@ class SessionMessagesMixin:"""Bind values for ``_INSERT_MESSAGE_SQL`` from one message dict.*tool_calls* is the already-parsed value (see ``_parse_tool_calls``).- *keep_reasoning* False stores NULL for every reasoning/codex column.- """+ *keep_reasoning* False stores NULL for every reasoning/codex column."""from hermes_state import _scrub_surrogatesdef _str_or_none(value):@@ -330,27 +320,13 @@ class SessionMessagesMixin:compression_lock_holder: Optional[str] = None, turn_lease_holder: Optional[str] = None,turn_lease_ttl_seconds: float = 300.0,) -> int:- """Append one message; returns the row id. Bumps ``message_count`` (and- ``tool_call_count`` when tool_calls are present).-- ``platform_message_id`` is the platform's own id (Telegram update_id, Yuanbao- msg_id) used by recall-style flows. ``api_content`` is the byte-fidelity- sidecar — the exact string sent to the API when it differed from ``content`` —- stored as sent except lone surrogates (which the loop scrubs anyway).- """- msg = {- "content": content, "tool_name": tool_name, "tool_call_id": tool_call_id,- "token_count": token_count, "finish_reason": finish_reason, "reasoning": reasoning,- "reasoning_content": reasoning_content, "reasoning_details": reasoning_details,- "codex_reasoning_items": codex_reasoning_items, "codex_message_items": codex_message_items,- "platform_message_id": platform_message_id, "message_id": platform_message_id,- "observed": observed, "effect_disposition": effect_disposition,- "_compressed_summary": _compressed_summary, "api_content": api_content,- "display_kind": display_kind, "display_metadata": display_metadata,- }+ """Append one message; returns the row id and bumps the session counters.+ ``platform_message_id``: the platform's own id (recall-style flows).+ ``api_content``: byte-fidelity sidecar — the exact string sent to the API when it+ differed from ``content`` — stored as sent except lone surrogates."""+ msg = dict(locals()) # every keyword above is a message-dict field of the same name# Encode outside the write txn (display metadata first: log-order parity).- display_metadata_json = self._encode_display_metadata(display_metadata)- msg["display_metadata"] = display_metadata_json+ msg["display_metadata"] = self._encode_display_metadata(display_metadata)tool_calls = _parse_tool_calls(tool_calls)message_timestamp = _coerce_timestamp(timestamp, time.time())num_tool_calls = _tool_calls_count(tool_calls)@@ -385,13 +361,10 @@ class SessionMessagesMixin:compression_lock_holder: Optional[str] = None, turn_lease_holder: Optional[str] = None,chunk_rows: Optional[int] = None, turn_lease_ttl_seconds: float = 300.0,) -> int:- """Append *messages* (``_insert_message_rows`` dict shape) in ONE write txn.-- All rows land or none do; the admission guards run once for the batch.- ``chunk_rows`` bounds transaction size for LARGE copies (branch seeds: FTS- triggers run per row, 10k rows ≈ 2.4s under one lock) — commits in chunks with- the old per-row-loop recovery semantics. Returns the inserted row count.- """+ """Append *messages* (``_insert_message_rows`` dict shape) in ONE write txn: all+ rows land or none, guards run once. ``chunk_rows`` bounds txn size for LARGE+ copies (branch seeds; FTS triggers run per row) by committing in chunks.+ Returns the inserted row count."""if not messages:return 0if chunk_rows is not None and len(messages) > chunk_rows:@@ -468,12 +441,9 @@ class SessionMessagesMixin:def set_message_reaction(self, session_id: str, message_row_id: int, emoji: Optional[str], *, author: str = "user",) -> Optional[List[Dict[str, Any]]]:- """Set (or with ``emoji=None`` clear) *author*'s reaction on one message.-- Tapback semantics: one reaction per author per message; the same emoji again- clears it, a different one replaces it. Returns the message's reaction list- after the write, or ``None`` when the row isn't part of *session_id*.- """+ """Set (``emoji=None``: clear) *author*'s reaction. Tapback semantics: one per+ author per message; the same emoji again clears it, a different one replaces it.+ Returns the reaction list after the write, or ``None`` for a foreign row."""from hermes_state import _scrub_surrogatesif not session_id or message_row_id is None:return None@@ -518,8 +488,7 @@ class SessionMessagesMixin:"""Return *author*'s not-yet-surfaced reactions and mark them seen.Reactions are announced on the NEXT user turn (never by rewriting the reacted- message — cache-safe); the ``seen`` stamp makes each announcement exactly once.- """+ message — cache-safe); the ``seen`` stamp makes each announcement exactly once."""if not session_id:return []@@ -562,12 +531,9 @@ class SessionMessagesMixin: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 message with *role*, or ``None``.-- ``offset`` steps to earlier turns (1 = the one before the latest). ``require_text``- skips rows without plain-text content (tool-call-only turns, attachment stubs)- so "the latest message" never resolves to an invisible bubble.- """+ """Row id of the most recent active *role* message, or ``None``. ``offset`` steps+ to earlier turns; ``require_text`` skips rows without plain-text content so "the+ latest message" never resolves to an invisible bubble."""if not session_id or role not in {"user", "assistant"} or offset < 0:return Nonetext_filter = "AND content IS NOT NULL AND TRIM(content) != '' " if require_text else ""@@ -594,12 +560,9 @@ class SessionMessagesMixin:return row[0] if row else Nonedef _insert_message_rows(self, conn, session_id: str, messages: List[Dict[str, Any]]) -> tuple[int, int]:- """Insert *messages* as fresh active rows inside the caller's write txn.-- Returns ``(inserted_count, tool_call_count)``; does NOT touch sessions.*- counters (callers reconcile them differently). Reasoning columns are kept for- assistant rows only. Stamps ``msg["_row_id"]``.- """+ """Insert *messages* as fresh active rows inside the caller's write txn. Returns+ ``(inserted, tool_call_count)``; never touches sessions.* counters (callers+ reconcile differently). Reasoning columns kept for assistant rows only."""now_ts = time.time()inserted = tool_calls_total = 0for msg in messages:@@ -623,18 +586,12 @@ class SessionMessagesMixin:self, session_id: str, 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 (/retry, /undo, /compress).-- DESTRUCTIVE by default: every row is DELETEd (and leaves the FTS index).- ``active_only=True`` replaces only ``active = 1`` rows, leaving soft-archived- rows (compacted turns, rewind rows) untouched — required when sharing a session- id with an agent doing in-place compaction. ``archive_dropped=True`` SOFT-archives- the live rows (``active = 0, compacted = 0``, rewind-style) instead of deleting:- the mode rewind/edit/regenerate must use, since a DELETE leaves nothing to- recover from; it implies active-only handling. ``reject_active_turn_lease=True``- runs the lease check in the same write txn for user-initiated rewrites that do- not own the cross-process lease.- """+ """Atomically replace a session's stored messages (/retry, /undo, /compress).+ DESTRUCTIVE by default (rows DELETEd, leave FTS). ``active_only`` spares+ soft-archived rows (needed alongside in-place compaction). ``archive_dropped``+ SOFT-archives the live rows rewind-style instead of deleting — what rewind/edit/+ regenerate must use, since a DELETE leaves nothing to recover. ``reject_active_+ turn_lease`` runs the lease check in-txn for user rewrites that don't own it."""from hermes_state import CompressionSessionClosedErroractive_clause = " AND active = 1" if active_only else ""@@ -713,28 +670,20 @@ class SessionMessagesMixin:model_config_patch: Optional[Dict[str, Any]] = None, watermark: Optional[int] = None,lock_holder: Optional[str] = None, tail_count: int = 0,) -> int:- """Non-destructive in-place compaction under ONE durable session id.-- Soft-archives the active rows (``active=0, compacted=1`` — "summarized away",- still found by search_messages and readable with include_inactive) and inserts- *compacted_messages* as fresh active rows, atomically. Live-context loads- filter ``active = 1`` so the model reloads only the compacted set.-- *watermark* (``get_active_message_watermark`` at compression START): rows with- ``id > watermark`` arrived during the slow summary and are re-sequenced after- the compacted set by a pure-SQL column clone (fresh ids — consumers re-resolve- by content); ``None`` archives everything. *lock_holder*: the commit verifies- inside the txn that the compression lock is still held and unexpired, so a- reclaimed lease fails instead of clobbering the winner. *tail_count*: the LAST- N rows of *compacted_messages* are the verbatim carried-forward tail; their- originals (at/below the watermark) and the watermark clones' originals are- superseded duplicates and get rewind-style flags (``active=0, compacted=0``) so- session_search doesn't return each carried message once per compaction.-- ``message_count`` becomes the ACTIVE count; ``model_config_patch`` merges into- the session JSON in the same txn (``None`` value removes a key). Returns the new- active count.- """+ """Non-destructive in-place compaction under ONE durable session id: soft-archive+ the active rows (``active=0, compacted=1`` — "summarized away", still searchable)+ and insert *compacted_messages* as fresh active rows, atomically.++ *watermark* (captured at compression START): rows with ``id > watermark`` arrived+ during the slow summary and are re-sequenced after the compacted set by a pure-+ SQL column clone (fresh ids); ``None`` archives everything. *lock_holder*: the+ commit verifies in-txn that the lease is still held, so a reclaimed lease fails+ instead of clobbering the winner. *tail_count*: the LAST N compacted rows are the+ verbatim carried-forward tail; their originals and the watermark clones' originals+ are superseded duplicates and get rewind-style flags (``active=0, compacted=0``)+ so search doesn't return each carried message once per compaction.+ ``message_count`` becomes the ACTIVE count; ``model_config_patch`` merges in the+ same txn (``None`` removes a key). Returns the new active count."""from hermes_state import SessionCompressionInProgressErrordef _do(conn):@@ -827,14 +776,10 @@ class SessionMessagesMixin:return colsdef set_latest_user_api_content(self, session_id: str, content: Any, api_content: str) -> int:- """Backfill the ``api_content`` sidecar onto the newest ACTIVE user row.-- In-place preflight compaction inserts the current user row BEFORE the turn- prologue composes the sidecar, and the later persist identity-skips compacted- dicts; without this the reload would replay clean content and reopen the- prompt-cache divergence. The ``content`` match guards against a racing rewrite.- Returns rows updated (0 or 1).- """+ """Backfill the ``api_content`` sidecar onto the newest ACTIVE user row. Preflight+ compaction inserts that row BEFORE the sidecar is composed and the later persist+ identity-skips compacted dicts; without this a reload would reopen the prompt-+ cache divergence. The ``content`` match guards a racing rewrite. Returns 0/1."""from hermes_state import _scrub_surrogatesreturn self._write_rowcount("UPDATE messages SET api_content = ? WHERE id = (SELECT id FROM messages "@@ -844,14 +789,10 @@ class SessionMessagesMixin:)def _dedupe_display_generations(self, rows):- """Collapse compaction generations so each logical message appears once.-- Compaction copies the protected tail into each generation (same- role/content/timestamp, different ``active``/id); prefer the live row, then the- newest generation. The ONE definition shared by every display projection- (get_messages, get_resume_conversations, get_ancestor_display_prefix,- get_messages_as_conversation). *rows* must be ordered by ``id``; order is kept.- """+ """Collapse compaction generations so each logical message appears once: the+ protected tail is copied into each generation (same role/content/timestamp,+ different ``active``/id); prefer the live row, then the newest. The ONE definition+ shared by every display projection. *rows* must be ordered by ``id``."""seen: Dict[Tuple[Any, ...], Any] = {}for row in rows:dedupe_content = row["content"]@@ -907,15 +848,10 @@ class SessionMessagesMixin:limit: Optional[int] = None, offset: int = 0, latest: bool = False,after_id: Optional[int] = None,) -> List[Dict[str, Any]]:- """Load messages for a session in insertion order (AUTOINCREMENT id, never- timestamp — clocks regress on WSL2/NTP steps).-- ``include_inactive`` loads soft-deleted rewind rows; ``include_compacted`` adds- rows preserved by in-place compaction (durable display history a transcript- read must not drop) but not rewind rows. ``limit``/``offset`` page; ``latest``- measures the offset back from the newest row and still returns chronological- order. ``after_id`` is keyset paging (``id > after_id``), ascending only.- """+ """Load a session's messages in insertion order (id, never timestamp — clocks+ regress). ``include_inactive``: rewind rows too; ``include_compacted``: compaction-+ archived display history (not rewind rows). ``latest`` pages back from the newest+ row but still returns chronological order; ``after_id`` is keyset paging."""if after_id is not None and (latest or offset):raise ValueError("after_id is incompatible with latest/offset paging")if after_id is not None and include_compacted:@@ -971,12 +907,9 @@ class SessionMessagesMixin:return founddef get_messages_around(self, session_id: str, around_message_id: int, window: int = 5) -> Dict[str, Any]:- """Window of up to *window* messages either side of an anchor id (id ascending).-- ``messages_before``/``messages_after`` count rows in the returned slice strictly- before/after the anchor; less than *window* means a session boundary. Empty- window when the anchor is not a row of *session_id*.- """+ """Up to *window* messages either side of an anchor id (ascending). ``messages_+ before``/``_after`` count the slice strictly around the anchor (fewer than+ *window* = session boundary). Empty when the anchor is not in *session_id*."""window = max(window, 0)with self._read_ctx() as conn:anchor_exists = conn.execute(@@ -999,16 +932,11 @@ class SessionMessagesMixin:return {"window": window_msgs, "messages_before": max(0, len(before_rows) - 1), "messages_after": len(after_rows)}def resolve_resume_session_id(self, session_id: str) -> str:- """Redirect a resume target to the descendant session that holds the messages.-- Follows the compression chain to the live tip first (``get_compression_tip`` is- lineage-aware: only children of compression-ended parents, so delegation/branch- children never hijack the resume), then walks ``parent_session_id`` forward,- returning the deepest node with messages — never short-circuiting on the start- node, since a continuation may hold the newer turns. Branch, delegate, reset- and tool children are skipped (they carry ``parent_session_id`` too). Returns- *session_id* unchanged when nothing has messages. Depth cap 32.- """+ """Redirect a resume target to the descendant that holds the messages: follow the+ compression chain to the live tip (lineage-aware, so delegate/branch children never+ hijack it), then walk ``parent_session_id`` forward to the DEEPEST node with+ messages (a continuation may hold newer turns), skipping branch/delegate/reset/+ tool children. Unchanged when nothing has messages. Depth cap 32."""if not session_id:return session_idtry:@@ -1063,15 +991,11 @@ class SessionMessagesMixin:repair_alternation: bool = False, include_row_ids: bool = False,include_compacted: bool = False,) -> List[Dict[str, Any]]:- """Load messages in OpenAI conversation format (gateway history restore).-- ``include_compacted`` adds compaction-archived rows deduped by- :meth:`_dedupe_display_generations` — DISPLAY reads only; the model-fed restore- must not pass it or a resume regrows the history compaction summarized away.- ``repair_alternation`` runs ``repair_message_sequence`` on the loaded list- (LIVE REPLAY callers) so a durable ``user;user`` pair doesn't re-trigger the- per-request repair forever; the stored transcript is never mutated.- """+ """Load messages in OpenAI conversation format. ``include_compacted`` (deduped+ display history) is for DISPLAY reads only — the model-fed restore must not regrow+ what compaction summarized away. ``repair_alternation`` repairs the loaded list for+ LIVE REPLAY callers (a durable ``user;user`` pair would otherwise re-trigger the+ per-request repair forever); the stored transcript is never mutated."""session_ids = [session_id]if include_ancestors and not self._is_explicit_branch_session(session_id):session_ids = self._session_lineage_root_to_tip(session_id)@@ -1086,14 +1010,10 @@ class SessionMessagesMixin:)def _dedupe_replayed_user(self, messages, msg, exact_user_clones) -> Tuple[bool, Any]:- """Ancestor-lineage dedupe for one decoded user *msg*.-- Returns ``(skip, exact_clone_key)``. Watermark rotation column-clones the- concurrent tail into the child after the summary, so the copies need not be- adjacent: an exact ``(timestamp, canonical content)`` clone index is checked- first, then the adjacent-duplicate heuristic. A rotated child carrier wins over- the simpler ancestor copy (it owns the durable row id and the summary scaffold).- """+ """Ancestor-lineage dedupe for one decoded user *msg* -> ``(skip, exact_clone_key)``.+ Rotation column-clones the concurrent tail into the child, so copies need not be+ adjacent: the exact ``(timestamp, canonical content)`` clone index is checked first,+ then the adjacent heuristic. A rotated child carrier wins over the ancestor copy."""canonical_content, _is_composite = self._canonical_replayed_user_content(msg)exact_clone_key = self._exact_replayed_user_clone_key(msg.get("timestamp"), canonical_content)previous_exact = exact_user_clones.get(exact_clone_key) if exact_clone_key is not None else None@@ -1122,8 +1042,7 @@ class SessionMessagesMixin:Every dict is stamped ``_DB_PERSISTED_MARKER_KEY`` at the source (born durable)so an identity-losing handoff never re-appends the whole transcript on flush.``_row_id`` is opt-in (gateway reactions). Reasoning fields are restored on- assistant rows only. Key order of each dict is stable (see the column tables).- """+ assistant rows only. Key order of each dict is stable (see the column tables)."""from hermes_state import _strip_background_review_harness, _strip_stale_tool_call_markersmessages = []exact_user_clones: Dict[Tuple[Any, str], Dict[str, Any]] = {}@@ -1186,14 +1105,10 @@ class SessionMessagesMixin:return messagesdef get_resume_conversations(self, session_id: str) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]]]:- """``(model_history, display_history)`` for a session resume from ONE SELECT.-- ``model_history``: the tip's active rows, alternation-repaired, with the summary- marker kept for pre-compress checkpointing. ``display_history``: the full- compression lineage (``/branch`` sessions are their own lineage) verbatim, with- compaction-archived rows included and deduped, plus replayed-user dedup. Byte-- identical to the separate reads (test_get_resume_conversations_matches_separate_reads).- """+ """``(model_history, display_history)`` for a resume from ONE SELECT. model: the+ tip's active rows, alternation-repaired, summary marker kept for pre-compress+ checkpointing. display: the full lineage (``/branch`` sessions stand alone) with+ compaction-archived rows deduped. Byte-identical to the separate reads."""session_ids = self._resume_lineage_ids(session_id)rows = self._fetch_conversation_rows(session_ids, _DISPLAY_ACTIVE_CLAUSE, with_session_id=True)# The model projection stays active-only: it is the compressed working context.@@ -1233,14 +1148,10 @@ class SessionMessagesMixin:return int(row[0] if row else 0)def assert_resume_safe(self, session_id: str, max_messages: Optional[int] = None, *, tip_only: bool = False) -> int:- """Return the resume row count or raise ``SessionResumeTooLargeError``.-- ``max_messages=None`` reads ``sessions.max_resume_messages``; 0 disables the- guard and returns 0 without counting. ``tip_only`` bounds only the tip's active- rows, for callers that never materialize the lineage in memory — a heavily- compressed conversation (~29k lineage rows behind a ~700-row tip) is exactly- what compression should produce and must not be rejected.- """+ """Resume row count, or raise ``SessionResumeTooLargeError``. ``max_messages=None``+ reads config; 0 disables the guard without counting. ``tip_only`` bounds only the+ tip's active rows for callers that never materialize the lineage — a heavily+ compressed conversation is what compression should produce, not a rejection."""from hermes_state import SessionResumeTooLargeError, resolved_max_resume_messagesif max_messages is None:max_messages = resolved_max_resume_messages()@@ -1264,12 +1175,9 @@ class SessionMessagesMixin:return message_countdef get_ancestor_display_prefix(self, session_id: str) -> List[Dict[str, Any]]:- """Ancestor-only display messages of a lineage (rows with ``session_id !=`` tip).-- ``session.resume`` prepends this to the live model history. Identifying- ancestors by row origin (not ``display[:len(display) - len(model)]``) avoids- overcounting when alternation repair removes tip messages from the middle.- """+ """Ancestor-only display messages of a lineage (row ``session_id != tip``), which+ ``session.resume`` prepends to the model history. Identified by row origin, not+ ``display[:len(display) - len(model)]``, so alternation repair cannot overcount."""session_ids = self._resume_lineage_ids(session_id)if len(session_ids) <= 1:return []@@ -1323,13 +1231,10 @@ class SessionMessagesMixin:def _find_duplicate_replayed_user_message(messages: List[Dict[str, Any]], msg: Dict[str, Any]) -> Optional[Tuple[int, bool]]:- """Return an adjacent replay duplicate and whether *msg* must win.-- Rotation may persist the current ask once in the parent and again inside a- composite child carrier; compare the canonical live payload for carriers while- keeping the exact-string dedupe for ordinary replayed users. The child carrier- wins (it owns the durable row id and the retained scaffold).- """+ """Adjacent replay duplicate ``(index, prefer_current)`` or None. Rotation may+ persist the current ask in the parent and again inside a composite child carrier:+ carriers compare by canonical live payload, ordinary users by exact string. The+ child carrier wins (it owns the durable row id and the retained scaffold)."""from hermes_state import SessionDBif msg.get("role") != "user":return None@@ -1363,12 +1268,9 @@ class SessionMessagesMixin:return len(rows), sum(_tool_calls_len(row[0], scalar=1) for row in rows)def _split_rewind_target(self, target_row: Dict[str, Any], expected_target_content: Any, preserve_compaction_handoff: bool):- """Validate an active rewind target and return its handoff scaffold (or None).-- Raises ``ValueError`` for an inactive / non-user-originated target or a missing- composite carrier, ``RuntimeError`` when the canonical live payload no longer- matches *expected_target_content*.- """+ """Validate an active rewind target; return its handoff scaffold (or None).+ ``ValueError``: inactive / non-user-originated target or missing composite+ carrier; ``RuntimeError``: live payload no longer matches *expected_target_content*."""if not target_row.get("active"):raise ValueError("rewind target is not active")from agent.context_compressor import split_user_originated_turn@@ -1392,21 +1294,16 @@ class SessionMessagesMixin:self, session_id: str, target_message_id: int, *, preserve_compaction_handoff: bool = False,expected_active_ids: Optional[List[int]] = None, expected_target_content: Any = None,) -> Dict[str, Any]:- """Soft-delete (``active=0``) every message with id >= *target_message_id*.-- The target itself goes inactive so the caller can pre-fill it as the next- prompt. Returns ``{"rewound_count", "target_message", "new_head_id"}`` (plus- ``replacement_message_id`` with ``preserve_compaction_handoff``, which archives a- composite summary carrier and inserts its hidden handoff scaffold as the new- head in the same txn). Raises ``ValueError`` when the target is missing or not a- ``user`` row.-- ``expected_active_ids`` / ``expected_target_content`` pin the active row set and- the canonical live payload inside the txn before any mutation (presentation-only- metadata changes do not invalidate a rewind). A live cross-process turn lease- refuses the rewind; expired/dead holders are reclaimed. ``rewind_count`` always- increments, even when the target was already inactive.- """+ """Soft-delete (``active=0``) every message with id >= *target_message_id*, the+ target included (the caller pre-fills it as the next prompt). Returns+ ``{"rewound_count", "target_message", "new_head_id"}``, plus+ ``replacement_message_id`` with ``preserve_compaction_handoff`` (archives a+ composite summary carrier, inserts its hidden handoff scaffold as the new head).+ ``ValueError`` when the target is missing or not a ``user`` row.+ ``expected_active_ids`` / ``expected_target_content`` pin the active set and the+ canonical live payload in-txn before any mutation (presentation-only metadata+ changes don't invalidate a rewind). A live turn lease refuses the rewind;+ expired/dead holders are reclaimed. ``rewind_count`` always increments."""def _do(conn):self._check_transcript_write_guards(@@ -1477,13 +1374,10 @@ class SessionMessagesMixin:) is not Nonedef _is_explicit_fork_child_row(self, session: Dict[str, Any]) -> bool:- """True when *session* is a branch, delegate, or tool child of its parent.-- Markers only count when they point at ``parent_session_id``: compression copies- ``model_config`` onto the continuation, so a delegate's continuation carries- ``_delegate_from=<the delegate's own parent>`` and presence-only matching would- misclassify it (same binding as ``_NON_CONTINUATION_CHILD_FILTER_SQL``).- """+ """True when *session* is a branch, delegate, or tool child of its parent. Markers+ only count when they point at ``parent_session_id``: compression copies+ ``model_config`` onto the continuation, so presence-only matching would misclassify+ a delegate's continuation (same binding as ``_NON_CONTINUATION_CHILD_FILTER_SQL``)."""if session.get("source") == "tool":return Trueraw = session.get("model_config")@@ -1506,16 +1400,12 @@ class SessionMessagesMixin:return bool(session and self._is_explicit_fork_child_row(session))def latest_conversation_boundary(self, session_key: str, source: str) -> Optional[int]:- """How many conversation boundaries (``_RESET_END_REASONS`` ends) this routing- peer has crossed, or ``None`` when never reset.-- The peer is ``(session_key, source)`` — the identity recovery uses — never the- key alone (an API caller may legally reuse a Telegram row's key). Read from- ``conversation_generations`` (advanced inside each boundary's txn), not an- aggregate over session rows: deletes/prunes would let an aggregate re-emit a- retired pair. Rows are never garbage-collected, by design (dropping one would- re-issue generation 1 — the ABA this counter prevents).- """+ """Conversation boundaries (``_RESET_END_REASONS`` ends) this routing peer has+ crossed, or ``None`` when never reset. The peer is ``(session_key, source)`` — never+ the key alone (an API caller may reuse a Telegram row's key). Read from+ ``conversation_generations``, not an aggregate over session rows (deletes/prunes+ would re-emit a retired pair); rows are never GC'd (dropping one would re-issue+ generation 1 — the ABA this counter prevents)."""if not session_key or not source:return Nonerow = self._read_one(@@ -1536,15 +1426,11 @@ class SessionMessagesMixin:self._execute_write(_do)def purge_stale_tool_call_markers(self, *, dry_run: bool = False, backup: bool = True) -> Dict[str, Any]:- """Permanently clear bare tool-call marker content (e.g. "[memory]") left by- pre-fix sessions. ``_rows_to_conversation`` repairs this in memory on every load,- so this is optional; it just stops the re-scan and removes the bytes.-- Only ``content`` is touched (tool_call pairing unaffected). With ``backup`` a- ``VACUUM INTO`` snapshot (safe against a live connection) is taken first; none- when nothing changes. ``dry_run`` reports without writing or backing up.- Returns ``{"dry_run", "rows_affected", "row_ids", "backup_path"}``.- """+ """Permanently clear bare tool-call marker content (e.g. "[memory]") left by pre-fix+ sessions (``_rows_to_conversation`` already repairs it in memory; this stops the+ re-scan). Only ``content`` is touched. ``backup``: ``VACUUM INTO`` snapshot first+ (none when nothing changes). Returns ``{"dry_run", "rows_affected", "row_ids",+ "backup_path"}``."""from hermes_state import _STALE_TOOL_CALL_MARKER_REdef _find_affected(conn) -> List[int]:diff --git a/hermes_state_titles.py b/hermes_state_titles.pyindex 64272588bfb..9aad6348955 100644--- a/hermes_state_titles.py+++ b/hermes_state_titles.py@@ -79,8 +79,7 @@ class SessionTitlesMixin:nothing overwrites a user name, re-running the titler on an llm row is a no-op).No writer may move a hidden canonical Bot Chat off its title. Read and write areone compare-and-swap transaction, so a manual ``/title`` racing an in-flight- generation is not clobbered.- """+ generation is not clobbered."""title = self.sanitize_title(title)is_user = source == self.TITLE_SOURCE_USERnew_rank = self._title_rank(source) if not is_user else Nonediff --git a/hermes_state_usage.py b/hermes_state_usage.pyindex 0b99762758f..90f32aded33 100644--- a/hermes_state_usage.py+++ b/hermes_state_usage.py@@ -361,8 +361,7 @@ class SessionUsageMixin:caller's write txn after the ``sessions`` UPDATE. A missing model/provider fallsback to the session row (same COALESCE behaviour as the summary update) — exceptfor aux rows (``task`` set), which must NOT inherit the main-loop route (vision- on gemini while the main loop runs anthropic): missing info stays 'unknown'/empty.- """+ on gemini while the main loop runs anthropic): missing info stays 'unknown'/empty."""row = conn.execute("SELECT model, billing_provider, billing_base_url, billing_mode ""FROM sessions WHERE id = ?", (session_id,),