The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(agent): compact restating docstrings in message_sanitization + micro_compaction
Teknium34271779eef3
diff --git a/agent/message_sanitization.py b/agent/message_sanitization.pyindex b929ad7aad2..760b5aaa611 100644--- a/agent/message_sanitization.py+++ b/agent/message_sanitization.py@@ -60,12 +60,9 @@ def _sanitize_structure(payload: Any, fix: Callable[[str], str]) -> bool:def _sanitize_messages(messages: list, fix: Callable[[str], str], *, deep: bool) -> bool:- """Apply ``fix`` to the string fields of every message dict in-place.-- Covers content / content-part text, name, tool_call arguments, and every non-core- top-level str field. ``deep=True`` additionally covers tool_call ids, function names,- and NESTED non-core fields (``reasoning_details`` arrays from byte-level reasoning models).- """+ """Apply ``fix`` to the string fields of every message dict in-place (content / part text,+ name, tool_call arguments, non-core top-level str fields). ``deep=True`` adds tool_call ids,+ function names, and NESTED non-core fields (``reasoning_details`` from byte-level models)."""found = Falsefor msg in messages:if not isinstance(msg, dict):@@ -186,12 +183,10 @@ def _repair_tool_call_arguments(raw_args: str, tool_name: str = "?") -> str:def close_interrupted_tool_sequence(messages: list, final_response: Any = None) -> bool:- """Append a synthetic assistant turn when an interrupted tail is a tool result.-- A transcript ending on a raw ``tool`` message makes the next user message land as- ``tool → user`` — an alternation violation strict providers (Gemini, Claude) answer by- hallucinating a continuation. Mutates in place; True if a closing turn was appended.- """+ """Append a synthetic assistant turn when an interrupted tail is a tool result: a transcript+ ending on a raw ``tool`` message makes the next user message land as ``tool → user``, an+ alternation violation strict providers (Gemini, Claude) answer by hallucinating a+ continuation. Mutates in place; True if a closing turn was appended."""last = messages[-1] if messages else Noneif not isinstance(last, dict) or last.get("role") != "tool":return False@@ -339,11 +334,9 @@ def tool_result_id_variants(tool_call_id: Any) -> frozenset[str]:def coalesce_tool_call_id(tc: Any) -> str:- """Effective call id of a tool_call entry (dict or object); ``""`` when none.-- Codex Responses calls carry ``call_id`` (authoritative pairing key), Chat Completions- carry ``id`` only, and bridge ids may be ``call_id|response_item_id``.- """+ """Effective call id of a tool_call entry (dict or object); ``""`` when none. Codex Responses+ carry ``call_id`` (authoritative pairing key), Chat Completions ``id`` only, and bridge ids+ may be ``call_id|response_item_id``."""for raw in (_tc_field(tc, "call_id"), _tc_field(tc, "id")):value = raw.strip() if isinstance(raw, str) else ""if value:diff --git a/agent/micro_compaction.py b/agent/micro_compaction.pyindex 697e6f361d8..6e4e5a01c60 100644--- a/agent/micro_compaction.py+++ b/agent/micro_compaction.py@@ -37,10 +37,8 @@ class MicroCompactionMixin:"""Rolling micro-compaction; host must be a ``ContextCompressor``."""def _resolve_compact_cursor(self, messages: List[Dict[str, Any]], head_end: int, tail_start: int) -> int:- """Index of the first message not yet absorbed into the rolling summary.-- Uses the in-memory cursor when valid; otherwise scans for the last summary marker.- """+ """Index of the first message not yet absorbed into the rolling summary: the in-memory+ cursor when valid, else just past the last summary marker."""if head_end < self._micro_compact_cursor < tail_start:return self._micro_compact_cursorsummaries = (i for i in range(head_end, tail_start) if self._is_context_summary_message(messages[i]))@@ -64,11 +62,9 @@ class MicroCompactionMixin:def _find_one_exchange(self, messages: List[Dict[str, Any]], start: int, tail_start: int,) -> Optional[tuple[int, int]]:- """Find the next complete exchange (full agent turn) starting at *start*.-- Returns ``(exchange_start, exchange_end)`` or ``None``. Spans assistant+tool rows up to the- next user message; user turns are never absorbed (alternation safety, verbatim user text).- """+ """Find the next complete exchange (full agent turn) starting at *start*; returns+ ``(exchange_start, exchange_end)`` or ``None``. Spans assistant+tool rows up to the next+ user message; user turns are never absorbed (alternation safety, verbatim user text)."""limit = min(tail_start, len(messages))def _turn_row(idx: int, roles: tuple) -> bool:@@ -196,11 +192,9 @@ class MicroCompactionMixin:self._micro_compact_last_failure_cursor = -1def _micro_compact(self, messages: List[Dict[str, Any]]) -> List[Dict[str, Any]]:- """Run one round of micro-compaction; public entry point from ``finalize_turn()``.-- Returns the (possibly modified) list and syncs the session DB via ``archive_and_compact``- (the append-only flush alone would double-load on resume).- """+ """Run one round of micro-compaction (entry point from ``finalize_turn()``). Returns the+ (possibly modified) list and syncs the session DB via ``archive_and_compact`` (the+ append-only flush alone would double-load on resume)."""if not self._micro_compact_enabled:return messages@@ -302,12 +296,9 @@ class MicroCompactionMixin:return (body[:end] if end != -1 else body).strip()def _cursor_after_splice(self, result: List[Dict[str, Any]], fallback: int) -> int:- """Cursor position just past the summary marker in *result*.-- Must derive from the SPLICED list: a splice collapses several rows into one marker- (and may drop a superseded one), so pre-splice indices land inside a later exchange- and silently skip it.- """+ """Cursor position just past the summary marker in *result*. Must derive from the SPLICED+ list: a splice collapses several rows into one marker (and may drop a superseded one), so+ pre-splice indices land inside a later exchange and silently skip it."""return next((idx + 1 for idx in range(len(result) - 1, -1, -1) if _is_summary_marker(result[idx])), fallback)def _emit_micro_compaction_telemetry(@@ -397,11 +388,9 @@ class MicroCompactionMixin:@staticmethoddef _merge_adjacent_user_turns(result: List[Dict[str, Any]]) -> List[Dict[str, Any]]:- """Merge consecutive plain-text real user turns left by a supersede.-- Same ``\\n\\n`` join as ``repair_message_sequence`` pass 2, done here so the marker- and cursor are never collateral damage of the downstream repair. Lists untouched.- """+ """Merge consecutive plain-text real user turns left by a supersede. Same ``\\n\\n`` join as+ ``repair_message_sequence`` pass 2, done here so the marker and cursor are never collateral+ damage of the downstream repair. Lists untouched."""from agent.turn_context import drop_stale_api_contentdef _plain_user(m: Any) -> bool: