Skip to content

The agent that grows with you

refactor(tui): compact module/function docstrings and comments (WHY preserved)

Tekniumac9f93525c90
diff --git a/tui_gateway/session_auto_continue.py b/tui_gateway/session_auto_continue.py
index ba694d100b3..cc968e48f2d 100644
--- a/tui_gateway/session_auto_continue.py
+++ b/tui_gateway/session_auto_continue.py
@@ -240,11 +240,10 @@ def _ac_try_correction(rid, session: dict, agent: Any, method: str, plain_text:
def _handle_busy_submit(rid, sid: str, session: dict, text: Any, transport: Any, queued: bool = False) -> dict | None:
- """Apply ``display.busy_input_mode`` to a prompt that lands mid-turn instead of rejecting it (rejection
- made clients busy-retry and silently drop sends). ``interrupt`` (default) → redirect the live turn,
- falling back to hard interrupt + queue for older agents; ``queue`` → queue only; ``steer`` → inject
- after the current atomic action. ``queued=True`` (client queue drain) forces queue mode: a "run
- after" message must NEVER become a live-turn correction, even if the drain loses the settle race."""
+ """Apply ``display.busy_input_mode`` to a mid-turn prompt instead of rejecting it (rejection made
+ clients busy-retry and drop sends): ``interrupt`` (default) → redirect, falling back to hard interrupt
+ + queue; ``queue`` → queue only; ``steer`` → inject after the current atomic action. ``queued=True``
+ (client queue drain) forces queue mode: a "run after" message must NEVER become a live correction."""
mode = "queue" if queued else _load_busy_input_mode()
agent = session.get("agent")
with session["history_lock"]:
@@ -364,10 +363,9 @@ def _inflight_snapshot(session: dict) -> dict | None:
def _emit_terminal_turn_error(
sid: str, session: dict, error: Any, error_surface: Optional[dict] = None, *, retire_marker: bool = True
) -> None:
- """Close a failed turn with the same ``status: "error"`` ``message.complete`` frame as
- ``_run_prompt_submit``'s returned-error path, retaining the turn (``_fail_inflight_turn``) so a client
- that missed the frame recovers it from ``session.resume``'s ``inflight``. ``error_surface`` ({layer,
- code, retryable}) is classified here from an exception when the caller doesn't know the layer."""
+ """Close a failed turn with the same ``status: "error"`` ``message.complete`` frame as the returned-error
+ path, retaining the turn so a client that missed the frame recovers it from ``session.resume``'s
+ ``inflight``. ``error_surface`` ({layer, code, retryable}) is classified from an exception if absent."""
agent = session.get("agent")
if error_surface is None and isinstance(error, BaseException):
with contextlib.suppress(Exception):
diff --git a/tui_gateway/session_compression.py b/tui_gateway/session_compression.py
index 1fb2fb07e85..1afdf071384 100644
--- a/tui_gateway/session_compression.py
+++ b/tui_gateway/session_compression.py
@@ -65,11 +65,9 @@ _COMPRESSION_INT_KEYS = (
def _apply_live_compression_config(agent: Any, cfg: dict | None) -> None:
- """Update a live session's compressor in place from current config.yaml (agent object, session
- identity, history and callbacks preserved). Every adopted key has UNSET semantics: a removed key
- restores the normalized default (or model-derived value) through the construction path's own
- derivation (ctor signature defaults, Codex autoraise, deferred context-length re-inference) —
- acting only on PRESENT keys would leave stale values active forever."""
+ """Update a live session's compressor in place from config.yaml. Every adopted key has UNSET semantics:
+ a removed key restores the normalized default (or model-derived value) through the construction
+ path's own derivation — acting only on PRESENT keys would leave stale values active forever."""
cfg = cfg if isinstance(cfg, dict) else {}
compression = cfg.get("compression") if isinstance(cfg.get("compression"), dict) else {}
model_cfg = cfg.get("model") if isinstance(cfg.get("model"), dict) else {}
@@ -187,11 +185,9 @@ def _compress_session_history(
session: dict, focus_topic: str | None = None, approx_tokens: int | None = None,
before_messages: list | None = None, history_version: int | None = None,
) -> tuple[int, dict]:
- """Single choke point for all manual-compress routes (session.compress RPC, command.dispatch
- /compress|/compact, slash-exec mirror). ``focus_topic`` is the RAW argument string after
- ``/compress``, parsed HERE (not per-route) so boundary forms (``here [N]``, ``up to here``,
- ``--keep N``) trigger a partial compress on EVERY route — otherwise "/compress here 3" would run a
- FULL compress focused on the literal text "here 3"."""
+ """Single choke point for all manual-compress routes. ``focus_topic`` is the RAW argument string after
+ ``/compress``, parsed HERE (not per-route) so boundary forms (``here [N]``, ``up to here``, ``--keep N``)
+ trigger a partial compress on EVERY route instead of a FULL compress focused on the literal text."""
from agent.conversation_compression import finalize_context_engine_compression_notification
from agent.model_metadata import estimate_request_tokens_rough
from hermes_cli.partial_compress import (
@@ -217,10 +213,8 @@ def _compress_session_history(
approx_tokens = estimate_request_tokens_rough(
history, system_prompt=getattr(agent, "_cached_system_prompt", "") or "", tools=getattr(agent, "tools", None) or None
)
- # system_message=None: _compress_context rebuilds the system prompt via _build_system_prompt(None);
- # passing the cached prompt (already holding the identity block) appends the identity twice.
- # force=True: every caller is a manual /compress path, which bypasses the summary-failure
- # cooldown like the CLI and gateway handlers. Partial compress has no focus topic (exclusive modes).
+ # system_message=None: passing the cached prompt (already holding the identity block) would append the
+ # identity twice. force=True: manual /compress bypasses the summary-failure cooldown like CLI/gateway.
try:
compressed, _ = agent._compress_context(
head, None, approx_tokens=approx_tokens, focus_topic=focus_topic or None, force=True,
@@ -252,11 +246,10 @@ def _compress_session_history(
def _sync_session_key_after_compress(
sid: str, session: dict, *, clear_pending_title: bool = True, restart_slash_worker: bool = True
) -> None:
- """Re-anchor the gateway-side ``session_key`` when _compress_context rotates ``agent.session_id`` to
- a SessionDB continuation; otherwise approval routing, slash worker init, DB title/history lookups
- and yolo state keep targeting the ended parent. ``clear_pending_title``: True for manual /compress
- (title belongs to the old session), False for post-turn auto-compression. ``restart_slash_worker``:
- False only when the caller manages the worker (it holds the stale key)."""
+ """Re-anchor the gateway-side ``session_key`` when _compress_context rotates ``agent.session_id``;
+ otherwise approval routing, slash worker, DB lookups and yolo state keep targeting the ended parent.
+ ``clear_pending_title``: True for manual /compress (title belongs to the old session), False for
+ post-turn auto-compression. ``restart_slash_worker``: False only when the caller manages the worker."""
agent = session.get("agent")
new_session_id = getattr(agent, "session_id", None) or ""
old_key = session.get("session_key", "") or ""
diff --git a/tui_gateway/session_notifications.py b/tui_gateway/session_notifications.py
index 5b72d451201..db9e24b5e4c 100644
--- a/tui_gateway/session_notifications.py
+++ b/tui_gateway/session_notifications.py
@@ -78,10 +78,9 @@ def _notification_event_belongs_elsewhere(sid: str, session: dict, evt: dict) ->
def _session_owns_notification_event(sid: str, session: dict, evt: dict) -> bool:
- """True iff *this* session PROVABLY owns ``evt``: positive mirror of
- ``_notification_event_belongs_elsewhere`` minus its orphan-adoption fallback (UI origin is this
- live session, or ``session_key`` raw/compression-resolved matches). Fail-closed gate for every
- addressed notification — "not provably elsewhere" is NOT enough."""
+ """True iff *this* session PROVABLY owns ``evt`` (UI origin is this live session, or ``session_key``
+ raw/compression-resolved matches) — the fail-closed gate for every addressed notification, without
+ ``_notification_event_belongs_elsewhere``'s orphan-adoption fallback."""
if session.get("_finalized"):
return False
if str(evt.get("origin_ui_session_id") or "") == str(sid or ""):
@@ -384,11 +383,10 @@ def _notif_dispatch_event(sid: str, session: dict, evt: dict, text: str) -> None
def _notif_handle_event(sid, session, evt, emitted, registry, fmt, deferred) -> bool:
- """Route one dequeued event: foreign (another live session owns it) → back on the queue, or onto
- ``deferred`` during the shutdown drain; unowned (addressed but unprovable — never adopt an orphan)
- → dropped, except delegation payloads deferred for a resume; ours (or ownerless legacy, kept
- process-global) → status.update once, then an agent turn if idle. Returns False when the drain
- must stop (session busy)."""
+ """Route one dequeued event: foreign (another live session owns it) → requeued, or onto ``deferred``
+ during the shutdown drain; unowned (addressed but unprovable — never adopt an orphan) → dropped, except
+ delegation payloads deferred for a resume; ours (or ownerless legacy, kept process-global) →
+ status.update once, then an agent turn if idle. False = the drain must stop (session busy)."""
queue = registry.completion_queue
evt_type, is_delegation = evt.get("type", "completion"), evt.get("type") == "async_delegation"
if _notification_event_belongs_elsewhere(sid, session, evt):
@@ -495,10 +493,9 @@ _desktop_ui_wired = False
def _wire_desktop_sinks() -> None:
- """Idempotently wire process-registry and desktop-tool sinks to renderer events: background-process
- output (`agent.terminal.output`) and `terminal.close` (drops a tab without killing the process) route
- to the window owning the process by process id; desktop-only tools (open_preview, focus_pane, …) pass
- the turn's ``HERMES_UI_SESSION_ID`` as ``sid``. `_emit` is `_stdout_lock`-guarded (thread-safe)."""
+ """Idempotently wire process-registry and desktop-tool sinks to renderer events: `agent.terminal.output`
+ and `terminal.close` (drops a tab without killing the process) route to the window owning the process;
+ desktop-only tools pass the turn's ``HERMES_UI_SESSION_ID`` as ``sid``. `_emit` is thread-safe."""
global _desktop_ui_wired
from tools.process_registry import process_registry
@@ -554,10 +551,9 @@ def _hud_surface_note(session: dict) -> str:
def _prepend_note(run_message: Any, note: str) -> Any:
- """Prefix a per-turn note onto the MODEL INPUT, leaving the prompt alone. Everything the model must
- know about the turn that the user did not type (interrupted reply, reactions, surface) arrives this
- way; persist_user_message keeps the clean prompt, so no scaffolding reaches the transcript, and
- annotating the NEW turn never rewrites a sent message — cached prefix survives."""
+ """Prefix a per-turn note onto the MODEL INPUT, leaving the prompt alone: everything the model must
+ know that the user did not type (interrupted reply, reactions, surface) arrives this way, so no
+ scaffolding reaches the transcript and no sent message is rewritten — the cached prefix survives."""
if not note:
return run_message
if isinstance(run_message, str):
diff --git a/tui_gateway/slash_fuzzy.py b/tui_gateway/slash_fuzzy.py
index c00e8641890..435a5e28235 100644
--- a/tui_gateway/slash_fuzzy.py
+++ b/tui_gateway/slash_fuzzy.py
@@ -1,12 +1,7 @@
-"""Description-aware fuzzy scoring for slash-menu completions.
-
-Ported from superagent-ai/grok-cli ``src/ui/slash-menu.ts`` (mirrored on the TUI client in
-``ui-tui/src/app/slash/fuzzyScore.ts``): candidates are scored in tiers — exact match on the
-command token (0), prefix (1), substring (2) — and the DESCRIPTION text is tokenized and matched
-at a +3 offset (exact word 3, word prefix 4, word substring 5). Typing ``/summary`` thus surfaces
-a command whose description mentions summaries even though no command name starts with it.
-Lower score wins; ``math.inf`` means no match.
-"""
+"""Description-aware fuzzy scoring for slash-menu completions (ported from superagent-ai/grok-cli
+``src/ui/slash-menu.ts``; mirrored in ``ui-tui/src/app/slash/fuzzyScore.ts``). Tiers: exact command
+token (0), prefix (1), substring (2); the DESCRIPTION is tokenized and matched at +3 (3/4/5), so
+``/summary`` surfaces a command whose description mentions summaries. Lower wins; ``math.inf`` = miss."""
from __future__ import annotations
@@ -52,12 +47,9 @@ def score_slash_completion_item(item: dict, query: str) -> float:
def fuzzy_rank_slash_items(
items: list[dict], catalog: list[dict], query: str
) -> tuple[list[dict], Callable[[dict], float]]:
- """Merge description/substring matches into ``items`` and sort by score.
- ``items`` are the completer's own (prefix-filtered) rows and keep their identity; ``catalog`` is
- the full command/skill universe, from which any entry the prefix filter missed but the fuzzy
- scorer matches is appended. Returns the score-sorted rows (stable within a tier) plus a
- ``score_of`` lookup for downstream rankers to use as a leading sort key.
- """
+ """Merge fuzzy-matched ``catalog`` entries the prefix filter missed into ``items`` (which keep their
+ identity) and sort by score (stable within a tier). Also returns a ``score_of`` lookup for downstream
+ rankers to use as a leading sort key."""
seen = {str(item.get("text", "")).strip() for item in items}
merged = list(items) + [
item for item in catalog
diff --git a/tui_gateway/slash_worker.py b/tui_gateway/slash_worker.py
index 8a8217ba588..3dc0bbbd679 100644
--- a/tui_gateway/slash_worker.py
+++ b/tui_gateway/slash_worker.py
@@ -3,11 +3,10 @@
Protocol: reads JSON lines from stdin {id, command}, writes {id, ok, output|error} to stdout.
"""
-# Stop a ``utils/`` (or ``proxy/``, ``ui/``) package in the launch directory from shadowing Hermes's
-# own top-level modules. This worker is spawned as ``-m tui_gateway.slash_worker`` and inherits the
-# user's CWD, so the ``import cli`` below would otherwise resolve ``utils`` to a colliding local
-# package and crash the child in a retry loop. ``hermes_bootstrap`` lives at the repo root (no
-# collision risk), so importing it before the guard runs is safe.
+# Stop a ``utils/`` (or ``proxy/``, ``ui/``) package in the launch directory from shadowing Hermes's own
+# top-level modules: this worker is spawned as ``-m tui_gateway.slash_worker`` with the user's CWD, so
+# ``import cli`` would otherwise resolve ``utils`` to a colliding local package and crash the child in a
+# retry loop. ``hermes_bootstrap`` lives at the repo root (no collision risk), so importing it first is safe.
import hermes_bootstrap
hermes_bootstrap.harden_import_path()
@@ -126,9 +125,8 @@ def main():
_reply(id=rid, ok=False, error=str(e))
finally:
_in_flight.clear()
- # Workers persist for the TUI session: release allocator pages at the command boundary
- # like other long-lived gateway processes (trim_memory's shared cooldown coalesces
- # nearby activity).
+ # Workers persist for the TUI session: release allocator pages at the command boundary like
+ # other long-lived gateway processes (trim_memory's shared cooldown coalesces nearby activity).
try:
from hermes_cli.mem_trim import trim_memory
trim_memory(reason="slash worker command completion")
diff --git a/tui_gateway/synthetic_turn.py b/tui_gateway/synthetic_turn.py
index b4e0db0f829..15f702eb7e1 100644
--- a/tui_gateway/synthetic_turn.py
+++ b/tui_gateway/synthetic_turn.py
@@ -1,16 +1,10 @@
-"""Synthetic GIL-heavy turn driver for the AC-4 isolation certify harness.
-
-The regime under test is interpreter-wide GIL starvation: concurrent heavy agent turns run compute in
-threads of the SERVING process and starve the event loop that flushes WebSocket frames (loop thread
-parked in ``take_gil`` — NOT blocked on I/O). To certify the isolation fix without spending real
-tokens the turn driver must reproduce THAT: sustained pure-Python CPU holding the GIL. A network/
-sleep stub is WRONG — it releases the GIL during I/O, so a green off it is fake.
-
-Test seam: dead unless ``HERMES_ISO_CERTIFY_SYNTH_TURN=1``. When armed, ``server._make_agent`` returns
-a :class:`SyntheticHeavyAgent` on both the in-process ``_pool`` path (isolation OFF) and the compute-
-host child path (isolation ON), so the isolation boundary is the only variable. Per-turn intensity
-rides in the prompt text as a JSON object; any other prompt falls back to env / built-in defaults.
-"""
+"""Synthetic GIL-heavy turn driver for the AC-4 isolation certify harness. The regime under test is
+interpreter-wide GIL starvation (serving-process turn threads park the WebSocket loop in ``take_gil``),
+so the driver must hold the GIL with sustained pure-Python CPU — a network/sleep stub releases the GIL
+and a green off it is fake. Test seam: dead unless ``HERMES_ISO_CERTIFY_SYNTH_TURN=1``; when armed,
+``server._make_agent`` returns a :class:`SyntheticHeavyAgent` on both the in-process and compute-host
+paths, so the isolation boundary is the only variable. Per-turn intensity rides in the prompt text as
+a JSON object; any other prompt falls back to env / built-in defaults."""
from __future__ import annotations
@@ -24,12 +18,11 @@ from typing import Any, Callable, Optional
from tui_gateway._env import env_float as _env_float, env_int as _env_int
-# Per-turn intensity spec: (key, caster, default source). ``chunk`` is pure-Python ops per
-# interrupt-check chunk (small enough that an interrupt lands within ms, large enough to stay hot on
-# the GIL); ``delta_interval_s`` is the streamed-delta cadence (each delta is a loop wakeup
-# marshalling a frame); ``tokens_per_delta`` drives the 100K+-token heavy-turn proxy; ``sleep_s`` is
-# an optional per-chunk sleep for a mixed regime (0 = pure burn; --dry-run uses a short duration, NOT
-# a sleep, so it still exercises the real seam).
+# Per-turn intensity spec: (key, caster, default source). ``chunk`` = pure-Python ops per interrupt
+# check (ms-level interrupt latency, still hot on the GIL); ``delta_interval_s`` = streamed-delta
+# cadence (each delta is a loop wakeup marshalling a frame); ``tokens_per_delta`` drives the 100K+-token
+# heavy-turn proxy; ``sleep_s`` = optional per-chunk sleep for a mixed regime (0 = pure burn; --dry-run
+# shortens duration instead, so it still exercises the real seam).
_SPEC_FIELDS = (
("duration_s", float, lambda: _env_float("HERMES_ISO_CERTIFY_DURATION_S", 8.0)),
("chunk", int, lambda: _env_int("HERMES_ISO_CERTIFY_CHUNK", 20_000)),
diff --git a/tui_gateway/turn_marker.py b/tui_gateway/turn_marker.py
index e1b89ac36bb..b9226f5efd0 100644
--- a/tui_gateway/turn_marker.py
+++ b/tui_gateway/turn_marker.py
@@ -1,14 +1,10 @@
-"""Durable interrupted-turn markers for the desktop/TUI auto-continue path.
-
-A running turn's progress lives only in process memory (the agent flushes to SQLite at turn end),
-so an app/backend/machine death mid-turn leaves no durable trace of the interrupted prompt. A marker
-is written when a turn starts and cleared when it concludes (success, handled error, or interrupt),
-so only a process death leaves one behind; ``session.resume`` reads it to decide whether to
-auto-continue (``_maybe_schedule_auto_continue``). Markers are stored per ``HERMES_HOME`` (profile
-sessions keep state in their own profile dir); writes prune entries older than ``_MAX_AGE_SECS`` and
-cap the count so a crash streak can't grow the file unboundedly. Every function is best-effort —
-marker bookkeeping must never break a turn — so I/O errors degrade to "no marker" instead of raising.
-"""
+"""Durable interrupted-turn markers for the desktop/TUI auto-continue path. A running turn's progress
+lives only in process memory (the agent flushes to SQLite at turn end), so a marker is written at turn
+start and cleared on any conclusion — only a process death leaves one behind, and ``session.resume``
+reads it (``_maybe_schedule_auto_continue``). Stored per ``HERMES_HOME`` (profile-aware); writes prune
+entries older than ``_MAX_AGE_SECS`` and cap the count so a crash streak can't grow the file. Every
+function is best-effort — marker bookkeeping must never break a turn — so I/O errors degrade to "no
+marker" instead of raising."""
from __future__ import annotations
@@ -88,10 +84,8 @@ def _update(home: Path | str, session_key: str, mutate, what: str) -> None:
def record_turn_start(home: Path | str, session_key: str, prompt: str, *, attempts: int = 0) -> None:
- """Persist the marker for a turn that is about to run.
- ``attempts`` counts how many auto-continues led to this run: 0 for a user-initiated turn, N for
- the Nth automatic re-run — the crash-loop breaker reads it back on the next resume.
- """
+ """Persist the marker for a turn that is about to run. ``attempts`` = how many auto-continues led to
+ this run (0 for a user-initiated turn); the crash-loop breaker reads it back on the next resume."""
if not session_key or not prompt:
return
now = time.time()