The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(logs): hermes logs --since/--level handle unstamped lines and MCP output
alt-glitchfc4dbe32df0a
diff --git a/apps/desktop/src/app/capabilities/mcp/mcp-logs.test.ts b/apps/desktop/src/app/capabilities/mcp/mcp-logs.test.tsnew file mode 100644index 00000000000..134fca14145--- /dev/null+++ b/apps/desktop/src/app/capabilities/mcp/mcp-logs.test.ts@@ -0,0 +1,19 @@+import { describe, expect, it } from 'vitest'++import { filterStdioSections } from './mcp-logs'++describe('filterStdioSections', () => {+ it('splits mcp-stderr.log by server for stamped and older banner lines', () => {+ const lines = [+ "===== [2026-09-27 09:00:00] starting MCP server 'fs' =====",+ 'old fs output',+ "2026-09-28 13:18:46,062 ===== starting MCP server 'git' =====",+ '2026-09-28 13:18:46,100 git output',+ "2026-09-28 13:18:47,000 ===== starting MCP server 'fs' =====",+ '2026-09-28 13:18:47,050 new fs output'+ ]++ expect(filterStdioSections(lines, 'fs')).toEqual([lines[0], lines[1], lines[4], lines[5]])+ expect(filterStdioSections(lines, 'git')).toEqual([lines[2], lines[3]])+ })+})diff --git a/apps/desktop/src/app/capabilities/mcp/mcp-logs.tsx b/apps/desktop/src/app/capabilities/mcp/mcp-logs.tsxindex f754ad79193..7cc66655cc2 100644--- a/apps/desktop/src/app/capabilities/mcp/mcp-logs.tsx+++ b/apps/desktop/src/app/capabilities/mcp/mcp-logs.tsx@@ -8,7 +8,8 @@ import { $activeGatewayProfile } from '@/store/profile'export const LOG_POLL_MS = 2000-const STDIO_MARKER_RE = /^===== \[.*\] starting MCP server '(.+)' =====$/+// Current banner: `<asctime> ===== starting …`; files written before it use `===== [<time>] starting …`.+const STDIO_MARKER_RE = /^(?:\d{4}-\d{2}-\d{2} [\d:,]+ )?===== (?:\[.*\] )?starting MCP server '(.+)' =====$/export function filterStdioSections(lines: string[], server: string): string[] {const out: string[] = []diff --git a/hermes_cli/logs.py b/hermes_cli/logs.pyindex f2b613a9b2e..ad5a69910a8 100644--- a/hermes_cli/logs.py+++ b/hermes_cli/logs.py@@ -76,7 +76,8 @@ def _matches_filters(since: Optional[datetime] = None,component_prefixes: Optional[Sequence[str]] = None,) -> bool:- """Whether a line passes all active filters (lines without a timestamp/level pass those)."""+ """Whether one line passes all active filters (a line without a timestamp/level passes those);+ ``_LineFilter`` decides for unstamped continuation lines."""if since is not None:ts = _parse_line_timestamp(line)if ts is not None and ts < since:@@ -90,6 +91,24 @@ def _matches_filters(return component_prefixes is None or _line_matches_component(line, component_prefixes)+class _LineFilter:+ """Stateful ``_matches_filters`` over consecutive lines of one file. A line with no stamp continues+ the record above it (traceback frames, multi-line messages), so it takes that record's verdict."""++ def __init__(self, **filters):+ self._filters = filters+ self._carry: Optional[bool] = None++ def __call__(self, line: str) -> bool:+ if _parse_line_timestamp(line) is not None:+ self._carry = _matches_filters(line, **self._filters)+ elif self._carry is None:+ # Before the first stamp: this record's time and level are unknown.+ timed = self._filters.get("since") is not None or self._filters.get("min_level") is not None+ return not timed and _matches_filters(line, **self._filters)+ return self._carry++def tail_log(log_name: str = "agent",*,@@ -170,7 +189,8 @@ def _read_tail(path: Path, num_lines: int, *, has_filters: bool = False, **filtereturn _read_last_n_lines(path, num_lines)# Over-read so enough lines survive filtering.raw_lines = _read_last_n_lines(path, max(num_lines * 20, 2000))- return [l for l in raw_lines if _matches_filters(l, **filters)][-num_lines:]+ keep = _LineFilter(**filters)+ return [l for l in raw_lines if keep(l)][-num_lines:]def _read_all_lines(path: Path) -> list:@@ -211,6 +231,7 @@ def _read_last_n_lines(path: Path, n: int) -> list:def _follow_log(path: Path, **filters) -> None:"""Poll a log file for new content and print matching lines."""+ keep = _LineFilter(**filters)with open(path, "r", encoding="utf-8-sig", errors="replace") as f:# Seek to endf.seek(0, 2)@@ -218,7 +239,7 @@ def _follow_log(path: Path, **filters) -> None:line = f.readline()if not line:time.sleep(0.3)- elif _matches_filters(line, **filters):+ elif keep(line):print(line, end="")sys.stdout.flush()diff --git a/hermes_cli/stderr_timestamp.py b/hermes_cli/stderr_timestamp.pyindex 3aafcdcd21b..47dc44c0855 100644--- a/hermes_cli/stderr_timestamp.py+++ b/hermes_cli/stderr_timestamp.py@@ -26,15 +26,20 @@ _TIMESTAMP_PREFIX = re.compile(r"^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2},\d{3}(?:\s_STDOUT_DRAIN_TIMEOUT_S = 5.0-def _timestamp() -> str:- """Match logging.Formatter's default ``%(asctime)s`` timestamp shape."""+def timestamp() -> str:+ """Local time in logging.Formatter's default ``%(asctime)s`` shape, which ``hermes logs --since`` parses."""return datetime.now().strftime("%Y-%m-%d %H:%M:%S,%f")[:23]-def _write_timestamped_line(log_file: TextIO, line: str) -> None:+def stamp_line(line: str) -> str:+ """*line* with a leading :func:`timestamp` (kept as-is if it already has one) and one ``\\n``."""rendered = line.rstrip("\r\n")- prefix = "" if _TIMESTAMP_PREFIX.match(rendered) else f"{_timestamp()} "- log_file.write(f"{prefix}{rendered}\n")+ prefix = "" if _TIMESTAMP_PREFIX.match(rendered) else f"{timestamp()} "+ return f"{prefix}{rendered}\n"+++def _write_timestamped_line(log_file: TextIO, line: str) -> None:+ log_file.write(stamp_line(line))log_file.flush()diff --git a/tests/hermes_cli/test_logs.py b/tests/hermes_cli/test_logs.pyindex a6378428cb7..fcce6be6d2c 100644--- a/tests/hermes_cli/test_logs.py+++ b/tests/hermes_cli/test_logs.py@@ -3,6 +3,7 @@from datetime import datetime, timedeltafrom hermes_cli.logs import (+ LOG_FILES,_extract_level,_extract_logger_name,_line_matches_component,@@ -10,6 +11,7 @@ from hermes_cli.logs import (_parse_line_timestamp,_parse_since,_read_last_n_lines,+ _read_tail,)# ---------------------------------------------------------------------------@@ -121,6 +123,78 @@ class TestReadTail:assert len(result) == 5assert "line 9" in result[-1]+ def test_unstamped_lines_share_the_verdict_of_the_record_above(self, tmp_path):+ old = (datetime.now() - timedelta(hours=3)).strftime("%Y-%m-%d %H:%M:%S,000")+ new = datetime.now().strftime("%Y-%m-%d %H:%M:%S,000")+ frames = ["Traceback (most recent call last):\n", ' File "x.py", line 1, in f\n']+ log_file = tmp_path / "errors.log"+ log_file.write_text("".join([+ "orphan tail of a record that started before the window\n",+ f"{old} ERROR gateway.run: old failure\n", *frames, "ValueError: old\n",+ f"{new} INFO tools.x: multi-line info\n", " info continuation\n",+ f"{new} ERROR gateway.run: new failure\n", *frames, "ValueError: new\n",+ ]))+ since = datetime.now() - timedelta(hours=1)+ from hermes_logging import COMPONENT_PREFIXES++ def read(**filters):+ return "".join(_read_tail(log_file, 50, has_filters=True, **filters))++ assert read(since=since) == "".join([+ f"{new} INFO tools.x: multi-line info\n", " info continuation\n",+ f"{new} ERROR gateway.run: new failure\n", *frames, "ValueError: new\n",+ ])+ new_failure = "".join([f"{new} ERROR gateway.run: new failure\n", *frames, "ValueError: new\n"])+ assert read(since=since, min_level="WARNING") == new_failure+ assert read(since=since, component_prefixes=COMPONENT_PREFIXES["gateway"]) == new_failure+ # No time/level filter: the orphan lines before the first stamp stay visible.+ assert read(session_filter="orphan") == "orphan tail of a record that started before the window\n"+# ---------------------------------------------------------------------------# LOG_FILES registry# ---------------------------------------------------------------------------++def _python_log_line(logger_name: str) -> str:+ import logging++ from agent.redact import RedactingFormatter+ from hermes_logging import _LOG_FORMAT++ record = logging.LogRecord(logger_name, logging.WARNING, __file__, 1, "sample", None, None)+ record.session_tag = ""+ return RedactingFormatter(_LOG_FORMAT).format(record)+++def _mcp_output_line() -> str:+ import io++ from tools.mcp_tool_config import _StderrTee++ log = io.StringIO()+ tee = _StderrTee(log)+ tee.sink.write(b"server says hello\n")+ tee.close()+ return log.getvalue()+++def _log_file_samples() -> dict:+ """One line per LOG_FILES entry, produced by that file's real writer where Python can run it."""+ return {+ "agent": _python_log_line("run_agent"),+ "errors": _python_log_line("run_agent"),+ "gateway": _python_log_line("gateway.run"),+ "gui": _python_log_line("hermes_cli.web_server"),+ # Written by TypeScript; apps/desktop/electron/desktop-log-line.test.ts pins the same shape.+ "desktop": "2026-09-28 13:18:46,062 [hermes] [boot] ready",+ "mcp": _mcp_output_line(),+ }+++def test_every_log_file_writes_a_stamp_hermes_logs_since_can_read():+ samples = _log_file_samples()+ assert set(samples) == set(LOG_FILES), "add a real sample line for each new LOG_FILES entry"+ for name, line in samples.items():+ assert _parse_line_timestamp(line) is not None, (name, line)+ # gateway.error.log (launchd stderr, not in LOG_FILES) uses the shared stamper.+ from hermes_cli.stderr_timestamp import stamp_line+ assert _parse_line_timestamp(stamp_line("raw gateway stderr")) is not Nonediff --git a/tests/tools/test_mcp_stderr_lifecycle.py b/tests/tools/test_mcp_stderr_lifecycle.pyindex 5430db640e7..d45338dedd9 100644--- a/tests/tools/test_mcp_stderr_lifecycle.py+++ b/tests/tools/test_mcp_stderr_lifecycle.py@@ -1,5 +1,6 @@"""MCP shutdown releases only the selected profile's cached stderr handle."""+import iofrom pathlib import Pathfrom hermes_constants import (@@ -7,7 +8,8 @@ from hermes_constants import (reset_hermes_home_override,set_hermes_home_override,)-from tools.mcp_tool_config import _get_mcp_stderr_log+from hermes_cli.logs import _parse_line_timestamp+from tools.mcp_tool_config import _StderrTee, _get_mcp_stderr_log, _write_stderr_log_headerfrom tools.mcp_tool_lifecycle import shutdown_mcp_servers@@ -65,3 +67,24 @@ def test_rename_profile_releases_cached_log_handle(tmp_path, monkeypatch):assert new_dir.is_dir() and not old_dir.exists()finally:handle.close()+++def test_every_mcp_log_line_carries_a_stamp_hermes_logs_since_reads(tmp_path):+ token = set_hermes_home_override(tmp_path)+ try:+ _write_stderr_log_header("probe")+ log = io.StringIO()+ tee = _StderrTee(log)+ # A line split across writes, a CRLF line and a last line with no newline.+ for chunk in (b"first half ", b"second half\n", b"crlf line\r\n", b"no newline at exit"):+ tee.sink.write(chunk)+ assert tee.close() == "first half second half\ncrlf line\r\nno newline at exit"+ banner = (tmp_path / "logs" / "mcp-stderr.log").read_text().strip()+ finally:+ reset_hermes_home_override(token)+ shutdown_mcp_servers(scope=hermes_home_key(tmp_path))+ lines = log.getvalue().splitlines()+ assert [line[24:] for line in lines] == ["first half second half", "crlf line", "no newline at exit"]+ for line in [banner, *lines]:+ assert _parse_line_timestamp(line) is not None, line+ assert banner.endswith("===== starting MCP server 'probe' =====")diff --git a/tools/mcp_tool_config.py b/tools/mcp_tool_config.pyindex 01e439a52ee..e08f102d37a 100644--- a/tools/mcp_tool_config.py+++ b/tools/mcp_tool_config.py@@ -10,8 +10,8 @@ import reimport shutilimport sysimport threading-from datetime import datetimefrom typing import Any, Dict, List, Optional, Set, Tuple+from hermes_cli.stderr_timestamp import stamp_line, timestampfrom tools.mcp_tool_common import _env_ref_name, _prepend_pathlogger = logging.getLogger("tools.mcp_tool")@@ -61,9 +61,9 @@ def _close_mcp_stderr_logs(*, scope: Optional[str] = None) -> None:class _StderrTee:- """A stdio child's stderr, copied into the shared log as it arrives while the last few KB stay- readable, so a server that dies at startup can say why on the MCP status surfaces instead of only in- the log (#124264). ``sink`` is handed to the child; ``close()`` returns the captured tail."""+ """A stdio child's stderr, copied into the shared log one stamped line at a time while the last few KB+ stay readable (raw), so a server that dies at startup can say why on the MCP status surfaces instead of+ only in the log (#124264). ``sink`` is handed to the child; ``close()`` returns the captured tail."""_TAIL_BYTES = 16384@@ -76,14 +76,24 @@ class _StderrTee:def _pump(self, read_fd: int) -> None:decoder = codecs.getincrementaldecoder("utf-8")(errors="replace")+ pending = ""with os.fdopen(read_fd, "rb", buffering=0) as source:while chunk := source.read(65536):self._tail = (self._tail + chunk)[-self._TAIL_BYTES:]- try:- self._log.write(decoder.decode(chunk))- self._log.flush()- except (OSError, ValueError): # log closed at shutdown: keep draining the child- pass+ # Stamp whole lines only; a partial line waits for its newline (or EOF).+ *lines, pending = (pending + decoder.decode(chunk)).split("\n")+ self._write_lines(lines)+ if rest := pending + decoder.decode(b"", final=True):+ self._write_lines([rest])++ def _write_lines(self, lines: List[str]) -> None:+ if not lines:+ return+ try:+ self._log.write("".join(stamp_line(line) for line in lines))+ self._log.flush()+ except (OSError, ValueError): # log closed at shutdown: keep draining the child+ passdef close(self, timeout: float = 2.0) -> str:"""Close our write end and give the reader *timeout* to drain (a surviving grandchild can keep@@ -94,11 +104,11 @@ class _StderrTee:def _write_stderr_log_header(server_name: str) -> None:- """Session marker so operators can find each server's output in the shared log- (per-line prefixes would need a pipe + reader thread)."""+ """Session marker so operators can find each server's output in the shared log; it leads with the+ same stamp as every server line (``_StderrTee``) so ``hermes logs mcp --since`` can filter it."""fh = _get_mcp_stderr_log()try:- fh.write(f"\n===== [{datetime.now():%Y-%m-%d %H:%M:%S}] starting MCP server '{server_name}' =====\n")+ fh.write(f"\n{timestamp()} ===== starting MCP server '{server_name}' =====\n")fh.flush()except Exception:passdiff --git a/website/docs/reference/cli-commands.md b/website/docs/reference/cli-commands.mdindex a4373c18c53..882f2c7c945 100644--- a/website/docs/reference/cli-commands.md+++ b/website/docs/reference/cli-commands.md@@ -1227,6 +1227,7 @@ View, tail, and filter Hermes log files. All logs are stored in `~/.hermes/logs/| `gateway` | `gateway.log` | Messaging gateway activity — platform connections, message dispatch, webhook events || `gui` | `gui.log` | Dashboard / TUI-gateway / PTY-bridge / websocket events || `desktop` | `desktop.log` | Electron desktop app — boot, backend spawn output, and recent Python tracebacks |+| `mcp` | `mcp-stderr.log` | stderr of every stdio MCP server, one `starting MCP server` banner per launch |### Options@@ -1240,6 +1241,8 @@ View, tail, and filter Hermes log files. All logs are stored in `~/.hermes/logs/| `--since <TIME>` | Show lines from a relative time ago: `30m`, `1h`, `2d`, etc. Supports `s` (seconds), `m` (minutes), `h` (hours), `d` (days). || `--component <NAME>` | Filter by component: `gateway`, `agent`, `tools`, `cli`, `cron`. |+A line without its own timestamp, such as a traceback frame or the rest of a multi-line message, is shown or hidden together with the timestamped line above it.+### Examples```bashdiff --git a/website/docs/user-guide/configuration.md b/website/docs/user-guide/configuration.mdindex 8e99de51529..b8fce780eba 100644--- a/website/docs/user-guide/configuration.md+++ b/website/docs/user-guide/configuration.md@@ -2778,7 +2778,7 @@ The browser toolset supports multiple providers. See the [Browser feature page](## Timezone-Override the server-local timezone with an IANA timezone string. Affects timestamps in logs, cron scheduling, and system prompt time injection.+Override the server-local timezone with an IANA timezone string. Affects cron scheduling and the time injected into the system prompt. It does not change log files: every line in `~/.hermes/logs/` is stamped in the machine's local time, which is what `hermes logs --since` compares against.```yamltimezone: "America/New_York" # IANA timezone (default: "" = server-local time)