Skip to content

The agent that grows with you

fix(gateway): launchd gateway stdout lines are timestamped

alt-glitch96aa40a49f8c
diff --git a/hermes_cli/stderr_timestamp.py b/hermes_cli/stderr_timestamp.py
index 6bb16e6c89c..3aafcdcd21b 100644
--- a/hermes_cli/stderr_timestamp.py
+++ b/hermes_cli/stderr_timestamp.py
@@ -1,4 +1,4 @@
-"""Run a child process while prefixing each stderr line with a timestamp."""
+"""Run a child process while prefixing each stdout and stderr line with a timestamp."""
from __future__ import annotations
@@ -8,6 +8,7 @@ import re
import signal
import subprocess
import sys
+import threading
from collections.abc import Mapping
from datetime import datetime
from pathlib import Path
@@ -20,6 +21,9 @@ _LAUNCHD_LABEL_ENV = "HERMES_LAUNCHD_LABEL"
_GATEWAY_FATAL_CONFIG_EXIT_CODE = 78
_TIMESTAMP_PREFIX = re.compile(r"^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2},\d{3}(?:\s|$)")
+# A grandchild that inherited stdout can hold the pipe open after the child exits; the
+# wrapper must still exit with the child's status so launchd KeepAlive sees it.
+_STDOUT_DRAIN_TIMEOUT_S = 5.0
def _timestamp() -> str:
@@ -45,6 +49,14 @@ def _copy_stderr_with_timestamps(stderr: BinaryIO, log_path: Path) -> None:
_write_timestamped_line(log_file, raw_line.decode("utf-8", errors="replace"))
+def _copy_stdout_with_timestamps(stdout: BinaryIO) -> None:
+ # fd 1 is the caller's target (launchd appends it to gateway.log, the logging handler's
+ # file), so lines keep their destination and gain the stamp `hermes logs --since` needs.
+ with open(1, "w", encoding="utf-8", buffering=1, closefd=False) as out:
+ for raw_line in iter(stdout.readline, b""):
+ _write_timestamped_line(out, raw_line.decode("utf-8", errors="replace"))
+
+
def _install_signal_forwarders(proc: subprocess.Popen[bytes]) -> dict[int, object]:
def _forward(signum: int, _frame: object) -> None:
try:
@@ -138,7 +150,9 @@ def _child_returncode_for_supervisor(command: Sequence[str], returncode: int) ->
def _parse_args(argv: Sequence[str] | None) -> argparse.Namespace:
- parser = argparse.ArgumentParser(description="Run a command and timestamp each stderr line into a log file.")
+ parser = argparse.ArgumentParser(
+ description="Run a command, timestamp each stderr line into a log file and each stdout line to stdout."
+ )
parser.add_argument("--error-log", required=True, type=Path)
parser.add_argument("command", nargs=argparse.REMAINDER)
args = parser.parse_args(argv)
@@ -156,6 +170,7 @@ def main(argv: Sequence[str] | None = None) -> int:
try:
proc = subprocess.Popen(
_prepare_child_command(args.command),
+ stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
env={**os.environ, **_child_launchd_label_env()},
)
@@ -164,13 +179,16 @@ def main(argv: Sequence[str] | None = None) -> int:
_write_timestamped_line(log_file, f"failed to start stderr-timestamped command: {exc}")
return 127
- assert proc.stderr is not None
+ assert proc.stdout is not None and proc.stderr is not None
+ stdout_pump = threading.Thread(target=_copy_stdout_with_timestamps, args=(proc.stdout,), daemon=True)
+ stdout_pump.start()
previous_handlers = _install_signal_forwarders(proc)
try:
_copy_stderr_with_timestamps(proc.stderr, log_path)
# Keep forwarding until the child has actually exited: a signal that lands between
# its stderr EOF and wait() would otherwise kill the wrapper with the default action.
returncode = proc.wait()
+ stdout_pump.join(_STDOUT_DRAIN_TIMEOUT_S)
finally:
proc.stderr.close()
for signum, handler in previous_handlers.items():
diff --git a/tests/hermes_cli/test_gateway_service.py b/tests/hermes_cli/test_gateway_service.py
index ddfb2ee4e50..c18e0fed126 100644
--- a/tests/hermes_cli/test_gateway_service.py
+++ b/tests/hermes_cli/test_gateway_service.py
@@ -1756,6 +1756,33 @@ class TestProfileArg:
assert int(stdout_log.read_text()) == wrapper.pid
assert stderr_log.read_text() == ""
+ @pytest.mark.platforms("macos")
+ def test_launchd_command_path_timestamps_gateway_stdout(self, tmp_path):
+ """gateway.log is also the logging handler's file: a raw print() through the plist's
+ osascript + stderr_timestamp chain must arrive stamped or ``--since`` cannot filter it."""
+ stdout_log = tmp_path / "gateway.log"
+ stderr_log = tmp_path / "gateway.error.log"
+ command = [
+ sys.executable, "-m", "hermes_cli.stderr_timestamp", "--error-log", str(stderr_log), "--",
+ sys.executable, "-c", "print('[whatsapp] Bridge started on port 3000')",
+ ]
+
+ wrapper = subprocess.Popen(
+ launchd_program_arguments(command, stdout_log, stderr_log), start_new_session=True
+ )
+ try:
+ returncode = wrapper.wait(timeout=30)
+ finally:
+ if wrapper.poll() is None:
+ os.killpg(wrapper.pid, signal.SIGKILL)
+ wrapper.wait()
+
+ assert returncode == 0
+ assert re.fullmatch(
+ r"\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2},\d{3} \[whatsapp\] Bridge started on port 3000\n",
+ stdout_log.read_text(encoding="utf-8"),
+ )
+
def test_launchd_plist_path_uses_real_user_home_not_profile_home(self, tmp_path, monkeypatch):
profile_dir = tmp_path / ".hermes" / "profiles" / "orcha"
profile_dir.mkdir(parents=True)
diff --git a/tests/hermes_cli/test_source_launcher_publication.py b/tests/hermes_cli/test_source_launcher_publication.py
index 43a95986312..623b4c9e9b3 100644
--- a/tests/hermes_cli/test_source_launcher_publication.py
+++ b/tests/hermes_cli/test_source_launcher_publication.py
@@ -317,8 +317,12 @@ def _command_survives_generation_collection(tmp_path, monkeypatch, surface):
assert collect_generations(repo, min_age_seconds=0) == [selected.parent.parent / "old"]
result = subprocess.run(command, cwd=tmp_path, capture_output=True, text=True, timeout=30, encoding="utf-8")
assert result.returncode == 7, result.stderr
- assert json.loads(result.stdout)["value"] == "new"
- assert json.loads(result.stdout)["argv"] == args
+ receipt = result.stdout
+ if surface == "launchd":
+ # stderr_timestamp stamps the child's stdout lines ("YYYY-MM-DD HH:MM:SS,mmm ").
+ receipt = receipt.split(" ", 2)[2]
+ assert json.loads(receipt)["value"] == "new"
+ assert json.loads(receipt)["argv"] == args
@pytest.mark.parametrize("surface", ["published", "systemd", "launchd", "ssh", "legacy"])
diff --git a/tests/hermes_cli/test_stderr_timestamp.py b/tests/hermes_cli/test_stderr_timestamp.py
index 37f233ea21c..565f391003d 100644
--- a/tests/hermes_cli/test_stderr_timestamp.py
+++ b/tests/hermes_cli/test_stderr_timestamp.py
@@ -73,6 +73,38 @@ def test_main_timestamps_each_stderr_line(tmp_path):
assert lines[2] == "2026-07-15 12:34:56,789 already timestamped"
+def test_wrapper_timestamps_child_stdout_into_its_own_stdout(tmp_path):
+ """launchd appends the wrapper's stdout to gateway.log; a raw print() there has no stamp,
+ so ``hermes logs gateway --since`` can never filter it out."""
+ stdout_log = tmp_path / "gateway.log"
+ error_log = tmp_path / "gateway.error.log"
+ code = (
+ "import sys\n"
+ "print('[whatsapp] Bridge started on port 3000')\n"
+ "sys.stderr.write('stderr line\\n')\n"
+ "sys.stdout.write('2026-07-15 12:34:56,789 INFO already timestamped\\n')\n"
+ "sys.stdout.write('last line without newline')\n"
+ "sys.exit(7)\n"
+ )
+
+ with open(stdout_log, "ab") as out:
+ rc = subprocess.run(
+ [sys.executable, "-m", "hermes_cli.stderr_timestamp", "--error-log", str(error_log), "--",
+ sys.executable, "-c", code],
+ stdout=out,
+ timeout=30,
+ ).returncode
+
+ assert rc == 7
+ timestamp = r"\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2},\d{3}"
+ lines = stdout_log.read_text(encoding="utf-8").splitlines()
+ assert len(lines) == 3
+ assert re.fullmatch(f"{timestamp} \\[whatsapp\\] Bridge started on port 3000", lines[0])
+ assert lines[1] == "2026-07-15 12:34:56,789 INFO already timestamped"
+ assert re.fullmatch(f"{timestamp} last line without newline", lines[2])
+ assert re.fullmatch(f"{timestamp} stderr line", error_log.read_text(encoding="utf-8").strip())
+
+
def test_prepare_upgrades_stale_gateway_argv_under_launchd():
upgraded = stderr_timestamp._prepare_child_command(
_STALE_GATEWAY_ARGV, _LAUNCHD_ENV