fix: finish the missing-encoding sweep — BOM-tolerant reads for user-edited stores
Complements the cherry-picked contributor fixes and closes out the remaining sites of the 'missing explicit encoding' bug class, which is now permanently gated by ruff PLW1514 (enabled repo-wide in pyproject.toml and enforced by the blocking `ruff check .` step in .github/workflows/lint.yml): - tools/memory_tool.py: read MEMORY.md/USER.md via utf-8-sig so a Notepad BOM never glues U+FEFF onto the first entry (issue #10878, PR #10888 by @easyvibecoding — strict-decode contract of _read_raw_checked preserved rather than errors="replace", so undecodable files still refuse read-modify-write instead of being lossily rewritten). Regression tests included. - tools/skills_tool.py: SKILL.md and skill file reads pinned to utf-8-sig + errors="replace" — deterministic across platforms instead of the locale fallback proposed in PR #51701 (superseded: falling back to cp1252/GBK makes the same skill render differently per host); .env reader aligned with the canonical utf-8-sig dialect in hermes_cli/config.py. - agent/shell_hooks.py, hermes_cli/main.py, gateway/slash_commands.py: explicit utf-8 on the remaining fdopen/open text-mode sites flagged by the AlexFucuson9 sweep series (#56033 #56940 #65565 #66782 #66791). Co-authored-by: easyvibecoding <easyvibecoding@users.noreply.github.com> Co-authored-by: AlexFucuson9 <AlexFucuson9@users.noreply.github.com> Co-authored-by: flyingdoubleg <wangzhe00zju@gmail.com> Co-authored-by: LeonSGP43 <cine.dreamer.one@gmail.com>
This commit is contained in:
@@ -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:
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
nolanchic
|
||||
@@ -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()
|
||||
|
||||
+1
-1
@@ -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 = -1
|
||||
token = token_stream.read(65)
|
||||
|
||||
|
||||
@@ -627,3 +627,41 @@ class TestLoadTimeSnapshotSanitization:
|
||||
# Block marker appears exactly once, not nested
|
||||
assert snapshot.count("[BLOCKED:") == 1
|
||||
assert "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 == ""
|
||||
|
||||
@@ -766,7 +766,15 @@ class MemoryStore:
|
||||
if not path.exists():
|
||||
return "", True
|
||||
try:
|
||||
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"), True
|
||||
except (OSError, IOError, UnicodeDecodeError):
|
||||
return "", False
|
||||
|
||||
|
||||
+16
-8
@@ -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.parent
|
||||
|
||||
try:
|
||||
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)
|
||||
continue
|
||||
try:
|
||||
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 below
|
||||
try:
|
||||
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 content
|
||||
try:
|
||||
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 instead
|
||||
return 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")
|
||||
|
||||
Reference in New Issue
Block a user