fix(memory): ignore incidental cwd prose (#4166)

## Description

Inline `cwd:` prose in a trusted system prompt was treated as a
working-directory marker. That could suppress a real environment block
and route memory to the prose fragment instead of the request project.

Closes #4163

## Type of Change

- [x] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [ ] Performance improvement
- [ ] Code refactoring (no functional changes)

## Changes Made

- Parse documented cwd markers only at the start of trimmed lines,
including the documented bullet form.
- Use the same line-aware parser when deciding whether trusted system
text already supplies a cwd, so valid user environment fallbacks remain
available.
- Add regressions for incidental prose and the affected
environment-block fallback.

## Testing

- [x] Unit tests pass (`pytest`)
- [ ] Linting passes (`ruff check .`)
- [ ] Type checking passes (`mypy headroom`)
- [ ] New tests added for new functionality
- [x] Manual testing performed

### Test Output

```text
uv run --no-sync pytest tests/test_memory_storage_router.py -q
======================== 39 passed, 1 warning in 0.46s =========================

uv run --no-sync ruff format --check headroom/memory/storage_router.py tests/test_memory_storage_router.py
2 files already formatted

uv run --no-sync ruff check headroom/memory/storage_router.py tests/test_memory_storage_router.py
All checks passed!
```

## Real Behavior Proof

- Environment: Linux x86_64, Python 3.11.16, checkout commit
`8cb856270bc889780febefdd3a4a5584d3008bde`.
- Exact command / steps: Run the issue reproduction with `uv run
--no-sync python -c` using a trusted system string containing `When
describing cwd: use the actual environment path.` and a user `<env>`
block containing `Primary working directory: /work/project-alpha`, then
call `ProjectResolver.resolve`.
- Observed result: At merge-base
`976aa714ef3e19174dc0cb586cee7b20d064e4ef`, the result was `use the
actual environment path.`; after this change, the user environment block
is retained and the result is `project-alpha`.
- Not tested: Full-repository pytest, full-repository ruff, Windows
behavior, and live provider requests.

## Runtime Rollout Safety

- Rollout-managed feature(s): Per-project memory cwd extraction and
fallback selection.
- Minimum rollout channel: Stable; no new flag or rollout control is
needed.
- Stable/default behavior changed: Inline prose no longer selects a
project; valid cwd lines retain existing precedence.
- Kill switch / disable path: Revert this change; no runtime switch is
added.
- Unsafe override required: No.
- Qualification impact: Focused resolver regressions and the issue
request-shape reproduction cover the changed path.
- Rollback path: Revert commit
`8cb856270bc889780febefdd3a4a5584d3008bde`.

## Review Readiness

- [x] I have performed a self-review
- [x] This PR is ready for human review

## Checklist

- [x] My code follows the project's style guidelines
- [x] I have performed a self-review of my code
- [ ] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation
- [ ] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] New and existing unit tests pass locally with my changes
- [x] I did **not** edit `CHANGELOG.md` - it is generated by
release-please from my Conventional Commit PR title (a CI guard enforces
this)

---------

Co-authored-by: JD Davis <mxjerrett@gmail.com>
This commit is contained in:
AxelRay
2026-10-24 08:44:31 -07:00
committed by GitHub
co-authored by JD Davis
parent c4ea31b156
commit 37654390b6
2 changed files with 67 additions and 12 deletions
+12 -12
View File
@@ -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)
+55
View File
@@ -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"}]}