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.
Python agentaianthropicclaude-codecompressioncontext-engineeringcontext-windowcursorfastapilangchainllmmcpopenaiprompt-engineeringproxypythonragtoken-optimizationtokenstypescript
fix(memory): align project routing with wrap headers (#3603)
AxelRayb1b005a9a867
diff --git a/headroom/cli/wrap.py b/headroom/cli/wrap.pyindex ac9d990e4..de0836a3c 100644--- a/headroom/cli/wrap.py+++ b/headroom/cli/wrap.py@@ -3027,6 +3027,7 @@ def _snapshot_codex_config_if_unwrapped(config_file: Path, backup_file: Path) -># Canonical casing for the proxy's per-project savings header (matched# case-insensitively by headroom.proxy.project_context.PROJECT_HEADER)._PROJECT_HEADER_NAME = "X-Headroom-Project"+_PROJECT_CWD_HEADER_NAME = "X-Headroom-Cwd"def _project_name_from_cwd() -> str | None:@@ -3042,29 +3043,52 @@ def _project_name_from_cwd() -> str | None:return urllib.parse.quote(name, safe="-_.() ")+def _project_cwd_from_cwd() -> str | None:+ """Return the canonical launch directory for X-Headroom-Cwd.++ The full path is the collision-resistant project identity used by memory+ and CCR routing. Percent-encoding keeps the value valid in an HTTP header;+ the resolver decodes it before normalising and hashing the path.+ """+ cwd = str(Path.cwd().resolve()).strip()+ if not cwd:+ return None+ return urllib.parse.quote(cwd, safe="/:._-~()")++def _apply_project_header_env(env: dict[str, str]) -> None:- """Inject X-Headroom-Project into ``ANTHROPIC_CUSTOM_HEADERS``.+ """Inject project label and routing identity into custom headers.Claude Code reads ``ANTHROPIC_CUSTOM_HEADERS`` as newline-separated``Name: value`` lines and attaches them to every API request; the- Headroom proxy uses the X-Headroom-Project header for per-project- savings attribution. An existing user-supplied x-headroom-project- header (any casing) always wins — we never duplicate or overwrite it,- and any other user headers are preserved by appending.+ Headroom proxy uses X-Headroom-Project for per-project savings+ attribution and X-Headroom-Cwd for collision-resistant memory/CCR+ routing. Existing user-supplied headers (any casing) always win — we+ never duplicate or overwrite them, and all other user headers are+ preserved by appending."""project = _project_name_from_cwd()if not project:return- header_line = f"{_PROJECT_HEADER_NAME}: {project}"+ cwd = _project_cwd_from_cwd()existing = env.get("ANTHROPIC_CUSTOM_HEADERS")+ existing_names: set[str] = set()if existing:for line in existing.splitlines():name = line.split(":", 1)[0].strip()- if name.lower() == _PROJECT_HEADER_NAME.lower():- return # user override wins- env["ANTHROPIC_CUSTOM_HEADERS"] = f"{existing}\n{header_line}"- else:- env["ANTHROPIC_CUSTOM_HEADERS"] = header_line+ existing_names.add(name.lower())++ generated: list[str] = []+ if _PROJECT_HEADER_NAME.lower() not in existing_names:+ generated.append(f"{_PROJECT_HEADER_NAME}: {project}")+ if cwd and _PROJECT_CWD_HEADER_NAME.lower() not in existing_names:+ generated.append(f"{_PROJECT_CWD_HEADER_NAME}: {cwd}")+ if not generated:+ return++ env["ANTHROPIC_CUSTOM_HEADERS"] = (+ "\n".join([existing, *generated]) if existing else "\n".join(generated)+ )# Codex's own built-in providers plus Headroom's injected one — never treateddiff --git a/headroom/memory/storage_router.py b/headroom/memory/storage_router.pyindex 6521f4674..8761d4753 100644--- a/headroom/memory/storage_router.py+++ b/headroom/memory/storage_router.py@@ -33,6 +33,7 @@ from dataclasses import dataclass, fieldfrom enum import Enumfrom pathlib import Pathfrom typing import Any+from urllib.parse import unquotefrom headroom.memory.backends.local import LocalBackend, LocalBackendConfig@@ -141,9 +142,8 @@ class ProjectResolver:"""Resolve a request to a (key, display_name) project identity.Looks at request signals in priority order and returns ``None`` when- no signal yields a project. The router uses that ``None`` to apply- the configured fallback (today: ``GLOBAL`` per the user's choice in- the bug-fix design discussion).+ no trusted signal yields a project. The router uses that ``None`` to+ apply the configured fallback (fail-closed ``empty`` by default)."""def resolve(self, ctx: RequestContext) -> tuple[str, str] | None:@@ -173,7 +173,7 @@ class ProjectResolver:# Tier 2: client-provided explicit cwd (any client).explicit_cwd = self._first_nonempty_header(ctx.headers, "x-headroom-cwd")if explicit_cwd:- ident = self._identity_from_cwd(explicit_cwd)+ ident = self._identity_from_cwd(explicit_cwd, percent_encoded=True)if ident is not None:return ident@@ -223,8 +223,18 @@ class ProjectResolver:return None@classmethod- def _identity_from_cwd(cls, raw_cwd: str) -> tuple[str, str] | None:- cwd = raw_cwd.strip()+ def _identity_from_cwd(+ cls, raw_cwd: str, *, percent_encoded: bool = False+ ) -> tuple[str, str] | None:+ # ``percent_encoded`` is set only for the ``x-headroom-cwd`` header,+ # which the wrapper percent-encodes so non-ASCII paths stay valid HTTP+ # values; there ``unquote`` restores the canonical path before+ # realpath/hash computation. Every other tier (CLI override, system+ # prompt) carries a literal filesystem path that was never encoded, so+ # decoding it would fold genuinely distinct directories together: a+ # real ``/work/acme%2Fapi`` would collapse onto ``/work/acme/api`` and+ # share its store. Decode at the boundary that encodes, nowhere else.+ cwd = unquote(raw_cwd.strip()) if percent_encoded else raw_cwd.strip()if not cwd:return None# Normalise so symlinked / trailing-slash variants collapse to@@ -333,7 +343,8 @@ class BackendRouter:# command).logger.warning("event=memory_project_unresolved behavior=empty user_id=%s "- "hint='set x-headroom-project-id or x-headroom-cwd header, "+ "hint='set x-headroom-project-id, x-headroom-cwd, or "+ "provide a cwd in the system prompt, ""or set memory.unresolved_project_fallback=global to opt-in ""to legacy cross-project GLOBAL pooling (cross-project leak risk).'",ctx.base_user_id,diff --git a/headroom/proxy/handlers/anthropic.py b/headroom/proxy/handlers/anthropic.pyindex 9ca8199f2..6e5a185d5 100644--- a/headroom/proxy/handlers/anthropic.py+++ b/headroom/proxy/handlers/anthropic.py@@ -365,7 +365,9 @@ class AnthropicHandlerMixin:(``headroom/memory/storage_router.py``) so CCR and memory alwaysagree on which project a request belongs to. Tier order matches:``x-headroom-project-id`` → ``x-headroom-cwd`` → CLI override →- ``cwd:`` line in the system prompt.+ ``cwd:`` line in the system prompt. ``x-headroom-project`` is only a+ human-readable savings label and is intentionally not an identity+ signal.Returns:``(workspace_key, workspace_label)``. If no signal yields a@@ -1299,7 +1301,8 @@ class AnthropicHandlerMixin:# Per-project memory routing (GH #462). Build the context# once here so save / search / inject all resolve against# the same workspace. Tier order: explicit project-id /- # cwd headers → CLI override → system prompt env block.+ # cwd / project headers → CLI override → system prompt env+ # block.from headroom.memory.storage_router import (RequestContext as _MemRequestContext,)@@ -2594,8 +2597,8 @@ class AnthropicHandlerMixin:elif self.ccr_context_tracker and not ccr_workspace_key:logger.info(f"[{request_id}] CCR: workspace unresolved; skipping "- "track_compression (fail-closed — no x-headroom-cwd / "- "x-headroom-project-id header and no cwd: in system prompt)"+ "track_compression (fail-closed — no workspace header "+ "and no cwd: in system prompt)")# CCR Proactive Expansion: Check if current query needs expanded context.diff --git a/headroom/proxy/memory_handler.py b/headroom/proxy/memory_handler.pyindex 10b35bce3..e6c618c40 100644--- a/headroom/proxy/memory_handler.py+++ b/headroom/proxy/memory_handler.py@@ -784,9 +784,10 @@ class MemoryHandler:# PROJECT mode and `unresolved_project_fallback="empty"` (the# default after the 2026-05-26 incident). The sentinel signal is# `mode=PROJECT` + `project_key=None`: project mode was requested- # but no x-headroom-project-id / x-headroom-cwd / system-prompt- # cwd: was available, so we have no idea which project this- # request belongs to. Returning None here skips injection+ # but no x-headroom-project-id / x-headroom-cwd /+ # system-prompt cwd: was available, so we+ # have no idea which project this request belongs to. Returning+ # None here skips injection# entirely — better than pooling into GLOBAL and surfacing# memories from unrelated past sessions (the TAM-550 imperative-# misread bug).diff --git a/tests/test_cli/test_wrap_helpers.py b/tests/test_cli/test_wrap_helpers.pyindex c8b83e716..5b5f961da 100644--- a/tests/test_cli/test_wrap_helpers.py+++ b/tests/test_cli/test_wrap_helpers.py@@ -18,6 +18,7 @@ import osimport signalfrom contextlib import contextmanagerfrom pathlib import Path+from types import SimpleNamespacefrom typing import Anyimport click@@ -27,6 +28,8 @@ from click.testing import CliRunnerfrom headroom import paths as paths_modfrom headroom.cli import wrap as wrap_modfrom headroom.cli.main import main+from headroom.memory.storage_router import ProjectResolver, RequestContext+from headroom.proxy.handlers.anthropic import AnthropicHandlerMixin# ---------------------------------------------------------------------------# _print_wrap_banner — centering math + box drawing.@@ -377,7 +380,79 @@ class TestApplyProjectHeaderEnv:env: dict[str, str] = {}wrap_mod._apply_project_header_env(env)- assert env["ANTHROPIC_CUSTOM_HEADERS"] == "X-Headroom-Project: my-project"+ assert env["ANTHROPIC_CUSTOM_HEADERS"].splitlines() == [+ "X-Headroom-Project: my-project",+ f"X-Headroom-Cwd: {wrap_mod._project_cwd_from_cwd()}",+ ]++ def test_wrap_project_header_resolves_ccr_workspace(+ self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path+ ) -> None:+ project_dir = tmp_path / "my-project"+ project_dir.mkdir()+ monkeypatch.chdir(project_dir)++ env: dict[str, str] = {}+ wrap_mod._apply_project_header_env(env)+ headers = {+ name.strip().lower(): value.strip()+ for name, value in (+ line.split(":", 1) for line in env["ANTHROPIC_CUSTOM_HEADERS"].splitlines()+ )+ }++ key, label = AnthropicHandlerMixin()._resolve_ccr_workspace(+ SimpleNamespace(headers=headers), {}+ )++ assert key.startswith("my-project-")+ assert label == "my-project"++ def test_wrap_same_basename_projects_get_distinct_memory_and_ccr_keys(+ self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path+ ) -> None:+ """The wrapped headers keep same-named projects in separate stores."""+ first = tmp_path / "one" / "api"+ second = tmp_path / "two" / "api"+ first.mkdir(parents=True)+ second.mkdir(parents=True)++ def wrapped_headers(project_dir: Path) -> dict[str, str]:+ monkeypatch.chdir(project_dir)+ env = {"ANTHROPIC_CUSTOM_HEADERS": "X-Headroom-Project: shared"}+ wrap_mod._apply_project_header_env(env)+ return {+ name.strip().lower(): value.strip()+ for name, value in (+ line.split(":", 1) for line in env["ANTHROPIC_CUSTOM_HEADERS"].splitlines()+ )+ }++ headers_a = wrapped_headers(first)+ headers_b = wrapped_headers(second)++ assert headers_a["x-headroom-project"] == headers_b["x-headroom-project"] == "shared"+ assert headers_a["x-headroom-cwd"] != headers_b["x-headroom-cwd"]++ resolver = ProjectResolver()+ memory_a = resolver.resolve(+ RequestContext(headers=headers_a, system_prompt="", base_user_id="")+ )+ memory_b = resolver.resolve(+ RequestContext(headers=headers_b, system_prompt="", base_user_id="")+ )+ assert memory_a is not None and memory_b is not None+ assert memory_a[0] != memory_b[0]++ ccr_a = AnthropicHandlerMixin()._resolve_ccr_workspace(+ SimpleNamespace(headers=headers_a), {}+ )+ ccr_b = AnthropicHandlerMixin()._resolve_ccr_workspace(+ SimpleNamespace(headers=headers_b), {}+ )+ assert ccr_a[0] == memory_a[0]+ assert ccr_b[0] == memory_b[0]+ assert ccr_a[0] != ccr_b[0]def test_appends_to_existing_custom_headers(self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path@@ -390,9 +465,11 @@ class TestApplyProjectHeaderEnv:wrap_mod._apply_project_header_env(env)# User header preserved verbatim, ours appended on a new line.- assert env["ANTHROPIC_CUSTOM_HEADERS"] == (- "X-Custom-Trace: abc123\nX-Headroom-Project: proj"- )+ assert env["ANTHROPIC_CUSTOM_HEADERS"].splitlines() == [+ "X-Custom-Trace: abc123",+ "X-Headroom-Project: proj",+ f"X-Headroom-Cwd: {wrap_mod._project_cwd_from_cwd()}",+ ]@pytest.mark.parametrize("user_value",@@ -416,8 +493,10 @@ class TestApplyProjectHeaderEnv:env = {"ANTHROPIC_CUSTOM_HEADERS": user_value}wrap_mod._apply_project_header_env(env)- # Untouched: no duplicate header, user override wins.- assert env["ANTHROPIC_CUSTOM_HEADERS"] == user_value+ # The user label remains untouched; the missing routing identity is appended.+ assert env["ANTHROPIC_CUSTOM_HEADERS"] == (+ f"{user_value}\nX-Headroom-Cwd: {wrap_mod._project_cwd_from_cwd()}"+ )@pytest.mark.parametrize("user_value",@@ -440,7 +519,10 @@ class TestApplyProjectHeaderEnv:wrap_mod._apply_project_header_env(env)# Only an exact header-name match counts as a user override.- assert env["ANTHROPIC_CUSTOM_HEADERS"] == (f"{user_value}\nX-Headroom-Project: proj")+ assert env["ANTHROPIC_CUSTOM_HEADERS"] == (+ f"{user_value}\nX-Headroom-Project: proj\n"+ f"X-Headroom-Cwd: {wrap_mod._project_cwd_from_cwd()}"+ )def test_empty_cwd_name_sets_nothing(self, monkeypatch: pytest.MonkeyPatch) -> None:"""A degenerate cwd (e.g. filesystem root → empty basename) is a no-op."""@@ -485,6 +567,34 @@ class TestApplyProjectHeaderEnv:assert urllib.parse.unquote(result) == "第二大脑共享"+ def test_project_cwd_is_percent_encoded_and_round_trips(+ self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path+ ) -> None:+ project_dir = tmp_path / "project with space-中文"+ project_dir.mkdir()+ monkeypatch.chdir(project_dir)++ result = wrap_mod._project_cwd_from_cwd()+ assert result is not None+ result.encode("ascii")++ import urllib.parse++ assert urllib.parse.unquote(result) == str(project_dir.resolve())++ def test_existing_cwd_header_wins_case_insensitive(+ self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path+ ) -> None:+ project_dir = tmp_path / "proj"+ project_dir.mkdir()+ monkeypatch.chdir(project_dir)++ user_value = "X-Headroom-Project: their-name\nx-headroom-cwd: /already/trusted"+ env = {"ANTHROPIC_CUSTOM_HEADERS": user_value}+ wrap_mod._apply_project_header_env(env)++ assert env["ANTHROPIC_CUSTOM_HEADERS"] == user_value+def test_non_ascii_cwd_header_is_ascii_safe(self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:@@ -498,6 +608,7 @@ class TestApplyProjectHeaderEnv:header_value = env["ANTHROPIC_CUSTOM_HEADERS"]assert header_value.startswith("X-Headroom-Project: ")+ assert "X-Headroom-Cwd: " in header_valueheader_value.encode("ascii") # raises UnicodeEncodeError if non-ASCIIdiff --git a/tests/test_memory_handler_project_isolation.py b/tests/test_memory_handler_project_isolation.pyindex bcc680184..9fce604d0 100644--- a/tests/test_memory_handler_project_isolation.py+++ b/tests/test_memory_handler_project_isolation.py@@ -259,8 +259,9 @@ def test_user_mode_partitions_by_user_id(tmp_path: Path) -> None:## When `mode=PROJECT` and `unresolved_project_fallback="empty"` (the new# default), an inbound request with no project-resolution signal-# (x-headroom-project-id / x-headroom-cwd / system-prompt cwd:) must-# return None from search_and_format_context — NOT silently pool the+# (x-headroom-project-id / x-headroom-cwd / x-headroom-project /+# system-prompt cwd:) must return None from search_and_format_context —+# NOT silently pool the# request's memory into the GLOBAL bucket. The old GLOBAL fallback was# what surfaced a memory from a prior unrelated TAM-550 session into# a live PR-review thread, where the agent misread it as a new command.diff --git a/tests/test_memory_storage_router.py b/tests/test_memory_storage_router.pyindex 080e6a304..9a001cc70 100644--- a/tests/test_memory_storage_router.py+++ b/tests/test_memory_storage_router.py@@ -77,6 +77,35 @@ def test_resolver_tier2_explicit_cwd_header() -> None:assert len(key.split("-")[-1]) == 16 # sha256 prefix length+def test_resolver_project_label_alone_fails_closed() -> None:+ r = ProjectResolver()+ # X-Headroom-Project is a display/savings label, not a trusted identity.+ assert r.resolve(_ctx(headers={"X-Headroom-Project": "wrapped-project"})) is None+++def test_resolver_project_label_does_not_collapse_distinct_cwds() -> None:+ r = ProjectResolver()+ out_a = r.resolve(+ _ctx(+ headers={+ "X-Headroom-Project": "api",+ "X-Headroom-Cwd": "/work/acme/api",+ }+ )+ )+ out_b = r.resolve(+ _ctx(+ headers={+ "X-Headroom-Project": "api",+ "X-Headroom-Cwd": "/work/other/api",+ }+ )+ )+ assert out_a is not None and out_b is not None+ assert out_a[0] != out_b[0]+ assert out_a[1] == out_b[1] == "api"++def test_resolver_tier3_cli_override() -> None:r = ProjectResolver()out = r.resolve(_ctx(project_root_override="/Users/foo/code/project-c"))@@ -414,6 +443,64 @@ def test_router_lru_eviction_drops_oldest(tmp_path: Path, monkeypatch: pytest.Mo# ---------------------------------------------------------------------------+# Percent-decoding is a header-boundary concern only (#3597 review round 2)+# ---------------------------------------------------------------------------+++def test_resolver_literal_percent_path_distinct_via_cli_override() -> None:+ """A literal ``%2F`` directory must not collapse onto the decoded path.++ Only ``x-headroom-cwd`` is percent-encoded by the wrapper. The CLI+ override carries a literal filesystem path, so decoding it would make+ ``/work/acme%2Fapi`` and ``/work/acme/api`` share one memory store.+ """+ r = ProjectResolver()+ literal = r.resolve(_ctx(project_root_override="/work/acme%2Fapi"))+ decoded = r.resolve(_ctx(project_root_override="/work/acme/api"))++ assert literal is not None and decoded is not None+ assert literal[0] != decoded[0]+++def test_resolver_literal_percent_path_distinct_via_system_prompt() -> None:+ """Same guarantee for the ``cwd:`` system-prompt tier."""+ r = ProjectResolver()+ literal = r.resolve(_ctx(system_prompt="Primary working directory: /work/acme%2Fapi"))+ decoded = r.resolve(_ctx(system_prompt="Primary working directory: /work/acme/api"))++ assert literal is not None and decoded is not None+ assert literal[0] != decoded[0]+++def test_resolver_literal_percent_space_path_distinct_from_space() -> None:+ """``%20`` in a real directory name stays distinct from a real space."""+ r = ProjectResolver()+ literal = r.resolve(_ctx(project_root_override="/work/my%20proj"))+ spaced = r.resolve(_ctx(project_root_override="/work/my proj"))++ assert literal is not None and spaced is not None+ assert literal[0] != spaced[0]+++def test_resolver_encoded_cwd_header_matches_literal_cwd_identity() -> None:+ """The wrapper's encoded header still resolves to the literal cwd identity.++ This is the behaviour the encoding exists for, and it must survive the+ boundary-only decode: ``quote(path)`` in the header and ``path`` from the+ CLI override have to land on the same project key.+ """+ from urllib.parse import quote++ path = "/work/acme/día-api"+ r = ProjectResolver()+ via_header = r.resolve(_ctx(headers={"x-headroom-cwd": quote(path, safe="/:._-~()")}))+ via_override = r.resolve(_ctx(project_root_override=path))++ assert via_header is not None and via_override is not None+ assert via_header[0] == via_override[0]+ assert via_header[1] == via_override[1] == "día-api"++# Claude Code 2.x sends the env block as an isMeta user message (#3595)# ---------------------------------------------------------------------------diff --git a/tests/test_proxy_handler_helpers.py b/tests/test_proxy_handler_helpers.pyindex 910ce58fd..240b614d1 100644--- a/tests/test_proxy_handler_helpers.py+++ b/tests/test_proxy_handler_helpers.py@@ -1105,8 +1105,8 @@ def test_anthropic_assistant_message_helper_requires_assistant_role() -> None:# anthropic handler uses to scope the proactive-expansion cache by# project identity. The resolver shares its tier order with the memory# subsystem's ProjectResolver: x-headroom-project-id → x-headroom-cwd →-# system-prompt `cwd:` line. Returns `("", None)` on no signal — the-# fail-closed signal that callers gate on.+# CLI override → system-prompt `cwd:` line. Returns `("", None)` on+# no signal — the fail-closed signal that callers gate on.# ============================================================================@@ -1159,6 +1159,38 @@ def test_resolve_ccr_workspace_two_cwds_get_distinct_keys() -> None:assert key_a != key_b, "different cwds must yield different workspace keys"+def test_resolve_ccr_workspace_project_label_alone_fails_closed() -> None:+ """The savings label must not become a memory/CCR identity."""+ key, label = AnthropicHandlerMixin()._resolve_ccr_workspace(+ _fake_request({"x-headroom-project": "api"}), {}+ )+ assert key == ""+ assert label is None+++def test_resolve_ccr_workspace_project_label_does_not_collapse_cwds() -> None:+ """A user-supplied label cannot merge two distinct cwd identities."""+ key_a, _ = AnthropicHandlerMixin()._resolve_ccr_workspace(+ _fake_request(+ {+ "x-headroom-project": "api",+ "x-headroom-cwd": "/work/acme/api",+ }+ ),+ {},+ )+ key_b, _ = AnthropicHandlerMixin()._resolve_ccr_workspace(+ _fake_request(+ {+ "x-headroom-project": "api",+ "x-headroom-cwd": "/work/other/api",+ }+ ),+ {},+ )+ assert key_a != key_b++def test_resolve_ccr_workspace_no_signal_returns_empty() -> None:"""No project-id, no cwd header, no system prompt → fail-closed signal."""request = _fake_request({})