The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: finish the missing-encoding sweep — BOM-tolerant reads for user-edited stores
Teknium9e6cfcda5aee
diff --git a/agent/shell_hooks.py b/agent/shell_hooks.pyindex f8af6a7cd12..2bdd9af1335 100644--- a/agent/shell_hooks.py+++ b/agent/shell_hooks.py@@ -793,7 +793,7 @@ def save_allowlist(data: Dict[str, Any]) -> None:prefix=f"{p.name}.", suffix=".tmp", dir=str(p.parent),)try:- with os.fdopen(fd, "w") as fh:+ with os.fdopen(fd, "w", encoding="utf-8") as fh:fh.write(json.dumps(data, indent=2, sort_keys=True))atomic_replace(tmp_path, p)except Exception:diff --git a/contributors/emails/[email protected] b/contributors/emails/[email protected]new file mode 100644index 00000000000..45ca053770b--- /dev/null+++ b/contributors/emails/[email protected]@@ -0,0 +1 @@+nolanchicdiff --git a/gateway/slash_commands.py b/gateway/slash_commands.pyindex 7205516a044..fe86f0ad7dd 100644--- a/gateway/slash_commands.py+++ b/gateway/slash_commands.py@@ -5655,7 +5655,7 @@ class GatewaySlashCommandsMixin:with open(output_path, "wb") as f:proc = subprocess.Popen(cmd, stdout=f, stderr=subprocess.STDOUT, env=env)rc = proc.wait(timeout=3600)- with open(exit_code_path, "w") as f:+ with open(exit_code_path, "w", encoding="utf-8") as f:f.write(str(rc))""").strip()diff --git a/hermes_cli/main.py b/hermes_cli/main.pyindex 5d41803230a..19c3ce0a8d5 100644--- a/hermes_cli/main.py+++ b/hermes_cli/main.py@@ -10210,7 +10210,7 @@ def _read_ssh_session_token_file(path: str) -> str:if hasattr(os, "getuid") and (file_stat.st_mode & 0o777) & ~0o600:raise SystemExit("--ssh-session-token-file has unsafe permissions")- with os.fdopen(file_fd, "r") as token_stream:+ with os.fdopen(file_fd, "r", encoding="utf-8") as token_stream:file_fd = -1token = token_stream.read(65)diff --git a/tests/tools/test_memory_tool.py b/tests/tools/test_memory_tool.pyindex 54fc53b6aed..d3fd4d1a0ec 100644--- a/tests/tools/test_memory_tool.py+++ b/tests/tools/test_memory_tool.py@@ -627,3 +627,41 @@ class TestLoadTimeSnapshotSanitization:# Block marker appears exactly once, not nestedassert snapshot.count("[BLOCKED:") == 1assert "Clean fact" in snapshot+++class TestBomToleranceInMemoryFiles:+ """A Notepad-edited MEMORY.md carries a UTF-8 BOM (issue #10878 / PR #10888).++ Reads go through utf-8-sig so the BOM never glues U+FEFF onto the first+ entry. Decode errors stay strict — invalid bytes must still surface as+ unreadable (read_ok=False) rather than silently degrade via replacement+ characters (which a read-modify-write would then persist over the real+ file contents).+ """++ def test_bom_is_stripped_from_first_entry(self, store, tmp_path):+ path = store._path_for("memory")+ path.write_bytes("\ufeffFirst fact.".encode("utf-8"))+ raw, read_ok = MemoryStore._read_raw_checked(path)+ assert read_ok is True+ assert not raw.startswith("\ufeff")+ entries, ok = MemoryStore._read_entries_checked(path)+ assert ok is True+ assert entries == ["First fact."]++ def test_bom_file_add_keeps_existing_entry_intact(self, store):+ path = store._path_for("memory")+ path.write_bytes("\ufeffExisting BOM fact.".encode("utf-8"))+ result = store.add("memory", "A second fact.")+ assert result["success"] is True+ text = path.read_text(encoding="utf-8")+ assert "\ufeff" not in text+ assert "Existing BOM fact." in text+ assert "A second fact." in text++ def test_invalid_utf8_still_reports_unreadable(self, store):+ path = store._path_for("memory")+ path.write_bytes(b"\xff\xfe\x80\x81 not utf-8")+ raw, read_ok = MemoryStore._read_raw_checked(path)+ assert read_ok is False+ assert raw == ""diff --git a/tools/memory_tool.py b/tools/memory_tool.pyindex 899da791474..d77aa9e285c 100644--- a/tools/memory_tool.py+++ b/tools/memory_tool.py@@ -766,7 +766,15 @@ class MemoryStore:if not path.exists():return "", Truetry:- return path.read_text(encoding="utf-8"), True+ # utf-8-sig strips a leading UTF-8 BOM (Notepad-edited memory+ # files on Windows) and is byte-identical to utf-8 otherwise.+ # Plain utf-8 kept U+FEFF glued to the first entry, corrupting+ # matching/dedup for that entry forever (#10878 / PR #10888).+ # Decode errors stay STRICT on purpose: errors="replace" would+ # hand read-modify-write callers a lossy view that a subsequent+ # save persists over the real bytes — the wipe class documented+ # above. Undecodable bytes must surface as read_ok=False.+ return path.read_text(encoding="utf-8-sig"), Trueexcept (OSError, IOError, UnicodeDecodeError):return "", Falsediff --git a/tools/skills_tool.py b/tools/skills_tool.pyindex e939224e347..8a39216f80b 100644--- a/tools/skills_tool.py+++ b/tools/skills_tool.py@@ -211,7 +211,10 @@ def load_env() -> Dict[str, str]:if not env_path.exists():return env_vars- with env_path.open(encoding="utf-8") as f:+ # utf-8-sig: users hand-edit .env in Notepad, which prepends a BOM that+ # would otherwise glue U+FEFF onto the first key name (same dialect as+ # the canonical readers in hermes_cli/config.py).+ with env_path.open(encoding="utf-8-sig", errors="replace") as f:for line in f:line = line.strip()if line and not line.startswith("#") and "=" in line:@@ -726,7 +729,7 @@ def _find_all_skills(*, skip_disabled: bool = False) -> List[Dict[str, Any]]:skill_dir = skill_md.parenttry:- content = skill_md.read_text(encoding="utf-8")[:4000]+ content = skill_md.read_text(encoding="utf-8-sig", errors="replace")[:4000]frontmatter, body = _parse_frontmatter(content)if not skill_matches_platform(frontmatter):@@ -884,7 +887,12 @@ def _serve_plugin_skill()try:- content = skill_md.read_text(encoding="utf-8")+ # utf-8-sig + errors="replace": SKILL.md files are user-authored and+ # sometimes carry a Notepad BOM or stray non-UTF-8 bytes. Pinning+ # UTF-8 with replacement keeps skill_view deterministic across+ # platforms — falling back to the machine locale (cp1252/GBK) would+ # make the same skill render differently per host (see PR #51701).+ content = skill_md.read_text(encoding="utf-8-sig", errors="replace")except Exception as e:return json.dumps({"success": False, "error": f"Failed to read skill '{namespace}:{bare}': {e}"},@@ -941,7 +949,7 @@ def _serve_plugin_skill(ensure_ascii=False,)try:- content = target.read_text(encoding="utf-8")+ content = target.read_text(encoding="utf-8-sig", errors="replace")except UnicodeDecodeError:return json.dumps({@@ -1251,7 +1259,7 @@ def skill_view(_record(found_skill_md.parent, found_skill_md)continuetry:- fm_content = found_skill_md.read_text(encoding="utf-8")+ fm_content = found_skill_md.read_text(encoding="utf-8-sig", errors="replace")fm, _ = _parse_frontmatter(fm_content)except Exception:fm = {}@@ -1309,7 +1317,7 @@ def skill_view(# Read the file once — reused for platform check and main content belowtry:- content = skill_md.read_text(encoding="utf-8")+ content = skill_md.read_text(encoding="utf-8-sig", errors="replace")except Exception as e:return json.dumps({@@ -1454,7 +1462,7 @@ def skill_view(# Read the file contenttry:- content = target_file.read_text(encoding="utf-8")+ content = target_file.read_text(encoding="utf-8-sig", errors="replace")except UnicodeDecodeError:# Binary file - return info about it insteadreturn json.dumps(@@ -1681,7 +1689,7 @@ def skill_view(/ "_org"/ prov_org/ ORG_PROVENANCE_FILE- ).read_text(encoding="utf-8")+ ).read_text(encoding="utf-8-sig", errors="replace"))author = str(prov.get("author_device")