Skip to content

Compress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.

fix(memory): treat a cwd with no UTF-8 form as unresolved instead of raising (#4167)

SD760c05e1b0ff
diff --git a/headroom/memory/storage_router.py b/headroom/memory/storage_router.py
index 2baa8ba4d..ef2b36318 100644
--- a/headroom/memory/storage_router.py
+++ b/headroom/memory/storage_router.py
@@ -248,9 +248,21 @@ class ProjectResolver:
except (OSError, ValueError):
normalised = cwd
normalised = normalised.rstrip(os.sep) or os.sep
+ # A path with no UTF-8 form cannot be hashed without a lossy encoding
+ # that could merge distinct directories onto one store. It reaches
+ # here either from the input (an unpaired surrogate, e.g. a
+ # JSON-decoded ``\ud800`` escape) or from ``realpath`` following a
+ # symlink to a non-UTF-8 filename, which POSIX returns as
+ # ``\udcXX`` surrogate escapes. Check after normalising so both are
+ # covered, and treat the cwd as unusable: resolution falls through to
+ # the next tier, or fails closed, instead of raising (#4162).
+ try:
+ encoded = normalised.encode("utf-8")
+ except UnicodeEncodeError:
+ return None
basename = os.path.basename(normalised) or "root"
safe_basename = cls._sanitize_basename(basename) or "project"
- digest = hashlib.sha256(normalised.encode("utf-8")).hexdigest()[:16]
+ digest = hashlib.sha256(encoded).hexdigest()[:16]
key = f"{safe_basename}-{digest}"
return key, basename
diff --git a/tests/test_memory_storage_router.py b/tests/test_memory_storage_router.py
index 7fe3f8569..dd98adea2 100644
--- a/tests/test_memory_storage_router.py
+++ b/tests/test_memory_storage_router.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+import os
from pathlib import Path
import pytest
@@ -186,6 +187,77 @@ def test_resolver_returns_none_when_nothing_resolves() -> None:
assert out is None
+def test_resolver_unencodable_system_prompt_cwd_does_not_raise() -> None:
+ # Issue #4162: a JSON-decoded ``\ud800`` escape leaves an unpaired
+ # surrogate in the cwd. It has no UTF-8 form, so it is not a usable
+ # identity: resolve to "no project" instead of raising.
+ r = ProjectResolver()
+ prompt = "Primary working directory: /work/" + chr(0xD800)
+ assert r.resolve(_ctx(system_prompt=prompt)) is None
+
+
+def test_resolver_unencodable_cli_override_falls_through_to_system_prompt() -> None:
+ # An unusable cwd in one tier must not block a usable one in a later tier.
+ r = ProjectResolver()
+ out = r.resolve(
+ _ctx(
+ project_root_override="/work/" + chr(0xDC80),
+ system_prompt="Primary working directory: /Users/foo/code/headroom\n",
+ )
+ )
+ assert out is not None
+ _, display = out
+ assert display == "headroom"
+
+
[email protected](os.name != "posix", reason="POSIX undecodable byte filenames and symlinks only")
+def test_resolver_symlink_to_undecodable_name_does_not_raise(tmp_path: Path) -> None:
+ # The cwd itself is plain UTF-8, but realpath follows the symlink to a
+ # non-UTF-8 filename and returns it as a ``\udcXX`` surrogate escape.
+ # Creating that fixture is a filesystem capability, not product behavior:
+ # skip if it is unavailable (e.g. macOS APFS rejects non-UTF-8 names).
+ # test_resolver_realpath_returning_surrogate_does_not_raise covers the
+ # same path on every platform.
+ base = os.fsencode(tmp_path)
+ try:
+ os.mkdir(base + b"/\xff-target")
+ os.symlink(base + b"/\xff-target", base + b"/link")
+ except (OSError, UnicodeError) as exc:
+ pytest.skip(f"cannot create a non-UTF-8 symlink fixture here: {exc}")
+ prompt = f"Primary working directory: {tmp_path}/link\n"
+ assert ProjectResolver().resolve(_ctx(system_prompt=prompt)) is None
+
+
+def test_resolver_realpath_returning_surrogate_does_not_raise(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ # Same case as above on any OS: realpath yields what Linux returns for a
+ # symlink to a non-UTF-8 filename.
+ monkeypatch.setattr(os.path, "realpath", lambda _p: "/work/\udcff-target")
+ prompt = "Primary working directory: /work/link\n"
+ assert ProjectResolver().resolve(_ctx(system_prompt=prompt)) is None
+
+
+def test_resolver_valid_non_ascii_cwd_still_resolves() -> None:
+ r = ProjectResolver()
+ out = r.resolve(_ctx(system_prompt="Primary working directory: /Users/foo/code/café\n"))
+ assert out is not None
+ key, display = out
+ assert display == "café"
+ assert key.startswith("caf")
+
+
+def test_router_project_mode_unencodable_cwd_fails_closed(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ router = _make_router(tmp_path, MemoryStorageMode.PROJECT, monkeypatch)
+ _, scope = router.backend_for(
+ _ctx(system_prompt="Primary working directory: /work/" + chr(0xD800))
+ )
+ assert scope.mode is MemoryStorageMode.PROJECT
+ assert scope.project_key is None
+
+
def test_resolver_same_cwd_yields_stable_key_across_calls() -> None:
r = ProjectResolver()
k1, _ = r.resolve(_ctx(headers={"x-headroom-cwd": "/Users/foo/code/x"})) # type: ignore[misc]