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): ignore incidental cwd prose (#4166)

AxelRay37654390b60c
diff --git a/headroom/memory/storage_router.py b/headroom/memory/storage_router.py
index 8761d4753..2baa8ba4d 100644
--- a/headroom/memory/storage_router.py
+++ b/headroom/memory/storage_router.py
@@ -43,7 +43,7 @@ logger = logging.getLogger(__name__)
# Known prefixes that mark a working-directory line inside a client's
# ``<env>`` / ``<environment>`` system-prompt block. Ordered so that the
# most specific / most recent client format is tried first. Matched with
-# literal ``str.find`` — no regex.
+# literal line-start checks after trimming — no regex.
_CWD_PREFIXES: tuple[str, ...] = (
"Primary working directory:", # Claude Code (current)
"Working directory:", # Claude Code (older) / Codex
@@ -211,15 +211,15 @@ class ProjectResolver:
if not system_prompt:
return None
for prefix in _CWD_PREFIXES:
- idx = system_prompt.find(prefix)
- if idx < 0:
- continue
- start = idx + len(prefix)
- end = system_prompt.find("\n", start)
- chunk = system_prompt[start:] if end < 0 else system_prompt[start:end]
- chunk = chunk.strip()
- if chunk:
- return chunk
+ for raw_line in system_prompt.split("\n"):
+ line = raw_line.strip()
+ if line.startswith("-"):
+ line = line[1:].lstrip()
+ if not line.startswith(prefix):
+ continue
+ chunk = line[len(prefix) :].strip()
+ if chunk:
+ return chunk
return None
@classmethod
@@ -481,7 +481,7 @@ def _first_user_text_with_cwd(messages: list[Any]) -> str:
continue
content = msg.get("content")
user_text = content if isinstance(content, str) else _text_from_blocks(content)
- if user_text and any(prefix in user_text for prefix in _CWD_PREFIXES):
+ if user_text and ProjectResolver._extract_cwd_from_system_prompt(user_text) is not None:
return user_text
return ""
@@ -520,7 +520,7 @@ def extract_system_prompt(body: Mapping[str, Any]) -> str:
# redirect this request at another project's memory store by pasting
# its own ``cwd:`` line.
trusted = "\n".join(parts)
- if not any(prefix in trusted for prefix in _CWD_PREFIXES):
+ if ProjectResolver._extract_cwd_from_system_prompt(trusted) is None:
cwd_text = _first_user_text_with_cwd(messages)
if cwd_text:
parts.append(cwd_text)
diff --git a/tests/test_memory_storage_router.py b/tests/test_memory_storage_router.py
index 9a001cc70..7fe3f8569 100644
--- a/tests/test_memory_storage_router.py
+++ b/tests/test_memory_storage_router.py
@@ -145,6 +145,41 @@ def test_resolver_tier4_env_block_cwd_format() -> None:
assert display == "cwd-style"
+def test_resolver_tier4_env_block_bulleted_cwd_format() -> None:
+ r = ProjectResolver()
+ prompt = "- cwd: /Users/foo/code/bulleted-cwd\n"
+ out = r.resolve(_ctx(system_prompt=prompt))
+ assert out is not None
+ _, display = out
+ assert display == "bulleted-cwd"
+
+
+def test_extract_cwd_prefers_primary_working_directory_over_earlier_cwd() -> None:
+ prompt = "cwd: /work/old\nPrimary working directory: /work/current\n"
+
+ assert ProjectResolver._extract_cwd_from_system_prompt(prompt) == "/work/current"
+
+
+def test_extract_cwd_preserves_vertical_tab_inside_path() -> None:
+ cwd = "/work/a\vpart"
+
+ assert ProjectResolver._extract_cwd_from_system_prompt(f"cwd: {cwd}\n") == cwd
+
+
+def test_extract_cwd_supports_crlf_line_endings() -> None:
+ prompt = "cwd: /work/current\r\n"
+
+ assert ProjectResolver._extract_cwd_from_system_prompt(prompt) == "/work/current"
+
+
+def test_resolver_ignores_incidental_cwd_prose() -> None:
+ r = ProjectResolver()
+ assert (
+ r.resolve(_ctx(system_prompt="When describing cwd: use the actual environment path."))
+ is None
+ )
+
+
def test_resolver_returns_none_when_nothing_resolves() -> None:
r = ProjectResolver()
out = r.resolve(_ctx(system_prompt="A generic system prompt with no env block."))
@@ -254,6 +289,26 @@ def test_extract_system_prompt_system_message_beats_user_cwd_fallback() -> None:
assert display == "project"
+def test_extract_system_prompt_ignores_incidental_cwd_prose_for_fallback() -> None:
+ body = {
+ "system": "When describing cwd: use the actual environment path.",
+ "messages": [
+ {
+ "role": "user",
+ "content": "<env>\nPrimary working directory: /work/project-alpha\n</env>",
+ }
+ ],
+ }
+
+ prompt = extract_system_prompt(body)
+ resolved = ProjectResolver().resolve(_ctx(system_prompt=prompt))
+
+ assert "Primary working directory: /work/project-alpha" in prompt
+ assert resolved is not None
+ _, display = resolved
+ assert display == "project-alpha"
+
+
def test_extract_system_prompt_cwd_in_non_user_message_returns_empty() -> None:
body = {"messages": [{"role": "assistant", "content": "cwd: /spoof/project"}]}