Skip to content

The agent that grows with you

fix(cli): pin utf-8 decoding on all text-mode subprocess readers

Austin Pickettb00b4bb7f2b1
diff --git a/hermes_cli/boot_bootstrap.py b/hermes_cli/boot_bootstrap.py
index e8951b1d955..80c8e924965 100644
--- a/hermes_cli/boot_bootstrap.py
+++ b/hermes_cli/boot_bootstrap.py
@@ -46,7 +46,7 @@ def read_git_head(root: Path) -> str | None:
out = subprocess.run(
[git, "-C", str(root), "rev-parse", "HEAD"],
capture_output=True,
- text=True,
+ text=True, encoding="utf-8", errors="replace",
timeout=10,
check=False,
)
diff --git a/hermes_cli/gitlock.py b/hermes_cli/gitlock.py
index d7ee1a510b9..223bc066a25 100644
--- a/hermes_cli/gitlock.py
+++ b/hermes_cli/gitlock.py
@@ -134,7 +134,7 @@ def is_ancestor_of_head(repo_root: Path, rev: str) -> bool:
result = subprocess.run(
["git", "merge-base", "--is-ancestor", rev, "HEAD"],
cwd=str(repo_root),
- capture_output=True, text=True, timeout=10,
+ capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=10,
)
return result.returncode == 0
except Exception:
@@ -148,7 +148,7 @@ def _git_stdout_lines(repo_root: Path, args: List[str]) -> List[str]:
try:
result = subprocess.run(
["git", *args], cwd=str(repo_root),
- capture_output=True, text=True, timeout=10,
+ capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=10,
)
if result.returncode != 0:
return []
diff --git a/hermes_cli/kanban_pr_acceptance.py b/hermes_cli/kanban_pr_acceptance.py
index 953dfd3c58a..9a3b7bfada8 100644
--- a/hermes_cli/kanban_pr_acceptance.py
+++ b/hermes_cli/kanban_pr_acceptance.py
@@ -29,7 +29,7 @@ def _api(endpoint: str, *, query: str | None = None, paginate: bool = False):
if paginate:
command += ["--paginate", "--slurp"]
result = subprocess.run(command, stdin=subprocess.DEVNULL, capture_output=True,
- text=True, timeout=30, check=True)
+ text=True, encoding="utf-8", errors="replace", timeout=30, check=True)
value = json.loads(result.stdout)
if isinstance(value, dict) and value.get("errors"):
raise ValueError("GitHub returned incomplete GraphQL evidence")
diff --git a/hermes_cli/local_runtime/bootstrap.py b/hermes_cli/local_runtime/bootstrap.py
index ac77f12adce..fcc2cab169d 100644
--- a/hermes_cli/local_runtime/bootstrap.py
+++ b/hermes_cli/local_runtime/bootstrap.py
@@ -35,7 +35,7 @@ def _detect_gpu_vendor() -> str | None:
with suppress(OSError, subprocess.TimeoutExpired):
out = subprocess.run(
[smi, "--query-gpu=name", "--format=csv,noheader"],
- capture_output=True, text=True, timeout=10)
+ capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=10)
if out.returncode == 0 and out.stdout.strip():
return "nvidia " + out.stdout.strip().splitlines()[0]
return None
diff --git a/hermes_cli/local_runtime/hardware.py b/hermes_cli/local_runtime/hardware.py
index 9665eaf558d..3252e97744e 100644
--- a/hermes_cli/local_runtime/hardware.py
+++ b/hermes_cli/local_runtime/hardware.py
@@ -203,7 +203,7 @@ def _nvidia_vram() -> tuple[int, int] | None:
out = subprocess.run(
[exe, "--query-gpu=memory.total,memory.free",
"--format=csv,noheader,nounits"],
- capture_output=True, text=True, timeout=10)
+ capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=10)
if out.returncode != 0 or not out.stdout.strip():
return None
total_mib, free_mib = (int(x) for x in out.stdout.strip().splitlines()[0].split(","))
@@ -258,7 +258,7 @@ def _engine_device_pool() -> "tuple[int, bool | None] | None":
return None
exe = engine.binary
out = subprocess.run([str(exe), "--list-devices"], capture_output=True,
- text=True, timeout=30, cwd=str(exe.parent))
+ text=True, encoding="utf-8", errors="replace", timeout=30, cwd=str(exe.parent))
if out.returncode != 0:
return None
for line in (out.stdout + out.stderr).splitlines():
diff --git a/hermes_cli/macos_signing.py b/hermes_cli/macos_signing.py
index 3f7017f623e..f3027d4541f 100644
--- a/hermes_cli/macos_signing.py
+++ b/hermes_cli/macos_signing.py
@@ -29,7 +29,7 @@ def sign_managed_python(python: Path) -> bool:
[codesign, "--force", "--deep", "--sign", "-", "--timestamp=none",
"--identifier", _IDENTIFIER, "--requirements",
f'=designated => identifier "{_IDENTIFIER}"', str(python)],
- check=False, capture_output=True, text=True,
+ check=False, capture_output=True, text=True, encoding="utf-8", errors="replace",
)
if signed.returncode != 0:
logger.warning("could not stably sign managed Python %s: %s", python,
@@ -37,7 +37,7 @@ def sign_managed_python(python: Path) -> bool:
return False
verified = subprocess.run(
[codesign, "--verify", "--deep", "--strict", str(python)],
- check=False, capture_output=True, text=True,
+ check=False, capture_output=True, text=True, encoding="utf-8", errors="replace",
)
if verified.returncode != 0:
logger.warning("macOS signature verification failed for managed Python %s: %s", python,
diff --git a/hermes_cli/macos_tcc_anchor.py b/hermes_cli/macos_tcc_anchor.py
index 3fc8f116dab..004d43dce62 100644
--- a/hermes_cli/macos_tcc_anchor.py
+++ b/hermes_cli/macos_tcc_anchor.py
@@ -256,7 +256,7 @@ def _passes_boot_gate(staged: Path, venv_dir: Path) -> bool:
proc = subprocess.run(
[str(staged), "-c", "import encodings, sys; print(sys.prefix)"],
capture_output=True,
- text=True,
+ text=True, encoding="utf-8", errors="replace",
timeout=30,
env=env,
)
diff --git a/hermes_cli/main_desktop.py b/hermes_cli/main_desktop.py
index dcfceb79a78..d90066ca0e4 100644
--- a/hermes_cli/main_desktop.py
+++ b/hermes_cli/main_desktop.py
@@ -555,7 +555,7 @@ def _desktop_macos_has_valid_real_signature(app: Path) -> bool:
return False
try:
info = subprocess.run(
- [codesign, "-dv", str(app)], check=False, capture_output=True, text=True)
+ [codesign, "-dv", str(app)], check=False, capture_output=True, text=True, encoding="utf-8", errors="replace")
output = f"{info.stdout}\n{info.stderr}"
if info.returncode != 0 or "TeamIdentifier=" not in output or "TeamIdentifier=not set" in output:
return False
@@ -636,7 +636,7 @@ def _macos_legacy_adhoc_resign(codesign: str, app: Path) -> bool:
prompt is recoverable, deletion is not)."""
try:
result = subprocess.run(
- [codesign, "--force", "--deep", "--sign", "-", str(app)], check=False, capture_output=True, text=True
+ [codesign, "--force", "--deep", "--sign", "-", str(app)], check=False, capture_output=True, text=True, encoding="utf-8", errors="replace"
)
if result.returncode != 0:
print(
@@ -644,7 +644,7 @@ def _macos_legacy_adhoc_resign(codesign: str, app: Path) -> bool:
"leaving safeStorage keychain item untouched)"
)
return False
- if _codesign_verify(codesign, app, check=False, text=True).returncode != 0:
+ if _codesign_verify(codesign, app, check=False, text=True, encoding="utf-8", errors="replace").returncode != 0:
print(
" (warning: legacy ad-hoc re-sign did not pass strict verification; "
"leaving safeStorage keychain item untouched)"
@@ -713,7 +713,7 @@ def _macos_codesigning_identity_valid(security: str, identity: str) -> bool:
shows untrusted certs codesign refuses. Idempotency probe + postcondition. Never raises."""
try:
result = subprocess.run(
- [security, "find-identity", "-v", "-p", "codesigning"], capture_output=True, text=True, check=False,
+ [security, "find-identity", "-v", "-p", "codesigning"], capture_output=True, text=True, encoding="utf-8", errors="replace", check=False,
)
except Exception:
return False
@@ -762,7 +762,7 @@ def _macos_create_signing_identity(
"-P", "hermeslocal",
"-T", codesign, "-T", "/usr/bin/codesign_allocate",
],
- capture_output=True, text=True, check=False)
+ capture_output=True, text=True, encoding="utf-8", errors="replace", check=False)
_export_p12([])
imported = _import_p12()
@@ -781,7 +781,7 @@ def _macos_create_signing_identity(
# command exists to front-load.
trusted = subprocess.run(
[security, "add-trusted-cert", "-r", "trustRoot", "-p", "codeSign", "-k", keychain, str(crt)],
- capture_output=True, text=True, check=False)
+ capture_output=True, text=True, encoding="utf-8", errors="replace", check=False)
if trusted.returncode != 0:
print(
" (could not trust the certificate for code signing: "
diff --git a/hermes_cli/plugin_catalog.py b/hermes_cli/plugin_catalog.py
index 05bc1664cce..0f81d1b71e8 100644
--- a/hermes_cli/plugin_catalog.py
+++ b/hermes_cli/plugin_catalog.py
@@ -385,7 +385,7 @@ def in_tree_catalog_time() -> Optional[float]:
try:
import subprocess
out = subprocess.run(["git", "-C", str(root), "log", "-1", "--format=%ct", "--", "plugin-catalog"],
- capture_output=True, text=True, timeout=10, stdin=subprocess.DEVNULL)
+ capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=10, stdin=subprocess.DEVNULL)
resolved = float(out.stdout.strip()) if out.returncode == 0 and out.stdout.strip() else None
except Exception as exc:
logger.debug("Plugin catalog: could not date the in-tree catalog: %s", exc)
diff --git a/hermes_cli/plugin_validate.py b/hermes_cli/plugin_validate.py
index d43b6cd8ad2..98fa14a3e90 100644
--- a/hermes_cli/plugin_validate.py
+++ b/hermes_cli/plugin_validate.py
@@ -337,7 +337,7 @@ def _run_capability_probe(plugin_dir: Path, manifest: dict) -> Tuple[Optional[di
json.dumps(_probe_options(manifest)),
],
capture_output=True,
- text=True,
+ text=True, encoding="utf-8", errors="replace",
timeout=_PROBE_TIMEOUT,
env=env,
)
diff --git a/hermes_cli/plugins_provenance.py b/hermes_cli/plugins_provenance.py
index c7d2242869a..350912068d5 100644
--- a/hermes_cli/plugins_provenance.py
+++ b/hermes_cli/plugins_provenance.py
@@ -69,7 +69,7 @@ def _git_origin_url(plugin_dir: Path) -> Optional[str]:
proc = subprocess.run(
[git, "-C", str(plugin_dir), "remote", "get-url", "origin"],
capture_output=True,
- text=True,
+ text=True, encoding="utf-8", errors="replace",
timeout=10,
)
if proc.returncode == 0:
diff --git a/hermes_cli/plugins_updates.py b/hermes_cli/plugins_updates.py
index c757b23c2e5..aac8312bbf0 100644
--- a/hermes_cli/plugins_updates.py
+++ b/hermes_cli/plugins_updates.py
@@ -393,7 +393,7 @@ def default_ls_remote(source: str) -> str:
proc = subprocess.run(
[_resolve_git_executable() or "git", "ls-remote", source, "HEAD"],
capture_output=True,
- text=True,
+ text=True, encoding="utf-8", errors="replace",
timeout=30,
)
if proc.returncode != 0:
diff --git a/hermes_cli/source_build.py b/hermes_cli/source_build.py
index a002bfa769f..656b82ac54c 100644
--- a/hermes_cli/source_build.py
+++ b/hermes_cli/source_build.py
@@ -19,7 +19,7 @@ def source_product_current(project_root: Path, product: str, out: Path) -> bool:
result = subprocess.run(
[node, str(project_root / "scripts/build/freshness.mjs"),
"--source", str(project_root), "--product", product, "--out", str(out)],
- cwd=project_root, env=env, capture_output=True, text=True, check=True,
+ cwd=project_root, env=env, capture_output=True, text=True, encoding="utf-8", errors="replace", check=True,
)
return result.stdout.strip() == "true"
except (OSError, subprocess.SubprocessError):
diff --git a/hermes_cli/sqlite_runtime.py b/hermes_cli/sqlite_runtime.py
index d46ef77fb3e..56e119f565b 100644
--- a/hermes_cli/sqlite_runtime.py
+++ b/hermes_cli/sqlite_runtime.py
@@ -76,7 +76,7 @@ def probe_sqlite_runtime(python: str | Path, *, timeout: float = 30.0) -> SQLite
"""Probe SQLite in *python*, never the caller's linked SQLite."""
try:
result = subprocess.run(
- [str(python), "-I", "-c", _PROBE_SCRIPT], capture_output=True, text=True, timeout=timeout,
+ [str(python), "-I", "-c", _PROBE_SCRIPT], capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=timeout,
check=False, env=isolated_interpreter_env())
except (OSError, subprocess.TimeoutExpired):
return None
diff --git a/hermes_cli/update_cmd_fleet_checkout.py b/hermes_cli/update_cmd_fleet_checkout.py
index c758f678b91..b67b40d4e14 100644
--- a/hermes_cli/update_cmd_fleet_checkout.py
+++ b/hermes_cli/update_cmd_fleet_checkout.py
@@ -34,7 +34,7 @@ def checkout_contains(sha: str) -> bool:
try:
result = subprocess.run(
["git", "merge-base", "--is-ancestor", sha, "HEAD"],
- cwd=_m().PROJECT_ROOT, capture_output=True, text=True, timeout=10,
+ cwd=_m().PROJECT_ROOT, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=10,
)
return result.returncode == 0
except Exception as exc:
diff --git a/hermes_cli/update_lock.py b/hermes_cli/update_lock.py
index 1c5a45860cd..04b56f06d5e 100644
--- a/hermes_cli/update_lock.py
+++ b/hermes_cli/update_lock.py
@@ -158,7 +158,7 @@ def _stdlib_parent_pid(pid: int) -> int | None:
else:
out = subprocess.run(
["ps", "-o", "ppid=", "-p", str(pid)],
- capture_output=True, text=True, check=True, timeout=5,
+ capture_output=True, text=True, encoding="utf-8", errors="replace", check=True, timeout=5,
).stdout
value = int(out.strip() or -1)
return value if value > 0 else None
diff --git a/hermes_cli/version_info.py b/hermes_cli/version_info.py
index c31256c665f..e7298fc0c2f 100644
--- a/hermes_cli/version_info.py
+++ b/hermes_cli/version_info.py
@@ -58,7 +58,7 @@ def _derived_version(
def _run_git(repo_dir: Path, *args: str) -> str | None:
try:
result = subprocess.run(
- ["git", *args], capture_output=True, text=True, timeout=3, cwd=str(repo_dir)
+ ["git", *args], capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=3, cwd=str(repo_dir)
)
except (OSError, subprocess.SubprocessError):
return None
@@ -220,7 +220,7 @@ def _git_version_info(repo_dir: Path, *, include_untracked: bool = False) -> Ver
dirty_result = subprocess.run(
status_command,
capture_output=True,
- text=True,
+ text=True, encoding="utf-8", errors="replace",
timeout=3,
cwd=str(repo_dir),
)
diff --git a/hermes_cli/web_routers/local_models.py b/hermes_cli/web_routers/local_models.py
index 399fc66b794..1751b40988d 100644
--- a/hermes_cli/web_routers/local_models.py
+++ b/hermes_cli/web_routers/local_models.py
@@ -528,7 +528,7 @@ def _nvidia_smi_facts() -> dict:
if not smi_exe:
return {}
smi = subprocess.run([smi_exe, "--query-gpu=name,utilization.gpu,memory.used", "--format=csv,noheader,nounits"],
- capture_output=True, text=True, timeout=5)
+ capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=5)
if smi.returncode != 0 or not smi.stdout.strip():
return {}
name, util, used_mib = (x.strip() for x in smi.stdout.strip().splitlines()[0].split(","))
diff --git a/tests/hermes_cli/test_subprocess_text_encoding.py b/tests/hermes_cli/test_subprocess_text_encoding.py
new file mode 100644
index 00000000000..556c07e8f41
--- /dev/null
+++ b/tests/hermes_cli/test_subprocess_text_encoding.py
@@ -0,0 +1,41 @@
+"""Guard: every text-mode subprocess call in hermes_cli pins utf-8 decoding (#55658).
+
+On Windows, ``text=True`` without ``encoding`` decodes child output with the ANSI
+code page (e.g. 'gbk'), and non-ASCII bytes raise UnicodeDecodeError inside
+``subprocess._readerthread``, killing the backend before it becomes ready.
+"""
+
+from __future__ import annotations
+
+import ast
+from pathlib import Path
+
+import pytest
+
+HERMES_CLI = Path(__file__).resolve().parents[2] / "hermes_cli"
+
+
+def _iter_call_text_nodes(tree: ast.AST) -> list[ast.Call]:
+ return [n for n in ast.walk(tree) if isinstance(n, ast.Call)]
+
+
+ "path",
+ sorted(p for p in HERMES_CLI.rglob("*.py") if "__pycache__" not in p.parts and "test" not in p.name),
+ ids=lambda p: str(p.relative_to(HERMES_CLI)),
+)
+def test_text_mode_subprocess_calls_pin_utf8(path: Path) -> None:
+ tree = ast.parse(path.read_text(encoding="utf-8"))
+ for call in _iter_call_text_nodes(tree):
+ names = {kw.arg for kw in call.keywords}
+ for kw in call.keywords:
+ if (
+ kw.arg == "text"
+ and isinstance(kw.value, ast.Constant)
+ and kw.value.value is True
+ ):
+ assert "encoding" in names, (
+ f"{path.relative_to(HERMES_CLI)}:{kw.lineno}: subprocess text=True "
+ "without encoding= — on Windows this decodes with the ANSI code page "
+ "and can raise UnicodeDecodeError on non-ASCII child output (#55658)"
+ )