The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: read source files with encoding=utf-8-sig
ethernet6e294f543d4d
diff --git a/acp_adapter/edit_approval.py b/acp_adapter/edit_approval.pyindex b73325ec093..f70eeb6b820 100644--- a/acp_adapter/edit_approval.py+++ b/acp_adapter/edit_approval.py@@ -76,7 +76,7 @@ def _read_text_if_exists(path: str) -> str | None:return Noneif not p.is_file():raise OSError(f"Cannot edit non-file path: {path}")- return p.read_text(encoding="utf-8", errors="replace")+ return p.read_text(encoding="utf-8-sig", errors="replace")def _proposal_for_write_file(arguments: dict[str, Any]) -> EditProposal:diff --git a/agent/coding_context.py b/agent/coding_context.pyindex 333de26b054..200d576cb2b 100644--- a/agent/coding_context.py+++ b/agent/coding_context.py@@ -773,7 +773,7 @@ def _read_small(path: Path) -> str:try:if not path.is_file() or path.stat().st_size > _MAX_FACT_FILE_BYTES:return ""- return path.read_text(encoding="utf-8", errors="replace")+ return path.read_text(encoding="utf-8-sig", errors="replace")except OSError:return ""diff --git a/agent/context_references.py b/agent/context_references.pyindex dd36e67672c..4ce6fd5809c 100644--- a/agent/context_references.py+++ b/agent/context_references.py@@ -387,7 +387,7 @@ def _expand_file_reference(# so it can read/convert/view the file itself.return None, _binary_reference_block(ref, path)- text = path.read_text(encoding="utf-8")+ text = path.read_text(encoding="utf-8-sig")if ref.line_start is not None:lines = text.splitlines()start_idx = max(ref.line_start - 1, 0)@@ -697,7 +697,7 @@ def _file_metadata(path: Path) -> str:if _is_binary_file(path):return f"{path.stat().st_size} bytes"try:- line_count = path.read_text(encoding="utf-8").count("\n") + 1+ line_count = path.read_text(encoding="utf-8-sig").count("\n") + 1except Exception:return f"{path.stat().st_size} bytes"return f"{line_count} lines"diff --git a/agent/copilot_acp_client.py b/agent/copilot_acp_client.pyindex a547895b261..b5692336829 100644--- a/agent/copilot_acp_client.py+++ b/agent/copilot_acp_client.py@@ -111,7 +111,11 @@ def _acp_supported(command: str, args: list[str]) -> bool | None:try:probe = subprocess.run([command, "--help"],- capture_output=True, text=True, timeout=5,+ # Explicit codec because text=True alone decodes with the+ # locale default and crashes on non-ASCII help text under+ # GBK/CP932 locales.+ capture_output=True, text=True, encoding="utf-8",+ errors="replace", timeout=5,)except (FileNotFoundError, subprocess.TimeoutExpired, OSError):return None@@ -622,7 +626,7 @@ class CopilotACPClient:if block_error:raise PermissionError(block_error)try:- content = path.read_text(encoding="utf-8")+ content = path.read_text(encoding="utf-8-sig")except FileNotFoundError:content = ""line = params.get("line")diff --git a/agent/credits_tracker.py b/agent/credits_tracker.pyindex 39c74ea58b9..6e3c51634c0 100644--- a/agent/credits_tracker.py+++ b/agent/credits_tracker.py@@ -725,7 +725,7 @@ def dev_fixture_credits_state() -> Optional[CreditsState]:name = rawif os.path.sep in raw or "/" in raw: # looks like a path → read the name from the filetry:- with open(raw, "r", encoding="utf-8") as fh:+ with open(raw, "r", encoding="utf-8-sig") as fh:name = fh.read().strip()except OSError:return Nonediff --git a/agent/curator.py b/agent/curator.pyindex c08d2496123..40d6648e3ab 100644--- a/agent/curator.py+++ b/agent/curator.py@@ -103,7 +103,7 @@ def load_state() -> Dict[str, Any]:if not path.exists():return _default_state()try:- data = json.loads(path.read_text(encoding="utf-8"))+ data = json.loads(path.read_text(encoding="utf-8-sig"))if isinstance(data, dict):base = _default_state()base.update({k: v for k, v in data.items() if k in base or k.startswith("_")})diff --git a/agent/curator_backup.py b/agent/curator_backup.pyindex dbd0f4701f5..7934ebdbcc5 100644--- a/agent/curator_backup.py+++ b/agent/curator_backup.py@@ -343,7 +343,7 @@ def _read_manifest(snap_dir: Path) -> Dict[str, Any]:if not mf.exists():return {}try:- return json.loads(mf.read_text(encoding="utf-8"))+ return json.loads(mf.read_text(encoding="utf-8-sig"))except (OSError, json.JSONDecodeError):return {}@@ -434,7 +434,7 @@ def _restore_cron_skill_links(snapshot_dir: Path) -> Dict[str, Any]:return reporttry:- backup_text = backup_file.read_text(encoding="utf-8")+ backup_text = backup_file.read_text(encoding="utf-8-sig")backup_parsed = json.loads(backup_text)except (OSError, json.JSONDecodeError) as e:report["error"] = f"failed to load backed-up jobs: {e}"diff --git a/agent/display.py b/agent/display.pyindex 2880cecccb8..8296b422430 100644--- a/agent/display.py+++ b/agent/display.py@@ -801,7 +801,7 @@ def _resolved_path(path: str) -> Path:def _snapshot_text(path: Path) -> str | None:"""Return UTF-8 file content, or None for missing/unreadable files."""try:- return path.read_text(encoding="utf-8")+ return path.read_text(encoding="utf-8-sig")except (FileNotFoundError, IsADirectoryError, UnicodeDecodeError, OSError):return Nonediff --git a/agent/estop.py b/agent/estop.pyindex 92cd7c32da7..d012aac127b 100644--- a/agent/estop.py+++ b/agent/estop.py@@ -113,7 +113,7 @@ def get_state() -> Optional[dict]:reason = Noneengaged_at = Nonetry:- raw = json.loads(path.read_text(encoding="utf-8"))+ raw = json.loads(path.read_text(encoding="utf-8-sig"))if isinstance(raw, dict):reason = raw.get("reason") or Noneengaged_at = raw.get("engaged_at") or Nonediff --git a/agent/i18n.py b/agent/i18n.pyindex 7c0dcf5c87e..f5e2b67d56f 100644--- a/agent/i18n.py+++ b/agent/i18n.py@@ -162,7 +162,7 @@ def _load_catalog(lang: str) -> dict[str, str]:try:import yaml # PyYAML is already a hermes dependency- with path.open("r", encoding="utf-8") as f:+ with path.open("r", encoding="utf-8-sig") as f:raw = yaml.safe_load(f) or {}except Exception as exc:logger.warning("Failed to load i18n catalog %s: %s", path, exc)diff --git a/agent/learning_graph.py b/agent/learning_graph.pyindex b655e3e948d..4547e0dc574 100644--- a/agent/learning_graph.py+++ b/agent/learning_graph.py@@ -89,7 +89,7 @@ def _load_usage() -> dict[str, dict[str, Any]]:except Exception:path = get_hermes_home() / "skills" / ".usage.json"try:- return json.loads(path.read_text(encoding="utf-8"))+ return json.loads(path.read_text(encoding="utf-8-sig"))except Exception:return {}@@ -130,7 +130,7 @@ def build_skill_nodes(skill_roots: list[tuple[str, Path]]) -> dict[str, SkillNodif any(p in {".archive", ".hub", "node_modules", ".git"} for p in skill_md.parts):continuetry:- fm = _frontmatter(skill_md.read_text(encoding="utf-8")[:4000])+ fm = _frontmatter(skill_md.read_text(encoding="utf-8-sig")[:4000])except OSError:continuename = str(fm.get("name") or skill_md.parent.name).strip()@@ -201,7 +201,7 @@ def _memory_cards() -> list[dict[str, Any]]:for fname, source in (("MEMORY.md", "memory"), ("USER.md", "profile")):path = base / fnametry:- text = path.read_text(encoding="utf-8").strip()+ text = path.read_text(encoding="utf-8-sig").strip()file_ts = _to_int_ts(path.stat().st_mtime)except OSError:continuediff --git a/agent/learning_mutations.py b/agent/learning_mutations.pyindex c723b6153bc..74e17cb85ae 100644--- a/agent/learning_mutations.py+++ b/agent/learning_mutations.py@@ -114,7 +114,7 @@ def _node_detail(node_id: str) -> dict[str, Any]:"kind": "skill","id": node_id,"label": node_id,- "content": skill_md.read_text(encoding="utf-8"),+ "content": skill_md.read_text(encoding="utf-8-sig"),}diff --git a/agent/lsp/client.py b/agent/lsp/client.pyindex 36c27210276..59de160f18e 100644--- a/agent/lsp/client.py+++ b/agent/lsp/client.py@@ -764,7 +764,7 @@ class LSPClient:abs_path = os.path.abspath(path)try:- text = Path(abs_path).read_text(encoding="utf-8", errors="replace")+ text = Path(abs_path).read_text(encoding="utf-8-sig", errors="replace")except OSError as e:raise LSPProtocolError(f"cannot read {abs_path}: {e}") from ediff --git a/agent/models_dev.py b/agent/models_dev.pyindex fca9201eb69..79046d5ae23 100644--- a/agent/models_dev.py+++ b/agent/models_dev.py@@ -248,7 +248,7 @@ def _load_etag() -> str:try:etag_path = _get_etag_path()if etag_path.exists():- return etag_path.read_text(encoding="utf-8").strip()+ return etag_path.read_text(encoding="utf-8-sig").strip()except Exception as e:logger.debug("Failed to load models.dev ETag: %s", e)return ""@@ -314,7 +314,7 @@ def _load_disk_cache() -> Dict[str, Any]:try:cache_path = _get_cache_path()if cache_path.exists():- with open(cache_path, encoding="utf-8") as f:+ with open(cache_path, encoding="utf-8-sig") as f:data = json.load(f)if not _validate_registry(data):logger.warning(diff --git a/agent/nous_rate_guard.py b/agent/nous_rate_guard.pyindex 0234eef2ea2..7ef4b850eca 100644--- a/agent/nous_rate_guard.py+++ b/agent/nous_rate_guard.py@@ -144,7 +144,7 @@ def nous_rate_limit_remaining() -> Optional[float]:"""path = _state_path()try:- with open(path, encoding="utf-8") as f:+ with open(path, encoding="utf-8-sig") as f:state = json.load(f)reset_at = state.get("reset_at", 0)remaining = reset_at - time.time()diff --git a/agent/onboarding.py b/agent/onboarding.pyindex 148fbcc9fda..e1cf450bc6d 100644--- a/agent/onboarding.py+++ b/agent/onboarding.py@@ -230,7 +230,7 @@ def mark_seen(config_path: Path, flag: str) -> bool:try:cfg: dict = {}if config_path.exists():- with open(config_path, encoding="utf-8") as f:+ with open(config_path, encoding="utf-8-sig") as f:cfg = yaml.safe_load(f) or {}if not isinstance(cfg.get("onboarding"), dict):cfg["onboarding"] = {}diff --git a/agent/pet/store.py b/agent/pet/store.pyindex 42627c1ac81..909042baaca 100644--- a/agent/pet/store.py+++ b/agent/pet/store.py@@ -65,7 +65,7 @@ def _read_pet_json(directory: Path) -> dict:if not pet_json.is_file():return {}try:- return json.loads(pet_json.read_text(encoding="utf-8"))+ return json.loads(pet_json.read_text(encoding="utf-8-sig"))except (OSError, ValueError) as exc:logger.debug("unreadable pet.json in %s: %s", directory, exc)return {}@@ -438,7 +438,7 @@ def rename_pet(slug: str, display_name: str) -> str | None:if not pet_json.is_file():return Nonetry:- meta = json.loads(pet_json.read_text(encoding="utf-8"))+ meta = json.loads(pet_json.read_text(encoding="utf-8-sig"))except (OSError, ValueError):meta = {}if not isinstance(meta, dict):diff --git a/agent/prompt_builder.py b/agent/prompt_builder.pyindex 55b1f4fd874..542b764c0c1 100644--- a/agent/prompt_builder.py+++ b/agent/prompt_builder.py@@ -1573,7 +1573,7 @@ def _load_skills_snapshot(skills_dir: Path) -> Optional[dict]:if not snapshot_path.exists():return Nonetry:- snapshot = json.loads(snapshot_path.read_text(encoding="utf-8"))+ snapshot = json.loads(snapshot_path.read_text(encoding="utf-8-sig"))except Exception:return Noneif not isinstance(snapshot, dict):@@ -1651,7 +1651,7 @@ def _build_snapshot_entry(prov_path = (skills_dir / ORG_MIRROR_DIR_NAME / org_id / ORG_PROVENANCE_FILE)- prov = _json.loads(prov_path.read_text(encoding="utf-8"))+ prov = _json.loads(prov_path.read_text(encoding="utf-8-sig"))device = str(prov.get("author_device") or "")entry["org_author"] = device or str(prov.get("author_user_id") or "")except Exception:@@ -1670,7 +1670,7 @@ def _parse_skill_file(skill_file: Path) -> tuple[bool, dict, str]:(True, {}, "") to err on the side of showing the skill."""try:- raw = skill_file.read_text(encoding="utf-8")+ raw = skill_file.read_text(encoding="utf-8-sig")frontmatter, _ = parse_frontmatter(raw)if not skill_matches_platform(frontmatter):@@ -1961,7 +1961,7 @@ def _build_skills_system_prompt_inner(# Read category-level DESCRIPTION.md filesfor desc_file in iter_skill_index_files(skills_dir, "DESCRIPTION.md"):try:- content = desc_file.read_text(encoding="utf-8")+ content = desc_file.read_text(encoding="utf-8-sig")fm, _ = parse_frontmatter(content)cat_desc = fm.get("description")if not cat_desc:@@ -2019,7 +2019,7 @@ def _build_skills_system_prompt_inner(# External category descriptionsfor desc_file in iter_skill_index_files(ext_dir, "DESCRIPTION.md"):try:- content = desc_file.read_text(encoding="utf-8")+ content = desc_file.read_text(encoding="utf-8-sig")fm, _ = parse_frontmatter(content)cat_desc = fm.get("description")if not cat_desc:@@ -2193,7 +2193,7 @@ def load_soul_md(if not soul_path.exists():return Nonetry:- content = soul_path.read_text(encoding="utf-8").strip()+ content = soul_path.read_text(encoding="utf-8-sig").strip()if not content:return Nonecontent = _scan_context_content(content, "SOUL.md")@@ -2213,7 +2213,7 @@ def _load_hermes_md(cwd_path: Path, context_length: Optional[int] = None) -> strif not hermes_md_path:return ""try:- content = hermes_md_path.read_text(encoding="utf-8").strip()+ content = hermes_md_path.read_text(encoding="utf-8-sig").strip()if not content:return ""content = _strip_yaml_frontmatter(content)@@ -2283,7 +2283,7 @@ def _load_agents_md(cwd_path: Path, context_length: Optional[int] = None) -> strif not candidate.exists():continuetry:- content = candidate.read_text(encoding="utf-8").strip()+ content = candidate.read_text(encoding="utf-8-sig").strip()except Exception as e:logger.debug("Could not read %s: %s", candidate, e)continue@@ -2324,7 +2324,7 @@ def _load_claude_md(cwd_path: Path, context_length: Optional[int] = None) -> strcandidate = cwd_path / nameif candidate.exists():try:- content = candidate.read_text(encoding="utf-8").strip()+ content = candidate.read_text(encoding="utf-8-sig").strip()if content:content = _scan_context_content(content, name)result = f"## {name}\n\n{content}"@@ -2343,7 +2343,7 @@ def _load_cursorrules(cwd_path: Path, context_length: Optional[int] = None) -> scursorrules_file = cwd_path / ".cursorrules"if cursorrules_file.exists():try:- content = cursorrules_file.read_text(encoding="utf-8").strip()+ content = cursorrules_file.read_text(encoding="utf-8-sig").strip()if content:content = _scan_context_content(content, ".cursorrules")cursorrules_content += f"## .cursorrules\n\n{content}\n\n"@@ -2355,7 +2355,7 @@ def _load_cursorrules(cwd_path: Path, context_length: Optional[int] = None) -> smdc_files = sorted(cursor_rules_dir.glob("*.mdc"))for mdc_file in mdc_files:try:- content = mdc_file.read_text(encoding="utf-8").strip()+ content = mdc_file.read_text(encoding="utf-8-sig").strip()if content:content = _scan_context_content(content, f".cursor/rules/{mdc_file.name}")cursorrules_content += f"## .cursor/rules/{mdc_file.name}\n\n{content}\n\n"diff --git a/agent/proxy_sources/iron_proxy.py b/agent/proxy_sources/iron_proxy.pyindex 277cd018654..21e468b202c 100644--- a/agent/proxy_sources/iron_proxy.py+++ b/agent/proxy_sources/iron_proxy.py@@ -632,7 +632,7 @@ def _verify_checksums_signature(tmp: Path, checksum_path: Path) -> bool:def _expected_sha256(checksum_file: Path, asset_name: str) -> str:"""Parse the standard ``sha256sum`` output: ``<hex> <filename>``."""- text = checksum_file.read_text(encoding="utf-8", errors="replace")+ text = checksum_file.read_text(encoding="utf-8-sig", errors="replace")for line in text.splitlines():parts = line.strip().split()if len(parts) >= 2 and parts[-1] == asset_name:@@ -854,7 +854,7 @@ def ensure_management_token(*, force: bool = False) -> str:p = _management_token_path()if not force and p.exists():try:- existing = p.read_text(encoding="utf-8").strip()+ existing = p.read_text(encoding="utf-8-sig").strip()if existing:return existingexcept OSError:@@ -879,7 +879,7 @@ def ensure_management_token(*, force: bool = False) -> str:def _read_management_token() -> Optional[str]:p = _proxy_state_dir_ro() / "management.token"try:- token = p.read_text(encoding="utf-8").strip()+ token = p.read_text(encoding="utf-8-sig").strip()except OSError:return Nonereturn token or None@@ -898,7 +898,7 @@ def _read_management_listen_from_config(except ImportError:return Nonetry:- data = yaml.safe_load(cfg.read_text(encoding="utf-8"))+ data = yaml.safe_load(cfg.read_text(encoding="utf-8-sig"))except (OSError, yaml.YAMLError):return Nonelisten = ((data or {}).get("management") or {}).get("listen") or ""@@ -1427,7 +1427,7 @@ def load_mappings() -> List[TokenMapping]:if not f.exists():return []try:- payload = json.loads(f.read_text(encoding="utf-8"))+ payload = json.loads(f.read_text(encoding="utf-8-sig"))except (OSError, json.JSONDecodeError) as exc:logger.warning("Failed to read iron-proxy mappings.json: %s", exc)return []@@ -1579,7 +1579,7 @@ def _read_pid() -> Optional[int]:if not pf.exists():return Nonetry:- pid = int(pf.read_text(encoding="utf-8").strip())+ pid = int(pf.read_text(encoding="utf-8-sig").strip())except (OSError, ValueError):return Nonereturn pid if pid > 0 else None@@ -1601,7 +1601,7 @@ def _pid_proc_starttime(pid: int) -> Optional[str]:the cmdline + nonce check."""try:- text = Path(f"/proc/{pid}/stat").read_text(encoding="utf-8")+ text = Path(f"/proc/{pid}/stat").read_text(encoding="utf-8-sig")except OSError:return None# /proc/<pid>/stat: pid (comm-with-parens) state ppid ... fields[21]=starttime@@ -2403,7 +2403,7 @@ def _read_http_listen_from_config() -> Optional[Tuple[str, int]]:except ImportError:return Nonetry:- data = yaml.safe_load(cfg.read_text(encoding="utf-8"))+ data = yaml.safe_load(cfg.read_text(encoding="utf-8-sig"))except (OSError, yaml.YAMLError):return Noneproxy_block = (data or {}).get("proxy") or {}diff --git a/agent/secret_sources/_cache.py b/agent/secret_sources/_cache.pyindex 64e1e5e13ca..aa6d20f81b9 100644--- a/agent/secret_sources/_cache.py+++ b/agent/secret_sources/_cache.py@@ -137,7 +137,7 @@ class DiskCache(Generic[K]):return Nonepath = self.path(home_path)try:- with open(path, "r", encoding="utf-8") as f:+ with open(path, "r", encoding="utf-8-sig") as f:payload = json.load(f)except (OSError, json.JSONDecodeError):return Nonediff --git a/agent/secret_sources/bitwarden.py b/agent/secret_sources/bitwarden.pyindex 64195221770..0614d15a56b 100644--- a/agent/secret_sources/bitwarden.py+++ b/agent/secret_sources/bitwarden.py@@ -289,7 +289,7 @@ def _expected_sha256(checksum_file: Path, asset_name: str) -> str:Format is the standard ``sha256sum`` output: ``<hex> <filename>``,one per line."""- text = checksum_file.read_text(encoding="utf-8", errors="replace")+ text = checksum_file.read_text(encoding="utf-8-sig", errors="replace")for line in text.splitlines():parts = line.strip().split()if len(parts) >= 2 and parts[-1] == asset_name:@@ -466,7 +466,7 @@ def _read_encrypted_disk_cache(try:from cryptography.hazmat.primitives.ciphers.aead import AESGCM- payload = json.loads(path.read_text(encoding="utf-8"))+ payload = json.loads(path.read_text(encoding="utf-8-sig"))if not isinstance(payload, dict):return Noneserialized_key = _cache_key_str(cache_key)diff --git a/agent/shell_hooks.py b/agent/shell_hooks.pyindex 8751aeb6fd9..aed3d252ff6 100644--- a/agent/shell_hooks.py+++ b/agent/shell_hooks.py@@ -853,7 +853,7 @@ def allowlist_path() -> Path:def load_allowlist() -> Dict[str, Any]:"""Return the parsed allowlist, or an empty skeleton if absent."""try:- raw = json.loads(allowlist_path().read_text(encoding="utf-8"))+ raw = json.loads(allowlist_path().read_text(encoding="utf-8-sig"))except (FileNotFoundError, json.JSONDecodeError, OSError):return {"approvals": []}if not isinstance(raw, dict):diff --git a/agent/skill_bundles.py b/agent/skill_bundles.pyindex 2727b5837c9..a28f746d13e 100644--- a/agent/skill_bundles.py+++ b/agent/skill_bundles.py@@ -120,7 +120,7 @@ def _load_bundle_file(path: Path) -> Optional[Dict[str, Any]]:shouldn't take down slash command discovery."""try:- raw = path.read_text(encoding="utf-8")+ raw = path.read_text(encoding="utf-8-sig")except OSError as exc:logger.warning("Could not read bundle %s: %s", path, exc)return Nonediff --git a/agent/skill_commands.py b/agent/skill_commands.pyindex f1e42e69023..cd0b9d17ad4 100644--- a/agent/skill_commands.py+++ b/agent/skill_commands.py@@ -467,7 +467,7 @@ def scan_skill_commands() -> Dict[str, Dict[str, Any]]:if any(part in {'.git', '.github', '.hub', '.archive'} for part in skill_md.parts):continuetry:- content = skill_md.read_text(encoding='utf-8')+ content = skill_md.read_text(encoding='utf-8-sig')frontmatter, body = _parse_frontmatter(content)# Skip skills incompatible with the current OS platformif not skill_matches_platform(frontmatter):diff --git a/agent/subdirectory_hints.py b/agent/subdirectory_hints.pyindex 11e4a7d4f9f..24dd6ad4dfc 100644--- a/agent/subdirectory_hints.py+++ b/agent/subdirectory_hints.py@@ -105,7 +105,7 @@ class SubdirectoryHintTracker: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):continueif content:@@ -285,7 +285,7 @@ class SubdirectoryHintTracker:except OSError:continuetry:- content = hint_path.read_text(encoding="utf-8").strip()+ content = hint_path.read_text(encoding="utf-8-sig").strip()if not content:continue# Skip content we've already injected. The same AGENTS.md isdiff --git a/agent/verify/environment.py b/agent/verify/environment.pyindex dc902fb6c1a..0c96da8342f 100644--- a/agent/verify/environment.py+++ b/agent/verify/environment.py@@ -32,7 +32,7 @@ def load_manifest(root: Path) -> Recipe | None:"""path = manifest_path(root)try:- raw = path.read_text(encoding="utf-8")+ raw = path.read_text(encoding="utf-8-sig")except OSError:return Nonetry:diff --git a/agent/verify/recipes.py b/agent/verify/recipes.pyindex 66578cb4fc2..d569fa6e93d 100644--- a/agent/verify/recipes.py+++ b/agent/verify/recipes.py@@ -121,7 +121,7 @@ class Recipe:def _read_text(root: Path, name: str) -> str | None:try:- return (root / name).read_text(encoding="utf-8")+ return (root / name).read_text(encoding="utf-8-sig")except OSError:return Nonediff --git a/cron/jobs.py b/cron/jobs.pyindex eb7a3a42e4e..eb183399f3f 100644--- a/cron/jobs.py+++ b/cron/jobs.py@@ -310,7 +310,7 @@ def _jobs_lock():try:try:ensure_dirs()- lock_fd = open(_jobs_lock_file(), "a+", encoding="utf-8")+ lock_fd = open(_jobs_lock_file(), "a+", encoding="utf-8-sig")lock_fd.seek(0)if fcntl is not None:# Bounded acquisition (#60703): a plain blocking@@ -1287,7 +1287,7 @@ def record_ticker_heartbeat(success: bool = False) -> None:def _epoch_file_age(path: Path) -> Optional[float]:try:- raw = path.read_text(encoding="utf-8").strip()+ raw = path.read_text(encoding="utf-8-sig").strip()return max(0.0, time.time() - float(raw))except Exception:return None@@ -1323,7 +1323,7 @@ def record_catch_up_occurrence() -> None:path = _current_cron_store().cron_dir / "catch_up_occurrences"try:try:- value = int(path.read_text(encoding="utf-8").strip())+ value = int(path.read_text(encoding="utf-8-sig").strip())except (OSError, ValueError):value = 0_atomic_write_counter(path, max(0, value) + 1)@@ -1370,7 +1370,7 @@ def get_catch_up_occurrence_count() -> int:"""Return the profile-local stale-schedule catch-up count."""path = _current_cron_store().cron_dir / "catch_up_occurrences"try:- return max(0, int(path.read_text(encoding="utf-8").strip()))+ return max(0, int(path.read_text(encoding="utf-8-sig").strip()))except (OSError, ValueError):return 0@@ -1388,7 +1388,7 @@ def get_ticker_last_error() -> Optional[str]:"""Return the most recent recorded tick error message, or None."""store = _current_cron_store()try:- raw = (store.cron_dir / "ticker_last_error").read_text(encoding="utf-8")+ raw = (store.cron_dir / "ticker_last_error").read_text(encoding="utf-8-sig")except Exception:return Nonelines = raw.splitlines()diff --git a/cron/monitor.py b/cron/monitor.pyindex e84c4ce4d73..faa99685ff6 100644--- a/cron/monitor.py+++ b/cron/monitor.py@@ -93,7 +93,7 @@ def _read_last_output(job_id: str) -> str:try:path = _snapshot_path(job_id)if path.exists():- return path.read_text(encoding="utf-8")+ return path.read_text(encoding="utf-8-sig")except Exception as exc:logger.warning("Monitor: failed to read last output for %r: %s", job_id, exc)return ""diff --git a/cron/scheduler.py b/cron/scheduler.pyindex 4b5af389eac..d8d9448b1ba 100644--- a/cron/scheduler.py+++ b/cron/scheduler.py@@ -4040,7 +4040,7 @@ def _get_session_db_timeout() -> float:def _read_windows_pyvenv_cfg(venv_dir: Path) -> dict[str, str]:cfg_path = venv_dir / "pyvenv.cfg"try:- lines = cfg_path.read_text(encoding="utf-8").splitlines()+ lines = cfg_path.read_text(encoding="utf-8-sig").splitlines()except OSError:return {}@@ -4665,7 +4665,7 @@ def _build_job_prompt()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()# Truncate to 8K characters to avoid prompt bloat_MAX_CONTEXT_CHARS = 8000if len(latest_output) > _MAX_CONTEXT_CHARS:@@ -6009,7 +6009,7 @@ def run_job(pfpath = _get_hermes_home() / pfpathif pfpath.exists():try:- with open(pfpath, "r", encoding="utf-8") as _pf:+ with open(pfpath, "r", encoding="utf-8-sig") as _pf:prefill_messages = json.load(_pf)if not isinstance(prefill_messages, list):prefill_messages = Nonediff --git a/cron/scripts/classify_items.py b/cron/scripts/classify_items.pyindex ba0cd42d4b4..968796a0b82 100644--- a/cron/scripts/classify_items.py+++ b/cron/scripts/classify_items.py@@ -48,7 +48,7 @@ def _eprint(*args: Any) -> None:def _load_items(input_file: Optional[str]) -> List[Dict[str, Any]]:raw = ""if input_file:- with open(input_file, encoding="utf-8") as f:+ with open(input_file, encoding="utf-8-sig") as f:raw = f.read()else:raw = sys.stdin.read()diff --git a/cron/suggestions.py b/cron/suggestions.pyindex d4e8107c20a..675de33bbd5 100644--- a/cron/suggestions.py+++ b/cron/suggestions.py@@ -79,7 +79,7 @@ def _load_raw() -> Dict[str, Any]:if not SUGGESTIONS_FILE.exists():return {"suggestions": []}try:- with open(SUGGESTIONS_FILE, "r", encoding="utf-8") as f:+ with open(SUGGESTIONS_FILE, "r", encoding="utf-8-sig") as f:data = json.load(f)except (json.JSONDecodeError, OSError) as e:logger.warning("suggestions.json unreadable (%s); starting empty", e)diff --git a/gateway/agent_cache_pressure.py b/gateway/agent_cache_pressure.pyindex 91fa999b64d..b2d5994886a 100644--- a/gateway/agent_cache_pressure.py+++ b/gateway/agent_cache_pressure.py@@ -124,7 +124,7 @@ def _cgroup_limit_bytes() -> Optional[int]:)for candidate in candidates:try:- raw = Path(candidate).read_text(encoding="utf-8").strip()+ raw = Path(candidate).read_text(encoding="utf-8-sig").strip()except OSError:continueif not raw or raw == "max":diff --git a/gateway/cgroup_cleanup.py b/gateway/cgroup_cleanup.pyindex a364294b909..2955fc0b32e 100644--- a/gateway/cgroup_cleanup.py+++ b/gateway/cgroup_cleanup.py@@ -24,7 +24,7 @@ from pathlib import Pathdef _own_cgroup_path() -> str | None:"""Return the cgroup v2 path for the calling process, or None."""try:- text = Path("/proc/self/cgroup").read_text(encoding="utf-8")+ text = Path("/proc/self/cgroup").read_text(encoding="utf-8-sig")except OSError:return Nonematch = re.search(r"^0::(.+)$", text, re.MULTILINE)@@ -36,7 +36,7 @@ def _own_cgroup_path() -> str | None:def _read_cgroup_pids(cgroup_path: str) -> list[int]:procs_file = Path(f"/sys/fs/cgroup{cgroup_path}/cgroup.procs")try:- raw = procs_file.read_text(encoding="utf-8")+ raw = procs_file.read_text(encoding="utf-8-sig")except OSError:return []pids: list[int] = []diff --git a/gateway/channel_directory.py b/gateway/channel_directory.pyindex 23d6f361e16..434f554c6ec 100644--- a/gateway/channel_directory.py+++ b/gateway/channel_directory.py@@ -40,7 +40,7 @@ def _load_channel_aliases() -> Dict[str, Dict[str, str]]:if not CHANNEL_ALIASES_PATH.exists():return {}try:- with open(CHANNEL_ALIASES_PATH, encoding="utf-8") as f:+ with open(CHANNEL_ALIASES_PATH, encoding="utf-8-sig") as f:data = json.load(f)return data if isinstance(data, dict) else {}except Exception:@@ -491,7 +491,7 @@ def _build_from_sessions_json(platform_name: str) -> List[Dict[str, str]]:entries = []try:- with open(sessions_path, encoding="utf-8") as f:+ with open(sessions_path, encoding="utf-8-sig") as f:data = json.load(f)seen_ids = set()@@ -530,7 +530,7 @@ def load_directory() -> Dict[str, Any]:_apply_channel_aliases(base["platforms"])return basetry:- with open(DIRECTORY_PATH, encoding="utf-8") as f:+ with open(DIRECTORY_PATH, encoding="utf-8-sig") as f:data = json.load(f)# Re-apply aliases on read so friendly names take effect immediately,# even between timed rebuilds and for brand-new alias entries.diff --git a/gateway/config.py b/gateway/config.pyindex 0931d067b66..18d8319b346 100644--- a/gateway/config.py+++ b/gateway/config.py@@ -1388,7 +1388,7 @@ def load_gateway_config() -> GatewayConfig:gateway_json_path = _home / "gateway.json"if gateway_json_path.exists():try:- with open(gateway_json_path, "r", encoding="utf-8") as f:+ with open(gateway_json_path, "r", encoding="utf-8-sig") as f:gw_data = json.load(f) or {}logger.info("Loaded legacy %s — consider moving settings to config.yaml",@@ -1402,7 +1402,7 @@ def load_gateway_config() -> GatewayConfig:import yamlconfig_yaml_path = _home / "config.yaml"if config_yaml_path.exists():- 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 so the gatewaydiff --git a/gateway/control_socket.py b/gateway/control_socket.pyindex 50c516f3937..c4a9ec7b1e5 100644--- a/gateway/control_socket.py+++ b/gateway/control_socket.py@@ -139,7 +139,7 @@ def resolve_client_socket_path(home: Path) -> Optional[Path]:pointer = _pointer_path(home)try:if pointer.is_file():- target = pointer.read_text(encoding="utf-8").strip()+ target = pointer.read_text(encoding="utf-8-sig").strip()if target:candidate = Path(target)if candidate.exists():diff --git a/gateway/dead_targets.py b/gateway/dead_targets.pyindex 15f9b908794..b2b5e901cdb 100644--- a/gateway/dead_targets.py+++ b/gateway/dead_targets.py@@ -67,7 +67,7 @@ class DeadTargetRegistry:def _load(self) -> None:try:if self._path.exists():- raw = json.loads(self._path.read_text(encoding="utf-8"))+ raw = json.loads(self._path.read_text(encoding="utf-8-sig"))if isinstance(raw, dict):# Only keep well-shaped entries.self._dead = {diff --git a/gateway/drain_control.py b/gateway/drain_control.pyindex ba7d9f6bf74..2003ad6e017 100644--- a/gateway/drain_control.py+++ b/gateway/drain_control.py@@ -131,7 +131,7 @@ def current_instantiation_epoch() -> str:try:boot_id = (Path("/proc/sys/kernel/random/boot_id")- .read_text(encoding="utf-8")+ .read_text(encoding="utf-8-sig").strip())except OSError:@@ -144,7 +144,7 @@ def current_instantiation_epoch() -> str:# index into the whitespace-delimited tail. starttime is field 22# (1-indexed); after the comm the tail starts at field 3, so it is the# tail's index 19.- stat = Path("/proc/1/stat").read_text(encoding="utf-8")+ stat = Path("/proc/1/stat").read_text(encoding="utf-8-sig")tail = stat.rsplit(")", 1)[1].split()pid1_start = tail[19]except (OSError, IndexError):@@ -357,7 +357,7 @@ def read_drain_request(*, home: Optional[Path] = None) -> Optional[dict[str, Any"""path = drain_request_path(home)try:- raw = path.read_text(encoding="utf-8")+ raw = path.read_text(encoding="utf-8-sig")except FileNotFoundError:return Noneexcept OSError as e:diff --git a/gateway/hooks.py b/gateway/hooks.pyindex 6ecba2a435b..acc2d16d3e0 100644--- a/gateway/hooks.py+++ b/gateway/hooks.py@@ -106,7 +106,7 @@ class HookRegistry:continuetry:- manifest = yaml.safe_load(manifest_path.read_text(encoding="utf-8"))+ manifest = yaml.safe_load(manifest_path.read_text(encoding="utf-8-sig"))if not manifest or not isinstance(manifest, dict):print(f"[hooks] Skipping {hook_dir.name}: invalid HOOK.yaml", flush=True)continuediff --git a/gateway/kanban_watchers.py b/gateway/kanban_watchers.pyindex ad8c64ae8b1..d958ceb8067 100644--- a/gateway/kanban_watchers.py+++ b/gateway/kanban_watchers.py@@ -146,7 +146,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-sig")except OSError:return None, "unavailable"if not _try_acquire_file_lock(handle):diff --git a/gateway/lifecycle_ledger.py b/gateway/lifecycle_ledger.pyindex 09500359395..39dbf9f80da 100644--- a/gateway/lifecycle_ledger.py+++ b/gateway/lifecycle_ledger.py@@ -82,7 +82,7 @@ def sample_memory() -> Dict[str, Any]:"""sample: Dict[str, Any] = {}try:- with open("/proc/self/status", encoding="utf-8") as fh:+ with open("/proc/self/status", encoding="utf-8-sig") as fh:for line in fh:if line.startswith("VmRSS:"):sample["rss_kib"] = int(line.split()[1])@@ -92,7 +92,7 @@ def sample_memory() -> Dict[str, Any]:try:meminfo: Dict[str, int] = {}wanted = {"MemTotal", "MemAvailable", "SwapTotal", "SwapFree"}- with open("/proc/meminfo", encoding="utf-8") as fh:+ with open("/proc/meminfo", encoding="utf-8-sig") as fh:for line in fh:key = line.split(":", 1)[0]if key in wanted:@@ -112,7 +112,7 @@ def sample_memory() -> Dict[str, Any]:def _read_json(path: Path) -> Optional[Dict[str, Any]]:try:- data = json.loads(path.read_text(encoding="utf-8"))+ data = json.loads(path.read_text(encoding="utf-8-sig"))except (OSError, ValueError):return Nonereturn data if isinstance(data, dict) else Nonediff --git a/gateway/mirror.py b/gateway/mirror.pyindex 2b086ce4f04..3742556e385 100644--- a/gateway/mirror.py+++ b/gateway/mirror.py@@ -155,7 +155,7 @@ def _find_session_id(return Nonetry:- with open(_SESSIONS_INDEX, encoding="utf-8") as f:+ with open(_SESSIONS_INDEX, encoding="utf-8-sig") as f:data = json.load(f)except Exception:return Nonediff --git a/gateway/pairing.py b/gateway/pairing.pyindex 23d213d689b..692fa719489 100644--- a/gateway/pairing.py+++ b/gateway/pairing.py@@ -360,7 +360,7 @@ def _sync_allowlist_remove(platform: str, user_id: str) -> None:def _load_json_file(path: Path) -> dict:if path.exists():try:- data = json.loads(path.read_text(encoding="utf-8"))+ data = json.loads(path.read_text(encoding="utf-8-sig"))return data if isinstance(data, dict) else {}except (json.JSONDecodeError, OSError):return {}@@ -497,7 +497,7 @@ class PairingStore:def _load_json(self, path: Path) -> dict:if path.exists():try:- return json.loads(path.read_text(encoding="utf-8"))+ return json.loads(path.read_text(encoding="utf-8-sig"))except PermissionError as e:# Surface this loudly: a 0600 file owned by a different user# (classic Docker symptom: `docker exec` runs as root and writesdiff --git a/gateway/platforms/helpers.py b/gateway/platforms/helpers.pyindex 9df6a8e0525..271e000681a 100644--- a/gateway/platforms/helpers.py+++ b/gateway/platforms/helpers.py@@ -250,7 +250,7 @@ class ThreadParticipationTracker:path = self._state_path()if path.exists():try:- data = json.loads(path.read_text(encoding="utf-8"))+ data = json.loads(path.read_text(encoding="utf-8-sig"))if isinstance(data, list):return [str(thread_id) for thread_id in data]except Exception:diff --git a/gateway/platforms/webhook.py b/gateway/platforms/webhook.pyindex 1ff741f1e25..6aa9c27ee32 100644--- a/gateway/platforms/webhook.py+++ b/gateway/platforms/webhook.py@@ -518,7 +518,7 @@ class WebhookAdapter(BasePlatformAdapter):mtime = subs_path.stat().st_mtimeif mtime <= self._dynamic_routes_mtime:return # No change- data = json.loads(subs_path.read_text(encoding="utf-8"))+ data = json.loads(subs_path.read_text(encoding="utf-8-sig"))if not isinstance(data, dict):return# Merge: static routes take precedence over dynamic ones.diff --git a/gateway/platforms/webhook_filters.py b/gateway/platforms/webhook_filters.pyindex 881effdf85a..e105dc2f30c 100644--- a/gateway/platforms/webhook_filters.py+++ b/gateway/platforms/webhook_filters.py@@ -76,7 +76,7 @@ def _load_filter_file_values(path_value: Any) -> list[Any]:if path is None:return []try:- raw = path.read_text(encoding="utf-8")+ raw = path.read_text(encoding="utf-8-sig")except OSError as exc:logger.warning("[webhook] filter in_file read failed for %s: %s", path, exc)return []diff --git a/gateway/platforms/weixin.py b/gateway/platforms/weixin.pyindex 8c2b18b7658..dfc23e51d46 100644--- a/gateway/platforms/weixin.py+++ b/gateway/platforms/weixin.py@@ -290,7 +290,7 @@ def load_weixin_account(hermes_home: str, account_id: str) -> Optional[Dict[str,if not path.exists():return Nonetry:- return json.loads(path.read_text(encoding="utf-8"))+ return json.loads(path.read_text(encoding="utf-8-sig"))except Exception:return None@@ -313,7 +313,7 @@ class ContextTokenStore:if not path.exists():returntry:- data = json.loads(path.read_text(encoding="utf-8"))+ data = json.loads(path.read_text(encoding="utf-8-sig"))except Exception as exc:logger.warning("weixin: failed to restore context tokens for %s: %s", _safe_id(account_id), exc)return@@ -1024,7 +1024,7 @@ def _load_sync_buf(hermes_home: str, account_id: str) -> str:if not path.exists():return ""try:- return json.loads(path.read_text(encoding="utf-8")).get("get_updates_buf", "")+ return json.loads(path.read_text(encoding="utf-8-sig")).get("get_updates_buf", "")except Exception:return ""diff --git a/gateway/readiness.py b/gateway/readiness.pyindex 9cffd39cce1..8f9e6a70e6b 100644--- a/gateway/readiness.py+++ b/gateway/readiness.py@@ -50,7 +50,7 @@ def _probe_config(home: Path) -> dict[str, Any]:if not path.exists():return _check("ok", "using defaults")try:- raw = yaml.safe_load(path.read_text(encoding="utf-8"))+ raw = yaml.safe_load(path.read_text(encoding="utf-8-sig"))if raw is not None and not isinstance(raw, dict):return _check("degraded", "top level is not a mapping")return _check("ok")diff --git a/gateway/restart_loop_guard.py b/gateway/restart_loop_guard.pyindex 581a1986cf2..0dd9c8984dc 100644--- a/gateway/restart_loop_guard.py+++ b/gateway/restart_loop_guard.py@@ -71,7 +71,7 @@ def _state_path():def _load_boots() -> List[float]:try:- raw = _state_path().read_text(encoding="utf-8")+ raw = _state_path().read_text(encoding="utf-8-sig")data = json.loads(raw)boots = data.get("boots", [])return [float(t) for t in boots if isinstance(t, (int, float))]diff --git a/gateway/rich_sent_store.py b/gateway/rich_sent_store.pyindex 264d030941d..c4a4d27bc04 100644--- a/gateway/rich_sent_store.py+++ b/gateway/rich_sent_store.py@@ -44,7 +44,7 @@ def record(chat_id, message_id, text: Optional[str]) -> None:try:os.makedirs(os.path.dirname(path), exist_ok=True)try:- with open(path, "r", encoding="utf-8") as fh:+ with open(path, "r", encoding="utf-8-sig") as fh:data = json.load(fh)if not isinstance(data, dict):data = {}@@ -73,7 +73,7 @@ def lookup(chat_id, message_id) -> Optional[str]:if message_id is None or chat_id is None:return Nonetry:- with open(_store_path(), "r", encoding="utf-8") as fh:+ with open(_store_path(), "r", encoding="utf-8-sig") as fh:data = json.load(fh)entry = data.get(_key(chat_id, message_id))if isinstance(entry, dict):diff --git a/gateway/session.py b/gateway/session.pyindex d7770188613..066b6f3504e 100644--- a/gateway/session.py+++ b/gateway/session.py@@ -1497,7 +1497,7 @@ class SessionStore:sessions_file = self.sessions_dir / "sessions.json"if sessions_file.exists():try:- 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/shutdown_flush.py b/gateway/shutdown_flush.pyindex a727dd975a0..6e3c00efe28 100644--- a/gateway/shutdown_flush.py+++ b/gateway/shutdown_flush.py@@ -211,7 +211,7 @@ def drain_transcript_spool(session_id: str, replay) -> tuple[int, int]:entries = []for path in candidates:try:- payload = json.loads(path.read_text(encoding="utf-8"))+ payload = json.loads(path.read_text(encoding="utf-8-sig"))except Exception:continueif payload.get("reason") != TRANSCRIPT_CAP_DROP_REASON:@@ -327,7 +327,7 @@ def recover_pending_to_db(recovered = 0for path in flush_files:try:- payload = json.loads(path.read_text(encoding="utf-8"))+ payload = json.loads(path.read_text(encoding="utf-8-sig"))# Agent-history snapshots use a different schema (reason +# messages list) and are meant for manual operator recovery,# not automatic DB insertion. Skip them silently.diff --git a/gateway/shutdown_forensics.py b/gateway/shutdown_forensics.pyindex 4a4a76925fd..f1c6af95c23 100644--- a/gateway/shutdown_forensics.py+++ b/gateway/shutdown_forensics.py@@ -53,7 +53,7 @@ def _signal_name(sig: Any) -> str:def _read_proc_field(pid: int, key: str) -> Optional[str]:"""Read a single field from /proc/<pid>/status. Linux only; None elsewhere."""try:- with open(f"/proc/{pid}/status", encoding="utf-8") as fh:+ with open(f"/proc/{pid}/status", encoding="utf-8-sig") as fh:for line in fh:if line.startswith(key + ":"):return line.split(":", 1)[1].strip()@@ -178,7 +178,7 @@ def snapshot_shutdown_context(received_signal: Any = None) -> Dict[str, Any]:takeover_path = Path(hermes_home_str) / ".gateway-takeover.json"if takeover_path.exists():try:- raw = takeover_path.read_text(encoding="utf-8")+ raw = takeover_path.read_text(encoding="utf-8-sig")ctx["takeover_marker"] = raw[:300]ctx["takeover_marker_for_self"] = (f'"target_pid": {pid}' in raw@@ -189,7 +189,7 @@ def snapshot_shutdown_context(received_signal: Any = None) -> Dict[str, Any]:planned_stop_path = Path(hermes_home_str) / ".gateway-planned-stop.json"if planned_stop_path.exists():try:- raw = planned_stop_path.read_text(encoding="utf-8")+ raw = planned_stop_path.read_text(encoding="utf-8-sig")ctx["planned_stop_marker"] = raw[:300]except OSError:pass@@ -353,7 +353,7 @@ def check_systemd_timing_alignment(unit_name: Optional[str] = Nonetry:# /proc/self/cgroup gives us "0::/user.slice/.../hermes-gateway.service"- with open("/proc/self/cgroup", encoding="utf-8") as fh:+ with open("/proc/self/cgroup", encoding="utf-8-sig") as fh:for line in fh:# systemd cgroup line ends with the unit nameif ".service" in line:diff --git a/gateway/status_phrases.py b/gateway/status_phrases.pyindex b7c490273e1..42f4cd07976 100644--- a/gateway/status_phrases.py+++ b/gateway/status_phrases.py@@ -77,7 +77,7 @@ def _merge_phrase_mapping(catalog: dict[str, list[str]], section: Mapping[str, Adef _merge_phrase_file(catalog: dict[str, list[str]], path: Path, *, inherited_mode: str | None = None) -> None:try:- loaded = yaml.safe_load(path.read_text(encoding="utf-8"))+ loaded = yaml.safe_load(path.read_text(encoding="utf-8-sig"))except Exception:returnif isinstance(loaded, Mapping):diff --git a/gateway/sticker_cache.py b/gateway/sticker_cache.pyindex c5368173067..3bdc0d98b7e 100644--- a/gateway/sticker_cache.py+++ b/gateway/sticker_cache.py@@ -30,7 +30,7 @@ def _load_cache() -> dict:"""Load the sticker cache from disk."""if CACHE_PATH.exists():try:- return json.loads(CACHE_PATH.read_text(encoding="utf-8"))+ return json.loads(CACHE_PATH.read_text(encoding="utf-8-sig"))except (json.JSONDecodeError, OSError):return {}return {}diff --git a/gateway/whatsapp_identity.py b/gateway/whatsapp_identity.pyindex 19fade10b4e..0f51ebf2329 100644--- a/gateway/whatsapp_identity.py+++ b/gateway/whatsapp_identity.py@@ -159,7 +159,7 @@ def expand_whatsapp_aliases(identifier: str) -> Set[str]:continuetry:mapped = normalize_whatsapp_identifier(- json.loads(mapping_path.read_text(encoding="utf-8"))+ json.loads(mapping_path.read_text(encoding="utf-8-sig")))except (OSError, json.JSONDecodeError) as exc:logger.debug("whatsapp_identity: failed to read %s: %s", mapping_path, exc)diff --git a/hermes_cli/_early_recovery.py b/hermes_cli/_early_recovery.pyindex 6bae52b9733..52e6eb1b240 100644--- a/hermes_cli/_early_recovery.py+++ b/hermes_cli/_early_recovery.py@@ -201,7 +201,7 @@ def _pid_is_running(pid: int) -> bool:def _marker_owner_is_live(marker: Path) -> bool:"""True when a legacy update marker names a process still running."""try:- body = marker.read_text(encoding="utf-8", errors="replace")+ body = marker.read_text(encoding="utf-8-sig", errors="replace")except OSError:return Falsefor line in body.splitlines():@@ -605,7 +605,7 @@ def _complete_pending_core_install(root: Path, core_marker: Path) -> bool:# increment the counter reflects THIS attempt.attempts = 0try:- raw = core_marker.read_text(encoding="utf-8", errors="replace").strip()+ raw = core_marker.read_text(encoding="utf-8-sig", errors="replace").strip()if raw:import json as _jsondiff --git a/hermes_cli/active_sessions.py b/hermes_cli/active_sessions.pyindex e1cd8b03072..996c53f69e2 100644--- a/hermes_cli/active_sessions.py+++ b/hermes_cli/active_sessions.py@@ -201,7 +201,7 @@ class _FileLock:def _read_entries(path: Path, *, strict: bool = False) -> list[dict[str, Any]]:try:- with open(path, "r", encoding="utf-8") as fh:+ with open(path, "r", encoding="utf-8-sig") as fh:data = json.load(fh)except FileNotFoundError:return []diff --git a/hermes_cli/agent_import.py b/hermes_cli/agent_import.pyindex 7439133a807..0076db56589 100644--- a/hermes_cli/agent_import.py+++ b/hermes_cli/agent_import.py@@ -92,7 +92,7 @@ def normalize_text(text: str) -> str:def read_text(path: Path) -> str:- return path.read_text(encoding="utf-8", errors="replace")+ return path.read_text(encoding="utf-8-sig", errors="replace")class ConfigReadError(RuntimeError):diff --git a/hermes_cli/agent_plugins.py b/hermes_cli/agent_plugins.pyindex af48727b08e..b2434e04aa2 100644--- a/hermes_cli/agent_plugins.py+++ b/hermes_cli/agent_plugins.py@@ -86,7 +86,7 @@ def _inside(path: Path, root: Path) -> bool:def _read_json_object(path: Path, *, label: str) -> dict:try:- value = json.loads(path.read_text(encoding="utf-8"))+ value = json.loads(path.read_text(encoding="utf-8-sig"))except (OSError, UnicodeError, json.JSONDecodeError) as exc:raise AgentPluginError(f"{label} is not valid readable JSON: {exc}") from excif not isinstance(value, dict):@@ -219,7 +219,7 @@ def _discover_skills()continuetry:- content = skill_md.read_text(encoding="utf-8")+ content = skill_md.read_text(encoding="utf-8-sig")content = content.lstrip("\ufeff")if not content.startswith("---"):raise ValueError("missing YAML frontmatter")diff --git a/hermes_cli/auth.py b/hermes_cli/auth.pyindex 8d3a3d13ae6..4497d6fb98a 100644--- a/hermes_cli/auth.py+++ b/hermes_cli/auth.py@@ -2794,7 +2794,7 @@ def _read_qwen_cli_tokens() -> Dict[str, Any]:code="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 AuthError(f"Failed to read Qwen CLI credentials from {auth_path}: {exc}",diff --git a/hermes_cli/browser_connect.py b/hermes_cli/browser_connect.pyindex 5db489206a0..cabdf692308 100644--- a/hermes_cli/browser_connect.py+++ b/hermes_cli/browser_connect.py@@ -528,7 +528,7 @@ def _last_used_profile(src: str) -> str:import jsontry:- with open(os.path.join(src, "Local State"), encoding="utf-8", errors="replace") as fh:+ with open(os.path.join(src, "Local State"), encoding="utf-8-sig", errors="replace") as fh:state = json.load(fh)last = ((state.get("profile") or {}).get("last_used")) or "Default"except (OSError, ValueError, AttributeError):diff --git a/hermes_cli/codex_models.py b/hermes_cli/codex_models.pyindex 2b17802d87d..d9fc24fe364 100644--- a/hermes_cli/codex_models.py+++ b/hermes_cli/codex_models.py@@ -204,7 +204,7 @@ def _read_default_model(codex_home: Path) -> Optional[str]:except Exception:return Nonetry:- payload = tomllib.loads(config_path.read_text(encoding="utf-8"))+ payload = tomllib.loads(config_path.read_text(encoding="utf-8-sig"))except Exception:return Nonemodel = payload.get("model") if isinstance(payload, dict) else None@@ -218,7 +218,7 @@ def _read_cache_models(codex_home: Path) -> List[str]:if not cache_path.exists():return []try:- raw = json.loads(cache_path.read_text(encoding="utf-8"))+ raw = json.loads(cache_path.read_text(encoding="utf-8-sig"))except Exception:return []diff --git a/hermes_cli/codex_runtime_plugin_migration.py b/hermes_cli/codex_runtime_plugin_migration.pyindex 4b30d3ebf26..5d0f4c3e1f2 100644--- a/hermes_cli/codex_runtime_plugin_migration.py+++ b/hermes_cli/codex_runtime_plugin_migration.py@@ -708,7 +708,7 @@ def migrate(# append the new one.if target.exists():try:- existing = target.read_text(encoding="utf-8")+ existing = target.read_text(encoding="utf-8-sig")except Exception as exc:report.errors.append(f"could not read {target}: {exc}")return reportdiff --git a/hermes_cli/config_migrations.py b/hermes_cli/config_migrations.pyindex 3357aaec16b..9c19f0c6d9b 100644--- a/hermes_cli/config_migrations.py+++ b/hermes_cli/config_migrations.py@@ -331,7 +331,7 @@ def _migrate_to_21(results: Dict[str, Any], quiet: bool) -> None:if not manifest_file.exists():continuetry:- with open(manifest_file, encoding="utf-8") as _mf:+ with open(manifest_file, encoding="utf-8-sig") as _mf:manifest = fast_safe_load(_mf) or {}except Exception:manifest = {}diff --git a/hermes_cli/container_boot.py b/hermes_cli/container_boot.pyindex b0e9821b7b8..560eb585b16 100644--- a/hermes_cli/container_boot.py+++ b/hermes_cli/container_boot.py@@ -395,7 +395,7 @@ def _read_desired_state(profile_dir: Path) -> str | None:if not state_file.exists():return Nonetry:- data = json.loads(state_file.read_text(encoding="utf-8"))+ data = json.loads(state_file.read_text(encoding="utf-8-sig"))desired_state = data.get("desired_state")if desired_state is not None:return desired_statediff --git a/hermes_cli/copilot_auth.py b/hermes_cli/copilot_auth.pyindex e851db5b2ea..4903822049b 100644--- a/hermes_cli/copilot_auth.py+++ b/hermes_cli/copilot_auth.py@@ -408,7 +408,7 @@ def _read_jwt_store(path: Path) -> Optional[dict]:"Persisted Copilot JWT store exceeds %d bytes; ignoring", _JWT_DISK_MAX_BYTES)return None- loaded = json.loads(path.read_text(encoding="utf-8"))+ loaded = json.loads(path.read_text(encoding="utf-8-sig"))return loaded if isinstance(loaded, dict) else Noneexcept Exception as exc:logger.debug("Failed to read persisted Copilot JWT store: %s", exc)diff --git a/hermes_cli/credential_lifecycle.py b/hermes_cli/credential_lifecycle.pyindex 7dbfc3fee72..fb73bb4c47e 100644--- a/hermes_cli/credential_lifecycle.py+++ b/hermes_cli/credential_lifecycle.py@@ -132,7 +132,7 @@ def _scrub_config_yaml_mirrors(old_value: str, new_value: str | None) -> List[stif not config_path.exists():return []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 {}except Exception:return []diff --git a/hermes_cli/debug.py b/hermes_cli/debug.pyindex f633df62f22..71a139e5139 100644--- a/hermes_cli/debug.py+++ b/hermes_cli/debug.py@@ -91,7 +91,7 @@ def _load_pending() -> list[dict]: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"))if isinstance(data, list):# Filter to well-formed entries onlyreturn [diff --git a/hermes_cli/env_loader.py b/hermes_cli/env_loader.pyindex f926c6ed4e5..434641b834d 100644--- a/hermes_cli/env_loader.py+++ b/hermes_cli/env_loader.py@@ -93,7 +93,7 @@ def _env_keys_defined_in_dotenv(path: Path) -> set[str]:"""keys: set[str] = set()try:- text = path.read_text(encoding="utf-8", errors="replace")+ text = path.read_text(encoding="utf-8-sig", errors="replace")except Exception:try:text = path.read_text(encoding="latin-1", errors="replace")@@ -786,7 +786,7 @@ def _load_secrets_config(home_path: Path) -> dict:except ImportError:return {}try:- with open(config_path, "r", encoding="utf-8") as f:+ with open(config_path, "r", encoding="utf-8-sig") as f:data = fast_safe_load(f) or {}except Exception: # noqa: BLE001return {}diff --git a/hermes_cli/foreign_sessions.py b/hermes_cli/foreign_sessions.pyindex 1d565c336f3..c718fe659a6 100644--- a/hermes_cli/foreign_sessions.py+++ b/hermes_cli/foreign_sessions.py@@ -78,7 +78,7 @@ class ForeignSession:def _read_json_lines(path: Path):"""Yield parsed JSON objects, silently skipping unparseable lines."""try:- with open(path, "r", encoding="utf-8", errors="replace") as f:+ with open(path, "r", encoding="utf-8-sig", errors="replace") as f:for line in f:line = line.strip()if not line:diff --git a/hermes_cli/gateway_windows.py b/hermes_cli/gateway_windows.pyindex 59a1d285421..bb2d5fe6309 100644--- a/hermes_cli/gateway_windows.py+++ b/hermes_cli/gateway_windows.py@@ -1347,7 +1347,7 @@ def _print_deep_probes() -> None:pid_value: int | None = Noneif pid_exists:try:- 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 Noneprint(f" [1] {_mark(True):4s} PID file present: {pid_path} (pid={pid_value})")except Exception as exc:@@ -1395,7 +1395,7 @@ def _print_deep_probes() -> None:# [5] runtime status fileif state_path.exists():try:- 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/hooks.py b/hermes_cli/hooks.pyindex 549ce0e68c4..4fd8189108b 100644--- a/hermes_cli/hooks.py+++ b/hermes_cli/hooks.py@@ -258,7 +258,7 @@ def _cmd_test(args) -> None:if getattr(args, "payload_file", None):try:- custom = json.loads(Path(args.payload_file).read_text(encoding="utf-8"))+ custom = json.loads(Path(args.payload_file).read_text(encoding="utf-8-sig"))if isinstance(custom, dict):payload.update(custom)else:diff --git a/hermes_cli/image_provenance.py b/hermes_cli/image_provenance.pyindex 188182e9fb0..c6939520a98 100644--- a/hermes_cli/image_provenance.py+++ b/hermes_cli/image_provenance.py@@ -89,7 +89,7 @@ def read_image_provenance(return _invalid(path, "marker_not_regular_file")try:- payload = json.loads(path.read_text(encoding="utf-8"))+ payload = json.loads(path.read_text(encoding="utf-8-sig"))except Exception as exc:# The file may disappear between lstat/read; it was nevertheless# observed present, so the decision remains fail-closed.diff --git a/hermes_cli/init_command.py b/hermes_cli/init_command.pyindex 576b84fbbc4..0ff45fbf732 100644--- a/hermes_cli/init_command.py+++ b/hermes_cli/init_command.py@@ -143,7 +143,7 @@ def build_init_prompt_for_cwd(cwd: str | None = None, extra: str = "") -> str:agents_path = os.path.join(resolved, "AGENTS.md")try:if os.path.isfile(agents_path):- with open(agents_path, encoding="utf-8", errors="replace") as fh:+ with open(agents_path, encoding="utf-8-sig", errors="replace") as fh:existing = fh.read()except OSError:existing = Nonediff --git a/hermes_cli/journey.py b/hermes_cli/journey.pyindex 27fb9d1ce36..c388d9f0a40 100644--- a/hermes_cli/journey.py+++ b/hermes_cli/journey.py@@ -356,7 +356,7 @@ def _open_in_editor(initial: str, *, suffix: str) -> Optional[str]:path = fh.nametry:subprocess.call([*editor.split(), path])- with open(path, encoding="utf-8") as fh:+ with open(path, encoding="utf-8-sig") as fh:return fh.read()except OSError as exc:print(f" editor failed: {exc}")diff --git a/hermes_cli/kanban_db.py b/hermes_cli/kanban_db.pyindex cb3863466b9..9f25bea6f1b 100644--- a/hermes_cli/kanban_db.py+++ b/hermes_cli/kanban_db.py@@ -642,7 +642,7 @@ def get_current_board() -> str:try:f = current_board_path()if f.exists():- val = f.read_text(encoding="utf-8").strip()+ val = f.read_text(encoding="utf-8-sig").strip()if val:try:normed = _normalize_board_slug(val)@@ -856,7 +856,7 @@ def read_board_metadata(board: Optional[str] = None) -> dict:try:p = board_metadata_path(slug)if p.exists():- raw = json.loads(p.read_text(encoding="utf-8"))+ raw = json.loads(p.read_text(encoding="utf-8-sig"))if isinstance(raw, dict):# Never let the metadata file claim a different slug than# its directory — trust the filesystem.@@ -8229,7 +8229,7 @@ def _pid_alive(pid: Optional[int]) -> bool:# where we have a cheap, deterministic process-state probe.if 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)" → dead@@ -11943,7 +11943,7 @@ def read_worker_log(return Nonetry:if tail_bytes is None:- return path.read_text(encoding="utf-8", errors="replace")+ return path.read_text(encoding="utf-8-sig", errors="replace")size = path.stat().st_sizewith open(path, "rb") as f:if size > tail_bytes:diff --git a/hermes_cli/linux_desktop_entry.py b/hermes_cli/linux_desktop_entry.pyindex a813702a25d..eef2a4376d4 100644--- a/hermes_cli/linux_desktop_entry.py+++ b/hermes_cli/linux_desktop_entry.py@@ -196,7 +196,7 @@ def install_desktop_entry(project_root: Path) -> Optional[Path]:entry_path.parent.mkdir(parents=True, exist_ok=True)# When nothing changed, skip the rewrite. Then a launch does not# churn the menu caches.- if entry_path.is_file() and entry_path.read_text(encoding="utf-8") == contents:+ if entry_path.is_file() and entry_path.read_text(encoding="utf-8-sig") == contents:return entry_pathentry_path.write_text(contents, encoding="utf-8")# Some launchers (and older Plasma) offer the entry only when itdiff --git a/hermes_cli/logs.py b/hermes_cli/logs.pyindex a214d52c8a5..0996afe7a90 100644--- a/hermes_cli/logs.py+++ b/hermes_cli/logs.py@@ -295,7 +295,7 @@ def _read_last_n_lines(path: Path, n: int) -> list:# For files up to 1MB, just read the whole thing — simple and correct.if size <= 1_048_576:- with open(path, "r", encoding="utf-8", errors="replace") as f:+ with open(path, "r", encoding="utf-8-sig", errors="replace") as f:all_lines = f.readlines()return all_lines[-n:]@@ -333,7 +333,7 @@ def _read_last_n_lines(path: Path, n: int) -> list:except Exception:# Fallback: read entire file- with open(path, "r", encoding="utf-8", errors="replace") as f:+ with open(path, "r", encoding="utf-8-sig", errors="replace") as f:all_lines = f.readlines()return all_lines[-n:]@@ -347,7 +347,7 @@ def _follow_log(component_prefixes: Optional[Sequence[str]] = None,) -> None:"""Poll a log file for new content and print matching lines."""- with open(path, "r", encoding="utf-8", errors="replace") as f:+ with open(path, "r", encoding="utf-8-sig", errors="replace") as f:# Seek to endf.seek(0, 2)while True:diff --git a/hermes_cli/managed_scope.py b/hermes_cli/managed_scope.pyindex 12af07ad1eb..dd413eb6019 100644--- a/hermes_cli/managed_scope.py+++ b/hermes_cli/managed_scope.py@@ -97,7 +97,7 @@ def _cached_read(path: Path, cache: Dict[str, tuple], parse):if hit is not None and hit[:2] == key:return copy.deepcopy(hit[2])try:- with open(path, encoding="utf-8") as f:+ with open(path, encoding="utf-8-sig") as f:parsed = parse(f)except Exception as exc: # noqa: BLE001 — fail-open, but LOUDlogger.warning(diff --git a/hermes_cli/mcp_catalog.py b/hermes_cli/mcp_catalog.pyindex 4489d187291..a4cb26c8c78 100644--- a/hermes_cli/mcp_catalog.py+++ b/hermes_cli/mcp_catalog.py@@ -190,7 +190,7 @@ def _parse_env_spec(raw: Any) -> EnvVarSpec:def _parse_manifest(path: Path) -> CatalogEntry:"""Read and validate a manifest.yaml. Raise CatalogError on any problem."""try:- with open(path, "r", encoding="utf-8") as f:+ with open(path, "r", encoding="utf-8-sig") as f:data = yaml.safe_load(f) or {}except Exception as exc:raise CatalogError(f"failed to read {path}: {exc}") from excdiff --git a/hermes_cli/mem_trim.py b/hermes_cli/mem_trim.pyindex ad54f59a38e..34f7ba7aac1 100644--- a/hermes_cli/mem_trim.py+++ b/hermes_cli/mem_trim.py@@ -98,7 +98,7 @@ def _read_proc_status() -> str | None:if sys.platform != "linux":return Nonetry:- return Path("/proc/self/status").read_text(encoding="utf-8")+ return Path("/proc/self/status").read_text(encoding="utf-8-sig")except OSError:return Nonediff --git a/hermes_cli/model_catalog.py b/hermes_cli/model_catalog.pyindex 5aa479fa876..761ab0d0960 100644--- a/hermes_cli/model_catalog.py+++ b/hermes_cli/model_catalog.py@@ -208,7 +208,7 @@ def _read_disk_cache() -> tuple[dict[str, Any] | None, float]:except (OSError, FileNotFoundError):return (None, 0.0)try:- with open(path, encoding="utf-8") as fh:+ with open(path, encoding="utf-8-sig") as fh:data = json.load(fh)except (OSError, json.JSONDecodeError):return (None, 0.0)@@ -451,7 +451,7 @@ def seed_cache_from_checkout(project_root: "Path | str") -> bool:"""src = Path(project_root) / "website" / "static" / "api" / "model-catalog.json"try:- with open(src, encoding="utf-8") as fh:+ with open(src, encoding="utf-8-sig") as fh:data = json.load(fh)except (OSError, json.JSONDecodeError) as exc:logger.debug("model catalog seed from checkout skipped (%s): %s", src, exc)diff --git a/hermes_cli/models.py b/hermes_cli/models.pyindex 451b01add47..5a2ebc19d9d 100644--- a/hermes_cli/models.py+++ b/hermes_cli/models.py@@ -1009,7 +1009,7 @@ def _read_nous_recommended_disk(base: str) -> dict[str, Any] | None:``{"<base>": {"data": {...}, "ts": <epoch_seconds>}}``."""try:- with open(_nous_recommended_disk_path(), encoding="utf-8") as fh:+ with open(_nous_recommended_disk_path(), encoding="utf-8-sig") as fh:blob = json.load(fh)except (OSError, json.JSONDecodeError):return None@@ -1033,7 +1033,7 @@ def _write_nous_recommended_disk(base: str, data: dict[str, Any]) -> None:path = _nous_recommended_disk_path()try:try:- with open(path, encoding="utf-8") as fh:+ with open(path, encoding="utf-8-sig") as fh:blob = json.load(fh)if not isinstance(blob, dict):blob = {}@@ -4386,7 +4386,7 @@ def _load_provider_models_cache() -> dict:path = _provider_models_cache_path()if not path.exists():return {}- with open(path, encoding="utf-8") as f:+ with open(path, encoding="utf-8-sig") as f:data = json.load(f)return data if isinstance(data, dict) else {}except Exception:@@ -6222,7 +6222,7 @@ def _load_ollama_cloud_cache(*, ignore_ttl: bool = False) -> Optional[dict]:cache_path = _ollama_cloud_cache_path()if not cache_path.exists():return None- with open(cache_path, encoding="utf-8") as f:+ with open(cache_path, encoding="utf-8-sig") as f:data = json.load(f)if not isinstance(data, dict):return Nonediff --git a/hermes_cli/plugin_index.py b/hermes_cli/plugin_index.pyindex 2cc92a76b7a..d1f6b2127ce 100644--- a/hermes_cli/plugin_index.py+++ b/hermes_cli/plugin_index.py@@ -151,7 +151,7 @@ def _parse_entries(raw: Any) -> List[PluginIndexEntry]:def _load_seed_entries() -> List[PluginIndexEntry]:try:- return _parse_entries(json.loads(SEED_INDEX_PATH.read_text(encoding="utf-8")))+ return _parse_entries(json.loads(SEED_INDEX_PATH.read_text(encoding="utf-8-sig")))except (OSError, ValueError) as exc: # pragma: no cover - bundled filelogger.warning("plugin index: bundled seed unreadable: %s", exc)return []@@ -167,7 +167,7 @@ def _read_cache(*, max_age: Optional[float]) -> Optional[List[PluginIndexEntry]]age = time.time() - cache.stat().st_mtimeif age > max_age:return None- return _parse_entries(json.loads(cache.read_text(encoding="utf-8")))+ return _parse_entries(json.loads(cache.read_text(encoding="utf-8-sig")))except (OSError, ValueError) as exc:logger.debug("plugin index: cache read failed: %s", exc)return Nonediff --git a/hermes_cli/plugin_packs.py b/hermes_cli/plugin_packs.pyindex 12f1ebe914b..51cc61139f2 100644--- a/hermes_cli/plugin_packs.py+++ b/hermes_cli/plugin_packs.py@@ -287,7 +287,7 @@ def load_pack(path_or_url: str) -> PluginPack:raise PackError(f"Pack file not found: {path}")if path.stat().st_size > _MAX_PACK_BYTES:raise PackError("Pack file exceeds the 1 MiB size limit.")- return parse_pack(path.read_text(encoding="utf-8"), source=str(path))+ return parse_pack(path.read_text(encoding="utf-8-sig"), source=str(path))# ---------------------------------------------------------------------------diff --git a/hermes_cli/plugins.py b/hermes_cli/plugins.pyindex 9028e285307..e9a5895ae7c 100644--- a/hermes_cli/plugins.py+++ b/hermes_cli/plugins.py@@ -716,6 +716,7 @@ _KNOWN_MANIFEST_FIELDS: Set[str] = {"name", "version", "description", "author", "requires_env","provides_tools", "provides_hooks", "kind", "hooks", "label","optional_env", "platforms", "external_dependencies", "pip_dependencies",+ "extra","provides_browser_providers", "provides_web_providers",# v2 (#64165)"manifest_version", "api_version", "requires_plugins",@@ -1018,7 +1019,7 @@ def _read_source_from_origin(origin: Optional[str], limit: int = 8192) -> str:if not origin.endswith(".py"):return ""try:- 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 ""@@ -1415,7 +1416,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 {}@@ -4775,7 +4776,7 @@ class PluginManager: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 name@@ -6372,7 +6373,7 @@ def _read_plugin_keys_cache() -> Optional[dict]:try:import json as _jsonblob = _json.loads(- _plugin_toolset_keys_cache_path().read_text(encoding="utf-8")+ _plugin_toolset_keys_cache_path().read_text(encoding="utf-8-sig"))if isinstance(blob, dict):return blobdiff --git a/hermes_cli/process_identity.py b/hermes_cli/process_identity.pyindex c84015d7c70..ec2778f9df5 100644--- a/hermes_cli/process_identity.py+++ b/hermes_cli/process_identity.py@@ -189,7 +189,7 @@ def _read_ledger(path: Path) -> Optional[list[dict]]:be silently treated as an empty roster."""try:- text = path.read_text(encoding="utf-8")+ text = path.read_text(encoding="utf-8-sig")except FileNotFoundError:return []except OSError:diff --git a/hermes_cli/prompt_size.py b/hermes_cli/prompt_size.pyindex aac473db3d0..d48de526523 100644--- a/hermes_cli/prompt_size.py+++ b/hermes_cli/prompt_size.py@@ -103,7 +103,7 @@ def _skill_md_paths_by_name() -> Dict[str, Path]:frontmatter_name = skill_file.parent.nametry:frontmatter, _ = parse_frontmatter(- skill_file.read_text(encoding="utf-8")+ skill_file.read_text(encoding="utf-8-sig"))frontmatter_name = str(frontmatter.get("name") or frontmatter_name)except Exception:diff --git a/hermes_cli/security_advisories.py b/hermes_cli/security_advisories.pyindex ef058a5a422..e5ea6874995 100644--- a/hermes_cli/security_advisories.py+++ b/hermes_cli/security_advisories.py@@ -340,7 +340,7 @@ def _read_banner_cache() -> dict[str, float]:return {}out: dict[str, float] = {}try:- for line in p.read_text(encoding="utf-8").splitlines():+ for line in p.read_text(encoding="utf-8-sig").splitlines():line = line.strip()if not line:continuediff --git a/hermes_cli/security_audit.py b/hermes_cli/security_audit.pyindex 78d8a8b7e04..147b67d36e0 100644--- a/hermes_cli/security_audit.py+++ b/hermes_cli/security_audit.py@@ -184,7 +184,7 @@ def _discover_plugins(hermes_home: Path) -> list[Component]:path = plugin_dir / req_fileif path.is_file():try:- pins = _parse_requirements(path.read_text(encoding="utf-8", errors="replace"))+ pins = _parse_requirements(path.read_text(encoding="utf-8-sig", errors="replace"))except OSError:continuefor name, version in pins:@@ -192,7 +192,7 @@ def _discover_plugins(hermes_home: Path) -> list[Component]:pyproject = plugin_dir / "pyproject.toml"if pyproject.is_file():try:- pins = _parse_pyproject_pins(pyproject.read_text(encoding="utf-8", errors="replace"))+ pins = _parse_pyproject_pins(pyproject.read_text(encoding="utf-8-sig", errors="replace"))except OSError:continuefor name, version in pins:diff --git a/hermes_cli/security_audit_startup.py b/hermes_cli/security_audit_startup.pyindex 91e677be311..6adb93dcdf0 100644--- a/hermes_cli/security_audit_startup.py+++ b/hermes_cli/security_audit_startup.py@@ -75,7 +75,7 @@ def _iter_sshd_config_lines() -> list[str]:passfor p in paths:try:- for raw in p.read_text(encoding="utf-8", errors="replace").splitlines():+ for raw in p.read_text(encoding="utf-8-sig", errors="replace").splitlines():stripped = raw.strip()if stripped and not stripped.startswith("#"):lines.append(stripped)@@ -119,7 +119,7 @@ def _in_container() -> bool:if os.environ.get("HERMES_DESKTOP_CHILD_PID"):return False # desktop child, not a server containertry:- cgroup = Path("/proc/1/cgroup").read_text(encoding="utf-8", errors="replace")+ cgroup = Path("/proc/1/cgroup").read_text(encoding="utf-8-sig", errors="replace")if any(tok in cgroup for tok in ("docker", "containerd", "kubepods", "libpod")):return Trueexcept Exception:@@ -140,7 +140,7 @@ def _path_is_mounted(path: Path) -> bool:except Exception:target = pathtry:- mounts = Path("/proc/mounts").read_text(encoding="utf-8", errors="replace").splitlines()+ mounts = Path("/proc/mounts").read_text(encoding="utf-8-sig", errors="replace").splitlines()except Exception:return True # can't tell — fail safe (no warning)best = Nonediff --git a/hermes_cli/send_cmd.py b/hermes_cli/send_cmd.pyindex 6d00e54c6c6..2a2590dba1b 100644--- a/hermes_cli/send_cmd.py+++ b/hermes_cli/send_cmd.py@@ -58,7 +58,7 @@ def _read_message_body(if file_path == "-":return sys.stdin.read()try:- return Path(file_path).read_text(encoding="utf-8")+ return Path(file_path).read_text(encoding="utf-8-sig")except UnicodeDecodeError:print(f"hermes send: {file_path} is not a text file. --file reads the "diff --git a/hermes_cli/session_export_md.py b/hermes_cli/session_export_md.pyindex e2ab0c8a6d3..9f4a32d9001 100644--- a/hermes_cli/session_export_md.py+++ b/hermes_cli/session_export_md.py@@ -201,7 +201,7 @@ def verify_export_file(path: Path | str, session: dict[str, Any]) -> tuple[bool,p = Path(path)if not p.exists():return False, "file missing"- text = p.read_text(encoding="utf-8")+ text = p.read_text(encoding="utf-8-sig")match = _SHA_LINE_RE.search(text)if not match:return False, "sha256 marker missing"diff --git a/hermes_cli/skills_hub.py b/hermes_cli/skills_hub.pyindex 7cca4335d7c..ac77f1fdda8 100644--- a/hermes_cli/skills_hub.py+++ b/hermes_cli/skills_hub.py@@ -1570,7 +1570,7 @@ def do_publish(skill_path: str, target: str = "github", repo: str = "",# Validate the skillimport yaml- skill_md = (path / "SKILL.md").read_text(encoding="utf-8")+ skill_md = (path / "SKILL.md").read_text(encoding="utf-8-sig")skill_md = skill_md.lstrip("\ufeff") # tolerate UTF-8 BOM (Windows editors)fm = {}if skill_md.startswith("---"):@@ -1771,7 +1771,7 @@ def do_snapshot_import(input_path: str, force: bool = False,returntry:- snapshot = json.loads(inp.read_text(encoding="utf-8"))+ snapshot = json.loads(inp.read_text(encoding="utf-8-sig"))except json.JSONDecodeError:c.print(f"[bold red]Error:[/] Invalid JSON in {inp}\n")returndiff --git a/hermes_cli/skin_cmd.py b/hermes_cli/skin_cmd.pyindex bde243bc48a..8d209a3be0f 100644--- a/hermes_cli/skin_cmd.py+++ b/hermes_cli/skin_cmd.py@@ -49,7 +49,7 @@ def _skin_set(key: str, value: str, skin: str | None) -> int:path = _skins_dir() / f"{name}.yaml"if path.exists():- data = yaml.safe_load(path.read_text(encoding="utf-8")) or {}+ data = yaml.safe_load(path.read_text(encoding="utf-8-sig")) or {}target = nameelse:# Built-in (or missing): fork into an editable copy that keeps its fulldiff --git a/hermes_cli/skin_engine.py b/hermes_cli/skin_engine.pyindex a2a093b7dc3..628e3db6709 100644--- a/hermes_cli/skin_engine.py+++ b/hermes_cli/skin_engine.py@@ -794,7 +794,7 @@ def _load_skin_from_yaml(path: Path) -> Optional[Dict[str, Any]]:"""Load a skin definition from a YAML file."""try:import yaml- with open(path, "r", encoding="utf-8") as f:+ with open(path, "r", encoding="utf-8-sig") as f:data = yaml.safe_load(f)if isinstance(data, dict) and "name" in data:return datadiff --git a/hermes_cli/slack_cli.py b/hermes_cli/slack_cli.pyindex 584a991a752..f72a418b382 100644--- a/hermes_cli/slack_cli.py+++ b/hermes_cli/slack_cli.py@@ -200,7 +200,7 @@ def slack_manifest_command(args) -> int:source_arg = str(long_description_file)try:source = Path(source_arg).expanduser()- with source.open("r", encoding="utf-8", newline="") as handle:+ with source.open("r", encoding="utf-8-sig", newline="") as handle:long_description = handle.read()except (OSError, UnicodeError, RuntimeError) as exc:print(diff --git a/hermes_cli/terminal_breadcrumbs.py b/hermes_cli/terminal_breadcrumbs.pyindex 8ea68af8265..d6616f66929 100644--- a/hermes_cli/terminal_breadcrumbs.py+++ b/hermes_cli/terminal_breadcrumbs.py@@ -136,7 +136,7 @@ def read_breadcrumb() -> Optional[dict]:if not terminal_id:return Nonepath = _breadcrumbs_dir() / terminal_id- data = json.loads(path.read_text(encoding="utf-8"))+ data = json.loads(path.read_text(encoding="utf-8-sig"))if not isinstance(data, dict) or not str(data.get("session_id") or "").strip():return Nonets = data.get("ts")diff --git a/hermes_cli/update_lock.py b/hermes_cli/update_lock.pyindex 964638df056..024c43ba0ae 100644--- a/hermes_cli/update_lock.py+++ b/hermes_cli/update_lock.py@@ -178,7 +178,7 @@ def read_live_update(*, path: Path | None = None) -> UpdateHolder | None:"""marker = path or update_marker_path()try:- raw = marker.read_text(encoding="utf-8")+ raw = marker.read_text(encoding="utf-8-sig")except OSError:return None # absent or unreadable => no live update@@ -268,7 +268,7 @@ class UpdateLock:returnself.acquired = Falsetry:- raw = self.path.read_text(encoding="utf-8")+ raw = self.path.read_text(encoding="utf-8-sig")owner = int(raw.splitlines()[0].strip())except (OSError, IndexError, ValueError):returndiff --git a/hermes_cli/web_routers/profiles.py b/hermes_cli/web_routers/profiles.pyindex c0669510a49..7377c6c51dd 100644--- a/hermes_cli/web_routers/profiles.py+++ b/hermes_cli/web_routers/profiles.py@@ -1054,7 +1054,7 @@ async def get_profile_soul(name: str):soul_path = _resolve_profile_dir(name) / "SOUL.md"if soul_path.exists():try:- return {"content": soul_path.read_text(encoding="utf-8"), "exists": True}+ return {"content": soul_path.read_text(encoding="utf-8-sig"), "exists": True}except OSError as e:raise HTTPException(status_code=500, detail=f"Could not read SOUL.md: {e}")return {"content": "", "exists": False}@@ -1236,7 +1236,7 @@ async def import_profile_endpoint(body: ProfileImport):if overlay_path.is_file():try:import json as _json- desktop_overlay = _json.loads(overlay_path.read_text(encoding="utf-8"))+ desktop_overlay = _json.loads(overlay_path.read_text(encoding="utf-8-sig"))except Exception:_log.exception("Reading desktop.json from imported profile %s failed", imported)@@ -1257,6 +1257,6 @@ async def get_profile_desktop_overlay(name: str):return {"exists": False, "desktop": None}try:import json as _json- return {"exists": True, "desktop": _json.loads(overlay_path.read_text(encoding="utf-8"))}+ return {"exists": True, "desktop": _json.loads(overlay_path.read_text(encoding="utf-8-sig"))}except Exception as e:raise HTTPException(status_code=500, detail=f"Could not read desktop.json: {e}")diff --git a/hermes_cli/web_routers/skills.py b/hermes_cli/web_routers/skills.pyindex d63540a8dbc..d47956b7e15 100644--- a/hermes_cli/web_routers/skills.py+++ b/hermes_cli/web_routers/skills.py@@ -495,7 +495,7 @@ async def get_skill_content(name: str, profile: Optional[str] = None):if not skill_md.exists():raise HTTPException(status_code=404, detail=f"Skill '{name}' has no SKILL.md.")try:- content = skill_md.read_text(encoding="utf-8")+ content = skill_md.read_text(encoding="utf-8-sig")except OSError as exc:raise HTTPException(status_code=500, detail=str(exc)) from excreturn {"name": name, "content": content, "path": str(skill_md)}diff --git a/hermes_cli/webhook.py b/hermes_cli/webhook.pyindex 9b9de6cd5a6..283470b377a 100644--- a/hermes_cli/webhook.py+++ b/hermes_cli/webhook.py@@ -42,7 +42,7 @@ def _load_subscriptions() -> Dict[str, dict]: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"))return data if isinstance(data, dict) else {}except Exception:return {}diff --git a/hermes_cli/xai_retirement.py b/hermes_cli/xai_retirement.pyindex 965cc1b13e2..86b04ab8fd8 100644--- a/hermes_cli/xai_retirement.py+++ b/hermes_cli/xai_retirement.py@@ -204,7 +204,7 @@ def apply_migration(yaml = YAML(typ="rt")yaml.preserve_quotes = True- with config_path.open("r", encoding="utf-8") as fh:+ with config_path.open("r", encoding="utf-8-sig") as fh:doc = yaml.load(fh)if doc is None:diff --git a/plugins/cron_providers/__init__.py b/plugins/cron_providers/__init__.pyindex 79dd1a2256e..1fae654b58a 100644--- a/plugins/cron_providers/__init__.py+++ b/plugins/cron_providers/__init__.py@@ -86,7 +86,7 @@ def _is_cron_provider_dir(path: Path) -> bool:if not init_file.exists():return Falsetry:- source = init_file.read_text(errors="replace", encoding="utf-8")[:8192]+ source = init_file.read_text(errors="replace", encoding="utf-8-sig")[:8192]return "register_cron_scheduler" in source or "CronScheduler" in sourceexcept Exception:return Falsediff --git a/plugins/disk-cleanup/disk_cleanup.py b/plugins/disk-cleanup/disk_cleanup.pyindex 8432c5a7bad..d04c4edb082 100755--- a/plugins/disk-cleanup/disk_cleanup.py+++ b/plugins/disk-cleanup/disk_cleanup.py@@ -110,12 +110,12 @@ def load_tracked() -> List[Dict[str, Any]]:return []try:- return json.loads(tf.read_text(encoding="utf-8"))+ return json.loads(tf.read_text(encoding="utf-8-sig"))except (json.JSONDecodeError, ValueError):bak = tf.with_suffix(".json.bak")if bak.exists():try:- data = json.loads(bak.read_text(encoding="utf-8"))+ data = json.loads(bak.read_text(encoding="utf-8-sig"))_log("WARN: tracked.json corrupted — restored from .bak")return dataexcept Exception:diff --git a/plugins/google_meet/node/registry.py b/plugins/google_meet/node/registry.pyindex 9be85755621..da412e51c03 100644--- a/plugins/google_meet/node/registry.py+++ b/plugins/google_meet/node/registry.py@@ -44,7 +44,7 @@ class NodeRegistry:if not self.path.is_file():return {"nodes": {}}try:- data = json.loads(self.path.read_text(encoding="utf-8"))+ data = json.loads(self.path.read_text(encoding="utf-8-sig"))except (OSError, json.JSONDecodeError):return {"nodes": {}}if not isinstance(data, dict) or not isinstance(data.get("nodes"), dict):diff --git a/plugins/google_meet/node/server.py b/plugins/google_meet/node/server.pyindex cff01d265ff..9df5cb5b928 100644--- a/plugins/google_meet/node/server.py+++ b/plugins/google_meet/node/server.py@@ -62,7 +62,7 @@ class NodeServer:return self._tokenif self.token_path.is_file():try:- data = json.loads(self.token_path.read_text(encoding="utf-8"))+ data = json.loads(self.token_path.read_text(encoding="utf-8-sig"))tok = data.get("token")if isinstance(tok, str) and tok:self._token = tokdiff --git a/plugins/google_meet/process_manager.py b/plugins/google_meet/process_manager.pyindex 4b2576efb48..20f7fb7eb8a 100644--- a/plugins/google_meet/process_manager.py+++ b/plugins/google_meet/process_manager.py@@ -49,7 +49,7 @@ def _read_active() -> Optional[Dict[str, Any]]:if not p.is_file():return Nonetry:- return json.loads(p.read_text(encoding="utf-8"))+ return json.loads(p.read_text(encoding="utf-8-sig"))except Exception:return None@@ -216,7 +216,7 @@ def status() -> Dict[str, Any]:bot_status: Dict[str, Any] = {}if status_path.is_file():try:- bot_status = json.loads(status_path.read_text(encoding="utf-8"))+ bot_status = json.loads(status_path.read_text(encoding="utf-8-sig"))except Exception:pass@@ -247,7 +247,7 @@ def transcript(last: Optional[int] = None) -> Dict[str, Any]:"total": 0,"path": str(tp),}- text = tp.read_text(encoding="utf-8", errors="replace")+ text = tp.read_text(encoding="utf-8-sig", errors="replace")all_lines = [ln for ln in text.splitlines() if ln.strip()]lines = all_lines[-last:] if last else all_linesreturn {diff --git a/plugins/google_meet/realtime/openai_client.py b/plugins/google_meet/realtime/openai_client.pyindex 2e84c89125c..e90ba4b4482 100644--- a/plugins/google_meet/realtime/openai_client.py+++ b/plugins/google_meet/realtime/openai_client.py@@ -262,7 +262,7 @@ class RealtimeSpeaker:if not self.queue_path.exists():return []out: list[dict] = []- for line in self.queue_path.read_text(encoding="utf-8").splitlines():+ for line in self.queue_path.read_text(encoding="utf-8-sig").splitlines():line = line.strip()if not line:continuediff --git a/plugins/hermes-achievements/dashboard/plugin_api.py b/plugins/hermes-achievements/dashboard/plugin_api.pyindex 643c306464b..f299c7ced55 100644--- a/plugins/hermes-achievements/dashboard/plugin_api.py+++ b/plugins/hermes-achievements/dashboard/plugin_api.py@@ -167,7 +167,10 @@ def _data_file(name: str) -> Path:legacy = get_hermes_home() / "plugins" / "hermes-achievements" / nameif legacy.exists():try:- path.write_text(legacy.read_text(encoding="utf-8"), encoding="utf-8")+ # Two statements so the read (utf-8-sig, tolerates a BOM)+ # and the write (utf-8, never emits one) stay distinct.+ legacy_text = legacy.read_text(encoding="utf-8-sig")+ path.write_text(legacy_text, encoding="utf-8")except Exception:passreturn path@@ -190,7 +193,7 @@ def load_state() -> Dict[str, Any]:if not path.exists():return {"unlocks": {}}try:- return json.loads(path.read_text(encoding="utf-8"))+ return json.loads(path.read_text(encoding="utf-8-sig"))except Exception:return {"unlocks": {}}@@ -216,7 +219,7 @@ def load_snapshot() -> Optional[Dict[str, Any]]:if not path.exists():return Nonetry:- data = json.loads(path.read_text(encoding="utf-8"))+ data = json.loads(path.read_text(encoding="utf-8-sig"))if isinstance(data, dict):return dataexcept Exception:@@ -235,7 +238,7 @@ def load_checkpoint() -> Dict[str, Any]:if not path.exists():return {"schema_version": 1, "generated_at": 0, "sessions": {}}try:- data = json.loads(path.read_text(encoding="utf-8"))+ data = json.loads(path.read_text(encoding="utf-8-sig"))if isinstance(data, dict):data.setdefault("schema_version", 1)data.setdefault("generated_at", 0)diff --git a/plugins/hermes-achievements/tests/test_achievement_engine.py b/plugins/hermes-achievements/tests/test_achievement_engine.pyindex 22342095269..44cc7810d14 100644--- a/plugins/hermes-achievements/tests/test_achievement_engine.py+++ b/plugins/hermes-achievements/tests/test_achievement_engine.py@@ -157,7 +157,7 @@ class AchievementEngineTests(unittest.TestCase):/ "dashboard"/ "dist"/ "style.css"- ).read_text(encoding="utf-8")+ ).read_text(encoding="utf-8-sig")hover_rule = next(line for line in style_css.splitlines() if line.startswith(".ha-card:hover")diff --git a/plugins/memory/__init__.py b/plugins/memory/__init__.pyindex a24029a0de3..c7cb6c16eb4 100644--- a/plugins/memory/__init__.py+++ b/plugins/memory/__init__.py@@ -115,7 +115,7 @@ def _is_memory_provider_dir(path: Path) -> bool:if not init_file.exists():return Falsetry:- source = init_file.read_text(errors="replace", encoding="utf-8")[:8192]+ source = init_file.read_text(errors="replace", encoding="utf-8-sig")[:8192]return "register_memory_provider" in source or "MemoryProvider" in sourceexcept Exception:return Falsediff --git a/plugins/memory/honcho/__init__.py b/plugins/memory/honcho/__init__.pyindex 1347014cea7..be6c7e53708 100644--- a/plugins/memory/honcho/__init__.py+++ b/plugins/memory/honcho/__init__.py@@ -346,7 +346,7 @@ class HonchoMemoryProvider(MemoryProvider):existing = {}if config_path.exists():try:- existing = json.loads(config_path.read_text(encoding="utf-8"))+ existing = json.loads(config_path.read_text(encoding="utf-8-sig"))except Exception:passexisting.update(values)diff --git a/plugins/memory/honcho/oauth.py b/plugins/memory/honcho/oauth.pyindex a51f03cf3e6..a89bf6b5852 100644--- a/plugins/memory/honcho/oauth.py+++ b/plugins/memory/honcho/oauth.py@@ -437,7 +437,7 @@ def _rotate_and_persist(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.py b/plugins/memory/honcho/session.pyindex 1ee7dc4fee3..004bcb3e28b 100644--- a/plugins/memory/honcho/session.py+++ b/plugins/memory/honcho/session.py@@ -1211,7 +1211,7 @@ class HonchoSessionManager:filepath = memory_path / filenameif not filepath.exists():continue- content = filepath.read_text(encoding="utf-8").strip()+ content = filepath.read_text(encoding="utf-8-sig").strip()if not content:continuediff --git a/plugins/memory/openviking/__init__.py b/plugins/memory/openviking/__init__.pyindex de298381877..fa372b71954 100644--- a/plugins/memory/openviking/__init__.py+++ b/plugins/memory/openviking/__init__.py@@ -868,7 +868,7 @@ def _load_ovcli_config(path: Optional[Path] = None) -> dict:config_path = path or _resolve_ovcli_config_path()if not config_path.exists():return {}- with config_path.open(encoding="utf-8") as f:+ with config_path.open(encoding="utf-8-sig") as f:data = json.load(f)if not isinstance(data, dict):raise ValueError(f"OpenViking CLI config must be a JSON object: {config_path}")@@ -3451,7 +3451,7 @@ class OpenVikingMemoryProvider(MemoryProvider):sid = ""owner_run_id = ""try:- raw = json.loads(path.read_text(encoding="utf-8"))+ raw = json.loads(path.read_text(encoding="utf-8-sig"))if isinstance(raw, dict):sid = str(raw.get("session_id") or "").strip()owner_run_id = str(raw.get("owner_run_id") or "").strip()diff --git a/plugins/memory/retaindb/__init__.py b/plugins/memory/retaindb/__init__.pyindex b4ca8452499..930873a3d39 100644--- a/plugins/memory/retaindb/__init__.py+++ b/plugins/memory/retaindb/__init__.py@@ -596,7 +596,7 @@ class RetainDBMemoryProvider(MemoryProvider):# Seed agent identity from SOUL.md in backgroundsoul_path = hermes_home_path / "SOUL.md"if soul_path.exists():- soul_content = soul_path.read_text(encoding="utf-8", errors="replace").strip()+ soul_content = soul_path.read_text(encoding="utf-8-sig", errors="replace").strip()if soul_content:threading.Thread(target=self._seed_soul,diff --git a/plugins/platforms/a2a/protocol.py b/plugins/platforms/a2a/protocol.pyindex f1522fccb1d..f0b0360d7f2 100644--- a/plugins/platforms/a2a/protocol.py+++ b/plugins/platforms/a2a/protocol.py@@ -820,7 +820,7 @@ def load_conversation(context_id: str, limit: int = 50) -> list[dict]:return []out: list[dict] = []try:- with path.open("r", encoding="utf-8") as fh:+ with path.open("r", encoding="utf-8-sig") as fh:for line in fh:line = line.strip()if not line:diff --git a/plugins/platforms/buzz/adapter.py b/plugins/platforms/buzz/adapter.pyindex dcb1ac3d8d1..e10a2b0dfee 100644--- a/plugins/platforms/buzz/adapter.py+++ b/plugins/platforms/buzz/adapter.py@@ -263,7 +263,7 @@ def _resolve_private_key(extra: Optional[dict] = None) -> str:candidates = []for path in candidates:try:- data = json.loads(path.read_text(encoding="utf-8"))+ data = json.loads(path.read_text(encoding="utf-8-sig"))except (OSError, ValueError):continueif not isinstance(data, dict):diff --git a/plugins/platforms/feishu/adapter.py b/plugins/platforms/feishu/adapter.pyindex 42a70e79fb5..cf43c7267c5 100644--- a/plugins/platforms/feishu/adapter.py+++ b/plugins/platforms/feishu/adapter.py@@ -3952,7 +3952,7 @@ class FeishuAdapter(BasePlatformAdapter):ext = Path(cached_path).suffix.lower()if ext not in {".txt", ".md"} and media_type not in {"text/plain", "text/markdown"}:return ""- content = Path(cached_path).read_text(encoding="utf-8")+ content = Path(cached_path).read_text(encoding="utf-8-sig")display_name = self._display_name_from_cached_path(cached_path)return f"[Content of {display_name}]:\n{content}"except (OSError, UnicodeDecodeError):@@ -4576,7 +4576,7 @@ class FeishuAdapter(BasePlatformAdapter):def _load_seen_message_ids(self) -> None:try:- payload = json.loads(self._dedup_state_path.read_text(encoding="utf-8"))+ payload = json.loads(self._dedup_state_path.read_text(encoding="utf-8-sig"))except FileNotFoundError:returnexcept (OSError, json.JSONDecodeError):diff --git a/plugins/platforms/feishu/feishu_comment_rules.py b/plugins/platforms/feishu/feishu_comment_rules.pyindex f3005731ea1..d2020df7713 100644--- a/plugins/platforms/feishu/feishu_comment_rules.py+++ b/plugins/platforms/feishu/feishu_comment_rules.py@@ -90,7 +90,7 @@ class _MtimeCache:return self._datatry:- with open(self._path, "r", encoding="utf-8") as f:+ with open(self._path, "r", encoding="utf-8-sig") as f:data = json.load(f)if not isinstance(data, dict):data = {}diff --git a/plugins/platforms/google_chat/adapter.py b/plugins/platforms/google_chat/adapter.pyindex 41c9b65500e..36643553f9f 100644--- a/plugins/platforms/google_chat/adapter.py+++ b/plugins/platforms/google_chat/adapter.py@@ -558,7 +558,7 @@ class _ThreadCountStore:self._counts = {}returntry:- raw = self._path.read_text(encoding="utf-8")+ raw = self._path.read_text(encoding="utf-8-sig")data = json.loads(raw) if raw.strip() else {}except json.JSONDecodeError as exc:logger.warning(@@ -799,7 +799,7 @@ class GoogleChatAdapter(BasePlatformAdapter):)# Validate file parses before handing to google-auth for nicer error.try:- with open(sa_path, "r", encoding="utf-8") as fh:+ with open(sa_path, "r", encoding="utf-8-sig") as fh:info = json.load(fh)except json.JSONDecodeError as exc:raise ValueError(@@ -924,7 +924,7 @@ class GoogleChatAdapter(BasePlatformAdapter):if not path.exists():return Nonetry:- data = json.loads(path.read_text(encoding="utf-8"))+ data = json.loads(path.read_text(encoding="utf-8-sig"))return data.get("bot_user_id") or Noneexcept (OSError, json.JSONDecodeError):return None@@ -3601,7 +3601,7 @@ async def _standalone_send(if not os.path.exists(sa_value):return {"error": f"Google Chat standalone send: SA JSON file not found at {sa_value}"}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:return {"error": f"Google Chat standalone send: SA JSON file is invalid: {exc}"}diff --git a/plugins/platforms/google_chat/oauth.py b/plugins/platforms/google_chat/oauth.pyindex 22bc62113d4..5ef7fdb067e 100644--- a/plugins/platforms/google_chat/oauth.py+++ b/plugins/platforms/google_chat/oauth.py@@ -447,7 +447,7 @@ def store_client_secret(path: str) -> None:sys.exit(1)try:- data = json.loads(src.read_text(encoding="utf-8"))+ data = json.loads(src.read_text(encoding="utf-8-sig"))except json.JSONDecodeError:print("ERROR: File is not valid JSON.")sys.exit(1)@@ -487,7 +487,7 @@ def _load_pending_auth(email: Optional[str] = None) -> dict:print("ERROR: No pending OAuth session found. Run --auth-url first.")sys.exit(1)try:- data = json.loads(pending.read_text(encoding="utf-8"))+ data = json.loads(pending.read_text(encoding="utf-8-sig"))except Exception as exc:print(f"ERROR: Could not read pending OAuth session: {exc}")print("Run --auth-url again to start a fresh session.")diff --git a/plugins/platforms/photon/auth.py b/plugins/platforms/photon/auth.pyindex 34b573a2d81..3b18cbd7d84 100644--- a/plugins/platforms/photon/auth.py+++ b/plugins/platforms/photon/auth.py@@ -125,7 +125,7 @@ def _load_auth() -> Dict[str, Any]:if not path.exists():return {}try:- with path.open("r", encoding="utf-8") as fh:+ with path.open("r", encoding="utf-8-sig") as fh:return json.load(fh) or {}except (OSError, json.JSONDecodeError) as e:logger.warning("photon: could not read %s: %s", path, e)diff --git a/plugins/platforms/slack/adapter.py b/plugins/platforms/slack/adapter.pyindex cd8e237d3b5..0a771ea789c 100644--- a/plugins/platforms/slack/adapter.py+++ b/plugins/platforms/slack/adapter.py@@ -2094,7 +2094,7 @@ class SlackAdapter(BasePlatformAdapter):warn_if_credential_file_broadly_readable(tokens_file, label="[Slack]", log=logger)- saved = json.loads(tokens_file.read_text(encoding="utf-8"))+ saved = json.loads(tokens_file.read_text(encoding="utf-8-sig"))for team_id, entry in saved.items():tok = entry.get("token", "") if isinstance(entry, dict) else ""if tok and tok not in bot_tokens:@@ -9446,7 +9446,7 @@ async def _standalone_send(_tokens_file = get_hermes_home() / "slack_tokens.json"if _tokens_file.exists():- _saved = json.loads(_tokens_file.read_text(encoding="utf-8"))+ _saved = json.loads(_tokens_file.read_text(encoding="utf-8-sig"))for _entry in _saved.values():_tok = _entry.get("token", "") if isinstance(_entry, dict) else ""if _tok and _tok not in tokens:diff --git a/plugins/platforms/whatsapp/adapter.py b/plugins/platforms/whatsapp/adapter.pyindex 282cb7c0cbd..3c21d2dbe01 100644--- a/plugins/platforms/whatsapp/adapter.py+++ b/plugins/platforms/whatsapp/adapter.py@@ -188,7 +188,7 @@ def _kill_stale_bridge_by_pidfile(session_path: Path) -> None:try:# Format: line 1 = pid, optional line 2 = kernel start time. Legacy# files written before the guard existed have only the pid.- lines = pid_file.read_text(encoding="utf-8").split("\n")+ lines = pid_file.read_text(encoding="utf-8-sig").split("\n")pid = int(lines[0].strip())if len(lines) > 1 and lines[1].strip():recorded_start = int(lines[1].strip())@@ -577,7 +577,7 @@ class WhatsAppAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):if (bridge_dir / "node_modules").exists():try:_deps_fresh = (- _dep_stamp.read_text(encoding="utf-8").strip() == _pkg_hash+ _dep_stamp.read_text(encoding="utf-8-sig").strip() == _pkg_hash) and bool(_pkg_hash)except OSError:_deps_fresh = False@@ -1598,7 +1598,7 @@ class WhatsAppAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):if file_size > MAX_TEXT_INJECT_BYTES:print(f"[{self.name}] Skipping text injection for {doc_path} ({file_size} bytes > {MAX_TEXT_INJECT_BYTES})", flush=True)continue- content = Path(doc_path).read_text(encoding="utf-8", errors="replace")+ content = Path(doc_path).read_text(encoding="utf-8-sig", errors="replace")fname = Path(doc_path).name# Remove the doc_<hex>_ prefix for displaydisplay_name = fnamediff --git a/plugins/teams_pipeline/store.py b/plugins/teams_pipeline/store.pyindex ceab28cb7ef..07b66af3568 100644--- a/plugins/teams_pipeline/store.py+++ b/plugins/teams_pipeline/store.py@@ -54,7 +54,7 @@ class TeamsPipelineStore:with self._lock:if not self.path.exists():return- data = json.loads(self.path.read_text(encoding="utf-8") or "{}")+ data = json.loads(self.path.read_text(encoding="utf-8-sig") or "{}")if not isinstance(data, dict):returnself._state["subscriptions"] = dict(data.get("subscriptions") or {})diff --git a/scripts/add_contributor.py b/scripts/add_contributor.pyindex cb64b331cbb..f8ef9ac611b 100644--- a/scripts/add_contributor.py+++ b/scripts/add_contributor.py@@ -35,7 +35,7 @@ _LOGIN_RE = re.compile(r"^[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$")def read_mapping_file(path: Path) -> str | None:"""Return the login from a mapping file (first non-comment line)."""try:- for line in path.read_text(encoding="utf-8").splitlines():+ for line in path.read_text(encoding="utf-8-sig").splitlines():line = line.strip()if line and not line.startswith("#"):return linediff --git a/scripts/analyze_livetest.py b/scripts/analyze_livetest.pyindex 6be6b7ad92f..0b892a126a2 100644--- a/scripts/analyze_livetest.py+++ b/scripts/analyze_livetest.py@@ -20,7 +20,7 @@ def load_record(scenario_id: str, mode: str):path = OUT / f"{scenario_id}__{mode}.json"if not path.exists():return None- return json.loads(path.read_text(encoding="utf-8"))+ return json.loads(path.read_text(encoding="utf-8-sig"))def fmt_tool_seq(calls):@@ -65,7 +65,7 @@ def main():print("No _summary.json yet")sys.exit(1)- summary = json.loads(summary_path.read_text(encoding="utf-8"))+ summary = json.loads(summary_path.read_text(encoding="utf-8-sig"))scenarios = sorted({row["scenario"] for row in summary})print(f"{'='*78}")diff --git a/scripts/audit_pr_attribution.py b/scripts/audit_pr_attribution.pyindex 1c998d81fb3..2b7685b082d 100644--- a/scripts/audit_pr_attribution.py+++ b/scripts/audit_pr_attribution.py@@ -70,7 +70,7 @@ def is_mapped(email: str) -> bool:return Truerelease_py = REPO_ROOT / "scripts" / "release.py"try:- if f'"{email}"' in release_py.read_text(encoding="utf-8", errors="replace"):+ if f'"{email}"' in release_py.read_text(encoding="utf-8-sig", errors="replace"):return Trueexcept OSError:passdiff --git a/scripts/check-windows-footguns.py b/scripts/check-windows-footguns.pyindex 30100402d0a..b28b385915d 100644--- a/scripts/check-windows-footguns.py+++ b/scripts/check-windows-footguns.py@@ -22,6 +22,11 @@ Exit status:0 — no Windows footguns found (or all matches suppressed)1 — at least one unsuppressed match+Encoding policy: READS pass encoding='utf-8-sig' (Windows tooling —+PowerShell Set-Content/Out-File, some editors — BOM-prefixes files it+touches; utf-8-sig reads BOM'd and BOM-less files alike). WRITES pass+encoding='utf-8' (never emit a BOM ourselves).+Suppress an intentional use (e.g. tests or platform-gated code) with:os.kill(pid, 0) # windows-footgun: ok — only called on POSIX"""@@ -153,12 +158,13 @@ FOOTGUNS: list[Footgun] = [message=("open() without an explicit encoding= uses the platform default ""(UTF-8 on POSIX, cp1252/mbcs on Windows) — files round-tripped "- "between hosts get mojibake. Always pass encoding='utf-8' for "- "text files, or use open(path, 'rb')/'wb' for binary."+ "between hosts get mojibake. Always pass encoding= explicitly: "+ "'utf-8-sig' for reads (tolerates a BOM), 'utf-8' for writes "+ "(never emit one), or open(path, 'rb')/'wb' for binary."),fix=(- "open(path, 'r', encoding='utf-8') # or 'utf-8-sig' if the "- "file may have a BOM"+ "reads: open(path, 'r', encoding='utf-8-sig') writes: "+ "open(path, 'w', encoding='utf-8')"),# Filter: only flag if mode is missing-or-text AND the line doesn't# already pass encoding=. Skip binary mode (contains "b").@@ -192,7 +198,8 @@ FOOTGUNS: list[Footgun] = ["fdopen, so this checker is the only gate."),fix=(- "os.fdopen(fd, 'w', encoding='utf-8') # or mode 'wb' for binary"+ "reads: os.fdopen(fd, 'r', encoding='utf-8-sig') writes: "+ "os.fdopen(fd, 'w', encoding='utf-8') binary: mode 'rb'/'wb'"),post_filter=lambda m, line: ("b" not in (m.group("mode") or "")@@ -416,7 +423,7 @@ FOOTGUNS: list[Footgun] = ["crashes with UnicodeDecodeError or writes mojibake. ""See issue #37423 and the #71014 / read_text campaign."),- fix='path.read_text(encoding="utf-8") / path.write_text(data, encoding="utf-8")',+ fix='path.read_text(encoding="utf-8-sig") / path.write_text(data, encoding="utf-8")',post_filter=lambda m, line: ("encoding=" not in lineand "encoding =" not in line@@ -431,6 +438,54 @@ FOOTGUNS: list[Footgun] = [and _call_closes_on_line(line, m.end())),),+ Footgun(+ name="read with encoding='utf-8' (BOM-intolerant — use 'utf-8-sig')",+ # Fires when a READ-shaped call passes plain utf-8. Windows tooling+ # (PowerShell Set-Content/Out-File, some editors) BOM-prefixes files+ # it touches; a plain-utf-8 read then hands '\ufeff{...' to+ # json.load, which dies with "Expecting value". utf-8-sig reads+ # BOM'd and BOM-less files identically, so it is strictly safer on+ # the read side. Live case: PR #3 — Set-Content BOM'd+ # install-stamp.json and read_build_info demoted the tree to+ # `unknown`. The quote pattern stops at the closing quote, so+ # 'utf-8-sig' itself never matches.+ pattern=re.compile(+ r"""encoding\s*=\s*['"]utf[-_]?8['"]""", re.IGNORECASE+ ),+ message=(+ "Reading with encoding='utf-8' breaks on BOM-prefixed files — "+ "Windows tooling (PowerShell Set-Content/Out-File, some "+ "editors) BOMs files it touches, and json.load on the result "+ "fails with 'Expecting value'. encoding='utf-8-sig' reads "+ "BOM'd and BOM-less files alike. Policy: reads utf-8-sig, "+ "writes utf-8."+ ),+ fix=(+ "path.read_text(encoding='utf-8-sig') / "+ "open(path, 'r', encoding='utf-8-sig')"+ ),+ post_filter=lambda m, line: _is_read_shaped(line),+ ),+ Footgun(+ name="write with encoding='utf-8-sig' (emits a BOM)",+ # The inverse direction: utf-8-sig on a WRITE emits the BOM — the+ # exact bytes the read-side rule exists to tolerate. Never produce+ # them ourselves.+ pattern=re.compile(+ r"""encoding\s*=\s*['"]utf[-_]?8[-_]sig['"]""", re.IGNORECASE+ ),+ message=(+ "Writing with encoding='utf-8-sig' EMITS a UTF-8 BOM — the "+ "exact bytes that break plain-utf-8 readers and non-Python "+ "tooling. Policy: reads utf-8-sig, writes utf-8 (never emit "+ "a BOM)."+ ),+ fix=(+ "path.write_text(data, encoding='utf-8') / "+ "open(path, 'w', encoding='utf-8')"+ ),+ post_filter=lambda m, line: _is_write_shaped(line),+ ),]@@ -591,6 +646,80 @@ def _looks_like_string_literal(line: str, match: "re.Match") -> bool:return in_s or in_d+# Mode-extraction for file-opening calls, so the encoding-direction rules+# can tell a read from a write. Three shapes, first match wins:+# builtin open(path, "r") / os.fdopen(fd, "w") — mode is the SECOND arg+# path.open("a") — Path.open: mode is FIRST+# open(..., mode="w") — keyword anywhere+# The capture is constrained to Python file-mode characters so a+# nested-call first argument (``open(os.path.join(root, "x.json"), ...)``)+# can't donate its string literal as a phantom mode — that exact line in+# _startup_fast.py false-positived the write rule during the first live+# sweep. The Path.open row exists because its first-arg mode made+# ``path.open("a", encoding=...)`` unclassifiable and the read-side+# fallback rewrote an APPEND to utf-8-sig (BOM'd gateway-exit-diag.log,+# caught by test_lifecycle_ledger).+_OPEN_MODE_RES = (+ re.compile(r"""\bmode\s*=\s*['"]([rwaxbtU+]{1,3})['"]"""),+ re.compile(r"""(?<![.\w])(?:open|fdopen)\s*\([^)]*?,\s*['"]([rwaxbtU+]{1,3})['"]"""),+ re.compile(r"""\bfdopen\s*\([^)]*?,\s*['"]([rwaxbtU+]{1,3})['"]"""),+ re.compile(r"""\.open\s*\(\s*['"]([rwaxbtU+]{1,3})['"]"""),+)+++def _extract_mode(line: str) -> str | None:+ for rx in _OPEN_MODE_RES:+ m = rx.search(line)+ if m:+ return m.group(1)+ return None+++def _is_read_shaped(line: str) -> bool:+ """Heuristic: does this line READ a file (so utf-8-sig applies)?++ read_text() is a read by name; write_text() a write. For open()/+ fdopen()/Path.open() the mode string decides: anything containing+ w/a/x/+ can write, plain 'r' is a read. A bare builtin open()/fdopen()+ with the mode omitted defaults to 'r' — but an omitted-mode `.open(`+ METHOD call is NOT classified (we can't know the receiver; Path.open+ defaults to read, but the sweep must never rewrite on a guess).+ Lines with no file-opening call at all (subprocess encoding=,+ TextIOWrapper, ...) are NOT classified as reads — the rule stays+ quiet rather than guess.+ """+ if ".read_text(" in line:+ return True+ if ".write_text(" in line:+ return False+ mode = _extract_mode(line)+ if mode is not None:+ return not any(c in mode for c in "wax+")+ # open()/fdopen() with the mode omitted defaults to 'r'. Builtin-call+ # boundary only: `.open(`-method calls without a recognizable mode+ # stay unclassified (the Path.open("a") lesson above).+ return bool(re.search(r"(?<![.\w])(?:open|fdopen)\s*\(", line)) or bool(+ re.search(r"\bfdopen\s*\(", line)+ )+++def _is_write_shaped(line: str) -> bool:+ """Heuristic: does this line WRITE a file (so a BOM would be emitted)?++ The mirror of _is_read_shaped, with the same conservative default:+ unclassifiable lines return False so the write rule never fires on+ non-file-call sites.+ """+ if ".write_text(" in line:+ return True+ if ".read_text(" in line:+ return False+ mode = _extract_mode(line)+ if mode is not None:+ return any(c in mode for c in "wax+")+ return False++def scan_file(path: Path, footguns: list[Footgun]) -> list[tuple[int, str, Footgun]]:"""Return a list of (line_number, line, footgun) for unsuppressed matches."""try:diff --git a/scripts/check_subprocess_stdin.py b/scripts/check_subprocess_stdin.pyindex 884923e2e04..8cb7459825c 100644--- a/scripts/check_subprocess_stdin.py+++ b/scripts/check_subprocess_stdin.py@@ -181,7 +181,7 @@ def main() -> int:if any(skip.rstrip("/") in parts for skip in SKIP_DIRS):continue- content = py_file.read_text(encoding="utf-8")+ content = py_file.read_text(encoding="utf-8-sig")violations = find_subprocess_calls(content, rel)all_violations.extend(violations)@@ -205,7 +205,7 @@ def main() -> int:continuetry:- content = py_file.read_text(encoding="utf-8")+ content = py_file.read_text(encoding="utf-8-sig")except Exception:continueviolations = find_subprocess_calls(content, rel)diff --git a/scripts/ci/e2e_screenshot_status.py b/scripts/ci/e2e_screenshot_status.pyindex e40b4157683..2de0a801535 100644--- a/scripts/ci/e2e_screenshot_status.py+++ b/scripts/ci/e2e_screenshot_status.py@@ -37,7 +37,7 @@ def _base_screenshot_names(path: Path | None) -> set[str] | None:if path is None or not path.is_file():return Nonetry:- data = json.loads(path.read_text(encoding="utf-8"))+ data = json.loads(path.read_text(encoding="utf-8-sig"))except json.JSONDecodeError:return Nonenames = data.get("screenshot_names", []) if isinstance(data, dict) else []diff --git a/scripts/ci/list_os_marked_tests.py b/scripts/ci/list_os_marked_tests.pyindex bfbc0a60c1d..950b7e3507f 100644--- a/scripts/ci/list_os_marked_tests.py+++ b/scripts/ci/list_os_marked_tests.py@@ -45,7 +45,7 @@ def find_marked_files(marker: str, root: Path) -> list[Path]:hits: list[Path] = []for path in sorted(root.rglob("test_*.py")):try:- text = path.read_text(encoding="utf-8", errors="replace")+ text = path.read_text(encoding="utf-8-sig", errors="replace")except OSError:continueif pattern.search(text):diff --git a/scripts/ci/live_comment.py b/scripts/ci/live_comment.pyindex 708906d3ae6..7a976825d4c 100644--- a/scripts/ci/live_comment.py+++ b/scripts/ci/live_comment.py@@ -425,7 +425,7 @@ def _download_artifact(def _parse_status_file(status_file: Path) -> list[dict]:"""Parse a review-status.json file in GITHUB_OUTPUT format."""try:- content = status_file.read_text(encoding="utf-8").strip()+ content = status_file.read_text(encoding="utf-8-sig").strip()if content.startswith("review_status="):content = content[len("review_status="):]statuses = json.loads(content)diff --git a/scripts/ci/publish_e2e_evidence.py b/scripts/ci/publish_e2e_evidence.pyindex 8105259063e..8562e24815b 100644--- a/scripts/ci/publish_e2e_evidence.py+++ b/scripts/ci/publish_e2e_evidence.py@@ -130,7 +130,7 @@ def load_evidence(evidence_dir: Path) -> tuple[list[EvidenceFile], dict[str, bytif not manifest_path.is_file() or manifest_path.is_symlink():raise ValueError("E2E evidence manifest is missing")try:- manifest = json.loads(manifest_path.read_text(encoding="utf-8"))+ manifest = json.loads(manifest_path.read_text(encoding="utf-8-sig"))except json.JSONDecodeError as exc:raise ValueError("E2E evidence manifest is not JSON") from excif not isinstance(manifest, dict):diff --git a/scripts/ci/timings_report.py b/scripts/ci/timings_report.pyindex 8a4d1cf669e..3cfeaeb0729 100644--- a/scripts/ci/timings_report.py+++ b/scripts/ci/timings_report.py@@ -1005,7 +1005,7 @@ def main():# Collect or load timingsif args.from_json:- with open(args.from_json, encoding="utf-8") as f:+ with open(args.from_json, encoding="utf-8-sig") as f:timings = json.load(f)else:repo = expect_env("GITHUB_REPOSITORY")@@ -1041,7 +1041,7 @@ def main():# Load baselinebaseline = Noneif os.path.exists(args.baseline):- with open(args.baseline, encoding="utf-8") as f:+ with open(args.baseline, encoding="utf-8-sig") as f:baseline = json.load(f)print(f"Loaded baseline from {args.baseline}")else:diff --git a/scripts/contributor_audit.py b/scripts/contributor_audit.pyindex 11a02dda245..965b4c72813 100644--- a/scripts/contributor_audit.py+++ b/scripts/contributor_audit.py@@ -311,7 +311,7 @@ def check_release_file(release_file, all_contributors):missing: set of handles NOT found in the file"""try:- content = Path(release_file).read_text(encoding="utf-8")+ content = Path(release_file).read_text(encoding="utf-8-sig")except FileNotFoundError:print(f" [error] Release file not found: {release_file}", file=sys.stderr)return set(), set(all_contributors)diff --git a/scripts/discord-voice-doctor.py b/scripts/discord-voice-doctor.pyindex e295225a0e3..dd552a87b75 100755--- a/scripts/discord-voice-doctor.py+++ b/scripts/discord-voice-doctor.py@@ -242,7 +242,7 @@ def check_config(groq_key, eleven_key):if config_path.exists():try:import yaml- with open(config_path, encoding="utf-8") as f:+ with open(config_path, encoding="utf-8-sig") as f:cfg = yaml.safe_load(f) or {}stt_provider = cfg.get("stt", {}).get("provider", "local")@@ -268,7 +268,7 @@ def check_config(groq_key, eleven_key):if voice_mode_path.exists():try:import json- modes = json.loads(voice_mode_path.read_text(encoding="utf-8"))+ modes = json.loads(voice_mode_path.read_text(encoding="utf-8-sig"))off_count = sum(1 for v in modes.values() if v == "off")all_count = sum(1 for v in modes.values() if v == "all")check("Voice mode state", True, f"{all_count} on, {off_count} off, {len(modes)} total")diff --git a/scripts/docker_rebootstrap_nous_session.py b/scripts/docker_rebootstrap_nous_session.pyindex 0c4125d64e2..4d6b03959f8 100644--- a/scripts/docker_rebootstrap_nous_session.py+++ b/scripts/docker_rebootstrap_nous_session.py@@ -161,7 +161,7 @@ def reseed_if_terminal(auth_path: str, seed_raw: str) -> str:return "no_auth_file"try:- with open(auth_path, "r", encoding="utf-8") as fh:+ with open(auth_path, "r", encoding="utf-8-sig") as fh:store = json.load(fh)except (OSError, ValueError):# Corrupt/unreadable auth.json: do NOT overwrite blindly. A separatediff --git a/scripts/lint_diff.py b/scripts/lint_diff.pyindex c8d88a25627..9bb7d2e55fe 100755--- a/scripts/lint_diff.py+++ b/scripts/lint_diff.py@@ -30,7 +30,7 @@ def _load_json(path: Path | None) -> list[dict]:if path is None or not path.exists() or path.stat().st_size == 0:return []try:- data = json.loads(path.read_text(encoding="utf-8"))+ data = json.loads(path.read_text(encoding="utf-8-sig"))except json.JSONDecodeError as exc:print(f"warning: could not parse {path}: {exc}", file=sys.stderr)return []diff --git a/scripts/micro_compaction_report.py b/scripts/micro_compaction_report.pyindex 30811a67178..61c95f72944 100644--- a/scripts/micro_compaction_report.py+++ b/scripts/micro_compaction_report.py@@ -53,7 +53,7 @@ def load(paths: list[Path]) -> tuple[list[dict], list[dict]]:batch: list[dict] = []for path in paths:try:- text = path.read_text(encoding="utf-8", errors="replace")+ text = path.read_text(encoding="utf-8-sig", errors="replace")except OSError as exc:print(f"warning: cannot read {path}: {exc}", file=sys.stderr)continuediff --git a/scripts/observability/gateway_health_export_probe.py b/scripts/observability/gateway_health_export_probe.pyindex e1064088e2a..3c7d2e15485 100644--- a/scripts/observability/gateway_health_export_probe.py+++ b/scripts/observability/gateway_health_export_probe.py@@ -77,7 +77,7 @@ def main() -> None:emitter.get_emitter().flush(timeout=2.0)log_path = Path(args.log)- rows = [json.loads(line) for line in log_path.read_text(encoding="utf-8").splitlines() if line.strip()]+ rows = [json.loads(line) for line in log_path.read_text(encoding="utf-8-sig").splitlines() if line.strip()]paths = {row["path"] for row in rows}print(json.dumps({"hermes_home": str(hermes_home), "requests": len(rows), "paths": sorted(paths)}, indent=2))if "/v1/traces" not in paths:diff --git a/scripts/profile-tui.py b/scripts/profile-tui.pyindex 4d86aa057bf..6c0fa2d4330 100755--- a/scripts/profile-tui.py+++ b/scripts/profile-tui.py@@ -114,7 +114,7 @@ def summarize(log: Path, since_ts_ms: int) -> dict[str, Any]:frame_events: list[dict[str, Any]] = []if not log.exists():return {"error": f"no log at {log}", "react": [], "frame": []}- for line in log.read_text(encoding="utf-8").splitlines():+ for line in log.read_text(encoding="utf-8-sig").splitlines():line = line.strip()if not line:continue@@ -516,7 +516,7 @@ def main() -> int:if not path.exists():print(f"\n⚠ no baseline at {path} — run with --save {args.compare} first")else:- before = json.loads(path.read_text(encoding="utf-8"))+ before = json.loads(path.read_text(encoding="utf-8-sig"))print(f"\n═══ A/B diff vs /tmp/perf-{args.compare}.json ═══")print(format_diff(before, metrics))diff --git a/scripts/run_tests_parallel.py b/scripts/run_tests_parallel.pyindex eb923cc9b43..7c760696cae 100755--- a/scripts/run_tests_parallel.py+++ b/scripts/run_tests_parallel.py@@ -166,7 +166,7 @@ def _off_host_marker_files(files: List[Path]) -> dict[str, int]:counts = {marker: 0 for marker in off_host}for path in files:try:- text = path.read_text(encoding="utf-8", errors="replace")+ text = path.read_text(encoding="utf-8-sig", errors="replace")except OSError:continuefor marker, pattern in off_host.items():@@ -191,7 +191,7 @@ def _approximately_count_tests(results = {}for path in files:- with open(path, "r", encoding="utf-8") as f:+ with open(path, "r", encoding="utf-8-sig") as f:contents = f.read()results[path] = contents.count("def test_")@@ -634,7 +634,7 @@ def _load_durations(repo_root: Path) -> dict[str, float]:if not path.is_file():return {}try:- return json.loads(path.read_text(encoding="utf-8"))+ return json.loads(path.read_text(encoding="utf-8-sig"))except (json.JSONDecodeError, OSError) as e:print("[ERROR] Failed to load json durations file! {e}")return {}diff --git a/scripts/sample_and_compress.py b/scripts/sample_and_compress.pyindex a8fcfd66b35..67b0f5ba35d 100644--- a/scripts/sample_and_compress.py+++ b/scripts/sample_and_compress.py@@ -298,7 +298,7 @@ def merge_output_to_single_jsonl(input_dir: Path, output_file: Path):for jsonl_file in sorted(input_dir.glob("*.jsonl")):if jsonl_file.name == output_file.name:continue- with open(jsonl_file, 'r', encoding='utf-8') as f:+ with open(jsonl_file, 'r', encoding='utf-8-sig') as f:for line in f:line = line.strip()if line:diff --git a/scripts/smoke_nemo_relay_shared_metrics.py b/scripts/smoke_nemo_relay_shared_metrics.pyindex ba11567532d..3ba4c55197a 100644--- a/scripts/smoke_nemo_relay_shared_metrics.py+++ b/scripts/smoke_nemo_relay_shared_metrics.py@@ -434,9 +434,9 @@ def _validate_packages(raise RuntimeError("The Hermes development environment requires jsonschema") from exc- schema = json.loads(schema_path.read_text(encoding="utf-8"))+ schema = json.loads(schema_path.read_text(encoding="utf-8-sig"))packages = [- json.loads(package_path.read_text(encoding="utf-8"))+ json.loads(package_path.read_text(encoding="utf-8-sig"))for package_path in package_paths]for package in packages:diff --git a/scripts/tool_search_livetest_ue.py b/scripts/tool_search_livetest_ue.pyindex 37940d7ad25..28ec7259911 100644--- a/scripts/tool_search_livetest_ue.py+++ b/scripts/tool_search_livetest_ue.py@@ -54,7 +54,7 @@ def _mock_result(tool_name: str) -> str:def load_epic_tools(scale: str) -> List[Dict[str, Any]]:- with open(PROBE, encoding="utf-8") as f:+ with open(PROBE, encoding="utf-8-sig") as f:raw = json.load(f)out = []for ts_name, ts in raw["toolsets"].items():diff --git a/scripts/toolperf_abeval/ab_eval.py b/scripts/toolperf_abeval/ab_eval.pyindex 01fa9a355bb..a7fe47b8ea4 100644--- a/scripts/toolperf_abeval/ab_eval.py+++ b/scripts/toolperf_abeval/ab_eval.py@@ -130,13 +130,13 @@ def make_sandbox(work: Path):SUCCESS = {"err_python_env": lambda t, w: "ENV_OK_4477" in t,"err_replay_patch": lambda t, w: "CONFIG_OK_881" in t and (- w / "proj" / "config.py").read_text(encoding="utf-8").count("RETRY_LIMIT = 30") == 1,+ w / "proj" / "config.py").read_text(encoding="utf-8-sig").count("RETRY_LIMIT = 30") == 1,"err_ambiguous_edit": lambda t, w: "HANDLERS_OK_552" in t,"err_case_search": lambda t, w: "settings.ini" in t and "client.go" in t,"err_hidden_search": lambda t, w: "rotation.cfg" in t and "ops.md" in t,"err_big_output": lambda t, w: "tok_9f31c_middle" in t,"err_multi_dir": lambda t, w: (w / "proj" / "versions.txt").exists()- and "1.4.2,0.9.7,3.2.1" in (w / "proj" / "versions.txt").read_text(encoding="utf-8"),+ and "1.4.2,0.9.7,3.2.1" in (w / "proj" / "versions.txt").read_text(encoding="utf-8-sig"),# sum of squares of 1..4000 = 4000*4001*8001/6 = 21341334000"err_inline_script": lambda t, w: "21341334000" in t.replace(",", ""),"err_big_file_read": lambda t, w: "X99Q" in t,@@ -149,7 +149,7 @@ def run(arm: str, model: str, reps: int, pythonpath: str, only=None):meta_path = resdir / "meta.jsonl"done = set()if meta_path.exists():- for line in meta_path.read_text(encoding="utf-8").splitlines():+ for line in meta_path.read_text(encoding="utf-8-sig").splitlines():try:done.add(json.loads(line)["run_id"])except (ValueError, KeyError):@@ -227,7 +227,7 @@ def score_run(atof: Path):last_err_tool = Noneif not atof.exists():return None- for line in atof.read_text(encoding="utf-8").splitlines():+ for line in atof.read_text(encoding="utf-8-sig").splitlines():try:ev = json.loads(line)except ValueError:@@ -266,7 +266,7 @@ def report(models):meta_path = mdir / arm / "meta.jsonl"if not meta_path.exists():continue- for line in meta_path.read_text(encoding="utf-8").splitlines():+ for line in meta_path.read_text(encoding="utf-8-sig").splitlines():m = json.loads(line)s = score_run(mdir / arm / f"{m['run_id']}.atof.jsonl") or {}work = ROOT / "runs" / model.replace("/", "_") / arm / m["run_id"]diff --git a/tests/agent/test_copilot_acp_client.py b/tests/agent/test_copilot_acp_client.pyindex 100dca67f46..20d086d4510 100644--- a/tests/agent/test_copilot_acp_client.py+++ b/tests/agent/test_copilot_acp_client.py@@ -75,7 +75,7 @@ class CopilotACPClientSafetyTests(unittest.TestCase):with tempfile.TemporaryDirectory() as tmpdir:root = Path(tmpdir)secret_file = root / "config.env"- secret_file.write_text("OPENAI_API_KEY=sk-proj-abc123def456ghi789jkl012")+ secret_file.write_text("OPENAI_API_KEY=sk-proj-abc123def456ghi789jkl012", encoding="utf-8")# agent.redact snapshots HERMES_REDACT_SECRETS at import time into# _REDACT_ENABLED, so patching os.environ is a no-op. Flip the@@ -109,7 +109,9 @@ class CopilotACPClientSafetyTests(unittest.TestCase):original_read_text = Path.read_textdef strict_read_text(self, encoding=None, errors=None, **kwargs):- if self == target and encoding != "utf-8":+ # The repo encoding policy makes reads BOM-tolerant, so both+ # UTF-8 family codecs satisfy this regression guard.+ if self == target and encoding not in ("utf-8", "utf-8-sig"):raise UnicodeDecodeError("gbk", b"\x94", 0, 1, "illegal multibyte sequence")diff --git a/tests/agent/test_nous_rate_guard.py b/tests/agent/test_nous_rate_guard.pyindex decdda54836..a56e79722a9 100644--- a/tests/agent/test_nous_rate_guard.py+++ b/tests/agent/test_nous_rate_guard.py@@ -28,7 +28,7 @@ class TestRecordNousRateLimit:path = _state_path()assert os.path.exists(path)- with open(path) as f:+ with open(path, encoding="utf-8-sig") as f:state = json.load(f)assert state["reset_seconds"] == pytest.approx(1800, abs=2)assert state["reset_at"] > time.time()@@ -45,7 +45,7 @@ class TestRecordNousRateLimit:error_context={"reset_at": future_reset},)- with open(_state_path()) as f:+ with open(_state_path(), encoding="utf-8-sig") as f:state = json.load(f)assert state["reset_at"] == pytest.approx(future_reset, abs=1)@@ -55,7 +55,7 @@ class TestRecordNousRateLimit:record_nous_rate_limit(headers=None, default_cooldown=120.0)- with open(_state_path()) as f:+ with open(_state_path(), encoding="utf-8-sig") as f:state = json.load(f)assert state["reset_seconds"] == pytest.approx(120, abs=2)@@ -77,9 +77,10 @@ class TestNousRateLimitRemaining:from agent.nous_rate_guard import nous_rate_limit_remaining, _state_path# Write an already-expired state- state_dir = os.path.dirname(_state_path())+ path = _state_path()+ state_dir = os.path.dirname(path)os.makedirs(state_dir, exist_ok=True)- with open(_state_path(), "w") as f:+ with open(path, "w", encoding="utf-8") as f:json.dump({"reset_at": time.time() - 10, "recorded_at": time.time() - 100}, f)assert nous_rate_limit_remaining() is None@@ -272,7 +273,13 @@ class TestRateGuardStateEncoding:is_target = str(file) == str(path)except Exception:is_target = False- if is_target and "b" not in mode and kwargs.get("encoding") != "utf-8":+ # The repo encoding policy makes reads BOM-tolerant, so both+ # UTF-8 family codecs satisfy this regression guard.+ if (+ is_target+ and "b" not in mode+ and kwargs.get("encoding") not in ("utf-8", "utf-8-sig")+ ):raise UnicodeDecodeError("gbk", b"\x94", 0, 1, "illegal multibyte sequence")diff --git a/tests/scripts/test_footgun_encoding_direction.py b/tests/scripts/test_footgun_encoding_direction.pynew file mode 100644index 00000000000..69fa2a2a125--- /dev/null+++ b/tests/scripts/test_footgun_encoding_direction.py@@ -0,0 +1,281 @@+"""Tests for the encoding-direction footgun rules in+``scripts/check-windows-footguns.py``.++Two rules enforce the repo encoding policy (reads ``utf-8-sig``, writes+``utf-8``):++- ``read with encoding='utf-8' (BOM-intolerant — use 'utf-8-sig')`` —+ Windows tooling (PowerShell Set-Content/Out-File, some editors)+ BOM-prefixes files it touches; a plain-utf-8 read hands ``'\\ufeff{...'``+ to ``json.load``, which fails with "Expecting value". Live case: PR #3 —+ a BOM'd ``install-stamp.json`` made ``read_build_info`` demote the tree+ to ``unknown``.+- ``write with encoding='utf-8-sig' (emits a BOM)`` — the inverse: writing+ with ``utf-8-sig`` emits the exact bytes the read rule exists to+ tolerate.+"""++from __future__ import annotations++import importlib.util+import sys+from pathlib import Path++import pytest++REPO_ROOT = Path(__file__).resolve().parents[2]+LINTER_PATH = REPO_ROOT / "scripts" / "check-windows-footguns.py"++READ_RULE = "read with encoding='utf-8' (BOM-intolerant — use 'utf-8-sig')"+WRITE_RULE = "write with encoding='utf-8-sig' (emits a BOM)"+++def _load_linter_module():+ """Import the linter script as a module (it's not a package).++ Register the module in sys.modules BEFORE exec_module so that+ ``@dataclass`` can resolve ``cls.__module__`` (CPython 3.11+).+ """+ spec = importlib.util.spec_from_file_location(+ "check_windows_footguns", LINTER_PATH+ )+ mod = importlib.util.module_from_spec(spec)+ sys.modules["check_windows_footguns"] = mod+ spec.loader.exec_module(mod)+ return mod++[email protected](scope="module")+def linter():+ return _load_linter_module()+++def _find_footgun(linter, name: str):+ for fg in linter.FOOTGUNS:+ if fg.name == name:+ return fg+ pytest.fail(f"Footgun rule '{name}' not found in FOOTGUNS")+++def _scan_line(linter, line: str, footgun_name: str) -> bool:+ """Return True if the given line triggers the named footgun rule.++ Replicates the relevant checks from scan_file(): suppression marker,+ guard hints, comment stripping, then pattern + post_filter — so the+ test exercises the real detection path.+ """+ fg = _find_footgun(linter, footgun_name)+ if linter.SUPPRESS_MARKER.search(line):+ return False+ if any(hint in line for hint in linter.GUARD_HINTS):+ return False+ code = linter._strip_code(line)+ if not code.strip():+ return False+ match = fg.pattern.search(code)+ if not match:+ return False+ if fg.post_filter is not None:+ try:+ if not fg.post_filter(match, line):+ return False+ except (IndexError, AttributeError):+ return False+ return True+++# ---------------------------------------------------------------------------+# READ rule — plain utf-8 on read-shaped lines SHOULD be flagged+# ---------------------------------------------------------------------------+++class TestReadRuleDetection:+ def test_flags_read_text_plain_utf8(self, linter):+ line = ' data = path.read_text(encoding="utf-8")'+ assert _scan_line(linter, line, READ_RULE)++ def test_flags_open_read_mode_plain_utf8(self, linter):+ line = " with open(path, 'r', encoding='utf-8') as f:"+ assert _scan_line(linter, line, READ_RULE)++ def test_flags_open_omitted_mode_plain_utf8(self, linter):+ # open() defaults to mode 'r' — still a read.+ line = " with open(path, encoding='utf-8') as f:"+ assert _scan_line(linter, line, READ_RULE)++ def test_flags_fdopen_read_mode_plain_utf8(self, linter):+ line = " f = os.fdopen(fd, 'r', encoding='utf-8')"+ assert _scan_line(linter, line, READ_RULE)++ def test_flags_underscore_spelling(self, linter):+ line = ' data = path.read_text(encoding="utf_8")'+ assert _scan_line(linter, line, READ_RULE)++ def test_flags_mode_keyword_read(self, linter):+ line = " with open(path, mode='r', encoding='utf-8') as f:"+ assert _scan_line(linter, line, READ_RULE)+++class TestReadRuleNegatives:+ def test_does_not_flag_utf8_sig_read(self, linter):+ # The policy-compliant form. The pattern must stop at the closing+ # quote of 'utf-8' and never match 'utf-8-sig'.+ line = ' data = path.read_text(encoding="utf-8-sig")'+ assert not _scan_line(linter, line, READ_RULE)++ def test_does_not_flag_write_text_plain_utf8(self, linter):+ # Writes with plain utf-8 are the CORRECT form.+ line = ' path.write_text(data, encoding="utf-8")'+ assert not _scan_line(linter, line, READ_RULE)++ def test_does_not_flag_open_write_mode_plain_utf8(self, linter):+ line = " with open(path, 'w', encoding='utf-8') as f:"+ assert not _scan_line(linter, line, READ_RULE)++ def test_does_not_flag_append_mode(self, linter):+ line = " with open(path, 'a', encoding='utf-8') as f:"+ assert not _scan_line(linter, line, READ_RULE)++ def test_does_not_flag_plus_mode(self, linter):+ # 'r+' can write — treat as write-capable, not a read.+ line = " with open(path, 'r+', encoding='utf-8') as f:"+ assert not _scan_line(linter, line, READ_RULE)++ def test_does_not_flag_subprocess_encoding(self, linter):+ # Not a file read; the rule stays quiet on unclassifiable lines.+ line = " subprocess.run(cmd, text=True, encoding='utf-8')"+ assert not _scan_line(linter, line, READ_RULE)++ def test_does_not_flag_suppressed_line(self, linter):+ line = (+ " data = path.read_text(encoding='utf-8')"+ " # windows-footgun: ok — file is repo-owned, never BOM'd"+ )+ assert not _scan_line(linter, line, READ_RULE)++ def test_does_not_flag_comment_only_line(self, linter):+ line = " # use path.read_text(encoding='utf-8') here"+ assert not _scan_line(linter, line, READ_RULE)+++# ---------------------------------------------------------------------------+# WRITE rule — utf-8-sig on write-shaped lines SHOULD be flagged+# ---------------------------------------------------------------------------+++class TestWriteRuleDetection:+ def test_flags_write_text_utf8_sig(self, linter):+ line = ' path.write_text(data, encoding="utf-8-sig")'+ assert _scan_line(linter, line, WRITE_RULE)++ def test_flags_open_write_mode_utf8_sig(self, linter):+ line = " with open(path, 'w', encoding='utf-8-sig') as f:"+ assert _scan_line(linter, line, WRITE_RULE)++ def test_flags_append_mode_utf8_sig(self, linter):+ line = " with open(path, 'a', encoding='utf-8-sig') as f:"+ assert _scan_line(linter, line, WRITE_RULE)++ def test_flags_fdopen_write_mode_utf8_sig(self, linter):+ line = " f = os.fdopen(fd, 'w', encoding='utf-8-sig')"+ assert _scan_line(linter, line, WRITE_RULE)++ def test_flags_path_open_append_utf8_sig(self, linter):+ # Path.open puts the mode in the FIRST argument — the original+ # classifier only understood the builtin second-arg shape, so the+ # live sweep rewrote 18 append/write sites to utf-8-sig (BOM per+ # append in jsonl logs; caught by test_lifecycle_ledger).+ line = ' with path.open("a", encoding="utf-8-sig") as fh:'+ assert _scan_line(linter, line, WRITE_RULE)++ def test_flags_path_open_plus_mode_utf8_sig(self, linter):+ # r+/a+ can write at position 0 — write-shaped.+ line = ' lock = path.open("a+", encoding="utf-8-sig")'+ assert _scan_line(linter, line, WRITE_RULE)++ def test_flags_underscore_spelling(self, linter):+ line = ' path.write_text(data, encoding="utf_8_sig")'+ assert _scan_line(linter, line, WRITE_RULE)+++class TestWriteRuleNegatives:+ def test_does_not_flag_utf8_sig_read(self, linter):+ # Reads with utf-8-sig are the CORRECT form.+ line = ' data = path.read_text(encoding="utf-8-sig")'+ assert not _scan_line(linter, line, WRITE_RULE)++ def test_does_not_flag_open_read_mode_utf8_sig(self, linter):+ line = " with open(path, 'r', encoding='utf-8-sig') as f:"+ assert not _scan_line(linter, line, WRITE_RULE)++ def test_does_not_flag_open_omitted_mode_utf8_sig(self, linter):+ # Omitted mode defaults to 'r' — a read.+ line = " with open(path, encoding='utf-8-sig') as f:"+ assert not _scan_line(linter, line, WRITE_RULE)++ def test_does_not_flag_plain_utf8_write(self, linter):+ line = ' path.write_text(data, encoding="utf-8")'+ assert not _scan_line(linter, line, WRITE_RULE)++ def test_does_not_flag_unclassifiable_line(self, linter):+ # No file-opening call — conservative default is no flag.+ line = " codec = 'utf-8-sig'"+ assert not _scan_line(linter, line, WRITE_RULE)++ def test_does_not_flag_nested_call_first_arg(self, linter):+ # Regression: the first live sweep false-positived this line from+ # _startup_fast.py — the old mode regex swallowed the nested+ # ``join(`` paren and captured "install-stamp.json" as the mode+ # (its 'a' made it look write-shaped). Omitted mode = read.+ line = (+ ' with open(os.path.join(root, "install-stamp.json"), '+ 'encoding="utf-8-sig") as handle:'+ )+ assert not _scan_line(linter, line, WRITE_RULE)++ def test_does_not_flag_path_open_read_mode_utf8_sig(self, linter):+ line = ' with path.open("r", encoding="utf-8-sig") as fh:'+ assert not _scan_line(linter, line, WRITE_RULE)++ def test_read_rule_does_not_rewrite_path_open_append(self, linter):+ # The inverse guard on the READ rule: an append-mode Path.open with+ # plain utf-8 is CORRECT and must never be flagged for conversion.+ line = ' with path.open("a", encoding="utf-8") as fh:'+ assert not _scan_line(linter, line, READ_RULE)++ def test_read_rule_skips_method_open_without_mode(self, linter):+ # `.open(` with no recognizable mode is unclassified — the sweep+ # must never rewrite on a guess about the receiver.+ line = ' with something.open(encoding="utf-8") as fh:'+ assert not _scan_line(linter, line, READ_RULE)++ def test_does_not_flag_suppressed_line(self, linter):+ line = (+ " path.write_text(data, encoding='utf-8-sig')"+ " # windows-footgun: ok — downstream consumer requires a BOM"+ )+ assert not _scan_line(linter, line, WRITE_RULE)+++# ---------------------------------------------------------------------------+# Suppression marker cannot be a bare comment mention (the real invariant —+# a comment that merely NAMES the marker text elsewhere must not exempt).+# ---------------------------------------------------------------------------+++class TestShapeHelpers:+ def test_read_shaped_read_text(self, linter):+ assert linter._is_read_shaped('x = p.read_text(encoding="utf-8")')++ def test_read_shaped_rejects_write_text(self, linter):+ assert not linter._is_read_shaped('p.write_text(d, encoding="utf-8")')++ def test_write_shaped_x_mode(self, linter):+ assert linter._is_write_shaped("open(p, 'x', encoding='utf-8-sig')")++ def test_write_shaped_rejects_no_call(self, linter):+ assert not linter._is_write_shaped("enc = 'utf-8-sig'")++ def test_read_shaped_rejects_no_call(self, linter):+ # No open/fdopen/read_text on the line at all.+ assert not linter._is_read_shaped("enc = 'utf-8'")diff --git a/tests/tools/test_working_diff.py b/tests/tools/test_working_diff.pyindex 6fec09030be..27a14188877 100644--- a/tests/tools/test_working_diff.py+++ b/tests/tools/test_working_diff.py@@ -121,3 +121,30 @@ def test_cp932_content_is_lossy_but_never_raises(repo):assert result["success"] is Trueassert "legacy.txt" in result["diff"]assert "\ufffd" in result["diff"] # lossy by design, matching _run_git+++def test_external_differ_is_ignored(repo):+ # A user-configured external differ (diff.external in gitconfig, e.g.+ # difftastic) replaces the unified-diff output of every plain "git+ # diff". collect_working_diff must force the internal engine+ # (--no-ext-diff) so the collected output stays parseable unified diff.+ _git(repo, "config", "diff.external", "echo EXTERNAL-DIFF-GARBAGE")+ (repo / "tracked.py").write_text("print('changed')\n")+ (repo / "brand_new.py").write_text("print('new')\n")++ result = collect_working_diff(str(repo))++ assert result["success"] is True+ assert "EXTERNAL-DIFF-GARBAGE" not in result["diff"]+ # tracked change comes through the plain-diff call site+ assert "-print('hello')" in result["diff"]+ assert "+print('changed')" in result["diff"]+ # untracked file comes through the --no-index call site+ assert "+print('new')" in result["diff"]++ # staged call site (--cached) is covered too+ _git(repo, "add", "tracked.py")+ staged = collect_working_diff(str(repo), mode="staged")+ assert staged["success"] is True+ assert "EXTERNAL-DIFF-GARBAGE" not in staged["diff"]+ assert "+print('changed')" in staged["diff"]diff --git a/tools/blueprints.py b/tools/blueprints.pyindex c236a32a8b4..3cb4c847cf6 100644--- a/tools/blueprints.py+++ b/tools/blueprints.py@@ -157,7 +157,7 @@ def blueprint_spec_for_installed(skill_name: str) -> Optional[BlueprintSpec]:candidates = list(base.glob(f"**/{skill_name}/SKILL.md"))for path in candidates:try:- text = path.read_text(encoding="utf-8")+ text = path.read_text(encoding="utf-8-sig")except OSError:continuespec = parse_blueprint(text)diff --git a/tools/bot_mode_dm.py b/tools/bot_mode_dm.pyindex 0cce0cfee69..a29bcea9d69 100644--- a/tools/bot_mode_dm.py+++ b/tools/bot_mode_dm.py@@ -567,7 +567,7 @@ def _run_delivery(argv: list[str], dm_file: str, *, stdin_file: bool) -> int:if stdin_file:# Keep the file open until the transport exits; cleanup occurs# after subprocess.run returns, not merely after stdin reaches EOF.- with open(dm_file, "r", encoding="utf-8") as stream:+ with open(dm_file, "r", encoding="utf-8-sig") as stream:return subprocess.run(argv, stdin=stream, check=False).returncodeproc = subprocess.run([*argv, "--query-file", dm_file],diff --git a/tools/bot_mode_probe.py b/tools/bot_mode_probe.pyindex ca92c6f26a4..440212c4aa9 100644--- a/tools/bot_mode_probe.py+++ b/tools/bot_mode_probe.py@@ -66,7 +66,7 @@ def _is_bot_managed(profile_dir: Path) -> bool:try:if not meta.is_file():return False- raw = meta.read_text(encoding="utf-8", errors="replace")+ raw = meta.read_text(encoding="utf-8-sig", errors="replace")if "hermes-bots" not in raw:return Falseimport yaml@@ -113,7 +113,7 @@ def is_bot_mode_managed(home: str | os.PathLike | None = None) -> bool:def _soul_has_protocol(profile_dir: Path) -> bool:try:soul = profile_dir / "SOUL.md"- return soul.is_file() and _PROTOCOL_HEADING in soul.read_text(encoding="utf-8", errors="replace")+ return soul.is_file() and _PROTOCOL_HEADING in soul.read_text(encoding="utf-8-sig", errors="replace")except Exception:return False@@ -135,7 +135,7 @@ def _profile_role(profile_dir: Path) -> str:try:if not meta.is_file():return ""- raw = meta.read_text(encoding="utf-8", errors="replace")+ raw = meta.read_text(encoding="utf-8-sig", errors="replace")import yamldata = yaml.safe_load(raw)@@ -178,7 +178,7 @@ def _peers(root: Path) -> list[str]:cfg_path = root / "config.yaml"if not cfg_path.is_file():return []- raw = cfg_path.read_text(encoding="utf-8", errors="replace")+ raw = cfg_path.read_text(encoding="utf-8-sig", errors="replace")if "bot_peers" not in raw:return []import yamldiff --git a/tools/bot_relay.py b/tools/bot_relay.pyindex 08c6d3b044e..8ac61e4b8b8 100644--- a/tools/bot_relay.py+++ b/tools/bot_relay.py@@ -181,7 +181,7 @@ def write_remote_roster(root: Path | str, rows: Any) -> int:def read_remote_roster(root: Path | str) -> list[dict]:"""The current remote roster (possibly empty). Never raises."""try:- raw = (relay_root(root) / ROSTER_FILE).read_text(encoding="utf-8")+ raw = (relay_root(root) / ROSTER_FILE).read_text(encoding="utf-8-sig")data = json.loads(raw)agents = data.get("agents") if isinstance(data, dict) else Noneif not isinstance(agents, list):@@ -367,7 +367,7 @@ def claim_pending_envelopes(root: Path | str) -> list[dict]:if ttl > 0:expired = Falsetry:- env = json.loads(path.read_text(encoding="utf-8"))+ env = json.loads(path.read_text(encoding="utf-8-sig"))created = float(env.get("created_at") or path.stat().st_mtime)if now - created > ttl:expired = True@@ -398,7 +398,7 @@ def claim_pending_envelopes(root: Path | str) -> list[dict]:claimed = base / CLAIMED_DIR / path.nametry:os.replace(path, claimed) # atomic claim- out.append(json.loads(claimed.read_text(encoding="utf-8")))+ out.append(json.loads(claimed.read_text(encoding="utf-8-sig")))except (OSError, ValueError):continuereturn out@@ -512,7 +512,7 @@ def waiter_command(root: Path | str, envelope: dict) -> str:f"deadline = time.time() + {REPLY_WAIT_SECONDS}\n""while time.time() < deadline:\n"" if os.path.exists(p):\n"- " d = json.load(open(p, encoding='utf-8'))\n"+ " d = json.load(open(p, encoding='utf-8-sig'))\n"" if d.get('error'):\n"# The typed reason code (#93091) rides ahead of the free text so the# sending agent can branch on it (auth vs rate limit vs offline)diff --git a/tools/browser_tool.py b/tools/browser_tool.pyindex 8630eed4032..673c6b1d7ec 100644--- a/tools/browser_tool.py+++ b/tools/browser_tool.py@@ -204,11 +204,8 @@ except ImportError:logger = logging.getLogger(__name__)# Standard PATH entries for environments with minimal PATH (e.g. systemd services).-# Includes Android/Termux and macOS Homebrew locations needed for agent-browser,-# npx, node, and Android's glibc runner (grun).+# Includes macOS Homebrew locations needed for agent-browser, npx, and node._SANE_PATH_DIRS = (- "/data/data/com.termux/files/usr/bin",- "/data/data/com.termux/files/usr/sbin","/opt/homebrew/bin","/opt/homebrew/sbin","/usr/local/sbin",@@ -403,7 +400,7 @@ def _needs_chromium_sandbox_bypass() -> bool:return Trueuserns_restrict = "/proc/sys/kernel/apparmor_restrict_unprivileged_userns"try:- with open(userns_restrict, encoding="utf-8") as f:+ with open(userns_restrict, encoding="utf-8-sig") as f:if f.read().strip() == "1":return Trueexcept OSError:@@ -416,7 +413,7 @@ def _read_command_output_files(stdout_path: str, stderr_path: str) -> tuple[str,stdout = stderr = ""for path, slot in ((stdout_path, "stdout"), (stderr_path, "stderr")):try:- with open(path, "r", encoding="utf-8") as f:+ with open(path, "r", encoding="utf-8-sig") as f:text = f.read().strip()except OSError:continue@@ -938,12 +935,7 @@ def _resolve_cloud_provider_uncached() -> Optional[CloudBrowserProvider]:return _cached_cloud_provider-from hermes_constants import is_termux as _is_termux_environment--def _browser_install_hint() -> str:- if _is_termux_environment():- return "npm install -g agent-browser && agent-browser install"return "npm install -g agent-browser && agent-browser install --with-deps"@@ -965,17 +957,6 @@ def _is_npx_agent_browser_sentinel(browser_cmd: str) -> bool:return browser_cmd.strip() == NPX_AGENT_BROWSER_SENTINEL-def _requires_real_termux_browser_install(browser_cmd: str) -> bool:- return _is_termux_environment() and _is_local_mode() and _is_npx_agent_browser_sentinel(browser_cmd)---def _termux_browser_install_error() -> str:- return (- "Local browser automation on Termux cannot rely on the bare npx fallback. "- f"Install agent-browser explicitly first: {_browser_install_hint()}"- )--def _is_local_mode() -> bool:"""Return True when the browser tool will use a local browser backend."""if _get_cdp_override_raw():@@ -1274,7 +1255,7 @@ def _run_chrome_fallback_command(# uses, not a bare shutil.which("npx") — Hermes-managed-Node-only setups# resolve npx only through the extended fallback path, and a bare lookup# would let a broken system npx shadow a healthy managed one. If npx isn't- # found at all (Termux, bare container), fall back to the bare name and+ # found at all (bare container), fall back to the bare name and# let Popen raise with a readable "FileNotFoundError: 'npx'" rather than# WinError 193.if _is_npx_agent_browser_sentinel(browser_cmd):@@ -1354,7 +1335,7 @@ def _run_chrome_fallback_command(proc.wait()return {"success": False, "error": f"Chrome fallback '{cmd}' timed out"}try:- with open(stdout_path, "r", encoding="utf-8") as f:+ with open(stdout_path, "r", encoding="utf-8-sig") as f:stdout = f.read().strip()if stdout:return json.loads(stdout.split("\n")[-1])@@ -1513,7 +1494,7 @@ def _cdp_on_data_dir(http_cdp: str, data_dir: str) -> bool:if not m:return Falsetry:- 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:port_line = fh.readline().strip()return port_line == m.group(1)except OSError:@@ -2369,7 +2350,7 @@ def _reap_orphaned_browser_sessions():owner_alive: Optional[bool] = None # None = owner_pid missing/unreadableif os.path.isfile(owner_pid_file):try:- owner_pid = int(Path(owner_pid_file).read_text(encoding="utf-8").strip())+ owner_pid = int(Path(owner_pid_file).read_text(encoding="utf-8-sig").strip())# ``os.kill(pid, 0)`` is NOT a no-op on Windows (bpo-14484).# Use the cross-platform existence check.from gateway.status import _pid_exists@@ -2418,7 +2399,7 @@ def _reap_orphaned_browser_sessions():continuetry:- 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())except (ValueError, OSError):shutil.rmtree(socket_dir, ignore_errors=True)continue@@ -2908,9 +2889,8 @@ def _resolve_npx_bin() -> Optional[str]:Checking bare PATH first would let a broken or unrelated system npxshadow a healthy Hermes-managed one with no recovery — every candidate- is therefore validated with ``node_tool_runnable`` (the same check- ``find_hermes_node_executable`` uses to self-heal a managed Node tree)- before being trusted, falling through to the next candidate otherwise.+ is therefore validated with ``node_tool_runnable`` before being trusted,+ falling through to the next candidate otherwise."""extended_path = _merge_browser_path("")if extended_path:@@ -2971,7 +2951,7 @@ def _find_agent_browser(*, validate: bool = True) -> str:return which_result# Build an extended search PATH including Hermes-managed Node, macOS- # versioned Homebrew installs, and fallback system dirs like Termux.+ # versioned Homebrew installs, and fallback system dirs.extended_path = _merge_browser_path("")if extended_path:which_result = shutil.which("agent-browser", path=extended_path)@@ -3255,7 +3235,7 @@ def _discard_timed_out_browser_session(pid_file = os.path.join(task_socket_dir, f"{session_name}.pid")if os.path.isfile(pid_file):try:- 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, task_socket_dir, session_name):return# Tree-kill (#68139 / #85125 4c): the daemon spawns Chromium@@ -3275,7 +3255,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@@ -3437,11 +3417,6 @@ def _run_browser_command(logger.warning("agent-browser CLI not found: %s", e)return {"success": False, "error": str(e)}- if _requires_real_termux_browser_install(browser_cmd):- error = _termux_browser_install_error()- logger.warning("browser command blocked on Termux: %s", error)- return {"success": False, "error": error}-# Local mode with no Chromium on disk: fail fast with an actionable# message instead of hanging for _command_timeout seconds per call.# Skip when engine=lightpanda — LP doesn't need Chromium for navigation.@@ -3632,9 +3607,9 @@ def _run_browser_command(}# Fall through to fallback check belowelse:- 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()returncode = proc.returncode@@ -5627,7 +5602,7 @@ def _cleanup_single_browser_session(task_id: str) -> None:if os.path.isfile(pid_file):try:from tools.process_registry import ProcessRegistry- 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())ProcessRegistry._terminate_host_pid(daemon_pid)logger.debug("Killed daemon pid %s for %s", daemon_pid, session_name)except (ProcessLookupError, ValueError, PermissionError, OSError):@@ -5806,7 +5781,7 @@ def _maybe_autoinstall_chromium() -> bool:if _running_in_docker():return False- from tools.lazy_deps import _allow_lazy_installs+ from pm.ensure import lazy_installs_allowed as _allow_lazy_installsif not _allow_lazy_installs():return False@@ -5855,7 +5830,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 False@@ -5904,13 +5879,6 @@ def check_browser_requirements() -> bool:except FileNotFoundError:return False- # On Termux, the bare npx fallback is too fragile to treat as a satisfied- # local browser dependency. Require a real install (global or local) so the- # browser tool is not advertised as available when it will likely fail on- # first use.- if _requires_real_termux_browser_install(browser_cmd):- return False-# In cloud mode, also require provider credentials. Cloud browsers# don't need a local Chromium binary.provider = _get_cloud_provider()@@ -5971,10 +5939,7 @@ if __name__ == "__main__":print("❌ Missing requirements:")try:browser_cmd = _find_agent_browser()- if _requires_real_termux_browser_install(browser_cmd):- print(" - bare npx fallback found (insufficient on Termux local mode)")- print(f" Install: {_browser_install_hint()}")- elif _cp is None and not _chromium_installed():+ if _cp is None and not _chromium_installed():print(" - Chromium browser binary not found")searched = ", ".join(_chromium_search_roots()) or "(no candidate paths)"print(f" Searched: {searched}")diff --git a/tools/code_execution_tool.py b/tools/code_execution_tool.pyindex 44b5188c5d3..36f4b939d6f 100644--- a/tools/code_execution_tool.py+++ b/tools/code_execution_tool.py@@ -1691,11 +1691,11 @@ def execute_code(# sandbox_tools is already the correct set (intersection with session# tools, or SANDBOX_ALLOWED_TOOLS as fallback — see lines above).tools_src = generate_hermes_tools_module(list(sandbox_tools))- with open(os.path.join(tmpdir, "hermes_tools.py"), "w", encoding="utf-8") as f:+ with open(os.path.join(tmpdir, "hermes_tools.py"), "w", encoding="utf-8") as f: # windows-footgun: ok (write policy is utf-8, never utf-8-sig)f.write(tools_src)# Write the user's script- with open(os.path.join(tmpdir, "script.py"), "w", encoding="utf-8") as f:+ with open(os.path.join(tmpdir, "script.py"), "w", encoding="utf-8") as f: # windows-footgun: ok (write policy is utf-8, never utf-8-sig)f.write(code)# --- Start RPC server ---diff --git a/tools/cronjob_tools.py b/tools/cronjob_tools.pyindex 5fd0619458a..974acc47e57 100644--- a/tools/cronjob_tools.py+++ b/tools/cronjob_tools.py@@ -1150,7 +1150,7 @@ def _latest_job_output_excerpt(job_id: str, max_chars: int = 2000) -> Optional[sfiles = sorted(out_dir.glob("*.md"))if not files:return None- text = files[-1].read_text(encoding="utf-8", errors="replace").strip()+ text = files[-1].read_text(encoding="utf-8-sig", errors="replace").strip()if not text:return Noneif len(text) > max_chars:diff --git a/tools/delegation_live_log.py b/tools/delegation_live_log.pyindex d355740be6f..ca9dd3c9e88 100644--- a/tools/delegation_live_log.py+++ b/tools/delegation_live_log.py@@ -391,7 +391,7 @@ def update_manifest_statuses(delegation_id: Optional[str],returntry:mp = _manifest_path(delegation_id)- manifest = json.loads(mp.read_text(encoding="utf-8"))+ manifest = json.loads(mp.read_text(encoding="utf-8-sig"))by_index = {r.get("task_index"): r for r in results if isinstance(r, dict)}for task in manifest.get("tasks", []):r = by_index.get(task.get("index"))diff --git a/tools/discord_tool.py b/tools/discord_tool.pyindex db979a21d87..ce9126e2974 100644--- a/tools/discord_tool.py+++ b/tools/discord_tool.py@@ -191,7 +191,7 @@ def _load_caps_from_disk(token: str) -> Optional[Dict[str, Any]]:try:path = _capability_disk_cache_path()- with path.open("r", encoding="utf-8") as f:+ with path.open("r", encoding="utf-8-sig") as f:data = json.load(f)entry = data.get(_token_cache_key(token))if not isinstance(entry, dict):@@ -213,7 +213,7 @@ def _save_caps_to_disk(token: str, caps: Dict[str, Any]) -> None:path = _capability_disk_cache_path()path.parent.mkdir(parents=True, exist_ok=True)try:- with path.open("r", encoding="utf-8") as f:+ with path.open("r", encoding="utf-8-sig") as f:data = json.load(f)if not isinstance(data, dict):data = {}diff --git a/tools/mcp_oauth.py b/tools/mcp_oauth.pyindex 134b260a266..3970fc04040 100644--- a/tools/mcp_oauth.py+++ b/tools/mcp_oauth.py@@ -405,7 +405,7 @@ def _read_json(path: Path) -> dict | None:if not path.exists():return Nonetry:- return json.loads(path.read_text(encoding="utf-8"))+ return json.loads(path.read_text(encoding="utf-8-sig"))except (json.JSONDecodeError, OSError) as exc:logger.warning("Failed to read %s: %s", path, exc)return Nonediff --git a/tools/mcp_schema_cache.py b/tools/mcp_schema_cache.pyindex 48bb5ae665c..56ddbf8728d 100644--- a/tools/mcp_schema_cache.py+++ b/tools/mcp_schema_cache.py@@ -48,7 +48,7 @@ def _load_all() -> 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"))return data if isinstance(data, dict) else {}except Exception as exc:logger.debug("Could not read MCP schema cache %s: %s", path, exc)diff --git a/tools/mcp_tool.py b/tools/mcp_tool.pyindex ffcdff532db..3ab60301ea3 100644--- a/tools/mcp_tool.py+++ b/tools/mcp_tool.py@@ -5413,7 +5413,7 @@ def _snapshot_child_pids() -> set:# Linux: read from /proctry:children_path = f"/proc/{my_pid}/task/{my_pid}/children"- with open(children_path, encoding="utf-8") as f:+ with open(children_path, encoding="utf-8-sig") as f:return {int(p) for p in f.read().split() if p.strip()}except (FileNotFoundError, OSError, ValueError):passdiff --git a/tools/neutts_synth.py b/tools/neutts_synth.pyindex 56ecee434da..328390a8084 100644--- a/tools/neutts_synth.py+++ b/tools/neutts_synth.py@@ -75,7 +75,7 @@ def main():print(f"Error: reference text not found: {ref_text_path}", file=sys.stderr)sys.exit(1)- ref_text = ref_text_path.read_text(encoding="utf-8").strip()+ ref_text = ref_text_path.read_text(encoding="utf-8-sig").strip()# Import and run NeuTTStry:diff --git a/tools/process_registry.py b/tools/process_registry.pyindex bca6f91a05d..902b2c11c45 100644--- a/tools/process_registry.py+++ b/tools/process_registry.py@@ -147,12 +147,12 @@ def _worker_memory_max_bytes() -> int:candidates: List[int] = []try:- for line in Path("/proc/self/cgroup").read_text(encoding="utf-8").splitlines():+ for line in Path("/proc/self/cgroup").read_text(encoding="utf-8-sig").splitlines():if line.startswith("0::"):relative = line.partition("::")[2].lstrip("/")raw_limit = (Path("/sys/fs/cgroup") / relative / "memory.max"- ).read_text(encoding="utf-8").strip()+ ).read_text(encoding="utf-8-sig").strip()if raw_limit.isdigit():cgroup_limit = int(raw_limit)if cgroup_limit >= _MIN_WORKER_MEMORY_MAX_BYTES:@@ -2842,7 +2842,7 @@ class ProcessRegistry:return 0try:- entries = json.loads(CHECKPOINT_PATH.read_text(encoding="utf-8"))+ entries = json.loads(CHECKPOINT_PATH.read_text(encoding="utf-8-sig"))except Exception:return 0diff --git a/tools/registry.py b/tools/registry.pyindex bf6d52f2ee6..5389f6a45f4 100644--- a/tools/registry.py+++ b/tools/registry.py@@ -95,7 +95,7 @@ def _module_registers_tools(module_path: Path) -> bool:top-level ``registry.register()`` call to exist."""try:- source = module_path.read_text(encoding="utf-8")+ source = module_path.read_text(encoding="utf-8-sig")except OSError:return Falseif "registry" not in source or "register" not in source:@@ -180,7 +180,7 @@ def _load_discovery_cache() -> Dict[str, list]:if path is None:return {}try:- with open(path, "r", encoding="utf-8") as fh:+ with open(path, "r", encoding="utf-8-sig") as fh:data = json.load(fh)return data if isinstance(data, dict) else {}except (OSError, ValueError):diff --git a/tools/skill_ledger.py b/tools/skill_ledger.pyindex bff84f0b56f..f67f3c991d3 100644--- a/tools/skill_ledger.py+++ b/tools/skill_ledger.py@@ -240,7 +240,7 @@ def list_entries(return []rows: List[Dict[str, Any]] = []try:- with open(path, "r", encoding="utf-8") as fh:+ with open(path, "r", encoding="utf-8-sig") as fh:for line in fh:line = line.strip()if not line:diff --git a/tools/skill_linter.py b/tools/skill_linter.pyindex bce44d21754..2914d62bd80 100644--- a/tools/skill_linter.py+++ b/tools/skill_linter.py@@ -304,7 +304,7 @@ def _check_platforms_gating(if 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]@@ -399,7 +399,7 @@ def lint_content(def lint_skill(skill_md_path: Path) -> List[LintFinding]:"""Lint a SKILL.md file on disk, with all on-disk checks enabled."""skill_md_path = Path(skill_md_path)- content = skill_md_path.read_text(encoding="utf-8", errors="ignore")+ content = skill_md_path.read_text(encoding="utf-8-sig", errors="ignore")return lint_content(content, skill_dir=skill_md_path.parent)diff --git a/tools/skill_manager_tool.py b/tools/skill_manager_tool.pyindex d28d178b1a0..710ca18a602 100644--- a/tools/skill_manager_tool.py+++ b/tools/skill_manager_tool.py@@ -1065,7 +1065,7 @@ def _edit_skill(name: str, content: str) -> Dict[str, Any]:return read_guard# Back up original content for rollback- original_content = skill_md.read_text(encoding="utf-8") if skill_md.exists() else None+ original_content = skill_md.read_text(encoding="utf-8-sig") if skill_md.exists() else Noneatomic_write_text(skill_md, content, preserve_mode=True, create_mode=0o644)# Security scan — roll back on block@@ -1153,7 +1153,7 @@ def _patch_skill(if read_guard:return read_guard- content = target.read_text(encoding="utf-8")+ content = target.read_text(encoding="utf-8-sig")# Use the same fuzzy matching engine as the file patch tool.# This handles whitespace normalization, indentation differences,@@ -1373,7 +1373,7 @@ def _write_file(name: str, file_path: str, file_content: str) -> Dict[str, Any]:return read_guardtarget.parent.mkdir(parents=True, exist_ok=True)# Back up for rollback- original_content = target.read_text(encoding="utf-8") if target.exists() else None+ original_content = target.read_text(encoding="utf-8-sig") if target.exists() else Noneatomic_write_text(target, file_content, preserve_mode=True, create_mode=0o644)# Security scan — roll back on blockdiff --git a/tools/skill_usage.py b/tools/skill_usage.pyindex 5fd6425cc7f..a0bc9729ebf 100644--- a/tools/skill_usage.py+++ b/tools/skill_usage.py@@ -189,7 +189,7 @@ def _read_bundled_manifest_names() -> Set[str]:return set()names: Set[str] = set()try:- for line in manifest.read_text(encoding="utf-8").splitlines():+ for line in manifest.read_text(encoding="utf-8-sig").splitlines():line = line.strip()if not line:continue@@ -218,7 +218,7 @@ def _read_hub_installed_names() -> Set[str]:# /api/skills endpoint. errors="replace" degrades the offending byte to# U+FFFD, keeping the (structurally valid) JSON — and every other# skill — readable. See #68053.- data = json.loads(lock_path.read_text(encoding="utf-8", errors="replace"))+ data = json.loads(lock_path.read_text(encoding="utf-8-sig", errors="replace"))if isinstance(data, dict):installed = data.get("installed") or {}if isinstance(installed, dict):@@ -284,7 +284,7 @@ def read_suppressed_names() -> Set[str]:return set()names: Set[str] = set()try:- for line in path.read_text(encoding="utf-8").splitlines():+ for line in path.read_text(encoding="utf-8-sig").splitlines():line = line.strip()if line and not line.startswith("#"):names.add(line)@@ -406,7 +406,7 @@ def list_archived_skill_names() -> List[str]:def _read_skill_name(skill_md: Path, fallback: str) -> str:"""Parse the `name:` field from a SKILL.md YAML frontmatter."""try:- text = skill_md.read_text(encoding="utf-8", errors="replace")[:4000]+ text = skill_md.read_text(encoding="utf-8-sig", errors="replace")[:4000]except OSError:return fallbackin_frontmatter = False@@ -665,7 +665,7 @@ def load_usage() -> Dict[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 (OSError, json.JSONDecodeError) as e:logger.debug("Failed to read %s: %s", path, e)return {}diff --git a/tools/skillevaluator_scan.py b/tools/skillevaluator_scan.pyindex bcf00b4086b..ffd61e71a98 100644--- a/tools/skillevaluator_scan.py+++ b/tools/skillevaluator_scan.py@@ -205,7 +205,7 @@ def run_tier1_scan(skill_dir: Path, timeout: int = SCAN_TIMEOUT_SECONDS) -> Tierif not reports:return Tier1Report(available=False, error="scanner produced no JSON report")try:- parsed = json.loads(reports[-1].read_text(encoding="utf-8"))+ parsed = json.loads(reports[-1].read_text(encoding="utf-8-sig"))except (json.JSONDecodeError, OSError) as exc:return Tier1Report(available=False, error=f"unparseable report: {exc}")if not isinstance(parsed, dict):diff --git a/tools/skills_ast_audit.py b/tools/skills_ast_audit.pyindex e127556c1d9..1a6e3a9af9a 100644--- a/tools/skills_ast_audit.py+++ b/tools/skills_ast_audit.py@@ -91,7 +91,7 @@ def ast_scan_path(path: Path) -> List[Finding]:if path.suffix.lower() != ".py":return []try:- content = path.read_text(encoding="utf-8", errors="replace")+ content = path.read_text(encoding="utf-8-sig", errors="replace")except OSError:return []return _scan_source(content, path.name)@@ -104,7 +104,7 @@ def ast_scan_path(path: Path) -> List[Finding]:if set(py.parent.parts) & _IGNORED_DIRS:continuetry:- content = py.read_text(encoding="utf-8", errors="replace")+ content = py.read_text(encoding="utf-8-sig", errors="replace")except OSError:continuetry:diff --git a/tools/skills_guard.py b/tools/skills_guard.pyindex c76bc762150..130baf782bf 100644--- a/tools/skills_guard.py+++ b/tools/skills_guard.py@@ -759,7 +759,7 @@ def scan_file(file_path: Path, rel_path: str = "") -> List[Finding]:return []try:- content = file_path.read_text(encoding='utf-8')+ content = file_path.read_text(encoding='utf-8-sig')except (UnicodeDecodeError, OSError):return []@@ -922,7 +922,7 @@ def scan_skill_cached(source_identity = hashlib.sha256(f"{source}\0{source_url}".encode("utf-8")).hexdigest()[:16]cache_file = cache_root / f"{bundle_hash.split(':', 1)[1]}-{source_identity}.json"try:- cached = json.loads(cache_file.read_text(encoding="utf-8"))+ cached = json.loads(cache_file.read_text(encoding="utf-8-sig"))except (OSError, json.JSONDecodeError):cached = Noneif (isinstance(cached, dict)@@ -1243,7 +1243,7 @@ def _load_skill_ignore(skill_dir: Path):ig = skill_dir / nametry:if ig.is_file():- for raw in ig.read_text(encoding="utf-8").splitlines():+ for raw in ig.read_text(encoding="utf-8-sig").splitlines():line = raw.strip()if not line or line.startswith("#"):continuediff --git a/tools/skills_hub.py b/tools/skills_hub.pyindex aebc5a5fe65..c87f19186e1 100644--- a/tools/skills_hub.py+++ b/tools/skills_hub.py@@ -449,7 +449,7 @@ class GitHubAuth:key_file = Path(key_path)if not key_file.exists():return None- private_key = key_file.read_text(encoding="utf-8")+ private_key = key_file.read_text(encoding="utf-8-sig")now = int(time.time())payload = {@@ -1152,7 +1152,7 @@ class GitHubSource(SkillSource):stat = cache_file.stat()if time.time() - stat.st_mtime > INDEX_CACHE_TTL:return None- return json.loads(cache_file.read_text(encoding="utf-8"))+ return json.loads(cache_file.read_text(encoding="utf-8-sig"))except (OSError, json.JSONDecodeError):return None@@ -3625,7 +3625,7 @@ class OptionalSkillSource(SkillSource):parent = skill_md.parenttry:- content = skill_md.read_text(encoding="utf-8")+ content = skill_md.read_text(encoding="utf-8-sig")except (OSError, UnicodeDecodeError):continue@@ -3685,7 +3685,7 @@ def _read_index_cache(key: str) -> Optional[Any]:stat = cache_file.stat()if time.time() - stat.st_mtime > INDEX_CACHE_TTL:return None- return json.loads(cache_file.read_text(encoding="utf-8"))+ return json.loads(cache_file.read_text(encoding="utf-8-sig"))except (OSError, json.JSONDecodeError):return None@@ -3739,7 +3739,7 @@ class HubLockFile:if not self.path.exists():return {"version": 1, "installed": {}}try:- return json.loads(self.path.read_text(encoding="utf-8"))+ return json.loads(self.path.read_text(encoding="utf-8-sig"))except (json.JSONDecodeError, OSError):return {"version": 1, "installed": {}}@@ -3813,7 +3813,7 @@ class TapsManager:if not self.path.exists():return []try:- data = json.loads(self.path.read_text(encoding="utf-8"))+ data = json.loads(self.path.read_text(encoding="utf-8-sig"))return data.get("taps", [])except (json.JSONDecodeError, OSError):return []@@ -4241,7 +4241,7 @@ def _load_hermes_index() -> Optional[dict]:try:age = time.time() - hermes_index_cache_file.stat().st_mtimeif age < HERMES_INDEX_TTL:- return json.loads(hermes_index_cache_file.read_text(encoding="utf-8"))+ return json.loads(hermes_index_cache_file.read_text(encoding="utf-8-sig"))except (OSError, json.JSONDecodeError):pass@@ -4307,7 +4307,7 @@ def _load_stale_index_cache() -> Optional[dict]:hermes_index_cache_file = _hermes_index_cache_file()if hermes_index_cache_file.exists():try:- return json.loads(hermes_index_cache_file.read_text(encoding="utf-8"))+ return json.loads(hermes_index_cache_file.read_text(encoding="utf-8-sig"))except (OSError, json.JSONDecodeError):passreturn Nonediff --git a/tools/skills_sync.py b/tools/skills_sync.pyindex cdf3ab09250..e5012c8cc54 100644--- a/tools/skills_sync.py+++ b/tools/skills_sync.py@@ -168,7 +168,7 @@ def _read_manifest() -> Dict[str, str]:return {}try:result = {}- for line in _manifest_file().read_text(encoding="utf-8").splitlines():+ for line in _manifest_file().read_text(encoding="utf-8-sig").splitlines():line = line.strip()if not line:continue@@ -201,7 +201,7 @@ def _read_suppressed_names() -> set:return set()names = set()try:- for line in path.read_text(encoding="utf-8").splitlines():+ for line in path.read_text(encoding="utf-8-sig").splitlines():line = line.strip()if line and not line.startswith("#"):names.add(line)@@ -235,7 +235,7 @@ def _write_manifest(entries: Dict[str, str]):def _read_skill_name(skill_md: Path, fallback: str) -> str:"""Read the name field from SKILL.md YAML frontmatter, falling back to *fallback*."""try:- content = skill_md.read_text(encoding="utf-8", errors="replace")[:4000]+ content = skill_md.read_text(encoding="utf-8-sig", errors="replace")[:4000]except OSError:return fallbackin_frontmatter = False@@ -503,7 +503,7 @@ def _backfill_optional_provenance(quiet: bool = False) -> List[str]:lock_path = _skills_dir() / ".hub" / "lock.json"try:- data = json.loads(lock_path.read_text(encoding="utf-8")) if lock_path.exists() else {"version": 1, "installed": {}}+ data = json.loads(lock_path.read_text(encoding="utf-8-sig")) if lock_path.exists() else {"version": 1, "installed": {}}except (json.JSONDecodeError, OSError):data = {"version": 1, "installed": {}}installed = data.setdefault("installed", {})@@ -612,7 +612,7 @@ def _read_hub_install_paths() -> Set[str]:if not lock_path.exists():return set()try:- data = json.loads(lock_path.read_text(encoding="utf-8"))+ data = json.loads(lock_path.read_text(encoding="utf-8-sig"))except (json.JSONDecodeError, OSError):return set()paths: Set[str] = set()diff --git a/tools/skills_sync_client.py b/tools/skills_sync_client.pyindex 1689edbe869..e3adaa0daf1 100644--- a/tools/skills_sync_client.py+++ b/tools/skills_sync_client.py@@ -686,7 +686,7 @@ def stable_device_id() -> str:path = _skills_dir() / ".sync_device_id"try:if path.exists():- val = path.read_text(encoding="utf-8").strip()+ val = path.read_text(encoding="utf-8-sig").strip()if val:return valexcept OSError:@@ -966,7 +966,7 @@ def read_sync_state() -> Dict[str, Any]:legacy = _legacy_sync_state_path()if legacy.exists():try:- data = json.loads(legacy.read_text(encoding="utf-8"))+ data = json.loads(legacy.read_text(encoding="utf-8-sig"))if isinstance(data, dict):data.setdefault("head", None)data.setdefault("skills", {})@@ -980,7 +980,7 @@ def read_sync_state() -> Dict[str, Any]:logger.debug("skills_sync_client: legacy sync state migrate failed: %s", e)return {"head": None, "skills": {}}try:- data = json.loads(path.read_text(encoding="utf-8"))+ data = json.loads(path.read_text(encoding="utf-8-sig"))if isinstance(data, dict):data.setdefault("head", None)data.setdefault("skills", {})@@ -1941,7 +1941,7 @@ def _org_baseline_path(org_id: str) -> Path:def _read_org_baseline(org_id: str) -> Dict[str, Any]:try:- return json.loads(_org_baseline_path(org_id).read_text(encoding="utf-8"))+ return json.loads(_org_baseline_path(org_id).read_text(encoding="utf-8-sig"))except Exception:return {}diff --git a/tools/terminal_tool.py b/tools/terminal_tool.pyindex afddd46dfdb..28ad1db6a82 100644--- a/tools/terminal_tool.py+++ b/tools/terminal_tool.py@@ -3780,7 +3780,7 @@ def terminal_tool(if spill_file_path:try:_sp = Path(spill_file_path)- raw_spill = _sp.read_text(encoding="utf-8", errors="replace")+ raw_spill = _sp.read_text(encoding="utf-8-sig", errors="replace")from tools.spill_safety import write_text_exclusive# Rewrite in place via lstat-checked unlink + exclusivediff --git a/tools/web_result_cache.py b/tools/web_result_cache.pyindex 98fe4d763af..8b9d949f4c3 100644--- a/tools/web_result_cache.py+++ b/tools/web_result_cache.py@@ -217,7 +217,7 @@ def _load_index() -> dict:if path is None or not path.exists():return {}try:- data = json.loads(path.read_text(encoding="utf-8"))+ data = json.loads(path.read_text(encoding="utf-8-sig"))return data if isinstance(data, dict) else {}except Exception: # noqa: BLE001 — corrupt index == empty cachereturn {}@@ -375,7 +375,7 @@ def extract_cache_get(# outside cache/web.if cache_root is None or cache_root.resolve() not in file_path.resolve().parents:return None- content = file_path.read_text(encoding="utf-8")+ content = file_path.read_text(encoding="utf-8-sig")except Exception: # noqa: BLE001 — evicted/pruned file == missreturn Nonelogger.info("web_extract cache hit: %s", url)diff --git a/tools/website_policy.py b/tools/website_policy.pyindex e193110fad9..d55447a7141 100644--- a/tools/website_policy.py+++ b/tools/website_policy.py@@ -71,7 +71,7 @@ def _iter_blocklist_file_rules(path: Path) -> List[str]:rather than raising — a bad file path should not disable all web tools."""try:- raw = path.read_text(encoding="utf-8")+ raw = path.read_text(encoding="utf-8-sig")except FileNotFoundError:logger.warning("Shared blocklist file not found (skipping): %s", path)return []@@ -102,7 +102,7 @@ def _load_policy_config(config_path: Optional[Path] = None) -> Dict[str, Any]:return dict(_DEFAULT_WEBSITE_BLOCKLIST)try:- with open(config_path, encoding="utf-8") as f:+ with open(config_path, encoding="utf-8-sig") as f:config = yaml.safe_load(f) or {}except yaml.YAMLError as exc:raise WebsitePolicyError(f"Invalid config YAML at {config_path}: {exc}") from excdiff --git a/tools/write_approval.py b/tools/write_approval.pyindex b017299d806..c48e449fe34 100644--- a/tools/write_approval.py+++ b/tools/write_approval.py@@ -159,7 +159,7 @@ def list_pending(subsystem: str) -> List[Dict[str, Any]]:records: List[Dict[str, Any]] = []for p in d.glob("*.json"):try:- records.append(json.loads(p.read_text(encoding="utf-8")))+ records.append(json.loads(p.read_text(encoding="utf-8-sig")))except Exception:logger.warning("Skipping unreadable pending record: %s", p)records.sort(key=lambda r: r.get("created_at", 0))@@ -172,7 +172,7 @@ def get_pending(subsystem: str, pending_id: str) -> Optional[Dict[str, Any]]:if not path.exists():return Nonetry:- return json.loads(path.read_text(encoding="utf-8"))+ return json.loads(path.read_text(encoding="utf-8-sig"))except Exception:return None@@ -464,7 +464,7 @@ def skill_pending_diff(record: Dict[str, Any]) -> str:p = base / "SKILL.md"try:if p.exists():- current = p.read_text(encoding="utf-8")+ current = p.read_text(encoding="utf-8-sig")except Exception:current = ""