The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(footguns): utf-8-sig on all reads flagged by check-windows-footguns (164 sites)
ethernet25ce047f9870
diff --git a/acp_adapter/edit_approval.py b/acp_adapter/edit_approval.pyindex 0e78915848f..f60c55ddce6 100644--- a/acp_adapter/edit_approval.py+++ b/acp_adapter/edit_approval.py@@ -59,7 +59,7 @@ def reset_edit_approval_requester(token: Token) -> None:def _read_text_if_exists(path: str) -> str | None:p = Path(path).expanduser()if p.is_file():- return p.read_text(encoding="utf-8", errors="replace")+ return p.read_text(encoding=utf-8-sig, errors="replace")if p.exists():raise OSError(f"Cannot edit non-file path: {path}")return Nonediff --git a/agent/learning_mutations.py b/agent/learning_mutations.pyindex 1024fdb12e6..f1962639f85 100644--- a/agent/learning_mutations.py+++ b/agent/learning_mutations.py@@ -210,7 +210,7 @@ def _skill_detail(node_id: str) -> dict[str, Any]:skill_md = Path(found["path"]) / "SKILL.md"if not skill_md.exists():return {"ok": False, "message": f"SKILL.md missing for '{node_id}'"}- return {"ok": True, "kind": "skill", "id": node_id, "label": node_id, "content": skill_md.read_text(encoding="utf-8")}+ return {"ok": True, "kind": "skill", "id": node_id, "label": node_id, "content": skill_md.read_text(encoding="utf-8-sig")}# ── Delete ──────────────────────────────────────────────────────────────────diff --git a/agent/prompt_builder.py b/agent/prompt_builder.pyindex 70fa4909320..6cf5d70dd0c 100644--- a/agent/prompt_builder.py+++ b/agent/prompt_builder.py@@ -1231,7 +1231,7 @@ def _read_category_descriptions(root: Path, log_fmt: str) -> dict[str, str]:found: dict[str, str] = {}for desc_file in iter_skill_index_files(root, "DESCRIPTION.md"):try:- cat_desc = parse_frontmatter(desc_file.read_text(encoding="utf-8"))[0].get("description")+ cat_desc = parse_frontmatter(desc_file.read_text(encoding="utf-8-sig"))[0].get("description")if cat_desc:rel = desc_file.relative_to(root)found["/".join(rel.parts[:-1]) if len(rel.parts) > 1 else "general"] = str(cat_desc).strip().strip("'\"")diff --git a/agent/proxy_sources/iron_proxy.py b/agent/proxy_sources/iron_proxy.pyindex 37e3280365d..a6df4deb8fa 100644--- a/agent/proxy_sources/iron_proxy.py+++ b/agent/proxy_sources/iron_proxy.py@@ -382,7 +382,7 @@ def mint_proxy_token(prefix: str = "hermes-proxy") -> str:def _read_text_or_none(p: Path) -> Optional[str]:"""Stripped file contents, or None when missing/unreadable/empty."""try:- return p.read_text(encoding="utf-8").strip() or None+ return p.read_text(encoding="utf-8-sig").strip() or Noneexcept OSError:return Nonediff --git a/agent/session_persistence.py b/agent/session_persistence.pyindex 544883d6a14..eb11f2b6603 100644--- a/agent/session_persistence.py+++ b/agent/session_persistence.py@@ -278,7 +278,7 @@ def _existing_log_is_larger(log_file, count: int) -> bool:if not log_file.exists():return Falsetry:- existing = json.loads(log_file.read_text(encoding="utf-8"))+ existing = json.loads(log_file.read_text(encoding=utf-8-sig))existing_count = existing.get("message_count", len(existing.get("messages", [])))except Exception:return Falsediff --git a/agent/shell_hooks.py b/agent/shell_hooks.pyindex ae261518ff1..17eec512215 100644--- a/agent/shell_hooks.py+++ b/agent/shell_hooks.py@@ -486,7 +486,7 @@ def _locked_update_approvals() -> Iterator[Dict[str, Any]]:if fcntl is None: # pragma: no cover — non-POSIX fallbackstack.enter_context(_allowlist_write_lock)else:- lock_fh = stack.enter_context(open(p.with_suffix(p.suffix + ".lock"), "a+", encoding="utf-8"))+ lock_fh = stack.enter_context(open(p.with_suffix(p.suffix + ".lock"), "a+", encoding="utf-8")) # windows-footgun: ok (write/append mode, not a read)fcntl.flock(lock_fh.fileno(), fcntl.LOCK_EX)stack.callback(_flock_unlock, lock_fh)data = load_allowlist()diff --git a/agent/subdirectory_hints.py b/agent/subdirectory_hints.pyindex 68512719cb1..06c70e03213 100644--- a/agent/subdirectory_hints.py+++ b/agent/subdirectory_hints.py@@ -45,7 +45,7 @@ def _first_hint_file(directory: Path):try:if not candidate.is_file():continue- content = candidate.read_text(encoding="utf-8").strip()+ content = candidate.read_text(encoding="utf-8-sig").strip()except (OSError, UnicodeDecodeError):continuereturn candidate, contentdiff --git a/cron/scheduler.py b/cron/scheduler.pyindex 81fdc228ae1..7719c871d81 100644--- a/cron/scheduler.py+++ b/cron/scheduler.py@@ -1431,7 +1431,7 @@ def _load_prefill_messages(cfg: dict, job_id: str) -> Optional[list]:if not pfpath.exists():return Nonetry:- with open(pfpath, "r", encoding="utf-8") as _pf:+ with open(pfpath, "r", encoding="utf-8-sig") as _pf:prefill_messages = json.load(_pf)return prefill_messages if isinstance(prefill_messages, list) else Noneexcept Exception as e:diff --git a/cron/scheduler_prompt.py b/cron/scheduler_prompt.pyindex 91d673649d6..28f54390af0 100644--- a/cron/scheduler_prompt.py+++ b/cron/scheduler_prompt.py@@ -93,7 +93,7 @@ def _inject_context_from(job: dict, prompt: str) -> tuple[str, bool]:)if not output_files:continue # silent skip — no output yet- latest_output = output_files[0].read_text(encoding="utf-8").strip()+ latest_output = output_files[0].read_text(encoding=utf-8-sig).strip()if len(latest_output) > _MAX_CONTEXT_CHARS:latest_output = (latest_output[:_MAX_CONTEXT_CHARS] + "\n\n[... output truncated ...]")diff --git a/cron/scheduler_script.py b/cron/scheduler_script.pyindex 04e66ae8eff..55a67153e70 100644--- a/cron/scheduler_script.py+++ b/cron/scheduler_script.py@@ -104,7 +104,7 @@ def _get_session_db_timeout() -> float:def _read_windows_pyvenv_cfg(venv_dir: Path) -> dict[str, str]:try:- lines = (venv_dir / "pyvenv.cfg").read_text(encoding="utf-8").splitlines()+ lines = (venv_dir / "pyvenv.cfg").read_text(encoding="utf-8-sig").splitlines()except OSError:return {}return {diff --git a/gateway/config_loader.py b/gateway/config_loader.pyindex 52167d67bdd..63d8268e84a 100644--- a/gateway/config_loader.py+++ b/gateway/config_loader.py@@ -25,7 +25,7 @@ def load_legacy_gateway_json(home: Path) -> Any:if not path.exists():return {}try:- with open(path, "r", encoding="utf-8") as f:+ with open(path, "r", encoding="utf-8-sig") as f:data = json.load(f) or {}logger.info("Loaded legacy %s — consider moving settings to config.yaml", path)return data@@ -343,7 +343,7 @@ def load_yaml_layer(home: Path, gw_data: dict) -> None:config_yaml_path = home / "config.yaml"if not config_yaml_path.exists():return- with open(config_yaml_path, encoding="utf-8") as f:+ with open(config_yaml_path, encoding="utf-8-sig") as f:yaml_cfg = yaml.safe_load(f) or {}# Managed scope: overlay administrator-pinned values (this loader bypassesdiff --git a/gateway/kanban_watchers_common.py b/gateway/kanban_watchers_common.pyindex c690c9f8bef..eb0bca88a41 100644--- a/gateway/kanban_watchers_common.py+++ b/gateway/kanban_watchers_common.py@@ -129,7 +129,7 @@ def _acquire_singleton_lock(lock_path) -> "tuple[Optional[object], str]":return None, "unavailable"try:Path(lock_path).parent.mkdir(parents=True, exist_ok=True)- handle = open(str(lock_path), "a+", encoding="utf-8")+ handle = open(str(lock_path), "a+", encoding="utf-8") # windows-footgun: ok (append-mode lock handle, write not read)except OSError:return None, "unavailable"if not _try_acquire_file_lock(handle):diff --git a/gateway/platforms/helpers.py b/gateway/platforms/helpers.pyindex 32717f83c5a..224773ecd6a 100644--- a/gateway/platforms/helpers.py+++ b/gateway/platforms/helpers.py@@ -96,7 +96,7 @@ class ThreadParticipationTracker:def _load(self) -> list[str]:try:- data = json.loads(self._state_path().read_text(encoding="utf-8"))+ data = json.loads(self._state_path().read_text(encoding=utf-8-sig))except Exception:return []return [str(thread_id) for thread_id in data] if isinstance(data, list) else []diff --git a/gateway/platforms/whatsapp_cloud.py b/gateway/platforms/whatsapp_cloud.pyindex f8ca5fea4da..d8d924d53a5 100644--- a/gateway/platforms/whatsapp_cloud.py+++ b/gateway/platforms/whatsapp_cloud.py@@ -950,7 +950,7 @@ class WhatsAppCloudAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):if file_size > _MAX_TEXT_INJECT_BYTES:logger.info("[whatsapp_cloud] skipping text injection for %s (%d bytes > %d)", doc, file_size, _MAX_TEXT_INJECT_BYTES)continue- injection = f"[Content of {doc.name}]:\n{doc.read_text(encoding='utf-8', errors='replace')}"+ injection = f"[Content of {doc.name}]:\n{doc.read_text(encoding='utf-8-sig', errors='replace')}"body = f"{injection}\n\n{body}" if body else injectionexcept OSError:logger.exception("[whatsapp_cloud] failed to read document text: %s", doc)diff --git a/gateway/run.py b/gateway/run.pyindex 57de3dd0f4c..0f15ed3e959 100644--- a/gateway/run.py+++ b/gateway/run.py@@ -2610,7 +2610,7 @@ def _skill_slug_from_frontmatter(skill_md: Path) -> tuple[str | None, str | None"""Derive ``(slug, declared_name)`` from a SKILL.md; ``(None, None)`` if unreadable or no ``name:``.Matches ``scan_skill_commands``: the slug comes from frontmatter ``name:``, NOT the directory."""try:- content = skill_md.read_text(encoding="utf-8", errors="replace")+ content = skill_md.read_text(encoding="utf-8-sig", errors="replace")except Exception:return None, Nonecontent = content.lstrip("\ufeff") # tolerate UTF-8 BOM (Windows editors)@@ -2720,7 +2720,7 @@ def _load_gateway_config(config_path: "Path | None" = None) -> dict:try:if config_path.exists():import yaml- with open(config_path, 'r', encoding='utf-8') as f:+ with open(config_path, 'r', encoding='utf-8-sig') as f:raw = yaml.safe_load(f) or {}except Exception:logger.debug("Could not load gateway config from %s", config_path)@@ -5355,7 +5355,7 @@ def main():config = Noneif args.config:import yaml- with open(args.config, encoding="utf-8") as f:+ with open(args.config, encoding="utf-8-sig") as f:config = GatewayConfig.from_dict(yaml.safe_load(f) or {})# start_gateway() completes teardown before returning/raising SystemExit; force-exit after so adiff --git a/gateway/run_busy.py b/gateway/run_busy.pyindex 3fcf447eb35..37d20c016d3 100644--- a/gateway/run_busy.py+++ b/gateway/run_busy.py@@ -985,7 +985,7 @@ class GatewayBusySessionMixin:self._booted_from_restart = Falsereturn Truereturn False- data = json.loads(marker_path.read_text(encoding="utf-8"))+ data = json.loads(marker_path.read_text(encoding="utf-8-sig"))except Exception:return Falsediff --git a/gateway/run_config_loaders.py b/gateway/run_config_loaders.pyindex 4bc0e1ed6d3..3e49ff6072e 100644--- a/gateway/run_config_loaders.py+++ b/gateway/run_config_loaders.py@@ -76,7 +76,7 @@ class GatewayConfigLoadersMixin:logger.warning("Prefill messages file not found: %s", path)return []try:- with open(path, "r", encoding="utf-8") as f:+ with open(path, "r", encoding=utf-8-sig) as f:data = json.load(f)if not isinstance(data, list):logger.warning("Prefill messages file must contain a JSON array: %s", path)diff --git a/gateway/run_notifications.py b/gateway/run_notifications.pyindex fc356f608c6..f897aa0570c 100644--- a/gateway/run_notifications.py+++ b/gateway/run_notifications.py@@ -367,7 +367,7 @@ class GatewayNotificationsMixin:if not path.exists():continuewith suppress(Exception):- pending = json.loads(path.read_text(encoding="utf-8"))+ pending = json.loads(path.read_text(encoding="utf-8-sig"))platform_str = pending.get("platform")chat_id = pending.get("chat_id")session_key = pending.get("session_key")@@ -406,7 +406,7 @@ class GatewayNotificationsMixin:@staticmethoddef _update_exit_code(paths: "_UpdatePaths") -> int:- return int(paths.exit_code.read_text(encoding="utf-8").strip() or "1")+ return int(paths.exit_code.read_text(encoding="utf-8-sig").strip() or "1")@staticmethoddef _read_update_output_since(path: Path, offset: int) -> tuple[str, int]:@@ -514,7 +514,7 @@ class GatewayNotificationsMixin:getattr(_pending_state, "persistent", None), "update_prompt_pending", False):try:- prompt_data = json.loads(paths.prompt.read_text(encoding="utf-8"))+ prompt_data = json.loads(paths.prompt.read_text(encoding="utf-8-sig"))prompt_text = prompt_data.get("prompt", "")if prompt_text:await _flush_buffer() # user sees context before the prompt@@ -559,7 +559,7 @@ class GatewayNotificationsMixin:return Trueelif not paths.claimed.exists():return True- pending = json.loads(paths.claimed.read_text(encoding="utf-8"))+ pending = json.loads(paths.claimed.read_text(encoding="utf-8-sig"))platform_str = pending.get("platform")chat_id = pending.get("chat_id")if not paths.exit_code.exists():@@ -604,7 +604,7 @@ class GatewayNotificationsMixin:if not notify_path.exists():return Nonetry:- data = json.loads(notify_path.read_text(encoding="utf-8"))+ data = json.loads(notify_path.read_text(encoding="utf-8-sig"))platform_str = data.get("platform")chat_id = data.get("chat_id")thread_id = data.get("thread_id")diff --git a/gateway/run_shutdown.py b/gateway/run_shutdown.pyindex 6a16d4674a1..8bd1b7bfcdc 100644--- a/gateway/run_shutdown.py+++ b/gateway/run_shutdown.py@@ -1050,7 +1050,7 @@ class GatewayShutdownMixin:def _read_json_counts(path: Path) -> Optional[dict]:"""Parsed counter dict, or None when the file is missing/unreadable (no exists() pre-check needed)."""try:- return json.loads(path.read_text(encoding="utf-8"))+ return json.loads(path.read_text(encoding="utf-8-sig"))except Exception:return Nonediff --git a/gateway/run_startup.py b/gateway/run_startup.pyindex b20d49e66a3..ff83ebcd0aa 100644--- a/gateway/run_startup.py+++ b/gateway/run_startup.py@@ -640,7 +640,7 @@ class GatewayStartupMixin:from gateway.run import get_hermes_homelog_dir = getattr(self.config, "log_dir", None) or os.path.join(str(get_hermes_home()), "logs")os.makedirs(log_dir, exist_ok=True)- return open(os.path.join(log_dir, "gateway_faulthandler.log"), "a", encoding="utf-8")+ return open(os.path.join(log_dir, "gateway_faulthandler.log"), "a", encoding="utf-8") # windows-footgun: ok (append log writer, not a read)def _start_install_faulthandler(self) -> None:"""Enable faulthandler (stderr or a log file) plus the SIGUSR2 stack-dump hook."""diff --git a/gateway/run_voice.py b/gateway/run_voice.pyindex 6d40cc813a5..b1fdad2e148 100644--- a/gateway/run_voice.py+++ b/gateway/run_voice.py@@ -55,7 +55,7 @@ class GatewayVoiceMixin:def _load_voice_modes(self) -> Dict[str, str]:try:- data = json.loads(self._VOICE_MODE_PATH.read_text(encoding="utf-8"))+ data = json.loads(self._VOICE_MODE_PATH.read_text(encoding=utf-8-sig))except (FileNotFoundError, json.JSONDecodeError, OSError):return {}if not isinstance(data, dict):diff --git a/gateway/session_persistence.py b/gateway/session_persistence.pyindex 95c0ef57571..8cba09f258c 100644--- a/gateway/session_persistence.py+++ b/gateway/session_persistence.py@@ -283,7 +283,7 @@ class SessionPersistenceMixin:if not sessions_file.exists():returntry:- with open(sessions_file, "r", encoding="utf-8") as f:+ with open(sessions_file, "r", encoding="utf-8-sig") as f:data = json.load(f)imported = 0for key, entry_data in data.items():diff --git a/gateway/status.py b/gateway/status.pyindex ffdf5925adc..6996c659399 100644--- a/gateway/status.py+++ b/gateway/status.py@@ -632,7 +632,7 @@ def _pid_exists(pid: int) -> bool:def _posix_is_zombie(pid: int) -> bool:"""Zombie via ``/proc/<pid>/stat`` field 3, or ``ps -o state=`` without /proc (macOS/BSD)."""try:- stat_fields = Path(f"/proc/{pid}/stat").read_text(encoding="utf-8").split()+ stat_fields = Path(f"/proc/{pid}/stat").read_text(encoding="utf-8-sig").split()return len(stat_fields) > 2 and stat_fields[2] == "Z"except FileNotFoundError:with contextlib.suppress(Exception):@@ -1060,7 +1060,7 @@ def _scoped_lock_record_is_stale(existing: dict[str, Any], existing_pid: Optionadef _process_is_stopped(pid: int) -> bool:"""True for a stopped / tracing-stop state (T/t) in ``/proc/<pid>/status``."""with contextlib.suppress(OSError):- for line in Path(f"/proc/{pid}/status").read_text(encoding="utf-8").splitlines():+ for line in Path(f"/proc/{pid}/status").read_text(encoding="utf-8-sig").splitlines():if line.startswith("State:"):return line.split()[1] in {"T", "t"}return Falsediff --git a/hermes_cli/__init__.py b/hermes_cli/__init__.pyindex a80622fc71a..ffcaba121ab 100644--- a/hermes_cli/__init__.py+++ b/hermes_cli/__init__.py@@ -29,7 +29,7 @@ def _ensure_utf8():reconfigure(encoding="utf-8", errors="replace")else:# No reconfigure(): reopen the fd as UTF-8 (closefd=False keeps the original fd open).- new_stream = open(stream.fileno(), "w", encoding="utf-8", errors="replace",+ new_stream = open(stream.fileno(), "w", encoding="utf-8", errors="replace", # windows-footgun: ok (stdout re-open for write, not a read)buffering=1, closefd=False)setattr(sys, stream_name, new_stream)repaired = Truediff --git a/hermes_cli/auth.py b/hermes_cli/auth.pyindex 9983ae61414..5a44fbf702e 100644--- a/hermes_cli/auth.py+++ b/hermes_cli/auth.py@@ -576,7 +576,7 @@ def _file_lock(lock_path.write_text(" ", encoding="utf-8")except (OSError, PermissionError):pass- lock_file = stack.enter_context(lock_path.open("r+" if msvcrt else "a+", encoding="utf-8"))+ lock_file = stack.enter_context(lock_path.open("r+" if msvcrt else "a+", encoding=utf-8-sig))deadline = time.monotonic() + max(1.0, timeout_seconds)while True:try:@@ -1820,7 +1820,7 @@ def _external_process_auth_evidence(provider_id: str) -> tuple[bool, Optional[sttry:cli_config = os.path.expanduser("~/.copilot/config.json")if os.path.isfile(cli_config):- with open(cli_config, "r", encoding="utf-8", errors="ignore") as fh:+ with open(cli_config, "r", encoding=utf-8-sig, errors="ignore") as fh:raw = "\n".join(line for line in fh.read().splitlines() if not line.lstrip().startswith("//"))tokens = (json.loads(raw) if raw.strip() else {}).get("copilotTokens")diff --git a/hermes_cli/auth_oauth_grants.py b/hermes_cli/auth_oauth_grants.pyindex 2e4dc8da664..e771abb8a4b 100644--- a/hermes_cli/auth_oauth_grants.py+++ b/hermes_cli/auth_oauth_grants.py@@ -224,7 +224,7 @@ def _adopt_oauth_material(target: Dict[str, Any], winner: Dict[str, Any]) -> Dicdef _singleton_as_row(path: Path) -> Optional[Dict[str, Any]]:"""Read a ``.anthropic_oauth.json`` as a pool-row-shaped dict, or None."""try:- data = json.loads(path.read_text(encoding="utf-8"))+ data = json.loads(path.read_text(encoding="utf-8-sig"))except (OSError, ValueError):return Noneif not isinstance(data, dict) or not str(data.get("accessToken") or "").strip():diff --git a/hermes_cli/auth_qwen.py b/hermes_cli/auth_qwen.pyindex 59181f08edf..27b0662c1dd 100644--- a/hermes_cli/auth_qwen.py+++ b/hermes_cli/auth_qwen.py@@ -32,7 +32,7 @@ def _read_qwen_cli_tokens() -> Dict[str, Any]:if not auth_path.exists():raise _qwen_err("Qwen CLI credentials not found. Run 'qwen auth qwen-oauth' first.", "qwen_auth_missing")try:- data = json.loads(auth_path.read_text(encoding="utf-8"))+ data = json.loads(auth_path.read_text(encoding="utf-8-sig"))except Exception as exc:raise _qwen_err(f"Failed to read Qwen CLI credentials from {auth_path}: {exc}", "qwen_auth_read_failed",diff --git a/hermes_cli/backup.py b/hermes_cli/backup.pyindex 57e0a460a94..4d74c441cbe 100644--- a/hermes_cli/backup.py+++ b/hermes_cli/backup.py@@ -1219,7 +1219,7 @@ def list_quick_snapshots(limit: int = 20, hermes_home: Optional[Path] = None) ->manifest_path = d / "manifest.json"if manifest_path.exists():try:- results.append(json.loads(manifest_path.read_text(encoding="utf-8")))+ results.append(json.loads(manifest_path.read_text(encoding="utf-8-sig")))except (json.JSONDecodeError, OSError):results.append({"id": d.name, "file_count": 0, "total_size": 0})if len(results) >= limit:@@ -1242,7 +1242,7 @@ def restore_quick_snapshot(snapshot_id: str, hermes_home: Optional[Path] = None)manifest_path = snap_dir / "manifest.json"if not snap_dir.is_dir() or not manifest_path.exists():return False- with open(manifest_path, encoding="utf-8") as f:+ with open(manifest_path, encoding="utf-8-sig") as f:meta = json.load(f)snap_res, home_res = snap_dir.resolve(), home.resolve()restored = 0@@ -1386,7 +1386,7 @@ def _read_raw_yaml_dict(path: Path) -> Optional[Dict[str, Any]]:return Nonetry:import yaml- data = yaml.safe_load(path.read_text(encoding="utf-8"))+ data = yaml.safe_load(path.read_text(encoding="utf-8-sig"))except Exception:return Nonereturn data if isinstance(data, dict) else Nonediff --git a/hermes_cli/banner.py b/hermes_cli/banner.pyindex 64f633d0382..f448df17e42 100644--- a/hermes_cli/banner.py+++ b/hermes_cli/banner.py@@ -317,7 +317,7 @@ def _check_via_local_git(repo_dir: Path) -> Optional[int]:def _read_json(path: Path) -> Optional[dict]:"""Parse ``path`` as a JSON object; None when missing, unreadable, or not a dict."""- blob = _quiet(lambda: json.loads(path.read_text(encoding="utf-8")))+ blob = _quiet(lambda: json.loads(path.read_text(encoding=utf-8-sig)))return blob if isinstance(blob, dict) else Nonediff --git a/hermes_cli/browser_connect.py b/hermes_cli/browser_connect.pyindex 0731a8b4eef..1f38d3871e8 100644--- a/hermes_cli/browser_connect.py+++ b/hermes_cli/browser_connect.py@@ -569,7 +569,7 @@ def _sync_local_state(src: str, dst: str, source_profile: str) -> None:except OSError as e:logger.debug("real-profile snapshot: skipped Local State: %s", e)try:- with open(ls_dst, encoding="utf-8") as fh:+ with open(ls_dst, encoding="utf-8-sig") as fh:state = json.load(fh)prof = state.get("profile")if isinstance(prof, dict):diff --git a/hermes_cli/cli_info_mixin.py b/hermes_cli/cli_info_mixin.pyindex 786e2b224f7..6f112ed1111 100644--- a/hermes_cli/cli_info_mixin.py+++ b/hermes_cli/cli_info_mixin.py@@ -817,7 +817,7 @@ class CLIInfoMixin:self._config_mtime = mtimetry:- with open(cfg_path, encoding="utf-8") as f:+ with open(cfg_path, encoding="utf-8-sig") as f:new_cfg = _yaml.safe_load(f) or {}except Exception:returndiff --git a/hermes_cli/cli_stream_mixin.py b/hermes_cli/cli_stream_mixin.pyindex 0561ecffb63..c1b6055db25 100644--- a/hermes_cli/cli_stream_mixin.py+++ b/hermes_cli/cli_stream_mixin.py@@ -199,7 +199,7 @@ class CLIStreamMixin:# check and read (TOCTOU), silently dropping the input.try:# See #17666.- return path.read_text(encoding="utf-8")+ return path.read_text(encoding="utf-8-sig")except (OSError, IOError):logger.warning("Paste file gone or unreadable, returning placeholder: %s", path)return match.group(0)diff --git a/hermes_cli/config.py b/hermes_cli/config.pyindex e384a4dca44..194cc85dfd1 100644--- a/hermes_cli/config.py+++ b/hermes_cli/config.py@@ -281,7 +281,7 @@ def get_managed_system() -> Optional[str]:managed_marker = get_hermes_home() / ".managed"if marker is None and managed_marker.exists():try:- marker = managed_marker.read_text(encoding="utf-8", errors="replace").strip().lower()+ marker = managed_marker.read_text(encoding=utf-8-sig, errors="replace").strip().lower()except OSError:marker = ""if marker is None or marker in _IGNORED_MANAGED_VALUES:@@ -317,7 +317,7 @@ _SUPPORTED_INSTALL_METHODS = frozenset({"apt", "docker", "nix", "nixos", "home-mdef _install_method_stamp(path: Path) -> Optional[str]:try:- method = path.read_text(encoding="utf-8").strip().lower()+ method = path.read_text(encoding=utf-8-sig).strip().lower()except OSError:return Nonereturn method if method in _SUPPORTED_INSTALL_METHODS else None@@ -364,7 +364,7 @@ def detect_install_method(project_root: Optional[Path] = None) -> str:# A .git directory, or a ``gitdir:`` pointer file for worktrees.git_path = root / ".git"try:- if git_path.is_dir() or git_path.read_text(encoding="utf-8").strip().startswith("gitdir:"):+ if git_path.is_dir() or git_path.read_text(encoding=utf-8-sig).strip().startswith("gitdir:"):return "git"except OSError:pass@@ -470,7 +470,7 @@ def get_container_exec_info() -> Optional[dict]:try:info = {}- with open(get_hermes_home() / ".container-mode", "r", encoding="utf-8") as f:+ with open(get_hermes_home() / ".container-mode", "r", encoding="utf-8-sig") as f:for line in f:line = line.strip()if "=" in line and not line.startswith("#"):@@ -504,7 +504,7 @@ def require_parseable_user_config(*, ignore_user_config: bool = False) -> None:config_path = get_config_path()try:- with open(config_path, encoding="utf-8") as f:+ with open(config_path, encoding=utf-8-sig) as f:data = fast_safe_load(f)except FileNotFoundError:return@@ -602,7 +602,7 @@ def _is_container() -> bool:or os.path.exists("/.dockerenv")):return Truetry:- with open("/proc/1/cgroup", "r", encoding="utf-8") as f:+ with open("/proc/1/cgroup", "r", encoding=utf-8-sig) as f:cgroup_content = f.read()return any(marker in cgroup_content for marker in ("docker", "lxc", "kubepods"))except (OSError, IOError):@@ -627,7 +627,7 @@ def _ensure_default_soul_md(home: Path) -> None:soul_path = home / "SOUL.md"if soul_path.exists():try:- existing = soul_path.read_text(encoding="utf-8")+ existing = soul_path.read_text(encoding=utf-8-sig)except (OSError, UnicodeDecodeError):returnif not is_legacy_template_soul(existing):@@ -1042,7 +1042,7 @@ def check_config_version(*, raise_on_parse_error: bool = False) -> Tuple[int, inreturn latest, latesttry:- with open(config_path, encoding="utf-8") as f:+ with open(config_path, encoding=utf-8-sig) as f:config = fast_safe_load(f)except Exception as e:_warn_config_parse_failure(config_path, e)@@ -1918,7 +1918,7 @@ def _read_raw_config_impl(*, want_deepcopy: bool) -> Dict[str, Any]:return copy.deepcopy(cached[2]) if want_deepcopy else cached[2]try:- with open(config_path, encoding="utf-8") as f:+ with open(config_path, encoding=utf-8-sig) as f:data = fast_safe_load(f) or {}except Exception as e:_warn_config_parse_failure(config_path, e)@@ -1946,7 +1946,7 @@ def read_user_config_raw(config_path: Optional[Path] = None) -> Dict[str, Any]:if config_path is None:config_path = get_config_path()try:- with open(config_path, encoding="utf-8") as f:+ with open(config_path, encoding=utf-8-sig) as f:data = fast_safe_load(f) or {}except FileNotFoundError:return {}@@ -1984,7 +1984,7 @@ def require_readable_config_before_write(config_path: Optional[Path] = None) ->raise _refuse_overwrite(config_path, "cannot be accessed", exc, _FIX_PERMS) from exctry:- with open(config_path, encoding="utf-8") as f:+ with open(config_path, encoding=utf-8-sig) as f:loaded = fast_safe_load(f)except OSError as exc:raise _refuse_overwrite(config_path, "cannot be read", exc, _FIX_PERMS) from exc@@ -2219,7 +2219,7 @@ def _load_config_impl(*, want_deepcopy: bool) -> Dict[str, Any]:if user_sig is not None:try:- with open(config_path, encoding="utf-8") as f:+ with open(config_path, encoding=utf-8-sig) as f:user_config = fast_safe_load(f) or {}if "max_turns" in user_config:@@ -3817,7 +3817,7 @@ def _platform_plugin_manifests():if manifest_path is None:continuetry:- with open(manifest_path, "r", encoding="utf-8") as f:+ with open(manifest_path, "r", encoding=utf-8-sig) as f:manifest = fast_safe_load(f) or {}except Exception:continuediff --git a/hermes_cli/doctor_config.py b/hermes_cli/doctor_config.pyindex ffe30b665cc..e218a81fde5 100644--- a/hermes_cli/doctor_config.py+++ b/hermes_cli/doctor_config.py@@ -138,7 +138,7 @@ def _check_env_file(should_fix: bool, f: Finding) -> None:check_ok(f"{_DHH}/.env file exists")# UTF-8 first; latin-1 fallback for Windows Notepad/cp1252 files (matches env_loader._load_dotenv_with_fallback).try:- content = env_path.read_text(encoding="utf-8")+ content = env_path.read_text(encoding="utf-8-sig")except UnicodeDecodeError:content = env_path.read_text(encoding="latin-1")if not check_bool(_has_provider_env_config(content), "API key or custom endpoint configured", f"No API key found in {_DHH}/.env"):diff --git a/hermes_cli/doctor_platform.py b/hermes_cli/doctor_platform.pyindex 9b1f7edf2da..d12fe8f6fd5 100644--- a/hermes_cli/doctor_platform.py+++ b/hermes_cli/doctor_platform.py@@ -125,7 +125,7 @@ def _read_pyproject_version() -> str | None:"""Read the ``[project]`` version from pyproject.toml; None for installed wheels (no pyproject) or unreadable files."""from hermes_cli.doctor import PROJECT_ROOTtry:- text = (PROJECT_ROOT / "pyproject.toml").read_text(encoding="utf-8")+ text = (PROJECT_ROOT / "pyproject.toml").read_text(encoding="utf-8-sig")except OSError:return Nonein_project = Falsediff --git a/hermes_cli/doctor_state.py b/hermes_cli/doctor_state.pyindex 940a5453277..099936ec239 100644--- a/hermes_cli/doctor_state.py+++ b/hermes_cli/doctor_state.py@@ -116,7 +116,7 @@ def _check_directory_structure(should_fix: bool, f: Finding) -> None:# SOUL.md persona filesoul_path = hermes_home / "SOUL.md"if soul_path.exists():- lines = soul_path.read_text(encoding="utf-8").strip().splitlines()+ lines = soul_path.read_text(encoding="utf-8-sig").strip().splitlines()if any(l.strip() and not l.strip().startswith(("<!--", "-->", "#")) for l in lines):check_ok(f"{_DHH}/SOUL.md exists (persona configured)")else: # template comments only (no real content)@@ -139,7 +139,7 @@ def _check_directory_structure(should_fix: bool, f: Finding) -> None:f"{_DHH}/memories/ not found")for fname in [n for on, n in ((_memory_enabled, "MEMORY.md"), (_user_profile_enabled, "USER.md")) if on and existed]:if (memories_dir / fname).exists():- check_ok(f"{fname} exists ({len((memories_dir / fname).read_text(encoding='utf-8').strip())} chars)")+ check_ok(f"{fname} exists ({len((memories_dir / fname).read_text(encoding='utf-8-sig').strip())} chars)")else:check_info(f"{fname} not created yet (will be created when the agent first writes a memory)")@@ -276,7 +276,7 @@ def _check_skills_hub(should_fix: bool, f: Finding) -> None:if lock_file.exists():with warn_on_error("Lock file", "(corrupted or unreadable)"):import json- count = len(json.loads(lock_file.read_text(encoding="utf-8")).get("installed", {}))+ count = len(json.loads(lock_file.read_text(encoding="utf-8-sig")).get("installed", {}))check_ok(f"Lock file OK ({count} hub-installed skill(s))")quarantine = hub_dir / "quarantine"q_count = sum(1 for d in quarantine.iterdir() if d.is_dir()) if quarantine.exists() else 0@@ -387,6 +387,6 @@ def _check_profiles(should_fix: bool, f: Finding) -> None:if not wrapper.is_file():continuewith warn_on_error(""):- _m = _re.search(r"hermes -p (\S+)", wrapper.read_text(encoding="utf-8"))+ _m = _re.search(r"hermes -p (\S+)", wrapper.read_text(encoding="utf-8-sig"))if _m and not profile_exists(_m.group(1)):check_warn(f"Orphan alias: {wrapper.name} → profile '{_m.group(1)}' no longer exists")diff --git a/hermes_cli/gateway_windows.py b/hermes_cli/gateway_windows.pyindex fdf89346059..a233dfe8046 100644--- a/hermes_cli/gateway_windows.py+++ b/hermes_cli/gateway_windows.py@@ -1087,7 +1087,7 @@ def _probe_pid_file(pid_path: Path) -> int | None:if _probe_missing(1, pid_path, "PID file"):return Nonetry:- data = json.loads(pid_path.read_text(encoding="utf-8"))+ data = json.loads(pid_path.read_text(encoding="utf-8-sig"))pid_value = int(data.get("pid")) if data.get("pid") is not None else None_probe(1, True, f"PID file present: {pid_path} (pid={pid_value})")return pid_value@@ -1136,7 +1136,7 @@ def _probe_state_file(state_path: Path) -> None:if _probe_missing(5, state_path, "gateway_state.json"):returntry:- state_data = json.loads(state_path.read_text(encoding="utf-8"))+ state_data = json.loads(state_path.read_text(encoding="utf-8-sig"))gateway_state = state_data.get("gateway_state")updated_at = state_data.get("updated_at")age_str = ""diff --git a/hermes_cli/kanban_db_dispatch.py b/hermes_cli/kanban_db_dispatch.pyindex 743e91dbb54..a3102532045 100644--- a/hermes_cli/kanban_db_dispatch.py+++ b/hermes_cli/kanban_db_dispatch.py@@ -226,7 +226,7 @@ def _pid_alive(pid: Optional[int]) -> bool:return Falseif sys.platform == "linux":try:- with open(f"/proc/{int(pid)}/status", "r", encoding="utf-8") as f:+ with open(f"/proc/{int(pid)}/status", "r", encoding="utf-8-sig") as f:for line in f:if line.startswith("State:"):# "State:\tZ (zombie)" → deaddiff --git a/hermes_cli/local_runtime/catalog.py b/hermes_cli/local_runtime/catalog.pyindex e73a336bd99..4af7dbf991c 100644--- a/hermes_cli/local_runtime/catalog.py+++ b/hermes_cli/local_runtime/catalog.py@@ -275,7 +275,7 @@ def _load_catalog(doc: dict) -> "tuple[CatalogEntry, ...]":def _packaged_catalog() -> "tuple[CatalogEntry, ...]":from importlib.resources import files- raw = files("hermes_cli.local_runtime").joinpath("catalog.json").read_text(encoding="utf-8")+ raw = files("hermes_cli.local_runtime").joinpath("catalog.json").read_text(encoding="utf-8-sig")return _load_catalog(json.loads(raw))diff --git a/hermes_cli/main.py b/hermes_cli/main.pyindex 016d7cd8ce5..59bf3d4668d 100644--- a/hermes_cli/main.py+++ b/hermes_cli/main.py@@ -231,7 +231,7 @@ def _config_default_interface_early() -> str:if os.path.exists(cfg_path):import yaml as _yaml_iface- with open(cfg_path, encoding="utf-8") as _f:+ with open(cfg_path, encoding=utf-8-sig) as _f:raw = _yaml_iface.load(_f, Loader=getattr(_yaml_iface, "CSafeLoader", None) or _yaml_iface.SafeLoader) or {}@@ -512,7 +512,7 @@ def _apply_profile_override() -> None:active_path = get_default_hermes_root() / "active_profile"if active_path.exists():- name = active_path.read_text(encoding="utf-8").strip()+ name = active_path.read_text(encoding=utf-8-sig).strip()if name and name != "default":profile_name = name # consume stays 0: nothing to stripexcept (UnicodeDecodeError, OSError):@@ -782,7 +782,7 @@ def _read_packed_ref(common_dir: Path, ref: str) -> str | None:peel lines and ``#``-prefixed comments / ``# pack-refs with:`` header."""try:- text = (common_dir / "packed-refs").read_text(encoding="utf-8", errors="replace")+ text = (common_dir / "packed-refs").read_text(encoding=utf-8-sig, errors="replace")except OSError:return Nonefor line in text.splitlines():@@ -799,7 +799,7 @@ def _read_git_revision_fingerprint(repo_root: Path) -> str | None:git_dir = repo_root / ".git"try:if git_dir.is_file():- for line in git_dir.read_text(encoding="utf-8", errors="replace").splitlines():+ for line in git_dir.read_text(encoding=utf-8-sig, errors="replace").splitlines():key, _, value = line.partition(":")if key.strip() == "gitdir" and value.strip():git_dir = (repo_root / value.strip()).resolve()@@ -811,12 +811,12 @@ def _read_git_revision_fingerprint(repo_root: Path) -> str | None:commondir_file = git_dir / "commondir"if commondir_file.exists():try:- rel = commondir_file.read_text(encoding="utf-8", errors="replace").strip()+ rel = commondir_file.read_text(encoding=utf-8-sig, errors="replace").strip()if rel:common_dir = (git_dir / rel).resolve()except OSError:pass- head = (git_dir / "HEAD").read_text(encoding="utf-8", errors="replace").strip()+ head = (git_dir / "HEAD").read_text(encoding=utf-8-sig, errors="replace").strip()if head.startswith("ref:"):ref = head.split(":", 1)[1].strip()# Loose refs may live in the worktree gitdir OR the common dir@@ -825,7 +825,7 @@ def _read_git_revision_fingerprint(repo_root: Path) -> str | None:for candidate in (git_dir, common_dir):ref_file = candidate / refif ref_file.exists():- return f"git:{ref}:{ref_file.read_text(encoding='utf-8', errors='replace').strip()}"+ return f"git:{ref}:{ref_file.read_text(encoding=utf-8-sig, errors='replace').strip()}"packed_sha = _read_packed_ref(common_dir, ref)if packed_sha:return f"git:{ref}:{packed_sha}"@@ -862,7 +862,7 @@ def _termux_bundled_skills_sync_needed() -> bool:return Truetry:stamp = _termux_bundled_skills_stamp_path()- return stamp.read_text(encoding="utf-8").strip() != _termux_bundled_skills_fingerprint()+ return stamp.read_text(encoding=utf-8-sig).strip() != _termux_bundled_skills_fingerprint()except OSError:return True@@ -906,7 +906,7 @@ def _dotenv_has_provider_key(env_file: Path, provider_env_vars: set) -> bool:if not env_file.exists():return Falsetry:- for line in env_file.read_text(encoding="utf-8").splitlines():+ for line in env_file.read_text(encoding=utf-8-sig).splitlines():line = line.strip()if line.startswith("#") or "=" not in line:continue@@ -1632,7 +1632,7 @@ def _read_query_file(args) -> None:if _qfile == "-":args.query = sys.stdin.read()else:- with open(_qfile, "r", encoding="utf-8", errors="replace") as _fh:+ with open(_qfile, "r", encoding=utf-8-sig, errors="replace") as _fh:args.query = _fh.read()except OSError as _e:print(f"Error: cannot read --query-file {_qfile}: {_e}", file=sys.stderr)diff --git a/hermes_cli/main_dashboard.py b/hermes_cli/main_dashboard.pyindex e482d74e833..0de5aae9879 100644--- a/hermes_cli/main_dashboard.py+++ b/hermes_cli/main_dashboard.py@@ -156,7 +156,7 @@ def _pid_unified_cgroup_entries(pid: int):cgroup_path = Path(f"/proc/{pid}/cgroup")if not cgroup_path.is_file():return- text = cgroup_path.read_text(encoding="utf-8", errors="replace")+ text = cgroup_path.read_text(encoding="utf-8-sig", errors="replace")except (OSError, PermissionError):returnfor line in text.splitlines():@@ -605,7 +605,7 @@ def _read_ssh_session_token_file(path: str) -> str:if uid is not None and (file_stat.st_mode & 0o777) & ~0o600:raise SystemExit("--ssh-session-token-file has unsafe permissions")- with os.fdopen(file_fd, "r", encoding="utf-8") as token_stream:+ with os.fdopen(file_fd, "r", encoding="utf-8-sig") as token_stream:file_fd = -1token = token_stream.read(65)diff --git a/hermes_cli/main_desktop.py b/hermes_cli/main_desktop.pyindex 42bd01e3636..c23b6a27daa 100644--- a/hermes_cli/main_desktop.py+++ b/hermes_cli/main_desktop.py@@ -78,7 +78,7 @@ def _renderer_bundle_torn(dist_dir: Path) -> bool:unreadable index or one naming nothing checkable is NOT torn."""try:- html = (dist_dir / "index.html").read_text(encoding="utf-8", errors="replace")+ html = (dist_dir / "index.html").read_text(encoding="utf-8-sig", errors="replace")except OSError:return False@@ -1063,7 +1063,7 @@ def _desktop_linux_needs_no_sandbox() -> bool:if hasattr(os, "geteuid") and os.geteuid() == 0:return Falsetry:- with open("/proc/sys/kernel/apparmor_restrict_unprivileged_userns", encoding="utf-8") as f:+ with open("/proc/sys/kernel/apparmor_restrict_unprivileged_userns", encoding="utf-8-sig") as f:return f.read().strip() == "1"except OSError:return Falsediff --git a/hermes_cli/main_tui_launch.py b/hermes_cli/main_tui_launch.pyindex 2a3d2381285..346e004c1b1 100644--- a/hermes_cli/main_tui_launch.py+++ b/hermes_cli/main_tui_launch.py@@ -23,7 +23,7 @@ def _read_tui_active_session_file(path: Optional[str]) -> Optional[str]:if not path:return Nonetry:- data = json.loads(Path(path).read_text(encoding="utf-8"))+ data = json.loads(Path(path).read_text(encoding="utf-8-sig"))return str(data.get("session_id") or "").strip() or Noneexcept Exception:return None@@ -228,8 +228,8 @@ def _tui_need_npm_install(root: Path) -> bool:return Truetry:- wanted = json.loads(lock.read_text(encoding="utf-8")).get("packages") or {}- installed = json.loads(marker.read_text(encoding="utf-8")).get("packages") or {}+ wanted = json.loads(lock.read_text(encoding="utf-8-sig")).get("packages") or {}+ installed = json.loads(marker.read_text(encoding="utf-8-sig")).get("packages") or {}except (OSError, UnicodeDecodeError, json.JSONDecodeError):return lock.stat().st_mtime > marker.stat().st_mtime@@ -616,7 +616,7 @@ def _read_cgroup_memory_limit() -> Optional[int]:)for path in candidates:try:- with open(path, "r", encoding="utf-8") as f:+ with open(path, "r", encoding="utf-8-sig") as f:raw = f.read().strip()except (OSError, ValueError):continuediff --git a/hermes_cli/main_web_build.py b/hermes_cli/main_web_build.pyindex 41cdbdad2c8..0d0e810d1bb 100644--- a/hermes_cli/main_web_build.py+++ b/hermes_cli/main_web_build.py@@ -64,7 +64,7 @@ def _sweep_stale_bytecode_if_checkout_changed() -> None:return # non-git install — the ZIP update path clears explicitlystamp_path = PROJECT_ROOT / _BYTECODE_FINGERPRINT_FILEtry:- recorded = stamp_path.read_text(encoding="utf-8").strip()+ recorded = stamp_path.read_text(encoding=utf-8-sig).strip()except OSError:recorded = ""if recorded == fingerprint:@@ -110,7 +110,7 @@ def _hash_source_tree(project_root: Path, tree_dir: Path) -> str:from pathspec import PathSpecgitignore = project_root / ".gitignore"- lines = gitignore.read_text(encoding="utf-8").splitlines() if gitignore.is_file() else []+ lines = gitignore.read_text(encoding=utf-8-sig).splitlines() if gitignore.is_file() else []spec = PathSpec.from_lines("gitignore", lines)def _ignored(path: Path) -> bool:@@ -141,7 +141,7 @@ def _stamp_is_current(stamp_file: Path, current_hash: Callable[[], str], **expecif not stamp_file.is_file():return Falsetry:- stamp_data = json.loads(stamp_file.read_text(encoding="utf-8"))+ stamp_data = json.loads(stamp_file.read_text(encoding=utf-8-sig))except (OSError, json.JSONDecodeError):return Falseif not isinstance(stamp_data, dict):@@ -285,7 +285,7 @@ def _nixos_build_env() -> dict[str, str] | None:from hermes_cli.main import PROJECT_ROOTimport retry:- os_release = Path("/etc/os-release").read_text(encoding="utf-8")+ os_release = Path("/etc/os-release").read_text(encoding=utf-8-sig)except OSError:return Noneif not re.search(r"^ID=nixos$", os_release, re.M) or shutil.which("python3"):diff --git a/hermes_cli/plugin_compat.py b/hermes_cli/plugin_compat.pyindex 310b077f1f1..4cdf04500cd 100644--- a/hermes_cli/plugin_compat.py+++ b/hermes_cli/plugin_compat.py@@ -67,7 +67,7 @@ def load_manifest() -> Dict[str, Dict[str, str]]:p = manifest_path()if p.exists():try:- for e in json.loads(p.read_text(encoding="utf-8"))["entries"]:+ for e in json.loads(p.read_text(encoding="utf-8-sig"))["entries"]:target = e.get("target") or ""if target.startswith("("): # restored-def etc.: no new home, just "gone later"new = f"{e['facade']}.{e['name']} (removed; no replacement — vendor a copy)"@@ -155,7 +155,7 @@ def scan_plugin(plugin_dir: Optional[Path], manifest: Optional[Dict[str, Dict[sthits: List[Hit] = []for p in _iter_py(Path(plugin_dir)):try:- src = p.read_text(encoding="utf-8", errors="replace")+ src = p.read_text(encoding="utf-8-sig", errors="replace")except OSError:continuehits += scan_source(src, str(p.relative_to(plugin_dir)), manifest)diff --git a/hermes_cli/plugins.py b/hermes_cli/plugins.pyindex a0765fa29c1..f84fcb87542 100644--- a/hermes_cli/plugins.py+++ b/hermes_cli/plugins.py@@ -1630,7 +1630,7 @@ def _nowait_plugin_set(cache_field: str, live: Callable[[PluginManager], "set[streturn live(manager)if in_flight:with suppress(Exception):- blob = json.loads(_plugin_toolset_keys_cache_path().read_text(encoding="utf-8"))+ blob = json.loads(_plugin_toolset_keys_cache_path().read_text(encoding="utf-8-sig"))values = blob.get(cache_field) if isinstance(blob, dict) else Noneif isinstance(values, list) and all(isinstance(v, str) for v in values):return set(values)diff --git a/hermes_cli/plugins_manifest.py b/hermes_cli/plugins_manifest.pyindex fec0acfbad4..d555632ee35 100644--- a/hermes_cli/plugins_manifest.py+++ b/hermes_cli/plugins_manifest.py@@ -263,7 +263,7 @@ def _read_source_from_origin(origin: Optional[str], limit: int = 8192) -> str:origin = importlib.util.source_from_cache(origin)if not origin or not origin.endswith(".py"):return ""- return Path(origin).read_text(encoding="utf-8", errors="replace")[:limit]+ return Path(origin).read_text(encoding="utf-8-sig", errors="replace")[:limit]except Exception:return ""@@ -392,7 +392,7 @@ def _manifest_kind(data: Mapping, key: str, plugin_dir: Path) -> str:init_file = plugin_dir / "__init__.py"if kind == "standalone" and "kind" not in data and init_file.exists():with suppress(Exception):- source_text = init_file.read_text(errors="replace", encoding="utf-8")[:8192]+ source_text = init_file.read_text(errors="replace", encoding="utf-8-sig")[:8192]detected = _detect_kind_from_source(source_text)if detected:kind = detected@@ -408,7 +408,7 @@ def parse_manifest_file(if yaml is None:logger.warning("PyYAML not installed – cannot load %s", manifest_file)return None- data = fast_safe_load(manifest_file.read_text(encoding="utf-8")) or {}+ data = fast_safe_load(manifest_file.read_text(encoding="utf-8-sig")) or {}name = data.get("name", plugin_dir.name)key = f"{prefix}/{plugin_dir.name}" if prefix else namekind = _manifest_kind(data, key, plugin_dir)diff --git a/hermes_cli/plugins_state.py b/hermes_cli/plugins_state.pyindex 5e7c7dbb1a7..946334c7561 100644--- a/hermes_cli/plugins_state.py+++ b/hermes_cli/plugins_state.py@@ -133,7 +133,7 @@ class PluginState:def _read_unlocked(self) -> dict[str, Any]:try:- with open(self.path, encoding="utf-8") as handle:+ with open(self.path, encoding=utf-8-sig) as handle:data = json.load(handle)except FileNotFoundError:return {}diff --git a/hermes_cli/setup_terminal.py b/hermes_cli/setup_terminal.pyindex f6e1f16da63..cc3cede674b 100644--- a/hermes_cli/setup_terminal.py+++ b/hermes_cli/setup_terminal.py@@ -72,7 +72,7 @@ def _read_nearest_vercel_project(start: Path | None = None) -> dict[str, str]:if not project_file.exists():continuetry:- data = json.loads(project_file.read_text(encoding="utf-8"))+ data = json.loads(project_file.read_text(encoding="utf-8-sig"))except (OSError, json.JSONDecodeError):return {}if not isinstance(data, dict):diff --git a/hermes_cli/tools_config_cua.py b/hermes_cli/tools_config_cua.pyindex 1d3246fdf45..a6abef75363 100644--- a/hermes_cli/tools_config_cua.py+++ b/hermes_cli/tools_config_cua.py@@ -419,7 +419,7 @@ def _clear_stale_cua_install_lock() -> None:if not lock_dir.is_dir():returntry:- lines = (lock_dir / "info").read_text(encoding="utf-8", errors="replace").splitlines()+ lines = (lock_dir / "info").read_text(encoding="utf-8-sig", errors="replace").splitlines()holder_pid = next((int(line.split("=", 1)[1].strip()) for line in linesif line.startswith("pid=")), None)except (OSError, ValueError):diff --git a/hermes_cli/update_cmd_deps.py b/hermes_cli/update_cmd_deps.pyindex 2e63135fe21..ff2bbb49212 100644--- a/hermes_cli/update_cmd_deps.py+++ b/hermes_cli/update_cmd_deps.py@@ -435,7 +435,7 @@ def _npm_manifest_paths() -> tuple[Path, ...]:root_pkg = _m().PROJECT_ROOT / "package.json"paths = [_m().PROJECT_ROOT / "package-lock.json", root_pkg]with suppress(OSError, json.JSONDecodeError, TypeError):- workspaces = json.loads(root_pkg.read_text(encoding="utf-8")).get("workspaces", [])+ workspaces = json.loads(root_pkg.read_text(encoding="utf-8-sig")).get("workspaces", [])if isinstance(workspaces, dict): # legacy {"packages": [...]} formworkspaces = workspaces.get("packages", [])for pattern in workspaces:@@ -478,7 +478,7 @@ def _npm_lockfile_changed(hermes_root: Path) -> bool:cache_file = _npm_lock_cache_file(hermes_root)if not cache_file.exists():return True- return cache_file.read_text(encoding="utf-8").strip() != current+ return cache_file.read_text(encoding="utf-8-sig").strip() != currentexcept OSError:return True@@ -714,7 +714,7 @@ def _dependency_sync_would_rewrite(dist_name: str) -> bool | None:from packaging.utils import canonicalize_namefrom packaging.version import Versionpyproject = _m().PROJECT_ROOT / "pyproject.toml"- data = tomllib.loads(pyproject.read_text(encoding="utf-8"))+ data = tomllib.loads(pyproject.read_text(encoding="utf-8-sig"))project = data.get("project") or {}req_strings: list[str] = list(project.get("dependencies") or [])for extra_reqs in (project.get("optional-dependencies") or {}).values():diff --git a/hermes_cli/update_cmd_maint.py b/hermes_cli/update_cmd_maint.pyindex fe7434ad722..c07ec0a6e88 100644--- a/hermes_cli/update_cmd_maint.py+++ b/hermes_cli/update_cmd_maint.py@@ -626,7 +626,7 @@ def _ensure_fhs_path_guard() -> None:if not cfg.is_file():continuetry:- existing = cfg.read_text(errors="replace", encoding="utf-8")+ existing = cfg.read_text(errors="replace", encoding="utf-8-sig")except OSError:continue# Idempotency: any uncommented PATH line referencing /usr/local/bin (install.sh grep).@@ -636,7 +636,7 @@ def _ensure_fhs_path_guard() -> None:):continuetry:- with cfg.open("a", encoding="utf-8") as f:+ with cfg.open("a", encoding=utf-8-sig) as f:f.write("\n" + path_comment + "\n" + path_line + "\n")except OSError as e:print(f" ⚠ Could not update {cfg}: {e}")diff --git a/hermes_cli/web_routers/analytics.py b/hermes_cli/web_routers/analytics.pyindex d3dac5f9bfc..81f82576f41 100644--- a/hermes_cli/web_routers/analytics.py+++ b/hermes_cli/web_routers/analytics.py@@ -42,7 +42,7 @@ async def get_config_raw(profile: Optional[str] = None):path = get_config_path()if not path.exists():return {"yaml": "", "path": str(path)}- return {"yaml": path.read_text(encoding="utf-8"), "path": str(path)}+ return {"yaml": path.read_text(encoding="utf-8-sig"), "path": str(path)}return await asyncio.to_thread(_run)diff --git a/hermes_cli/web_routers/chat_ws.py b/hermes_cli/web_routers/chat_ws.pyindex 64f792d3f3f..06275171b94 100644--- a/hermes_cli/web_routers/chat_ws.py+++ b/hermes_cli/web_routers/chat_ws.py@@ -83,7 +83,7 @@ def _channel_or_close_code(ws: WebSocket) -> Optional[str]:def _read_active_session_file(path: Path) -> Optional[str]:try:- data = json.loads(path.read_text(encoding="utf-8"))+ data = json.loads(path.read_text(encoding="utf-8-sig"))except (OSError, json.JSONDecodeError):return Nonereturn str(data.get("session_id") or "").strip() or Nonediff --git a/hermes_cli/web_routers/local_models.py b/hermes_cli/web_routers/local_models.pyindex 6669d436052..5c490a32e06 100644--- a/hermes_cli/web_routers/local_models.py+++ b/hermes_cli/web_routers/local_models.py@@ -866,7 +866,7 @@ def _terminate_state_pid() -> None:"""Server owned by another process (or an orphan): terminate via the state file's pid, then clear the state."""import psutil # type: ignore- state = json.loads(supervisor.state_path().read_text(encoding="utf-8"))+ state = json.loads(supervisor.state_path().read_text(encoding="utf-8-sig"))pid = int(state.get("pid") or 0)if pid > 0 and psutil.pid_exists(pid):psutil.Process(pid).terminate()diff --git a/hermes_cli/web_routers/memory_providers.py b/hermes_cli/web_routers/memory_providers.pyindex 11485d22926..80c63e1c9cb 100644--- a/hermes_cli/web_routers/memory_providers.py+++ b/hermes_cli/web_routers/memory_providers.py@@ -108,7 +108,7 @@ def _read_json_dict(path: Path, what: str) -> Dict[str, Any]:if not path.exists():return {}try:- data = json.loads(path.read_text(encoding="utf-8"))+ data = json.loads(path.read_text(encoding=utf-8-sig))except Exception:_log.warning("Failed to read %s from %s", what, path, exc_info=True)return {}diff --git a/hermes_cli/web_routers/messaging.py b/hermes_cli/web_routers/messaging.pyindex 6c38c5c9dc1..43b76c1bd59 100644--- a/hermes_cli/web_routers/messaging.py+++ b/hermes_cli/web_routers/messaging.py@@ -321,7 +321,7 @@ def _first_str(candidate: Any, keys: tuple[str, ...]) -> str | None:def _whatsapp_linked_account_from_session(session_path: Path) -> tuple[str | None, str | None, str | None]:try:- payload = json.loads((session_path / "creds.json").read_text(encoding="utf-8"))+ payload = json.loads((session_path / "creds.json").read_text(encoding="utf-8-sig"))except Exception:return None, None, Nonecandidates = (payload.get("me"), payload.get("account"), payload)diff --git a/hermes_cli/web_server_cron.py b/hermes_cli/web_server_cron.pyindex 907753f863c..0f0c583c57f 100644--- a/hermes_cli/web_server_cron.py+++ b/hermes_cli/web_server_cron.py@@ -296,7 +296,7 @@ def _profile_env_value(home: Path, key: str) -> str:env_path = home / ".env"if not env_path.is_file():return ""- for line in env_path.read_text(encoding="utf-8").splitlines():+ for line in env_path.read_text(encoding="utf-8-sig").splitlines():line = line.strip()if not line or line.startswith("#") or "=" not in line:continue@@ -414,7 +414,7 @@ def _gateway_intentionally_stopped(profile: Optional[str]) -> bool:"""import json as _jsontry:- data = _json.loads((_cron_profile_home(profile)[1] / "gateway_state.json").read_text(encoding="utf-8"))+ data = _json.loads((_cron_profile_home(profile)[1] / "gateway_state.json").read_text(encoding="utf-8-sig"))return isinstance(data, dict) and data.get("desired_state") == "stopped"except Exception:return Falsediff --git a/hermes_cli/web_server_dashboard.py b/hermes_cli/web_server_dashboard.pyindex ca54274b82a..0e2882d5d53 100644--- a/hermes_cli/web_server_dashboard.py+++ b/hermes_cli/web_server_dashboard.py@@ -145,7 +145,7 @@ def mount_spa(application: FastAPI):and /api/ws (ticket vs token)."""try:- html = (WEB_DIST / "index.html").read_text(encoding="utf-8")+ html = (WEB_DIST / "index.html").read_text(encoding="utf-8-sig")except OSError:# Partial build / wiped dist / permissions: same JSON 404 as a fully-missing dist.return JSONResponse({"error": "Frontend not built. Run: cd web && npm run build"}, status_code=404)@@ -179,7 +179,7 @@ def mount_spa(application: FastAPI):if not css_path.is_file() or not css_path.resolve().is_relative_to(WEB_DIST.resolve()):return JSONResponse({"error": "not found"}, status_code=404)prefix = _normalise_prefix(request.headers.get("x-forwarded-prefix"))- css = css_path.read_text(encoding="utf-8")+ css = css_path.read_text(encoding="utf-8-sig")if prefix:for asset_dir in ("/fonts/", "/fonts-terminal/", "/ds-assets/", "/assets/"):for quote in ("", '"', "'"):@@ -411,7 +411,7 @@ def _discover_user_themes() -> list:result = []for f in sorted(themes_dir.glob("*.yaml")):try:- data = yaml.safe_load(f.read_text(encoding="utf-8"))+ data = yaml.safe_load(f.read_text(encoding="utf-8-sig"))except Exception:continuenormalised = _normalise_theme_definition(data)@@ -548,7 +548,7 @@ def _discover_dashboard_plugins() -> list:if not child.is_dir() or not manifest_file.exists():continuetry:- data = json.loads(manifest_file.read_text(encoding="utf-8"))+ data = json.loads(manifest_file.read_text(encoding="utf-8-sig"))name = data.get("name", child.name)if name in seen_names:continuediff --git a/hermes_cli/web_server_lifecycle.py b/hermes_cli/web_server_lifecycle.pyindex e3a2b1a6e47..0c19e6eeea0 100644--- a/hermes_cli/web_server_lifecycle.py+++ b/hermes_cli/web_server_lifecycle.py@@ -28,7 +28,7 @@ def _process_start_marker(pid: int) -> str:"""if sys.platform == "linux":try:- stat_line = Path(f"/proc/{pid}/stat").read_text(encoding="utf-8")+ stat_line = Path(f"/proc/{pid}/stat").read_text(encoding=utf-8-sig)except FileNotFoundError as exc:raise ProcessLookupError(pid) from excdiff --git a/hermes_cli/web_server_memory.py b/hermes_cli/web_server_memory.pyindex 379dd81dd41..9cd4afaf456 100644--- a/hermes_cli/web_server_memory.py+++ b/hermes_cli/web_server_memory.py@@ -212,7 +212,7 @@ def _normalize_memory_provider_schema(name: str, provider: Any) -> List[Dict[strdef _read_json_file(path: Path) -> Dict[str, Any]:try:- data = json.loads(path.read_text(encoding="utf-8")) if path.exists() else {}+ data = json.loads(path.read_text(encoding="utf-8-sig")) if path.exists() else {}except Exception:_log.debug("Failed to read JSON config from %s", path, exc_info=True)return {}diff --git a/hermes_cli/worktree_ops.py b/hermes_cli/worktree_ops.pyindex e9e69650331..2b7c22307fa 100644--- a/hermes_cli/worktree_ops.py+++ b/hermes_cli/worktree_ops.py@@ -449,7 +449,7 @@ def _worktree_merge_cache_path() -> Path:def _load_worktree_merge_cache() -> Dict[str, bool]:"""Load the ``git cherry`` verdict cache. Missing/corrupt cache = empty."""try:- entries = json.loads(_worktree_merge_cache_path().read_text(encoding="utf-8")).get("verdicts")+ entries = json.loads(_worktree_merge_cache_path().read_text(encoding="utf-8-sig")).get("verdicts")except Exception:return {}# A hand-edited or partially written cache must never inject a non-bool verdict.diff --git a/plugins/google_meet/_jsonfile.py b/plugins/google_meet/_jsonfile.pyindex dd3a5549b38..38f9a325dd5 100644--- a/plugins/google_meet/_jsonfile.py+++ b/plugins/google_meet/_jsonfile.py@@ -13,7 +13,7 @@ def read_json(path: Path) -> Optional[Any]:if not path.is_file():return Nonetry:- return json.loads(path.read_text(encoding="utf-8"))+ return json.loads(path.read_text(encoding="utf-8-sig"))except (OSError, ValueError):return Nonediff --git a/plugins/memory/hindsight/setup.py b/plugins/memory/hindsight/setup.pyindex 5f6692c64e4..8da84f58618 100644--- a/plugins/memory/hindsight/setup.py+++ b/plugins/memory/hindsight/setup.py@@ -168,7 +168,7 @@ def run_setup(provider, hermes_home: str, config: dict) -> None:materialized_config = dict(provider_config)with contextlib.suppress(Exception):materialized_config = json.loads(- (Path(hermes_home) / "hindsight" / "config.json").read_text(encoding="utf-8")+ (Path(hermes_home) / "hindsight" / "config.json").read_text(encoding=utf-8-sig))llm_api_key = (env_writes.get("HINDSIGHT_LLM_API_KEY", "")diff --git a/plugins/memory/honcho/cli.py b/plugins/memory/honcho/cli.pyindex ca3718d0d02..d18a51d4139 100644--- a/plugins/memory/honcho/cli.py+++ b/plugins/memory/honcho/cli.py@@ -1676,7 +1676,7 @@ def _migrate_upload(mgr, session_key: str, user_files: list[Path]) -> None:def _migrate_seed(mgr, session_key: str, agent_files: list[Path]) -> None:for f in agent_files:- content = f.read_text(encoding="utf-8").strip()+ content = f.read_text(encoding="utf-8-sig").strip()if content:ok = mgr.seed_ai_identity(session_key, content, source=f.name)print(f" {f.name}: {'seeded' if ok else 'failed'}")diff --git a/plugins/memory/honcho/client_cache.py b/plugins/memory/honcho/client_cache.pyindex 6af5549ec91..e17dc2e87e0 100644--- a/plugins/memory/honcho/client_cache.py+++ b/plugins/memory/honcho/client_cache.py@@ -75,7 +75,7 @@ def _ambient_host_block() -> tuple[dict | None, dict]:path = resolve_config_path()if not path.exists():return None, {}- raw = json.loads(path.read_text(encoding="utf-8"))+ raw = json.loads(path.read_text(encoding="utf-8-sig"))return raw, _host_block(raw, resolve_active_host())diff --git a/plugins/memory/honcho/oauth.py b/plugins/memory/honcho/oauth.pyindex bcdac62f126..18fa66cf21f 100644--- a/plugins/memory/honcho/oauth.py+++ b/plugins/memory/honcho/oauth.py@@ -109,7 +109,7 @@ def _mark_grant_dead(key: tuple[str, str], cred: OAuthCredential) -> None:def _read_config(path: Path) -> dict[str, Any]:try:- return json.loads(path.read_text(encoding="utf-8"))+ return json.loads(path.read_text(encoding="utf-8-sig"))except (OSError, json.JSONDecodeError):return {}diff --git a/plugins/memory/honcho/session_migration.py b/plugins/memory/honcho/session_migration.pyindex 575dfb86392..2c1e2d1caf5 100644--- a/plugins/memory/honcho/session_migration.py+++ b/plugins/memory/honcho/session_migration.py@@ -49,7 +49,7 @@ class SessionMigrationMixin:uploaded = Falsefor filename, upload_name, description, target_kind in _MEMORY_FILES:filepath = memory_path / filename- content = filepath.read_text(encoding="utf-8").strip() if filepath.exists() else ""+ content = filepath.read_text(encoding=utf-8-sig).strip() if filepath.exists() else ""if not content:continuetarget_peer_id = session.user_peer_id if target_kind == "user" else session.assistant_peer_iddiff --git a/plugins/memory/mem0/__init__.py b/plugins/memory/mem0/__init__.pyindex 8f736751cce..76d14e320f7 100644--- a/plugins/memory/mem0/__init__.py+++ b/plugins/memory/mem0/__init__.py@@ -44,7 +44,7 @@ def _read_mem0_json(config_path: Path) -> dict:"""Best-effort read of mem0.json; missing/corrupt file -> {}."""if config_path.exists():with suppress(Exception):- return json.loads(config_path.read_text(encoding="utf-8"))+ return json.loads(config_path.read_text(encoding="utf-8-sig"))return {}diff --git a/plugins/memory/retaindb/__init__.py b/plugins/memory/retaindb/__init__.pyindex 95ed0ded36d..0802ef61823 100644--- a/plugins/memory/retaindb/__init__.py+++ b/plugins/memory/retaindb/__init__.py@@ -341,7 +341,7 @@ class RetainDBMemoryProvider(MemoryProvider):from hermes_constants import get_hermes_homehome = get_hermes_home()self._queue = _WriteQueue(self._client, home / "retaindb_queue.db")- soul = (home / "SOUL.md").read_text(encoding="utf-8", errors="replace").strip() if (home / "SOUL.md").exists() else ""+ soul = (home / "SOUL.md").read_text(encoding="utf-8-sig", errors="replace").strip() if (home / "SOUL.md").exists() else ""if soul: # seed agent identity from SOUL.md in backgroundseed = lambda: self._client.seed_agent_identity(self._agent_id, soul, source="soul_md") # noqa: E731threading.Thread(target=_quiet, args=("soul seed", seed), name="retaindb-soul-seed", daemon=True).start()diff --git a/plugins/memory/supermemory/__init__.py b/plugins/memory/supermemory/__init__.pyindex ad4a138fe56..c6fa66856e4 100644--- a/plugins/memory/supermemory/__init__.py+++ b/plugins/memory/supermemory/__init__.py@@ -95,7 +95,7 @@ _CONFIG_SPEC: Dict[str, tuple] = {def _read_json_dict(path: Path) -> dict:- raw = _quietly(lambda: json.loads(path.read_text(encoding="utf-8")), "Failed to parse %s", path) if path.exists() else None+ raw = _quietly(lambda: json.loads(path.read_text(encoding="utf-8-sig")), "Failed to parse %s", path) if path.exists() else Nonereturn raw if isinstance(raw, dict) else {}diff --git a/plugins/platforms/a2a/protocol.py b/plugins/platforms/a2a/protocol.pyindex 1b3c2c5f35b..c3ab04a3b21 100644--- a/plugins/platforms/a2a/protocol.py+++ b/plugins/platforms/a2a/protocol.py@@ -445,7 +445,7 @@ def persist_message(context_id: str, role: str, text: str, task_id: str = "") ->try:path = _conv_path(context_id)path.parent.mkdir(parents=True, exist_ok=True)- with path.open("a", encoding="utf-8") as fh:+ with path.open("a", encoding=utf-8-sig) as fh:fh.write(json.dumps({"ts": time.time(), "role": role, "text": text, "task_id": task_id}, ensure_ascii=False) + "\n")except Exception:pass@@ -454,7 +454,7 @@ def persist_message(context_id: str, role: str, text: str, task_id: str = "") ->def load_conversation(context_id: str, limit: int = 50) -> list[dict]:"""Last *limit* messages for a context (empty list if none / unreadable)."""try:- lines = _conv_path(context_id).read_text(encoding="utf-8").splitlines()+ lines = _conv_path(context_id).read_text(encoding=utf-8-sig).splitlines()except Exception:return []out: list[dict] = []diff --git a/plugins/platforms/feishu/feishu_comment_rules.py b/plugins/platforms/feishu/feishu_comment_rules.pyindex 7c83327b66c..13261c153c8 100644--- a/plugins/platforms/feishu/feishu_comment_rules.py+++ b/plugins/platforms/feishu/feishu_comment_rules.py@@ -138,7 +138,7 @@ def _load_pairing_approved() -> set:def _save_pairing(data: dict) -> None:PAIRING_FILE.parent.mkdir(parents=True, exist_ok=True)- with open(PAIRING_FILE.with_suffix(".tmp"), "w", encoding="utf-8") as f:+ with open(PAIRING_FILE.with_suffix(".tmp"), "w", encoding="utf-8") as f: # windows-footgun: ok (write/append mode, not a read)json.dump(data, f, indent=2, ensure_ascii=False)PAIRING_FILE.with_suffix(".tmp").replace(PAIRING_FILE)_pairing_cache._mtime, _pairing_cache._data = 0.0, None # invalidate so the next load re-readsdiff --git a/plugins/platforms/google_chat/adapter.py b/plugins/platforms/google_chat/adapter.pyindex 36d541646d3..ebdf0415205 100644--- a/plugins/platforms/google_chat/adapter.py+++ b/plugins/platforms/google_chat/adapter.py@@ -237,7 +237,7 @@ def _load_sa_credentials_from(sa_value: Optional[str]) -> Any:raise _SACredentialError("not_found")else:try:- with open(sa_value, "r", encoding="utf-8") as fh:+ with open(sa_value, "r", encoding="utf-8-sig") as fh:info = json.load(fh)except json.JSONDecodeError as exc:raise _SACredentialError("file_invalid", exc) from excdiff --git a/plugins/platforms/whatsapp/adapter.py b/plugins/platforms/whatsapp/adapter.pyindex 433f5248063..44715d919bc 100644--- a/plugins/platforms/whatsapp/adapter.py+++ b/plugins/platforms/whatsapp/adapter.py@@ -344,7 +344,7 @@ class WhatsAppAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):_dep_stamp = bridge_dir / "node_modules" / ".hermes-pkg-hash" # holds the package.json hash of the last install_pkg_hash = _file_content_hash(bridge_dir / "package.json")try:- if (bridge_dir / "node_modules").exists() and _dep_stamp.read_text(encoding="utf-8").strip() == _pkg_hash and bool(_pkg_hash):+ if (bridge_dir / "node_modules").exists() and _dep_stamp.read_text(encoding="utf-8-sig").strip() == _pkg_hash and bool(_pkg_hash):return Trueexcept OSError:passdiff --git a/scripts/check_compat_pointers.py b/scripts/check_compat_pointers.pyindex c36bea08ecf..d3572a104dc 100644--- a/scripts/check_compat_pointers.py+++ b/scripts/check_compat_pointers.py@@ -41,7 +41,7 @@ def main() -> int:if not MANIFEST.exists():print("compat_manifest.json missing — nothing to check (compat layer already reverted?)")return 0- entries = json.loads(MANIFEST.read_text(encoding="utf-8"))["entries"]+ entries = json.loads(MANIFEST.read_text(encoding=utf-8-sig))["entries"]compat: dict[str, set[str]] = {}for e in entries:compat.setdefault(e["facade"], set()).add(e["name"])@@ -51,7 +51,7 @@ def main() -> int:for path in _py_files():rel = path.relative_to(ROOT)try:- src = path.read_text(encoding="utf-8", errors="ignore")+ src = path.read_text(encoding=utf-8-sig, errors="ignore")tree = ast.parse(src)except SyntaxError:continuediff --git a/tools/browser_tool_install.py b/tools/browser_tool_install.pyindex f4df1d2f4a9..232026e0b45 100644--- a/tools/browser_tool_install.py+++ b/tools/browser_tool_install.py@@ -285,7 +285,7 @@ def _running_in_docker() -> bool:if os.path.exists("/.dockerenv"):return Truetry:- with open("/proc/1/cgroup", "rt", encoding="utf-8") as fp:+ with open("/proc/1/cgroup", "rt", encoding="utf-8-sig") as fp:return "docker" in fp.read()except OSError:return Falsediff --git a/tools/browser_tool_lifecycle.py b/tools/browser_tool_lifecycle.pyindex 4e8451a6b2d..d29ffe94c04 100644--- a/tools/browser_tool_lifecycle.py+++ b/tools/browser_tool_lifecycle.py@@ -261,7 +261,7 @@ def _socket_dir_idle_seconds(socket_dir: str) -> Optional[float]:def _read_pid_file(path: str) -> Optional[int]:"""Integer PID from ``path``; None when missing or corrupt."""try:- return int(Path(path).read_text(encoding="utf-8").strip())+ return int(Path(path).read_text(encoding="utf-8-sig").strip())except (ValueError, OSError):return None@@ -564,7 +564,7 @@ def _kill_verified_daemon(socket_dir: str, session_name: str) -> bool:if not os.path.isfile(pid_file):return Falsetry:- daemon_pid = int(Path(pid_file).read_text(encoding="utf-8").strip())+ daemon_pid = int(Path(pid_file).read_text(encoding="utf-8-sig").strip())if not _verify_reapable_browser_daemon(daemon_pid, socket_dir, session_name):_bt.logger.debug("Skipped daemon kill for %s: pid %s failed identity verification", session_name, daemon_pid)return Falsediff --git a/tools/browser_tool_lightpanda_fallback.py b/tools/browser_tool_lightpanda_fallback.pyindex f1f86aa855d..561a56939e0 100644--- a/tools/browser_tool_lightpanda_fallback.py+++ b/tools/browser_tool_lightpanda_fallback.py@@ -164,7 +164,7 @@ def _run_chrome_fallback_command(task_id: str, command: str, args: List[str], tiproc.wait()return {"success": False, "error": f"Chrome fallback '{cmd}' timed out"}try:- with open(stdout_path, encoding="utf-8") as f:+ with open(stdout_path, encoding="utf-8-sig") as f:stdout = f.read().strip()if stdout:return json.loads(stdout.split("\n")[-1])diff --git a/tools/browser_tool_real_profile.py b/tools/browser_tool_real_profile.pyindex 4d2624a948b..9ddee281cb5 100644--- a/tools/browser_tool_real_profile.py+++ b/tools/browser_tool_real_profile.py@@ -62,7 +62,7 @@ def _agent_browser_get_cdp(session_name: str) -> Optional[str]:def _read_devtools_port(data_dir: str) -> Optional[str]:"""First line of Chrome's ``DevToolsActivePort`` in ``data_dir`` (None when unreadable)."""try:- with open(os.path.join(data_dir, "DevToolsActivePort"), encoding="utf-8") as fh:+ with open(os.path.join(data_dir, "DevToolsActivePort"), encoding="utf-8-sig") as fh:return fh.readline().strip()except OSError:return Nonediff --git a/tools/browser_tool_session.py b/tools/browser_tool_session.pyindex 4b9b353b3e0..4cb9040d549 100644--- a/tools/browser_tool_session.py+++ b/tools/browser_tool_session.py@@ -37,7 +37,7 @@ def _needs_chromium_sandbox_bypass() -> bool:if _install._running_in_docker():return Truetry:- with open("/proc/sys/kernel/apparmor_restrict_unprivileged_userns", encoding="utf-8") as f:+ with open("/proc/sys/kernel/apparmor_restrict_unprivileged_userns", encoding="utf-8-sig") as f:return f.read().strip() == "1"except OSError:return False@@ -56,7 +56,7 @@ def _read_command_output_files(stdout_path: str, stderr_path: str) -> tuple[str,out = []for path in (stdout_path, stderr_path):try:- with open(path, "r", encoding="utf-8") as f:+ with open(path, "r", encoding="utf-8-sig") as f:out.append(f.read().strip())except OSError:out.append("")@@ -357,7 +357,7 @@ def _read_browser_daemon_pid(task_socket_dir: str, session_name: str) -> Optiona"""Read the agent-browser daemon PID for a session (best-effort)."""pid_file = os.path.join(task_socket_dir, f"{session_name}.pid")try:- return int(Path(pid_file).read_text(encoding="utf-8").strip())+ return int(Path(pid_file).read_text(encoding="utf-8-sig").strip())except (OSError, ValueError):return None@@ -542,9 +542,9 @@ def _spawn_and_collect(_bt.logger.warning("browser '%s' timed out after %ds (task=%s, socket_dir=%s)",command, timeout, task_id, task_socket_dir)return {"success": False, "error": _format_browser_timeout_error(command, timeout, stdout, stderr)}- with open(stdout_path, "r", encoding="utf-8") as f:+ with open(stdout_path, "r", encoding="utf-8-sig") as f:stdout = f.read()- with open(stderr_path, "r", encoding="utf-8") as f:+ with open(stderr_path, "r", encoding="utf-8-sig") as f:stderr = f.read()_unlink_command_output_files(stdout_path, stderr_path)return _interpret_browser_command_output(command, stdout, stderr, proc.returncode)diff --git a/tools/environments/base_output.py b/tools/environments/base_output.pyindex 48350450a19..01626945b74 100644--- a/tools/environments/base_output.py+++ b/tools/environments/base_output.py@@ -295,7 +295,7 @@ class _ThreadedProcessHandle:# Pipe for stdout — the drain thread in _wait_for_process reads the read end.read_fd, write_fd = os.pipe()- self._stdout = os.fdopen(read_fd, "r", encoding="utf-8", errors="replace")+ self._stdout = os.fdopen(read_fd, "r", encoding="utf-8-sig", errors="replace")self._write_fd = write_fddef _worker():diff --git a/tools/mcp_tool_config.py b/tools/mcp_tool_config.pyindex cdf80c4b734..a2b1b46bc65 100644--- a/tools/mcp_tool_config.py+++ b/tools/mcp_tool_config.py@@ -206,7 +206,7 @@ def _npx_cached_bin(args: list) -> Optional[tuple]:for entry in entries:manifest = os.path.join(npx_root, entry, "package.json")try:- with open(manifest, "r", encoding="utf-8") as fh:+ with open(manifest, "r", encoding="utf-8-sig") as fh:deps = (json.load(fh) or {}).get("dependencies") or {}except (OSError, ValueError, TypeError):continue@@ -214,7 +214,7 @@ def _npx_cached_bin(args: list) -> Optional[tuple]:continuepkg_json = os.path.join(npx_root, entry, "node_modules", spec, "package.json")try:- with open(pkg_json, "r", encoding="utf-8") as fh:+ with open(pkg_json, "r", encoding="utf-8-sig") as fh:bin_field = (json.load(fh) or {}).get("bin")except (OSError, ValueError, TypeError):continuediff --git a/tools/mcp_tool_lifecycle.py b/tools/mcp_tool_lifecycle.pyindex a1377368d31..fd9519ed657 100644--- a/tools/mcp_tool_lifecycle.py+++ b/tools/mcp_tool_lifecycle.py@@ -40,7 +40,7 @@ def _snapshot_child_pids() -> set:found: set = set()for tid in os.listdir(task_dir):try:- with open(f"{task_dir}/{tid}/children", encoding="utf-8") as f:+ with open(f"{task_dir}/{tid}/children", encoding=utf-8-sig) as f:found.update(int(p) for p in f.read().split() if p.strip())except (FileNotFoundError, OSError, ValueError):continue # thread exited between listdir and opendiff --git a/tools/skill_linter.py b/tools/skill_linter.pyindex fa2f7a59c89..652a7a1d526 100644--- a/tools/skill_linter.py+++ b/tools/skill_linter.py@@ -159,7 +159,7 @@ def _check_files(frontmatter: Dict[str, Any], skill_dir: Path) -> Iterator[LintFif not script.is_file() or script.suffix not in (".py", ".sh", ".bash"):continuetry:- text = script.read_text(encoding="utf-8", errors="ignore")+ text = script.read_text(encoding="utf-8-sig", errors="ignore")except OSError:continuehit = [p for p in _POSIX_PRIMITIVES if p in text]diff --git a/tools/skill_manager_tool.py b/tools/skill_manager_tool.pyindex dbf56ccdb2d..08df9998dd8 100644--- a/tools/skill_manager_tool.py+++ b/tools/skill_manager_tool.py@@ -338,7 +338,7 @@ def _guarded_write(name: str, skill_dir: Path, target: Path, action: str, label:if target.exists():if read_guard := _background_review_read_before_write_guard(name, target, action, label):return read_guard- original = target.read_text(encoding="utf-8")+ original = target.read_text(encoding="utf-8-sig")target.parent.mkdir(parents=True, exist_ok=True)atomic_write_text(target, content, preserve_mode=True, create_mode=0o644)scan_error = _security_scan_skill(skill_dir)diff --git a/tools/skill_usage.py b/tools/skill_usage.pyindex ab5fd9dbb8e..7b2ac378c43 100644--- a/tools/skill_usage.py+++ b/tools/skill_usage.py@@ -229,7 +229,7 @@ def list_archived_skill_names() -> List[str]:def _read_skill_name(skill_md: Path, fallback: str) -> str:"""The frontmatter ``name:`` field of a SKILL.md (first 4000 chars), else *fallback*."""try:- lines = [line.strip() for line in skill_md.read_text(encoding="utf-8", errors="replace")[:4000].split("\n")]+ lines = [line.strip() for line in skill_md.read_text(encoding="utf-8-sig", errors="replace")[:4000].split("\n")]except OSError:return fallbackif "---" not in lines:@@ -351,7 +351,7 @@ def load_usage() -> Dict[str, Dict[str, Any]]:"""The whole .usage.json map (non-dict values dropped); {} on missing/corrupt."""path = _usage_file()try:- data = json.loads(path.read_text(encoding="utf-8")) if path.exists() else {}+ data = json.loads(path.read_text(encoding="utf-8-sig")) if path.exists() else {}except (OSError, json.JSONDecodeError) as e:logger.debug("Failed to read %s: %s", path, e)return {}diff --git a/tools/skills_hub_github.py b/tools/skills_hub_github.pyindex 3f4b3cb9c3a..92d7e617a6f 100644--- a/tools/skills_hub_github.py+++ b/tools/skills_hub_github.py@@ -130,7 +130,7 @@ class GitHubAuth:now = int(time.time())encoded_jwt = jwt.encode({"iat": now - 60, "exp": now + (10 * 60), "iss": app_id},- key_file.read_text(encoding="utf-8"), algorithm="RS256",+ key_file.read_text(encoding=utf-8-sig), algorithm="RS256",)resp = httpx.post(f"https://api.github.com/app/installations/{installation_id}/access_tokens",diff --git a/tools/skills_hub_official.py b/tools/skills_hub_official.pyindex 73bec7682eb..a636767837e 100644--- a/tools/skills_hub_official.py+++ b/tools/skills_hub_official.py@@ -112,7 +112,7 @@ class OptionalSkillSource(SkillSource):# Catalog stubs point at the real skill in an upstream-maintained repo# (metadata.hermes.upstream); install pulls the live content from there.try:- skill_md = (skill_dir / "SKILL.md").read_text(encoding="utf-8")+ skill_md = (skill_dir / "SKILL.md").read_text(encoding="utf-8-sig")except (OSError, UnicodeDecodeError):skill_md = Noneupstream = None if skill_md is None else self._upstream_pointer_from_content(skill_md)@@ -264,7 +264,7 @@ class OptionalSkillSource(SkillSource):for skill_md in self._local_skill_mds():parent = skill_md.parenttry:- content = skill_md.read_text(encoding="utf-8")+ content = skill_md.read_text(encoding="utf-8-sig")except (OSError, UnicodeDecodeError):continuefm = _parse_frontmatter(content)diff --git a/tools/skills_sync_client.py b/tools/skills_sync_client.pyindex abd6399b6dc..b1eae053dad 100644--- a/tools/skills_sync_client.py+++ b/tools/skills_sync_client.py@@ -223,7 +223,7 @@ def stable_device_id() -> str:"""Per-device label at ~/.hermes/skills/.sync_device_id. An existing file always wins; else seededfrom HERMES_SYNC_DEVICE_NAME (first use only, for Hermes Cloud) or a friendly default, then persisted."""with suppress(OSError):- val = _device_id_path().read_text(encoding="utf-8").strip()+ val = _device_id_path().read_text(encoding="utf-8-sig").strip()if val:return valval = (os.environ.get("HERMES_SYNC_DEVICE_NAME") or "").strip() or _default_device_label()@@ -259,7 +259,7 @@ _EMPTY_STATE: Dict[str, Any] = {"head": None, "skills": {}}def _load_state_file(path: Path, what: str = "sync state read") -> Optional[Dict[str, Any]]:"""Parse a state file; None if missing / corrupt / not a dict."""try:- data = json.loads(path.read_text(encoding="utf-8"))+ data = json.loads(path.read_text(encoding="utf-8-sig"))except (OSError, json.JSONDecodeError) as e:logger.debug("skills_sync_client: %s failed: %s", what, e)return Nonediff --git a/tools/skills_sync_client_org.py b/tools/skills_sync_client_org.pyindex 936d9156934..f8cc09157d4 100644--- a/tools/skills_sync_client_org.py+++ b/tools/skills_sync_client_org.py@@ -111,7 +111,7 @@ def _sidecar_path(org_id: Optional[str], const: str) -> Path:def _read_org_baseline(org_id: str) -> Dict[str, Any]:"""The baseline sidecar: upstream fingerprint + tree of each mirrored skill ({} if absent)."""try:- return json.loads(_sidecar_path(org_id, "ORG_BASELINE_FILE").read_text(encoding="utf-8"))+ return json.loads(_sidecar_path(org_id, "ORG_BASELINE_FILE").read_text(encoding="utf-8-sig"))except Exception:return {}diff --git a/tools/skills_sync_optional.py b/tools/skills_sync_optional.pyindex 20bcf969363..dd7d8626d11 100644--- a/tools/skills_sync_optional.py+++ b/tools/skills_sync_optional.py@@ -46,7 +46,7 @@ def _skill_file_list(skill_dir: Path) -> List[str]:def _load_hub_lock() -> Optional[dict]:"""Parse the skills-hub lock; None when missing or unreadable."""try:- return json.loads((_ss()._skills_dir() / ".hub" / "lock.json").read_text(encoding="utf-8"))+ return json.loads((_ss()._skills_dir() / ".hub" / "lock.json").read_text(encoding=utf-8-sig))except (FileNotFoundError, json.JSONDecodeError, OSError):return Nonediff --git a/tools/terminal_tool_result.py b/tools/terminal_tool_result.pyindex 344a286681f..7118af24425 100644--- a/tools/terminal_tool_result.py+++ b/tools/terminal_tool_result.py@@ -168,7 +168,7 @@ def _redact_spill_file(path, total_chars, command) -> list[tuple[str, Any]]:from agent.redact import redact_terminal_outputfrom tools.ansi_strip import strip_ansifrom tools.spill_safety import write_text_exclusive- raw_spill = Path(path).read_text(encoding="utf-8", errors="replace")+ raw_spill = Path(path).read_text(encoding="utf-8-sig", errors="replace")# lstat-checked unlink + exclusive create: the redacted copy can't# be diverted through a symlink planted since the collector's write.write_text_exclusive(Path(path), redact_terminal_output(strip_ansi(raw_spill), command),diff --git a/tools/transcription_local.py b/tools/transcription_local.pyindex 1dfd606db5e..0dd110dceef 100644--- a/tools/transcription_local.py+++ b/tools/transcription_local.py@@ -248,7 +248,7 @@ def _transcribe_local_command(txt_files = sorted(Path(output_dir).glob("*.txt"))if not txt_files:return _error_result("Local STT command completed but did not produce a .txt transcript")- transcript_text = txt_files[0].read_text(encoding="utf-8").strip()+ transcript_text = txt_files[0].read_text(encoding="utf-8-sig").strip()logger.info("Transcribed %s via local STT command (%s, %d chars)",Path(file_path).name, normalized_model, len(transcript_text))return _ok_result(transcript_text, "local_command")diff --git a/tools/tts_tool_providers.py b/tools/tts_tool_providers.pyindex 09b12a02eaa..7c2e81cea9e 100644--- a/tools/tts_tool_providers.py+++ b/tools/tts_tool_providers.py@@ -480,7 +480,7 @@ def _read_gemini_persona_prompt(gemini_config: Dict[str, Any]) -> str:except Exception:path = Path.cwd() / pathtry:- return path.read_text(encoding="utf-8").strip()+ return path.read_text(encoding="utf-8-sig").strip()except (OSError, UnicodeDecodeError) as exc:logger.warning("Gemini TTS persona prompt file unavailable at %s: %s", path, exc)return ""diff --git a/tools/write_approval.py b/tools/write_approval.pyindex 43111a484e8..000ef2eea68 100644--- a/tools/write_approval.py+++ b/tools/write_approval.py@@ -270,7 +270,7 @@ def skill_pending_diff(record: Dict[str, Any]) -> str:target_label = payload.get("file_path") or "SKILL.md"with suppress(Exception):p = skill_dir / target_label- current = p.read_text(encoding="utf-8") if p.exists() else ""+ current = p.read_text(encoding=utf-8-sig) if p.exists() else ""if action == "patch":old_s, new_s = payload.get("old_string") or "", payload.get("new_string") or ""