Files
hermes-agent/agent/compaction_display.py
yoniebans b945f98433 refactor(agent): turn constants come from session_rules.turns; the turn flush passes the lock holder only to SessionDB
- agent/ modules import the turn constants session_rules.turns owns instead of keeping equal copies

session_rules.turns defines the private turn constants (skill scaffolding markers, continuation nudges, compaction markers and summary prefixes, image part types, the ephemeral scaffolding flags), and ten agent/ modules kept their own copies of 28 of them, 34 copies with values equal to the owner's. Two copies of one rule drift apart.

Each equal copy is now an import from session_rules.turns, so one definition serves every module; the name stays bound in each module, so its readers and anything that reads or patches it there are unchanged. The three copies whose values differ (_EPHEMERAL_SCAFFOLDING_FLAGS in agent/turn_final_response.py, _IMAGE_PART_TYPES in agent/codex_responses_adapter.py and agent/vision_message_prep.py) are module-local sets that share a name and keep their own values.

Proof: scripts/const_parity.py reports equal 34, differ 3 before and after, and after the change each of the 34 names in its module is the same object as session_rules.turns'. Four _IMAGE_PART_TYPES copies were frozensets and the owner's is a set; every reader only tests membership. The touched modules' test files (33): 705 passed.

- the agent's turn flush passes the compression lock holder only to SessionDB, not to the store's append_batch

On main the turn flush calls SessionDB.append_messages_batch with compression_lock_holder, turn_lease_holder and turn_lease_ttl_seconds. The storage interface's messages.append and append_batch take no compression_lock_holder (an append is never blocked by the compression lock), and the agent's flush still splatted it into store.messages.append_batch, so every turn flushed through a store raised TypeError and was logged as "Session DB append_message failed".

The store call now gets the turn-lease guards only; the compression lock holder goes to the outside SessionDB's append_messages_batch, the one writer that takes it, as on main. No other call in agent, gateway, cron, hermes_cli, tui_gateway, tools, run_agent.py or cli.py passes compression_lock_holder to messages.append or append_batch (publish_compression_child takes it by contract).

Proof: the existing store-flush cases were red with the TypeError (test_identity_flush.py 8, test_flush_uid_reinsert_guard.py 9, test_restored_row_flush_stamp.py 1, test_rotation_flush_persisted_boundary.py 1: 19 failed) and pass with the fix (19 passed).
2026-11-17 19:10:42 +01:00

73 lines
3.6 KiB
Python

"""Client-facing projection helpers for model-only compaction carriers."""
from __future__ import annotations
import re
from typing import Any, Dict, Optional
from agent.context_compressor import _LEAN_RECOVERY_HEADING, _LEAN_USER_MESSAGES_HEADING, ContextCompressor
from session_rules.turns import flatten_message_text, is_compaction_summary_message
from session_rules.turns import _COMPACTION_INTERNAL_FIELDS
def project_compaction_message_for_display(message: dict[str, Any]) -> Optional[dict[str, Any]]:
"""Return authentic transcript content, or ``None`` for a pure handoff.
Model-facing recovery history retains the complete carrier. Display
projections instead remove the handoff, inherited tool state, and internal
reasoning while preserving any real prior-tail content or live user ask
embedded in the carrier.
"""
if not isinstance(message, dict):
return None
if not is_compaction_summary_message(message):
return message.copy()
projected = ContextCompressor._strip_context_summary_handoff_message(message)
if projected is None:
return None
projected = projected.copy()
for key in _COMPACTION_INTERNAL_FIELDS:
projected.pop(key, None)
# A safety-refused ask embedded in a composite carrier keeps its ``content_refused`` tag through
# the unwrap, or a reopened chat would redraw it as an ordinary user bubble with no refused notice
# (#149708 review): the model-facing handoff is gone, the user's live ask survives as a greyed
# refused block. Every other carrier drops its internal ``display_kind`` as before.
from agent.turn_failure_copy import CONTENT_REFUSED_DISPLAY_KIND
if projected.get("display_kind") != CONTENT_REFUSED_DISPLAY_KIND:
projected.pop("display_kind", None)
return projected
# Lean-mode sections written for the model, not for a reader: the compacted turns' user messages
# quoted again, and the footer naming ``session_search`` (``ContextCompressor._augment_summary_lean``).
_MODEL_ONLY_SECTIONS = (_LEAN_USER_MESSAGES_HEADING, _LEAN_RECOVERY_HEADING)
_HISTORICAL_ONLY_LINE = "Historical only; newer protected-tail messages after this summary win."
_COMPACTED_COUNT = re.compile(r"The (\d+) compacted message\(s\) remain fully preserved")
def compaction_summary(message: Any) -> Optional[dict[str, Any]]:
"""What a compaction handoff tells a reader: ``{summary, compacted_messages}``, or ``None`` for any
other message. ``summary`` is the summary as the compressor wrote it, without the model-facing
preamble and end marker, prior-tail content or live ask merged into the carrier, the lean
sections above and the snapshot's ranking line; ``compacted_messages`` is the count the recovery
footer names (``None`` when it has none)."""
if not is_compaction_summary_message(message):
return None
text = ContextCompressor._strip_summary_prefix(flatten_message_text(message.get("content")))
sections = {}
for heading in _MODEL_ONLY_SECTIONS:
start = text.find(heading)
if start >= 0:
end = text.find("\n## ", start + len(heading))
sections[heading] = text[start:end if end >= 0 else len(text)]
text = text[:start] + (text[end + 1:] if end >= 0 else "")
# The footer's count, never one a quoted user message happens to spell out (the quotes are cut first).
counts = _COMPACTED_COUNT.findall(sections.get(_LEAN_RECOVERY_HEADING, text))
text = "\n".join(line for line in text.splitlines() if line.strip() != _HISTORICAL_ONLY_LINE)
return {"summary": re.sub(r"\n{3,}", "\n\n", text).strip(),
"compacted_messages": int(counts[-1]) if counts else None}