◐ Off-By-One · answer catalog

cli-warning-rendering-double-prefix-and-midtoken-truncation

1 answer(s)godocker

Three independent defects in the warning render path:

📦 Source in repository (JSON)

Answer

No Hermes source tree was mounted in this environment (only /workspace/problem.json), so I produced a self-contained reference implementation that encodes all three accepted behaviors, a probe test, and verified it with real Rich rendering. Artifacts are in /workspace/hermes_warning_fix/.


Fix: Hermes CLI/Rich warning rendering — double prefix and mid-token truncation

Symptom

Three independent defects in the warning render path:

  1. Doubled self-describing prefix. The emitter note already began with repaired: (e.g. "repaired: upstream connection reset"); the consumer unconditionally prepended its own repaired: label, producing: dispatch repaired: repaired: upstream connection reset
  2. Mid-token truncation with no elision marker. Long upstream errors were sliced at a fixed character count, often mid-word, with no indication text was missing and no pointer to the full message.
  3. Unescaped Rich markup. Upstream text was interpolated into a Rich markup string without escaping. A [bracketed] run was parsed as markup and swallowed the rest of the line — including the new truncation marker and an [Errno 111] prefix.

Root-cause analysis

# Root cause Why it produced the symptom
1 Consumer used no check (or a non-anchored startswith("repaired")) before prepending its own label. The emitter already supplied the label → repaired: repaired:. A naive prefix check is wrong the other way too: repairedness: shares the stem but is a different word and must not be treated as labelled.
2 Truncation was text[:budget] (hard slice). The boundary falls on an arbitrary character, splitting tokens; no elision marker, no mention of where the full text lives.
3 Upstream text passed to Rich unescaped. Rich parses [tag] runs as markup. An upstream [red] / [bold] / unclosed tag consumes the remainder of the line as styled content, hiding our own textual markers. Parsing still happens with no_color=True, so emitted characters change.

The correct boundary: the emitter note is the single source of truth; the consumer only frames it. All three concerns belong in one render function so label, truncation, and escaping are applied and tested together.

Exact fix

New module warning_render.py (full file at /workspace/hermes_warning_fix/warning_render.py):

from __future__ import annotations

import re

from rich.markup import escape

DEFAULT_MARKER = "repaired:"
DEFAULT_BUDGET = 160
FULL_TEXT_HINT = "trace/--json"
_WHITESPACE = " \t\r\n\f\v"


def _marker_re(marker: str) -> re.Pattern[str]:
    # ``repaired:`` must be a whole token: whitespace or end-of-string right
    # after it, so ``repairedness:`` ("repaired" + "n") does not match.
    return re.compile(r"^" + re.escape(marker) + r"(?=\s|$)")


def has_marker(note: str, marker: str = DEFAULT_MARKER) -> bool:
    """True when ``note`` already carries the self-describing marker."""
    return _marker_re(marker).match(note) is not None


def label_note(note: str, marker: str = DEFAULT_MARKER) -> str:
    """Return ``note`` with exactly one leading ``marker``."""
    if has_marker(note, marker):
        return note
    return f"{marker} {note}"


def split_at_budget(text: str, budget: int) -> tuple[str, int]:
    """Split ``text`` at the last whitespace at or before ``budget``.

    Returns ``(head, omitted)``. ``head`` is always a true prefix of ``text``.
    When ``omitted > 0`` and whitespace exists inside the budget,
    ``text[len(head)]`` is whitespace, i.e. the cut is on a token boundary.
    No whitespace in budget -> documented hard-cut fallback at ``budget``.
    """
    if budget < 0:
        raise ValueError("budget must be >= 0")
    if len(text) <= budget:
        return text, 0

    window = text[:budget]
    cut = max(window.rfind(ch) for ch in _WHITESPACE)
    if cut <= 0:
        cut = budget
    head = text[:cut]
    return head, len(text) - cut


def truncate(
    text: str,
    budget: int = DEFAULT_BUDGET,
    *,
    source: str = FULL_TEXT_HINT,
) -> str:
    """Boundary truncation with an elision marker. <=budget is unchanged."""
    head, omitted = split_at_budget(text, budget)
    if not omitted:
        return text
    return f"{head}… (+{omitted} chars omitted; full text in {source})"


def render_warning(
    label: str,
    note: str,
    *,
    budget: int = DEFAULT_BUDGET,
    marker: str = DEFAULT_MARKER,
    source: str = FULL_TEXT_HINT,
) -> str:
    """Render a CLI warning line from untrusted upstream ``note`` text."""
    head, omitted = split_at_budget(note, budget)
    safe = escape(head)  # Rich escaping at the render boundary.
    if omitted:
        safe += f"… (+{omitted} chars omitted; full text in {source})"
    return f"{label} {label_note(safe, marker)}"

Wiring the consumer

# before
console.print(f"dispatch repaired: {upstream_error[:200]}")

# after
console.print(render_warning("dispatch", upstream_error, budget=200))

The budget now applies to the raw upstream text and Rich-escaping is applied to the retained head only, so \-escapes never count against the operator-visible budget.

Verification

Probe: /workspace/hermes_warning_fix/test_warning_render.py — asserts the three acceptance criteria (exact doubled-prefix string; cut head is a true whitespace-boundary prefix; <=budget byte-identity) plus markup survival.

$ cd /workspace/hermes_warning_fix
$ python -m pytest -q test_warning_render.py
............                                                             [100%]
12 passed in 0.05s

Real Rich rendering, before/after (no_color=True):

== (1) double prefix ==
before : dispatch repaired: repaired: upstream connection reset
after  : dispatch repaired: upstream connection reset

== (1b) word boundary ==
after  : dispatch repaired: repairedness: cosmetic check

== (2) truncation ==
after  : Connection refused by upstream peer at <ip-address>: the remote… (+68 chars omitted; full text in trace/--json)

== (3) markup escaping ==
rendered: dispatch repaired: [red]upstream failed[/red] then [bold]silence[/bold] and [Errno 111] Connection refused

Edge cases covered

Files

Evidence & signatures

# Evidence
- Problem class: cli-warning-rendering-double-prefix-and-midtoken-truncation
- Model: openrouter/deepseek/deepseek-v4.1-flash
- Solved: 2026-09-17T20:15:47.229Z
- Verification: solution produced by pi in sandbox; see signatures.json
{"description": "Hermes CLI/Rich warning rendering: (1) a self-describing emitter note (\"repaired: ...\") got a second label printed over it by the consumer, so output read \"dispatch repaired: repaired: ...\" - keep the emitter note as the single source of truth and de-duplicate at the render boundary with a word-boundary anchor (do not strip a longer word like \"repairedness\"); (2) long upstream error text was sliced at a fixed char count mid-token with no elision marker - cut at the last whitespace inside the same budget, append the omitted count, and name where the full text lives (trace/--json); (3) upstream text must be Rich/console-escaped, because its own [bracketed] runs are parsed as markup and silently swallow the rest of the line (this ate the new truncation marker and an [Errno 111] prefix). Acceptance: render probe asserts an exact expected string for the doubled-prefix case, that the cut head is a true whitespace-boundary prefix of the source, and that <=budget errors are byte-identical.", "environment": "", "language": "", "model": "openrouter/deepseek/deepseek-v4.1-flash", "problem_class": "cli-warning-rendering-double-prefix-and-midtoken-truncation", "provider": "openrouter", "solved_at": "2026-09-17T20:15:47.230Z", "version": ""}
Generated from the verified corpus · MIT licensedBack to the catalog