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: per-project memory storage so projects can no longer bleed memories (GH #462)

chopratejas7694f050fe3b
diff --git a/headroom/ccr/context_tracker.py b/headroom/ccr/context_tracker.py
index 596b80ae3..65ffda525 100644
--- a/headroom/ccr/context_tracker.py
+++ b/headroom/ccr/context_tracker.py
@@ -500,11 +500,19 @@ class ContextTracker:
def format_expansions_for_context(
self,
expansions: list[dict[str, Any]],
+ *,
+ workspace_label: str | None = None,
) -> str:
"""Format expansions as additional context for the LLM.
Args:
expansions: Results from execute_expansions.
+ workspace_label: Optional workspace name (e.g. project
+ basename) printed in the block header. Symmetry with the
+ memory injection block — both surfaces declare their
+ provenance so the model can reason about applicability
+ instead of treating the block as prompt injection.
+ See GH #462 (Fix C).
Returns:
Formatted string to add to context.
@@ -512,7 +520,11 @@ class ContextTracker:
if not expansions:
return ""
- parts = ["[Proactive Context Expansion - relevant to your query]"]
+ header = "[Proactive Context Expansion - relevant to your query"
+ if workspace_label:
+ header += f" | workspace: {workspace_label}"
+ header += "]"
+ parts = [header]
for exp in expansions:
if exp["type"] == "full":
diff --git a/headroom/cli/proxy.py b/headroom/cli/proxy.py
index 8220aa048..f0c478adc 100644
--- a/headroom/cli/proxy.py
+++ b/headroom/cli/proxy.py
@@ -2,7 +2,7 @@
import os
import sys
-from typing import Any
+from typing import Any, Literal, cast
import click
@@ -267,13 +267,44 @@ def _selected_context_tool() -> str:
@click.option(
"--memory",
is_flag=True,
- help="Enable persistent user memory. Auto-detects provider and uses appropriate tool format. "
- "Set x-headroom-user-id header for per-user memory (defaults to 'default').",
+ help=(
+ "Enable persistent memory. Auto-detects provider and uses appropriate tool format. "
+ "By default (--memory-storage=project) each workspace gets its own DB so memories "
+ "from unrelated projects can never bleed in (GH #462). Override scoping with "
+ "x-headroom-user-id and/or x-headroom-project-id / x-headroom-cwd request headers."
+ ),
)
@click.option(
"--memory-db-path",
default="",
- help="Path to memory database file (default: {cwd}/.headroom/memory.db)",
+ help=(
+ "Path to the legacy single-file memory DB (used in --memory-storage=global, "
+ "and as the seed for the project-mode storage root). "
+ "Default: {cwd}/.headroom/memory.db"
+ ),
+)
+ "--memory-storage",
+ type=click.Choice(["project", "user", "global"], case_sensitive=False),
+ default="project",
+ show_default=True,
+ help=(
+ "Memory partitioning strategy. project (default): one SQLite DB per resolved "
+ "workspace under <db_path_dir>/memories/projects/<basename>-<hash>/memory.db — "
+ "no cross-project bleed. user: one DB per x-headroom-user-id. global: a single "
+ "shared DB (pre-fix behaviour; --memory-db-path file is reused so existing "
+ "memories remain reachable)."
+ ),
+)
+ "--memory-project-root",
+ default="",
+ help=(
+ "Override the project root used for --memory-storage=project. Useful when the "
+ "client doesn't put a cwd in the system prompt or you want to force a specific "
+ "workspace. Takes effect after the x-headroom-project-id and x-headroom-cwd "
+ "headers."
+ ),
)
@click.option("--no-memory-tools", is_flag=True, help="Disable automatic memory tool injection")
@click.option(
@@ -433,6 +464,8 @@ def proxy(
no_read_lifecycle: bool,
memory: bool,
memory_db_path: str,
+ memory_storage: str,
+ memory_project_root: str,
no_memory_tools: bool,
no_memory_context: bool,
memory_top_k: int,
@@ -610,6 +643,8 @@ def proxy(
# Stateless mode disables memory (requires SQLite on disk)
memory_enabled=False if is_stateless else (memory or (learn and not no_learn)),
memory_db_path=memory_db_path,
+ memory_storage_mode=cast(Literal["project", "user", "global"], memory_storage.lower()),
+ memory_project_root_override=memory_project_root,
memory_inject_tools=not no_memory_tools,
memory_inject_context=not no_memory_context,
memory_top_k=memory_top_k,
@@ -696,10 +731,10 @@ Memory (Multi-Provider):
- Anthropic: Uses native memory tool (memory_20250818) - subscription safe
- OpenAI/Gemini/Others: Uses function calling format
- All providers share the same semantic vector store backend
- - Set x-headroom-user-id header for per-user memory (defaults to 'default')
+ - Storage mode: {config.memory_storage_mode} (per-project DB by default — set x-headroom-project-id / x-headroom-cwd to override)
- Tools: {"ENABLED" if config.memory_inject_tools else "DISABLED"}
- Context injection: {"ENABLED" if config.memory_inject_context else "DISABLED"}
- - Database: {config.memory_db_path}
+ - Database: {config.memory_db_path} (legacy / global-mode DB)
"""
# Stateless mode warning
diff --git a/headroom/memory/factory.py b/headroom/memory/factory.py
index 528c9d384..271279eed 100644
--- a/headroom/memory/factory.py
+++ b/headroom/memory/factory.py
@@ -7,6 +7,7 @@ and proper wiring between components.
from __future__ import annotations
+import threading
from importlib.metadata import entry_points
from pathlib import Path
from typing import TYPE_CHECKING, Any
@@ -28,6 +29,14 @@ _MEMORY_STORE_GROUP = "headroom.memory_store"
_MEMORY_VECTOR_GROUP = "headroom.memory_vector"
_MEMORY_TEXT_GROUP = "headroom.memory_text"
+# Process-wide embedder cache keyed by (backend, model). Embedders are
+# stateless with respect to the memory store, so a single instance can
+# safely serve every per-project ``LocalBackend`` created by the
+# BackendRouter. Without this cache, opening N project DBs would load
+# the sentence-transformers / ONNX model N times.
+_EMBEDDER_CACHE: dict[tuple[str, str], Embedder] = {}
+_EMBEDDER_CACHE_LOCK = threading.Lock()
+
def _load_external_backend(
group: str,
@@ -133,7 +142,13 @@ def _create_store(config: MemoryConfig) -> MemoryStore:
def _create_embedder(config: MemoryConfig) -> Embedder:
- """Create an embedder backend.
+ """Create or return a cached embedder backend.
+
+ The embedder is shared across every ``LocalBackend`` instance that
+ requests the same ``(embedder_backend, embedder_model)`` pair. This
+ matters for the per-project storage router, which can open many
+ backends in the same process and must not pay the
+ sentence-transformers / ONNX model-load cost more than once.
Args:
config: Memory system configuration.
@@ -144,35 +159,64 @@ def _create_embedder(config: MemoryConfig) -> Embedder:
Raises:
ValueError: If the embedder backend is not supported.
"""
- if config.embedder_backend == EmbedderBackend.LOCAL:
- from headroom.memory.adapters.embedders import LocalEmbedder
- return LocalEmbedder(model_name=config.embedder_model)
+ # Validate inputs ahead of the cache. The cache key is
+ # ``(backend, model)`` and intentionally does NOT include the API
+ # key — but that means a cached OpenAI embedder would shadow the
+ # config-validation step for a subsequent caller who forgot to pass
+ # ``openai_api_key``. Run the validation up front instead.
+ if config.embedder_backend == EmbedderBackend.OPENAI and not config.openai_api_key:
+ raise ValueError("openai_api_key is required for OpenAI embedder")
- if config.embedder_backend == EmbedderBackend.ONNX:
- from headroom.memory.adapters.embedders import OnnxLocalEmbedder
+ key = (
+ config.embedder_backend.value
+ if hasattr(config.embedder_backend, "value")
+ else str(config.embedder_backend),
+ config.embedder_model or "",
+ )
- return OnnxLocalEmbedder()
+ with _EMBEDDER_CACHE_LOCK:
+ cached = _EMBEDDER_CACHE.get(key)
+ if cached is not None:
+ return cached
- if config.embedder_backend == EmbedderBackend.OPENAI:
- from headroom.memory.adapters.embedders import OpenAIEmbedder
+ if config.embedder_backend == EmbedderBackend.LOCAL:
+ from headroom.memory.adapters.embedders import LocalEmbedder
- if not config.openai_api_key:
- raise ValueError("openai_api_key is required for OpenAI embedder")
- return OpenAIEmbedder(
- api_key=config.openai_api_key,
- model_name=config.embedder_model,
- )
+ embedder: Embedder = LocalEmbedder(model_name=config.embedder_model)
- if config.embedder_backend == EmbedderBackend.OLLAMA:
- from headroom.memory.adapters.embedders import OllamaEmbedder
+ elif config.embedder_backend == EmbedderBackend.ONNX:
+ from headroom.memory.adapters.embedders import OnnxLocalEmbedder
- return OllamaEmbedder(
- base_url=config.ollama_base_url,
- model_name=config.embedder_model,
- )
+ embedder = OnnxLocalEmbedder()
+
+ elif config.embedder_backend == EmbedderBackend.OPENAI:
+ from headroom.memory.adapters.embedders import OpenAIEmbedder
+
+ embedder = OpenAIEmbedder(
+ api_key=config.openai_api_key,
+ model_name=config.embedder_model,
+ )
+
+ elif config.embedder_backend == EmbedderBackend.OLLAMA:
+ from headroom.memory.adapters.embedders import OllamaEmbedder
+
+ embedder = OllamaEmbedder(
+ base_url=config.ollama_base_url,
+ model_name=config.embedder_model,
+ )
+ else:
+ raise ValueError(f"Unknown embedder backend: {config.embedder_backend}")
+
+ _EMBEDDER_CACHE[key] = embedder
+ return embedder
+
+
+def _reset_embedder_cache_for_tests() -> None:
+ """Clear the process-wide embedder cache. Test-only seam."""
- raise ValueError(f"Unknown embedder backend: {config.embedder_backend}")
+ with _EMBEDDER_CACHE_LOCK:
+ _EMBEDDER_CACHE.clear()
def _create_vector_index(config: MemoryConfig) -> VectorIndex:
diff --git a/headroom/memory/storage_router.py b/headroom/memory/storage_router.py
new file mode 100644
index 000000000..f0293deea
--- /dev/null
+++ b/headroom/memory/storage_router.py
@@ -0,0 +1,405 @@
+"""Per-project memory storage routing.
+
+Fixes the "memories bleed across projects" bug (GH #462) by giving each
+workspace a physically isolated SQLite database file. Cross-project bleed
+becomes structurally impossible: the wrong DB is simply not open during
+a request.
+
+Three storage modes:
+
+* ``PROJECT`` (default): one DB per resolved project. The project is
+ identified from request headers (explicit) or by parsing a Claude
+ Code / Codex ``<env>`` block for the working directory.
+* ``USER``: one DB per ``x-headroom-user-id`` (no project axis).
+* ``GLOBAL``: a single DB shared across everything. Matches the pre-fix
+ behaviour and is preserved so users can still reach memories written
+ before the fix landed.
+
+A ``BackendRouter`` owns an LRU cache of open ``LocalBackend`` instances
+keyed by their on-disk path so that repeated requests for the same
+project hit a warm backend. The cache is bounded to keep file-handle
+and embedder-index pressure predictable.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import os
+import threading
+from collections import OrderedDict
+from collections.abc import Mapping
+from dataclasses import dataclass, field
+from enum import Enum
+from pathlib import Path
+from typing import Any
+
+from headroom.memory.backends.local import LocalBackend, LocalBackendConfig
+
+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.
+_CWD_PREFIXES: tuple[str, ...] = (
+ "Primary working directory:", # Claude Code (current)
+ "Working directory:", # Claude Code (older) / Codex
+ "cwd:", # Generic / debug format
+)
+
+# Whitelist of characters allowed in on-disk basenames. Anything else is
+# collapsed to a single ``-``. Kept as an explicit set instead of a
+# regex character-class so the sanitiser stays trivially auditable.
+_BASENAME_ALLOWED: frozenset[str] = frozenset(
+ "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789._-"
+)
+
+
+class MemoryStorageMode(str, Enum):
+ """Physical layout for the on-disk memory store."""
+
+ PROJECT = "project"
+ USER = "user"
+ GLOBAL = "global"
+
+
+@dataclass
+class RequestContext:
+ """The slice of request state the router needs to resolve a project.
+
+ Built fresh per request at the provider-handler seam. Stays small so
+ handlers do not pay for memory routing on requests that never touch
+ the memory pipeline.
+ """
+
+ headers: Mapping[str, str]
+ system_prompt: str
+ base_user_id: str
+ project_root_override: str | None = None
+
+
+@dataclass(frozen=True)
+class ResolvedScope:
+ """The outcome of project resolution for one request.
+
+ Carried back to the caller so injected memory blocks can advertise
+ their provenance (Fix C in the original design) and so structured
+ logs can be tagged with the same key the DB uses.
+ """
+
+ mode: MemoryStorageMode
+ db_path: Path
+ display_name: str # human-readable label, e.g. project basename
+ project_key: str | None # stable hash, None for USER/GLOBAL
+
+
+@dataclass
+class BackendRouterConfig:
+ """Configuration for ``BackendRouter``.
+
+ Attributes:
+ mode: Storage mode (PROJECT / USER / GLOBAL).
+ root_dir: Filesystem root under which mode-specific subdirectories
+ are created.
+ global_db_path: Path used for ``GLOBAL`` mode. Defaults to the
+ legacy ``<root_dir>/memory.db`` so memories written before
+ the per-project fix landed remain reachable via
+ ``--memory-storage=global``.
+ max_open_backends: LRU cap on simultaneously-open backends.
+ backend_config_template: Template ``LocalBackendConfig`` to clone
+ for each backend; only ``db_path`` / ``graph_db_path`` differ
+ per project.
+ """
+
+ mode: MemoryStorageMode
+ root_dir: Path
+ global_db_path: Path
+ max_open_backends: int = 16
+ backend_config_template: LocalBackendConfig = field(default_factory=LocalBackendConfig)
+
+
+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).
+ """
+
+ def resolve(self, ctx: RequestContext) -> tuple[str, str] | None:
+ """Return ``(project_key, display_name)`` or ``None``.
+
+ ``project_key`` is a stable, filesystem-safe identifier suitable
+ for use as a directory or hash. ``display_name`` is a
+ human-readable label for log lines and the provenance header in
+ the injected memory block.
+ """
+
+ # Tier 1: client-provided explicit project id (any client).
+ explicit = self._first_nonempty_header(ctx.headers, "x-headroom-project-id")
+ if explicit:
+ safe = self._sanitize_basename(explicit)
+ if safe:
+ return safe, explicit
+
+ # 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)
+ if ident is not None:
+ return ident
+
+ # Tier 3: CLI-level override of the project root.
+ if ctx.project_root_override:
+ ident = self._identity_from_cwd(ctx.project_root_override)
+ if ident is not None:
+ return ident
+
+ # Tier 4: parse the system prompt for a ``<env>`` cwd line.
+ sys_cwd = self._extract_cwd_from_system_prompt(ctx.system_prompt)
+ if sys_cwd:
+ ident = self._identity_from_cwd(sys_cwd)
+ if ident is not None:
+ return ident
+
+ return None
+
+ @staticmethod
+ def _first_nonempty_header(headers: Mapping[str, str], name: str) -> str | None:
+ # FastAPI/Starlette headers are case-insensitive but the mapping
+ # passed in may be either kind. Try the canonical lowercase form
+ # first, then fall through to a full case-insensitive sweep.
+ v = headers.get(name) or headers.get(name.lower())
+ if v:
+ return v.strip() or None
+ lower = name.lower()
+ for k, val in headers.items():
+ if k.lower() == lower and val and val.strip():
+ return val.strip()
+ return None
+
+ @classmethod
+ def _extract_cwd_from_system_prompt(cls, system_prompt: str) -> str | None:
+ 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
+ return None
+
+ @classmethod
+ def _identity_from_cwd(cls, raw_cwd: str) -> tuple[str, str] | None:
+ cwd = raw_cwd.strip()
+ if not cwd:
+ return None
+ # Normalise so symlinked / trailing-slash variants collapse to
+ # the same key. ``realpath`` falls back to the input when the
+ # path doesn't exist on this host, which is the right behaviour
+ # for a proxy that may run on a different machine than the
+ # client (in that case we still want a stable key per cwd
+ # string).
+ try:
+ normalised = os.path.realpath(cwd)
+ except (OSError, ValueError):
+ normalised = cwd
+ normalised = normalised.rstrip(os.sep) or os.sep
+ basename = os.path.basename(normalised) or "root"
+ safe_basename = cls._sanitize_basename(basename) or "project"
+ digest = hashlib.sha256(normalised.encode("utf-8")).hexdigest()[:16]
+ key = f"{safe_basename}-{digest}"
+ return key, basename
+
+ @staticmethod
+ def _sanitize_basename(value: str) -> str:
+ out: list[str] = []
+ last_was_dash = False
+ for ch in value.strip():
+ if ch in _BASENAME_ALLOWED:
+ out.append(ch)
+ last_was_dash = False
+ elif not last_was_dash:
+ out.append("-")
+ last_was_dash = True
+ cleaned = "".join(out).strip("-._")
+ # Bound the length so a long override doesn't create unwieldy
+ # directory names.
+ return cleaned[:64]
+
+
+class BackendRouter:
+ """Maps a ``RequestContext`` to a ``LocalBackend`` for save/search.
+
+ Holds an LRU of open backends so repeated traffic for the same
+ project hits a warm instance. Eviction simply drops the Python
+ reference; SQLite connections are closed by the backend's own
+ finalisers. Acquisition takes a lock to keep the cache consistent
+ under the proxy's async-but-multi-task workload — the lock is held
+ only for the lookup, never across IO.
+ """
+
+ def __init__(
+ self,
+ config: BackendRouterConfig,
+ resolver: ProjectResolver | None = None,
+ ) -> None:
+ self._config = config
+ self._resolver = resolver or ProjectResolver()
+ self._backends: OrderedDict[Path, LocalBackend] = OrderedDict()
+ self._lock = threading.Lock()
+
+ def backend_for(self, ctx: RequestContext) -> tuple[LocalBackend, ResolvedScope]:
+ """Return the backend + scope metadata to use for this request."""
+
+ scope = self._resolve_scope(ctx)
+ backend = self._get_or_create_backend(scope.db_path)
+ return backend, scope
+
+ def _resolve_scope(self, ctx: RequestContext) -> ResolvedScope:
+ mode = self._config.mode
+
+ if mode is MemoryStorageMode.GLOBAL:
+ return ResolvedScope(
+ mode=MemoryStorageMode.GLOBAL,
+ db_path=self._config.global_db_path,
+ display_name="global",
+ project_key=None,
+ )
+
+ if mode is MemoryStorageMode.USER:
+ user_safe = ProjectResolver._sanitize_basename(ctx.base_user_id) or "default"
+ db_path = self._config.root_dir / "users" / user_safe / "memory.db"
+ return ResolvedScope(
+ mode=MemoryStorageMode.USER,
+ db_path=db_path,
+ display_name=ctx.base_user_id,
+ project_key=user_safe,
+ )
+
+ # PROJECT mode.
+ ident = self._resolver.resolve(ctx)
+ if ident is None:
+ logger.warning(
+ "event=memory_project_unresolved fallback=global user_id=%s",
+ ctx.base_user_id,
+ )
+ return ResolvedScope(
+ mode=MemoryStorageMode.GLOBAL,
+ db_path=self._config.global_db_path,
+ display_name="global (unresolved)",
+ project_key=None,
+ )
+
+ project_key, display_name = ident
+ db_path = self._config.root_dir / "projects" / project_key / "memory.db"
+ logger.info(
+ "event=memory_project_resolved key=%s display=%s db_path=%s user_id=%s",
+ project_key,
+ display_name,
+ db_path,
+ ctx.base_user_id,
+ )
+ return ResolvedScope(
+ mode=MemoryStorageMode.PROJECT,
+ db_path=db_path,
+ display_name=display_name,
+ project_key=project_key,
+ )
+
+ def _get_or_create_backend(self, db_path: Path) -> LocalBackend:
+ with self._lock:
+ existing = self._backends.get(db_path)
+ if existing is not None:
+ self._backends.move_to_end(db_path)
+ return existing
+
+ db_path.parent.mkdir(parents=True, exist_ok=True)
+
+ template = self._config.backend_config_template
+ cfg = LocalBackendConfig(
+ db_path=str(db_path),
+ graph_db_path=str(db_path.with_name(f"{db_path.stem}_graph{db_path.suffix}")),
+ embedder_backend=template.embedder_backend,
+ embedder_model=template.embedder_model,
+ vector_dimension=template.vector_dimension,
+ openai_api_key=template.openai_api_key,
+ ollama_base_url=template.ollama_base_url,
+ graph_persist=template.graph_persist,
+ graph_cache_size_kb=template.graph_cache_size_kb,
+ cache_enabled=template.cache_enabled,
+ cache_max_size=template.cache_max_size,
+ )
+
+ backend = LocalBackend(cfg)
+ self._backends[db_path] = backend
+
+ while len(self._backends) > self._config.max_open_backends:
+ evicted_path, _evicted = self._backends.popitem(last=False)
+ logger.debug(
+ "event=memory_backend_evicted db_path=%s reason=lru open=%d",
+ evicted_path,
+ len(self._backends),
+ )
+
+ return backend
+
+ def open_backends(self) -> list[Path]:
+ """Snapshot of currently-cached backend paths. For tests / stats."""
+
+ with self._lock:
+ return list(self._backends.keys())
+
+
+def extract_system_prompt(body: Mapping[str, Any]) -> str:
+ """Best-effort extraction of the system prompt across providers.
+
+ Anthropic puts it on the top-level ``system`` field (string or list
+ of content blocks); OpenAI/Gemini-style payloads put it as a message
+ with ``role=system``. Returns an empty string when nothing is found
+ rather than raising — the resolver tolerates an empty prompt and
+ will fall through to the configured fallback.
+ """
+
+ system_field = body.get("system")
+ if isinstance(system_field, str):
+ return system_field
+ if isinstance(system_field, list):
+ parts: list[str] = []
+ for block in system_field:
+ if isinstance(block, dict):
+ text = block.get("text")
+ if isinstance(text, str):
+ parts.append(text)
+ if parts:
+ return "\n".join(parts)
+
+ messages = body.get("messages")
+ if isinstance(messages, list):
+ for msg in messages:
+ if not isinstance(msg, dict):
+ continue
+ if msg.get("role") != "system":
+ continue
+ content = msg.get("content")
+ if isinstance(content, str):
+ return content
+ if isinstance(content, list):
+ parts = []
+ for block in content:
+ if isinstance(block, dict):
+ text = block.get("text")
+ if isinstance(text, str):
+ parts.append(text)
+ if parts:
+ return "\n".join(parts)
+
+ return ""
diff --git a/headroom/proxy/handlers/anthropic.py b/headroom/proxy/handlers/anthropic.py
index ee66dae90..4f66f1fd2 100644
--- a/headroom/proxy/handlers/anthropic.py
+++ b/headroom/proxy/handlers/anthropic.py
@@ -657,11 +657,31 @@ class AnthropicHandlerMixin:
# Reads `request.headers` directly because the local `headers` dict was
# stripped of `x-headroom-*` above for the upstream-bound copy (PR-A5).
memory_user_id: str | None = None
+ memory_request_ctx = None
if self.memory_handler:
memory_user_id = request.headers.get(
"x-headroom-user-id",
os.environ.get("USER", os.environ.get("USERNAME", "default")),
)
+ # 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.
+ from headroom.memory.storage_router import (
+ RequestContext as _MemRequestContext,
+ )
+ from headroom.memory.storage_router import (
+ extract_system_prompt as _extract_sys_prompt,
+ )
+
+ memory_request_ctx = _MemRequestContext(
+ headers=dict(request.headers),
+ system_prompt=_extract_sys_prompt(body),
+ base_user_id=memory_user_id,
+ project_root_override=(
+ getattr(self.memory_handler.config, "project_root_override", "") or None
+ ),
+ )
# Check cache (non-streaming only)
cache_hit = False
@@ -1256,7 +1276,9 @@ class AnthropicHandlerMixin:
async with stage_timer.measure("memory_context"):
memory_context = await asyncio.wait_for(
self.memory_handler.search_and_format_context(
- memory_user_id, optimized_messages
+ memory_user_id,
+ optimized_messages,
+ request_context=memory_request_ctx,
),
timeout=(
self.config.anthropic_pre_upstream_memory_context_timeout_seconds
@@ -1685,6 +1707,7 @@ class AnthropicHandlerMixin:
original_body_bytes=original_body_bytes,
body_mutated=body_mutation_tracker.mutated,
mutation_reasons=body_mutation_tracker.reasons,
+ memory_request_ctx=memory_request_ctx,
)
else:
async with stage_timer.measure("upstream_connect"):
@@ -1975,7 +1998,10 @@ class AnthropicHandlerMixin:
try:
# Execute memory tool calls
tool_results = await self.memory_handler.handle_memory_tool_calls(
- resp_json, memory_user_id, "anthropic"
+ resp_json,
+ memory_user_id,
+ "anthropic",
+ request_context=memory_request_ctx,
)
if tool_results:
diff --git a/headroom/proxy/handlers/gemini.py b/headroom/proxy/handlers/gemini.py
index 28bbed10d..1da75635a 100644
--- a/headroom/proxy/handlers/gemini.py
+++ b/headroom/proxy/handlers/gemini.py
@@ -207,11 +207,45 @@ class GeminiHandlerMixin:
# Memory: Get user ID when memory is enabled. Reads `request.headers`
# directly because `headers` was stripped of `x-headroom-*` (PR-A5).
memory_user_id: str | None = None
+ memory_request_ctx = None
if self.memory_handler:
memory_user_id = request.headers.get(
"x-headroom-user-id",
os.environ.get("USER", os.environ.get("USERNAME", "default")),
)
+ # Per-project memory routing (GH #462). Gemini's
+ # ``systemInstruction`` field carries the system prompt;
+ # ``extract_system_prompt`` doesn't know that shape, so we
+ # pull it directly when present and fall back to the
+ # request body for OpenAI/Anthropic-shaped payloads.
+ from headroom.memory.storage_router import (
+ RequestContext as _MemRequestContext,
+ )
+ from headroom.memory.storage_router import (
+ extract_system_prompt as _extract_sys_prompt,
+ )
+
+ gemini_sys = body.get("systemInstruction") or body.get("system_instruction") or {}
+ sys_text = ""
+ if isinstance(gemini_sys, dict):
+ parts = gemini_sys.get("parts") or []
+ if isinstance(parts, list):
+ for p in parts:
+ if isinstance(p, dict):
+ t = p.get("text")
+ if isinstance(t, str):
+ sys_text += ("\n" if sys_text else "") + t
+ if not sys_text:
+ sys_text = _extract_sys_prompt(body)
+
+ memory_request_ctx = _MemRequestContext(
+ headers=dict(request.headers),
+ system_prompt=sys_text,
+ base_user_id=memory_user_id,
+ project_root_override=(
+ getattr(self.memory_handler.config, "project_root_override", "") or None
+ ),
+ )
# Rate limiting (use Gemini API key)
if self.rate_limiter:
@@ -333,7 +367,9 @@ class GeminiHandlerMixin:
try:
if self.memory_handler.config.inject_context:
memory_context = await self.memory_handler.search_and_format_context(
- memory_user_id, optimized_messages
+ memory_user_id,
+ optimized_messages,
+ request_context=memory_request_ctx,
)
if memory_context:
new_messages, bytes_appended = (
diff --git a/headroom/proxy/handlers/openai.py b/headroom/proxy/handlers/openai.py
index faad122d3..9b99d3f03 100644
--- a/headroom/proxy/handlers/openai.py
+++ b/headroom/proxy/handlers/openai.py
@@ -1252,11 +1252,29 @@ class OpenAIHandlerMixin:
# directly because `headers` was stripped of `x-headroom-*` for the
# upstream-bound copy (PR-A5).
memory_user_id: str | None = None
+ memory_request_ctx = None
if self.memory_handler:
memory_user_id = request.headers.get(
"x-headroom-user-id",
os.environ.get("USER", os.environ.get("USERNAME", "default")),
)
+ # Per-project memory routing (GH #462). Built once per request
+ # so every save/search/inject resolves to the same workspace.
+ from headroom.memory.storage_router import (
+ RequestContext as _MemRequestContext,
+ )
+ from headroom.memory.storage_router import (
+ extract_system_prompt as _extract_sys_prompt,
+ )
+
+ memory_request_ctx = _MemRequestContext(
+ headers=dict(request.headers),
+ system_prompt=_extract_sys_prompt(body),
+ base_user_id=memory_user_id,
+ project_root_override=(
+ getattr(self.memory_handler.config, "project_root_override", "") or None
+ ),
+ )
# Rate limiting
if self.rate_limiter:
@@ -1584,7 +1602,9 @@ class OpenAIHandlerMixin:
try:
if self.memory_handler.config.inject_context:
memory_context = await self.memory_handler.search_and_format_context(
- memory_user_id, optimized_messages
+ memory_user_id,
+ optimized_messages,
+ request_context=memory_request_ctx,
)
if memory_context:
from headroom.proxy.helpers import (
@@ -2054,7 +2074,10 @@ class OpenAIHandlerMixin:
):
try:
tool_results = await self.memory_handler.handle_memory_tool_calls(
- resp_json, memory_user_id, "openai"
+ resp_json,
+ memory_user_id,
+ "openai",
+ request_context=memory_request_ctx,
)
if tool_results:
# Build continuation: original messages + assistant tool_calls + tool results
@@ -2373,11 +2396,27 @@ class OpenAIHandlerMixin:
# Memory: Get user ID when memory is enabled. Reads `request.headers`
# directly because `headers` was stripped of `x-headroom-*` (PR-A5).
memory_user_id: str | None = None
+ memory_request_ctx = None
if self.memory_handler:
memory_user_id = request.headers.get(
"x-headroom-user-id",
os.environ.get("USER", os.environ.get("USERNAME", "default")),
)
+ from headroom.memory.storage_router import (
+ RequestContext as _MemRequestContext,
+ )
+ from headroom.memory.storage_router import (
+ extract_system_prompt as _extract_sys_prompt,
+ )
+
+ memory_request_ctx = _MemRequestContext(
+ headers=dict(request.headers),
+ system_prompt=_extract_sys_prompt(body),
+ base_user_id=memory_user_id,
+ project_root_override=(
+ getattr(self.memory_handler.config, "project_root_override", "") or None
+ ),
+ )
# Rate limiting
if self.rate_limiter:
@@ -2419,7 +2458,9 @@ class OpenAIHandlerMixin:
try:
memory_context = await asyncio.wait_for(
self.memory_handler.search_and_format_context(
- memory_user_id, optimized_messages
+ memory_user_id,
+ optimized_messages,
+ request_context=memory_request_ctx,
),
timeout=RESPONSES_CONTEXT_SEARCH_TIMEOUT_SECONDS,
)
@@ -2654,6 +2695,7 @@ class OpenAIHandlerMixin:
tags,
optimization_latency,
memory_user_id=memory_user_id,
+ memory_request_ctx=memory_request_ctx,
)
else:
headers = await apply_copilot_api_auth(headers, url=url)
@@ -3388,6 +3430,7 @@ class OpenAIHandlerMixin:
# --- Memory: inject context, tools, and instructions ---
memory_user_id: str | None = None
+ memory_request_ctx = None
if self.memory_handler and body and not _ws_bypass:
memory_user_id = ws_headers.get(
"x-headroom-user-id",
@@ -3397,6 +3440,23 @@ class OpenAIHandlerMixin:
# Unwrap response.create envelope to access the response body
ws_response_body = body.get("response", body)
+ # Per-project memory routing (GH #462). For WS,
+ # ``ws_response_body`` carries ``instructions`` —
+ # that's the system-prompt-equivalent we feed to the
+ # resolver.
+ from headroom.memory.storage_router import (
+ RequestContext as _MemRequestContext,
+ )
+
+ memory_request_ctx = _MemRequestContext(
+ headers=dict(ws_headers),
+ system_prompt=str(ws_response_body.get("instructions") or ""),
+ base_user_id=memory_user_id,
+ project_root_override=(
+ getattr(self.memory_handler.config, "project_root_override", "") or None
+ ),
+ )
+
# Debug: log what Codex sends so we can see the full tool list
existing_tool_names = [
t.get("name") or t.get("function", {}).get("name", "?")
@@ -3428,7 +3488,9 @@ class OpenAIHandlerMixin:
async with stage_timer.measure("memory_context"):
memory_context = await asyncio.wait_for(
self.memory_handler.search_and_format_context(
- memory_user_id, ws_msgs
+ memory_user_id,
+ ws_msgs,
+ request_context=memory_request_ctx,
),
timeout=RESPONSES_CONTEXT_SEARCH_TIMEOUT_SECONDS,
)
diff --git a/headroom/proxy/handlers/streaming.py b/headroom/proxy/handlers/streaming.py
index 0f2146b4b..2c60548a0 100644
--- a/headroom/proxy/handlers/streaming.py
+++ b/headroom/proxy/handlers/streaming.py
@@ -783,6 +783,7 @@ class StreamingMixin:
original_body_bytes: bytes | None = None,
body_mutated: bool = True,
mutation_reasons: list[str] | None = None,
+ memory_request_ctx: Any | None = None,
) -> Response | StreamingResponse:
"""Stream response with metrics tracking and memory tool handling.
@@ -1162,7 +1163,10 @@ class StreamingMixin:
# in SSE streaming mode. The WS and non-streaming paths
# handle continuation properly.
tool_results = await self.memory_handler.handle_memory_tool_calls(
- parsed_response, memory_user_id, provider
+ parsed_response,
+ memory_user_id,
+ provider,
+ request_context=memory_request_ctx,
)
if tool_results:
logger.info(
diff --git a/headroom/proxy/memory_handler.py b/headroom/proxy/memory_handler.py
index f6b82020e..641de9caa 100644
--- a/headroom/proxy/memory_handler.py
+++ b/headroom/proxy/memory_handler.py
@@ -35,6 +35,13 @@ from pathlib import Path
from typing import TYPE_CHECKING, Any, Literal
from headroom.memory import qdrant_env
+from headroom.memory.storage_router import (
+ BackendRouter,
+ BackendRouterConfig,
+ MemoryStorageMode,
+ RequestContext,
+ ResolvedScope,
+)
if TYPE_CHECKING:
from headroom.memory.backends.local import LocalBackend
@@ -97,6 +104,14 @@ class MemoryConfig:
inject_context: bool = True
top_k: int = 10
min_similarity: float = 0.3
+ # Per-project storage routing (GH #462). When ``storage_mode`` is
+ # PROJECT (default), each resolved workspace lands in its own SQLite
+ # file under ``storage_root``; cross-project bleed becomes
+ # structurally impossible. USER and GLOBAL preserve previous shapes
+ # for users who explicitly opt back in.
+ storage_mode: MemoryStorageMode = MemoryStorageMode.PROJECT
+ storage_root: str = "" # Defaults to dirname(db_path)/memories
+ project_root_override: str = "" # CLI ``--memory-project-root``
# PR-B6: Memory injection mode. AUTO_TAIL (default) auto-appends retrieved
# memory to the latest user message tail. TOOL disables auto-injection;
# the model must call ``memory_search`` to retrieve. Configurable per
@@ -143,6 +158,12 @@ class MemoryHandler:
self.config = config
self.agent_type = agent_type
self._backend: LocalBackend | Any = None
+ # Per-project routing for the local backend. Built in
+ # ``_init_backend_locked`` so a single, shared resolver / LRU is
+ # kept on the handler. Qdrant deployments use composite user-id
+ # partitioning instead (see ``_compose_effective_user_id``) — the
+ # router stays None in that case.
+ self._router: BackendRouter | None = None
self._initialized = False
# Async singleflight guard for backend init. Ensures concurrent first
# callers land on one init (double-checked pattern inside
@@ -303,6 +324,37 @@ class MemoryHandler:
f"(embedder: {embedder_backend})"
)
+ # Per-project routing (GH #462). The router shares the same
+ # backend_config_template so every project DB inherits the
+ # embedder / cache settings selected above. ``self._backend``
+ # remains the GLOBAL-mode fallback / legacy compatibility
+ # backend; callers that pass a ``RequestContext`` route
+ # through ``self._router`` instead.
+ storage_root = (
+ Path(self.config.storage_root)
+ if self.config.storage_root
+ else (Path(self.config.db_path).resolve().parent / "memories")
+ )
+ global_db_path = Path(self.config.db_path).resolve()
+ router_cfg = BackendRouterConfig(
+ mode=self.config.storage_mode,
+ root_dir=storage_root,
+ global_db_path=global_db_path,
+ backend_config_template=backend_config,
+ )
+ self._router = BackendRouter(router_cfg)
+ # Seed the router's LRU with the already-initialized
+ # legacy backend so GLOBAL-mode requests reuse it instead
+ # of opening a second handle to the same file.
+ with self._router._lock: # type: ignore[attr-defined]
+ self._router._backends[global_db_path] = self._backend # type: ignore[attr-defined]
+ logger.info(
+ "event=memory_router_initialized mode=%s root=%s global_db=%s",
+ self.config.storage_mode.value,
+ storage_root,
+ global_db_path,
+ )
+
elif self.config.backend == "qdrant-neo4j":
try:
from headroom.memory.backends.direct_mem0 import (
@@ -508,16 +560,82 @@ class MemoryHandler:
)
return tools, True
+ def _resolve_for_request(
+ self, base_user_id: str, request_context: RequestContext | None
+ ) -> tuple[Any, ResolvedScope | None, str]:
+ """Pick the backend + effective user_id for a single request.
+
+ Returns ``(backend, scope, effective_user_id)``. ``scope`` is
+ ``None`` when the caller did not provide a ``RequestContext``
+ (e.g. legacy tests, qdrant deployments that pre-date the router)
+ — in that case the legacy ``self._backend`` and the bare
+ ``base_user_id`` are returned, matching pre-fix behaviour.
+
+ For the local backend with a ``RequestContext`` the router picks
+ the project DB; the user_id passed into the backend stays the
+ raw user_id (physical isolation is the partition).
+
+ For the qdrant-neo4j backend a composite ``user_id::project_key``
+ is used so projects partition logically inside the single
+ Qdrant collection. The router does not own qdrant connections.
+ """
+
+ if request_context is None or self._router is None:
+ return self._backend, None, base_user_id
+
+ if self.config.backend == "local":
+ backend, scope = self._router.backend_for(request_context)
+ return backend, scope, base_user_id
+
+ # Non-local backends: derive scope but keep one shared backend
+ # and compose the user_id so the partition lives in the user_id
+ # column instead of in a separate file.
+ scope = self._router._resolve_scope(request_context)
+ composed = (
+ base_user_id
+ if scope.project_key is None or scope.mode is MemoryStorageMode.GLOBAL
+ else f"{base_user_id}::{scope.project_key}"
+ )
+ return self._backend, scope, composed
+
+ @staticmethod
+ def _format_memory_block_header(scope: ResolvedScope | None) -> str:
+ """Workspace / scope provenance header for the injected memory block.
+
+ Fix C from GH #462: the previous header (``## Relevant Memories for
+ This User``) had no scope information, so a model receiving cross-
+ project leakage could not reason about whether the memories
+ applied — Claude flagged the block as prompt injection. Including
+ the workspace name and scope mode makes the provenance visible.
+ """
+
+ if scope is None:
+ return "## Relevant Memories for This User"
+ if scope.mode is MemoryStorageMode.PROJECT:
+ return f"## Relevant Memories (workspace: {scope.display_name}, scope: project)"
+ if scope.mode is MemoryStorageMode.USER:
+ return f"## Relevant Memories (user: {scope.display_name}, scope: user)"
+ return "## Relevant Memories (scope: global)"
+
async def search_and_format_context(
self,
user_id: str,
messages: list[dict[str, Any]],
+ request_context: RequestContext | None = None,
) -> str | None:
"""Search memories and format as context injection.
Args:
- user_id: User identifier for memory scoping.
+ user_id: User identifier for memory scoping (the base user
+ id, derived from ``x-headroom-user-id`` upstream).
messages: Conversation messages (used to extract query).
+ request_context: Optional request envelope (headers, system
+ prompt, base user id). When provided, memory retrieval
+ is scoped to the resolved workspace / project so memories
+ from unrelated projects can never bleed in (GH #462). When
+ omitted, behaves as before this fix — single-bucket search
+ against the legacy backend. Production handlers always
+ pass it; tests / mocks can keep the simpler call shape.
Returns:
Formatted context string, or None if no relevant memories.
@@ -546,6 +664,8 @@ class MemoryHandler:
if not self._backend:
return None
+ backend, scope, effective_user_id = self._resolve_for_request(user_id, request_context)
+
# Extract query from last user message
query = self._extract_user_query(messages)
if not query:
@@ -553,16 +673,20 @@ class MemoryHandler:
return None
try:
- # Search memories
- results = await self._backend.search_memories(
+ # Search memories on the per-request resolved backend.
+ results = await backend.search_memories(
query=query,
- user_id=user_id,
+ user_id=effective_user_id,
top_k=self.config.top_k,
include_related=True,
)
if not results:
- logger.debug(f"Memory: No memories found for user {user_id}")
+ logger.debug(
+ "Memory: No memories found for user=%s scope=%s",
+ effective_user_id,
+ scope.display_name if scope else "<legacy>",
+ )
return None
# Filter by minimum similarity
@@ -584,23 +708,27 @@ class MemoryHandler:
memory_lines.append(f" (Related: {entities_str})")
except Exception as e:
- logger.warning(f"Memory: Search failed for user {user_id}: {e}")
+ logger.warning(f"Memory: Search failed for user {effective_user_id}: {e}")
return None
if not memory_lines:
return None
- context = f"""## Relevant Memories for This User
+ header = self._format_memory_block_header(scope)
+ context = f"""{header}
-The following information was previously saved about this user:
+The following information was previously saved in this scope:
{chr(10).join(memory_lines)}
Use this context to provide personalized and contextually relevant responses."""
logger.info(
- f"Memory: Injecting {len(memory_lines)} memories "
- f"({len(context)} chars) for user {user_id}"
+ "event=memory_inject user=%s scope=%s count=%d chars=%d",
+ effective_user_id,
+ scope.display_name if scope else "<legacy>",
+ len(memory_lines),
+ len(context),
)
return context
@@ -742,6 +870,7 @@ Use this context to provide personalized and contextually relevant responses."""
response: dict[str, Any],
user_id: str,
provider: str = "anthropic",
+ request_context: RequestContext | None = None,
) -> list[dict[str, Any]]:
"""Execute memory tool calls and return results.
@@ -749,6 +878,10 @@ Use this context to provide personalized and contextually relevant responses."""
response: The API response containing tool calls.
user_id: User identifier for memory operations.
provider: Provider format ("anthropic" or "openai").
+ request_context: Optional request envelope. When provided,
+ save/search/update/delete operations route to the per-
+ workspace DB so projects cannot read or overwrite each
+ other's memories (GH #462).
Returns:
List of tool results in provider format.
@@ -781,7 +914,11 @@ Use this context to provide personalized and contextually relevant responses."""
if not self._backend:
continue
result_content = await self._execute_memory_tool(
- tool_name, input_data, user_id, provider
+ tool_name,
+ input_data,
+ user_id,
+ provider,
+ request_context=request_context,
)
else:
continue
@@ -814,17 +951,19 @@ Use this context to provide personalized and contextually relevant responses."""
input_data: dict[str, Any],
user_id: str,
provider: str = "anthropic",
+ *,
+ request_context: RequestContext | None = None,
) -> str:
"""Execute a memory tool and return result string."""
try:
if tool_name == "memory_save":
- return await self._execute_save(input_data, user_id, provider)
+ return await self._execute_save(input_data, user_id, provider, request_context)
elif tool_name == "memory_search":
- return await self._execute_search(input_data, user_id)
+ return await self._execute_search(input_data, user_id, request_context)
elif tool_name == "memory_update":
- return await self._execute_update(input_data, user_id, provider)
+ return await self._execute_update(input_data, user_id, provider, request_context)
elif tool_name == "memory_delete":
- return await self._execute_delete(input_data, user_id)
+ return await self._execute_delete(input_data, user_id, request_context)
else:
return json.dumps({"error": f"Unknown tool: {tool_name}"})
@@ -833,7 +972,11 @@ Use this context to provide personalized and contextually relevant responses."""
return json.dumps({"status": "error", "error": str(e)})
async def _execute_save(
- self, input_data: dict[str, Any], user_id: str, provider: str = "anthropic"
+ self,
+ input_data: dict[str, Any],
+ user_id: str,
+ provider: str = "anthropic",
+ request_context: RequestContext | None = None,
) -> str:
"""Execute memory_save tool with provenance, dedup hints, and async background dedup."""
content = input_data.get("content", "")
@@ -848,18 +991,26 @@ Use this context to provide personalized and contextually relevant responses."""
relationships = input_data.get("relationships")
extracted_relationships = input_data.get("extracted_relationships")
- # Agent provenance metadata
- provenance_metadata = {
+ backend, scope, effective_user_id = self._resolve_for_request(user_id, request_context)
+
+ # Agent provenance metadata. Workspace lineage is recorded on
+ # the memory itself so cross-project leaks (if any ever
+ # reappear) are forensically attributable.
+ provenance_metadata: dict[str, Any] = {
"source_agent": self.agent_type,
"source_provider": provider,
"created_via": "tool_call",
"created_at_utc": datetime.now(timezone.utc).isoformat(),
}
+ if scope is not None:
+ provenance_metadata["workspace_display"] = scope.display_name
+ provenance_metadata["workspace_key"] = scope.project_key or ""
+ provenance_metadata["storage_mode"] = scope.mode.value
- # Save to backend
- memory = await self._backend.save_memory(
+ # Save to the resolved backend.
+ memory = await backend.save_memory(
content=content,
- user_id=user_id,
+ user_id=effective_user_id,
importance=importance,
facts=facts,
entities=entities,
@@ -872,9 +1023,9 @@ Use this context to provide personalized and contextually relevant responses."""
# Search for similar existing memories (for hints + async dedup)
similar_memories = []
try:
- results = await self._backend.search_memories(
+ results = await backend.search_memories(
query=content,
- user_id=user_id,
+ user_id=effective_user_id,
top_k=5,
)
# Exclude the memory we just saved
@@ -908,12 +1059,17 @@ Use this context to provide personalized and contextually relevant responses."""
# Async background dedup: auto-supersede obvious duplicates
if similar_memories:
- asyncio.create_task(self._background_dedup(memory.id, similar_memories, user_id))
+ asyncio.create_task(
+ self._background_dedup(memory.id, similar_memories, effective_user_id, backend)
+ )
logger.info(
- f"Memory: Saved '{content[:60]}' for user {user_id} "
- f"(agent={self.agent_type}, provider={provider}, "
- f"similar={len(similar_memories)})"
+ "event=memory_save user=%s scope=%s agent=%s provider=%s similar=%d",
+ effective_user_id,
+ scope.display_name if scope else "<legacy>",
+ self.agent_type,
+ provider,
+ len(similar_memories),
)
return json.dumps(result)
@@ -923,13 +1079,22 @@ Use this context to provide personalized and contextually relevant responses."""
new_memory_id: str,
similar_results: list[Any],
user_id: str,
+ backend: Any | None = None,
) -> None:
"""Auto-supersede obvious duplicates in background (fire-and-forget).
If an existing memory has >0.92 cosine similarity to the new one,
mark the older one as superseded. This runs asynchronously and
never blocks the tool response.
+
+ ``backend`` defaults to the legacy ``self._backend`` so existing
+ non-routed callers keep working; routed callers pass the same
+ per-project backend they wrote to so dedup never crosses
+ workspaces.
"""
+ target = backend if backend is not None else self._backend
+ if target is None:
+ return
try:
for result in similar_results:
if result.score < self.DEDUP_AUTO_THRESHOLD:
@@ -944,8 +1109,8 @@ Use this context to provide personalized and contextually relevant responses."""
# Mark old memory as superseded by deleting it
# (update_memory creates a new version — for dedup we just remove the duplicate)
- if hasattr(self._backend, "delete_memory"):
- await self._backend.delete_memory(old.id)
+ if hasattr(target, "delete_memory"):
+ await target.delete_memory(old.id)
logger.info(
f"Memory dedup: removed '{old.content[:50]}' "
f"(superseded by {new_memory_id}, {result.score:.2f} cosine, "
@@ -954,7 +1119,12 @@ Use this context to provide personalized and contextually relevant responses."""
except Exception as e:
logger.warning(f"Memory background dedup failed: {e}")
- async def _execute_search(self, input_data: dict[str, Any], user_id: str) -> str:
+ async def _execute_search(
+ self,
+ input_data: dict[str, Any],
+ user_id: str,
+ request_context: RequestContext | None = None,
+ ) -> str:
"""Execute memory_search tool."""
query = input_data.get("query", "")
if not query:
@@ -964,9 +1134,11 @@ Use this context to provide personalized and contextually relevant responses."""
include_related = input_data.get("include_related", True)
entities_filter = input_data.get("entities")
- results = await self._backend.search_memories(
+ backend, _scope, effective_user_id = self._resolve_for_request(user_id, request_context)
+
+ results = await backend.search_memories(
query=query,
- user_id=user_id,
+ user_id=effective_user_id,
top_k=top_k,
include_related=include_related,
entities=entities_filter,
@@ -993,7 +1165,11 @@ Use this context to provide personalized and contextually relevant responses."""
)
async def _execute_update(
- self, input_data: dict[str, Any], user_id: str, provider: str = "anthropic"
+ self,
+ input_data: dict[str, Any],
+ user_id: str,
+ provider: str = "anthropic",
+ request_context: RequestContext | None = None,
) -> str:
"""Execute memory_update tool with edit history tracking."""
memory_id = input_data.get("memory_id", "")
@@ -1014,13 +1190,15 @@ Use this context to provide personalized and contextually relevant responses."""
"reason": reason,
}
+ backend, _scope, effective_user_id = self._resolve_for_request(user_id, request_context)
+
# Check if backend has update_memory method
- if hasattr(self._backend, "update_memory"):
+ if hasattr(backend, "update_memory"):
# Try to get old memory for history
old_content = ""
try:
- old_results = await self._backend.search_memories(
- query=memory_id, user_id=user_id, top_k=1
+ old_results = await backend.search_memories(
+ query=memory_id, user_id=effective_user_id, top_k=1
)
if old_results:
old_content = old_results[0].memory.content[:200]
@@ -1028,11 +1206,11 @@ Use this context to provide personalized and contextually relevant responses."""
except Exception:
pass
- memory = await self._backend.update_memory(
+ memory = await backend.update_memory(
memory_id=memory_id,
new_content=new_content,
reason=f"Updated by {self.agent_type} via {provider}: {reason or 'no reason'}",
- user_id=user_id,
+ user_id=effective_user_id,
)
logger.info(
f"Memory: Updated {memory_id} by {self.agent_type} "
@@ -1041,10 +1219,10 @@ Use this context to provide personalized and contextually relevant responses."""
return json.dumps({"status": "updated", "memory_id": memory.id})
else:
# Fallback: delete old, save new
- await self._backend.delete_memory(memory_id)
- memory = await self._backend.save_memory(
+ await backend.delete_memory(memory_id)
+ memory = await backend.save_memory(
content=new_content,
- user_id=user_id,
+ user_id=effective_user_id,
importance=0.5,
metadata={
"source_agent": self.agent_type,
@@ -1061,13 +1239,19 @@ Use this context to provide personalized and contextually relevant responses."""
}
)
- async def _execute_delete(self, input_data: dict[str, Any], user_id: str) -> str:
+ async def _execute_delete(
+ self,
+ input_data: dict[str, Any],
+ user_id: str,
+ request_context: RequestContext | None = None,
+ ) -> str:
"""Execute memory_delete tool."""
memory_id = input_data.get("memory_id", "")
if not memory_id:
return json.dumps({"status": "error", "error": "memory_id is required"})
- deleted = await self._backend.delete_memory(memory_id)
+ backend, _scope, _effective = self._resolve_for_request(user_id, request_context)
+ deleted = await backend.delete_memory(memory_id)
return json.dumps(
{
diff --git a/headroom/proxy/models.py b/headroom/proxy/models.py
index 7eb1c1d39..604fabb09 100644
--- a/headroom/proxy/models.py
+++ b/headroom/proxy/models.py
@@ -205,6 +205,13 @@ class ProxyConfig:
memory_enabled: bool = False
memory_backend: Literal["local", "qdrant-neo4j"] = "local"
memory_db_path: str = "" # Empty = auto: {cwd}/.headroom/memory.db
+ # Per-project memory routing (GH #462). ``project`` (the new default)
+ # gives each resolved workspace its own SQLite DB so cross-project
+ # bleed becomes structurally impossible. ``user`` partitions by
+ # x-headroom-user-id only. ``global`` keeps the pre-fix single-DB
+ # behaviour (existing memories remain reachable here).
+ memory_storage_mode: Literal["project", "user", "global"] = "project"
+ memory_project_root_override: str = ""
memory_inject_tools: bool = True
traffic_learning_enabled: bool = False
traffic_learning_agent_type: str = "unknown" # Which agent is being wrapped
diff --git a/headroom/proxy/server.py b/headroom/proxy/server.py
index 5319feba6..f2e963754 100644
--- a/headroom/proxy/server.py
+++ b/headroom/proxy/server.py
@@ -592,6 +592,16 @@ class HeadroomProxy(
f"expected one of {[m.value for m in MemoryMode]}"
) from exc
+ from headroom.memory.storage_router import MemoryStorageMode
+
+ try:
+ _storage_mode = MemoryStorageMode(config.memory_storage_mode)
+ except ValueError as exc:
+ raise ValueError(
+ f"Invalid memory_storage_mode={config.memory_storage_mode!r}; "
+ f"expected one of {[m.value for m in MemoryStorageMode]}"
+ ) from exc
+
memory_config = MemoryConfig(
enabled=True,
backend=config.memory_backend,
@@ -602,6 +612,8 @@ class HeadroomProxy(
top_k=config.memory_top_k,
min_similarity=config.memory_min_similarity,
mode=_memory_mode,
+ storage_mode=_storage_mode,
+ project_root_override=config.memory_project_root_override,
qdrant_url=config.memory_qdrant_url,
qdrant_host=config.memory_qdrant_host,
qdrant_port=config.memory_qdrant_port,
@@ -620,6 +632,29 @@ class HeadroomProxy(
agent_type=config.traffic_learning_agent_type,
)
+ # Migration UX (GH #462). When the user is on the new
+ # project-scoped default but a legacy single-file DB exists
+ # with prior memories, surface that clearly so it doesn't
+ # look like an upgrade ate their data.
+ if _storage_mode is MemoryStorageMode.PROJECT:
+ _legacy_path = Path(_mem_db_path)
+ if _legacy_path.exists() and _legacy_path.stat().st_size > 0:
+ logger.info(
+ "event=memory_storage_legacy_detected path=%s mode=project "
+ "hint=pass_--memory-storage=global_to_reach_pre-fix_memories",
+ _legacy_path,
+ )
+
+ # The Memory Bridge binds to the single legacy backend at
+ # init time; it doesn't (yet) follow per-project routing.
+ # Warn so users running bridge + project mode aren't
+ # surprised that only the legacy DB syncs with markdown.
+ if config.memory_bridge_enabled and _storage_mode is MemoryStorageMode.PROJECT:
+ logger.warning(
+ "event=memory_bridge_global_only mode=project "
+ "hint=bridge_syncs_only_the_legacy_DB_today_per-project_bridge_follow-up_planned"
+ )
+
# Usage Reporter (license validation + phone-home for managed/enterprise)
self.usage_reporter: UsageReporter | None = None
if config.license_key:
diff --git a/tests/test_anthropic_pre_upstream_backpressure.py b/tests/test_anthropic_pre_upstream_backpressure.py
index 97aea531c..bd198cce7 100644
--- a/tests/test_anthropic_pre_upstream_backpressure.py
+++ b/tests/test_anthropic_pre_upstream_backpressure.py
@@ -550,7 +550,7 @@ def test_memory_context_timeout_fails_open_and_releases_semaphore():
self.initialized = False
self.backend = None
- async def search_and_format_context(self, _user_id, _messages):
+ async def search_and_format_context(self, _user_id, _messages, **_kwargs):
await asyncio.sleep(5.0)
return "should-timeout"
@@ -563,7 +563,7 @@ def test_memory_context_timeout_fails_open_and_releases_semaphore():
def has_memory_tool_calls(self, _response, _provider) -> bool:
return False
- async def handle_memory_tool_calls(self, _response, _user_id, _provider):
+ async def handle_memory_tool_calls(self, _response, _user_id, _provider, **_kwargs):
return []
async def _run() -> None:
diff --git a/tests/test_memory_handler_native_ops.py b/tests/test_memory_handler_native_ops.py
index c7045716f..44f687969 100644
--- a/tests/test_memory_handler_native_ops.py
+++ b/tests/test_memory_handler_native_ops.py
@@ -971,7 +971,9 @@ async def test_search_and_format_context_and_handle_memory_tool_calls(
async def fake_ensure_initialized() -> None:
return None
- async def fake_execute_memory_tool(tool_name, input_data, user_id, provider="anthropic"): # noqa: ANN001
+ async def fake_execute_memory_tool(
+ tool_name, input_data, user_id, provider="anthropic", *, request_context=None
+ ): # noqa: ANN001
return f"ran:{tool_name}:{user_id}:{provider}:{input_data}"
async def fake_execute_native(input_data, user_id): # noqa: ANN001
@@ -1374,7 +1376,9 @@ async def test_extract_tool_calls_and_handle_tool_calls_parse_edges(
async def fake_ensure_initialized() -> None:
return None
- async def fake_execute(tool_name, input_data, user_id, provider="anthropic"): # noqa: ANN001
+ async def fake_execute(
+ tool_name, input_data, user_id, provider="anthropic", *, request_context=None
+ ): # noqa: ANN001
return f"ok:{tool_name}:{input_data}"
monkeypatch.setattr(handler, "_ensure_initialized", fake_ensure_initialized)
diff --git a/tests/test_memory_handler_project_isolation.py b/tests/test_memory_handler_project_isolation.py
new file mode 100644
index 000000000..f86533a0b
--- /dev/null
+++ b/tests/test_memory_handler_project_isolation.py
@@ -0,0 +1,254 @@
+"""End-to-end isolation test for the per-project memory router (GH #462).
+
+Verifies that two sessions running in different working directories
+never see each other's memories — neither at search-time, nor in the
+injected ``## Relevant Memories`` block.
+
+The test stubs out the real backend so we don't have to load embedders
+or open SQLite files. The interesting invariant is that the router
+hands a *different* backend instance to each cwd, and that the handler
+calls ``search_memories`` on the backend it received (not on the legacy
+``self._backend``).
+"""
+
+from __future__ import annotations
+
+import asyncio
+from pathlib import Path
+from types import SimpleNamespace
+from typing import Any
+
+import pytest
+
+from headroom.memory import storage_router as sr_mod
+from headroom.proxy.memory_handler import (
+ MemoryConfig,
+ MemoryHandler,
+ MemoryMode,
+)
+
+
+class _FakeBackend:
+ """Minimal stand-in for ``LocalBackend`` used by the router cache.
+
+ Each instance tracks its own write log so we can prove that
+ Project A's saves and Project B's saves landed on different
+ backends.
+ """
+
+ instances: list[_FakeBackend] = []
+
+ def __init__(self, cfg: Any) -> None:
+ self.cfg = cfg
+ self.saved_contents: list[str] = []
+ self.search_results: list[Any] = []
+ # Tag the backend with its db_path so tests can assert on it.
+ self.db_path = getattr(cfg, "db_path", "<unknown>")
+ _FakeBackend.instances.append(self)
+
+ async def _ensure_initialized(self) -> None:
+ return None
+
+ async def search_memories(self, **kwargs: Any) -> list[Any]:
+ return list(self.search_results)
+
+ async def save_memory(self, **kwargs: Any) -> Any:
+ content = kwargs["content"]
+ self.saved_contents.append(content)
+ return SimpleNamespace(
+ id=f"mem-{self.db_path}-{len(self.saved_contents)}",
+ content=content,
+ metadata={},
+ )
+
+ async def delete_memory(self, memory_id: str) -> bool:
+ return True
+
+
[email protected](autouse=True)
+def patch_backend(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Swap LocalBackend out at every import site the handler/router uses."""
+
+ _FakeBackend.instances.clear()
+ monkeypatch.setattr(sr_mod, "LocalBackend", _FakeBackend)
+
+ # The handler's _init_backend_locked imports LocalBackend locally;
+ # patch the same target there too. The route below is the canonical
+ # import path used by the handler.
+ import headroom.memory.backends.local as _local_mod
+
+ monkeypatch.setattr(_local_mod, "LocalBackend", _FakeBackend)
+
+
+def handler(tmp_path: Path) -> MemoryHandler:
+ cfg = MemoryConfig(
+ enabled=True,
+ backend="local",
+ db_path=str(tmp_path / "memory.db"),
+ inject_context=True,
+ mode=MemoryMode.AUTO_TAIL,
+ )
+ h = MemoryHandler(cfg, agent_type="test")
+ return h
+
+
+def _ctx_for_cwd(cwd: str, user_id: str = "alice") -> Any:
+ return sr_mod.RequestContext(
+ headers={"x-headroom-cwd": cwd},
+ system_prompt="",
+ base_user_id=user_id,
+ )
+
+
+def test_two_cwds_route_to_two_backends(handler: MemoryHandler) -> None:
+ """Saves under different cwds must land on different backends."""
+
+ async def run() -> None:
+ await handler._ensure_initialized()
+ ctx_a = _ctx_for_cwd("/Users/me/code/project-a")
+ ctx_b = _ctx_for_cwd("/Users/me/code/project-b")
+
+ await handler._execute_save(
+ {"content": "Note about Project A's redis config"},
+ "alice",
+ "anthropic",
+ request_context=ctx_a,
+ )
+ await handler._execute_save(
+ {"content": "Note about Project B's auth setup"},
+ "alice",
+ "anthropic",
+ request_context=ctx_b,
+ )
+
+ # The router must have created at least 3 backends:
+ # 1 legacy (during init), 1 for project-a, 1 for project-b.
+ backends_with_content = [b for b in _FakeBackend.instances if b.saved_contents]
+ assert len(backends_with_content) == 2
+
+ contents_per_backend = {tuple(b.saved_contents) for b in backends_with_content}
+ assert ("Note about Project A's redis config",) in contents_per_backend
+ assert ("Note about Project B's auth setup",) in contents_per_backend
+
+ asyncio.run(run())
+
+
+def test_search_returns_only_current_workspace_memories(handler: MemoryHandler) -> None:
+ """Project A's search must not see Project B's memories."""
+
+ async def run() -> None:
+ await handler._ensure_initialized()
+ ctx_a = _ctx_for_cwd("/Users/me/code/project-a")
+ ctx_b = _ctx_for_cwd("/Users/me/code/project-b")
+
+ # Save under A and B.
+ await handler._execute_save(
+ {"content": "A memory"}, "alice", "anthropic", request_context=ctx_a
+ )
+ await handler._execute_save(
+ {"content": "B memory"}, "alice", "anthropic", request_context=ctx_b
+ )
+
+ # Seed each fake backend's search return so we can detect bleed.
+ backend_a, _, _ = handler._resolve_for_request("alice", ctx_a)
+ backend_b, _, _ = handler._resolve_for_request("alice", ctx_b)
+
+ backend_a.search_results = [ # type: ignore[attr-defined]
+ SimpleNamespace(
+ memory=SimpleNamespace(id="a1", content="A memory", metadata={}),
+ score=0.9,
+ related_entities=[],
+ )
+ ]
+ backend_b.search_results = [ # type: ignore[attr-defined]
+ SimpleNamespace(
+ memory=SimpleNamespace(id="b1", content="B memory", metadata={}),
+ score=0.9,
+ related_entities=[],
+ )
+ ]
+
+ msgs_a = [{"role": "user", "content": "what's the redis config?"}]
+ msgs_b = [{"role": "user", "content": "what's the auth setup?"}]
+
+ ctx_block_a = await handler.search_and_format_context(
+ "alice", msgs_a, request_context=ctx_a
+ )
+ ctx_block_b = await handler.search_and_format_context(
+ "alice", msgs_b, request_context=ctx_b
+ )
+
+ assert ctx_block_a is not None
+ assert ctx_block_b is not None
+
+ # The block from Project A must contain A's memory and *not* B's.
+ assert "A memory" in ctx_block_a
+ assert "B memory" not in ctx_block_a
+ # Symmetric assertion for B.
+ assert "B memory" in ctx_block_b
+ assert "A memory" not in ctx_block_b
+
+ # Provenance header (Fix C) must include the workspace name.
+ assert "workspace: project-a" in ctx_block_a
+ assert "workspace: project-b" in ctx_block_b
+
+ asyncio.run(run())
+
+
+def test_legacy_callers_without_ctx_hit_legacy_backend(handler: MemoryHandler) -> None:
+ """Callers that don't pass a RequestContext keep the pre-fix shape.
+
+ Verifies the backward-compatibility seam: legacy tests / mocks that
+ call ``search_and_format_context(user, messages)`` get the same
+ behaviour they had before — the legacy single-DB backend, no scope
+ header. This is the path tests + qdrant deployments take.
+ """
+
+ async def run() -> None:
+ await handler._ensure_initialized()
+ legacy_backend = handler._backend
+ legacy_backend.search_results = [ # type: ignore[attr-defined]
+ SimpleNamespace(
+ memory=SimpleNamespace(id="g1", content="Global memory", metadata={}),
+ score=0.9,
+ related_entities=[],
+ )
+ ]
+
+ block = await handler.search_and_format_context(
+ "alice", [{"role": "user", "content": "anything"}]
+ )
+
+ assert block is not None
+ assert "Global memory" in block
+ # No provenance suffix in legacy header.
+ assert block.startswith("## Relevant Memories for This User")
+
+ asyncio.run(run())
+
+
+def test_user_mode_partitions_by_user_id(tmp_path: Path) -> None:
+ """``--memory-storage=user`` opens one DB per base_user_id."""
+
+ cfg = MemoryConfig(
+ enabled=True,
+ backend="local",
+ db_path=str(tmp_path / "memory.db"),
+ storage_mode=sr_mod.MemoryStorageMode.USER,
+ )
+ h = MemoryHandler(cfg, agent_type="test")
+
+ async def run() -> None:
+ await h._ensure_initialized()
+ ctx_alice = sr_mod.RequestContext(headers={}, system_prompt="", base_user_id="alice")
+ ctx_bob = sr_mod.RequestContext(headers={}, system_prompt="", base_user_id="bob")
+
+ backend_alice, scope_a, _ = h._resolve_for_request("alice", ctx_alice)
+ backend_bob, scope_b, _ = h._resolve_for_request("bob", ctx_bob)
+
+ assert scope_a.mode is sr_mod.MemoryStorageMode.USER
+ assert scope_b.mode is sr_mod.MemoryStorageMode.USER
+ assert backend_alice is not backend_bob
+
+ asyncio.run(run())
diff --git a/tests/test_memory_storage_router.py b/tests/test_memory_storage_router.py
new file mode 100644
index 000000000..b12446a85
--- /dev/null
+++ b/tests/test_memory_storage_router.py
@@ -0,0 +1,263 @@
+"""Unit tests for the per-project memory storage router (GH #462)."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+from headroom.memory.backends.local import LocalBackendConfig
+from headroom.memory.storage_router import (
+ BackendRouter,
+ BackendRouterConfig,
+ MemoryStorageMode,
+ ProjectResolver,
+ RequestContext,
+ extract_system_prompt,
+)
+
+# ---------------------------------------------------------------------------
+# Resolver tier-order tests
+# ---------------------------------------------------------------------------
+
+
+def _ctx(
+ *,
+ headers: dict[str, str] | None = None,
+ system_prompt: str = "",
+ base_user_id: str = "alice",
+ project_root_override: str | None = None,
+) -> RequestContext:
+ return RequestContext(
+ headers=headers or {},
+ system_prompt=system_prompt,
+ base_user_id=base_user_id,
+ project_root_override=project_root_override,
+ )
+
+
+def test_resolver_tier1_explicit_project_id_wins() -> None:
+ r = ProjectResolver()
+ # An explicit project id beats everything else.
+ out = r.resolve(
+ _ctx(
+ headers={"x-headroom-project-id": "billing-svc"},
+ system_prompt="Primary working directory: /Users/foo/code/other\n",
+ project_root_override="/also/ignored",
+ )
+ )
+ assert out is not None
+ key, display = out
+ assert key == "billing-svc"
+ assert display == "billing-svc"
+
+
+def test_resolver_tier2_explicit_cwd_header() -> None:
+ r = ProjectResolver()
+ out = r.resolve(_ctx(headers={"x-headroom-cwd": "/Users/foo/code/project-b"}))
+ assert out is not None
+ key, display = out
+ assert display == "project-b"
+ assert key.startswith("project-b-")
+ assert len(key.split("-")[-1]) == 16 # sha256 prefix length
+
+
+def test_resolver_tier3_cli_override() -> None:
+ r = ProjectResolver()
+ out = r.resolve(_ctx(project_root_override="/Users/foo/code/project-c"))
+ assert out is not None
+ _, display = out
+ assert display == "project-c"
+
+
+def test_resolver_tier4_env_block_primary_working_directory() -> None:
+ r = ProjectResolver()
+ prompt = (
+ "You have been invoked in the following environment:\n"
+ " - Primary working directory: /Users/foo/code/headroom\n"
+ " - Is a git repo: yes\n"
+ )
+ out = r.resolve(_ctx(system_prompt=prompt))
+ assert out is not None
+ _, display = out
+ assert display == "headroom"
+
+
+def test_resolver_tier4_env_block_older_working_directory_format() -> None:
+ r = ProjectResolver()
+ prompt = "Working directory: /Users/foo/code/legacy-project\n"
+ out = r.resolve(_ctx(system_prompt=prompt))
+ assert out is not None
+ _, display = out
+ assert display == "legacy-project"
+
+
+def test_resolver_tier4_env_block_cwd_format() -> None:
+ r = ProjectResolver()
+ prompt = " cwd: /Users/foo/code/cwd-style\n"
+ out = r.resolve(_ctx(system_prompt=prompt))
+ assert out is not None
+ _, display = out
+ assert display == "cwd-style"
+
+
+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."))
+ assert out 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]
+ k2, _ = r.resolve(_ctx(headers={"x-headroom-cwd": "/Users/foo/code/x"})) # type: ignore[misc]
+ assert k1 == k2
+
+
+def test_resolver_distinct_cwds_yield_distinct_keys() -> None:
+ r = ProjectResolver()
+ k1, _ = r.resolve(_ctx(headers={"x-headroom-cwd": "/Users/foo/code/a"})) # type: ignore[misc]
+ k2, _ = r.resolve(_ctx(headers={"x-headroom-cwd": "/Users/foo/code/b"})) # type: ignore[misc]
+ assert k1 != k2
+
+
+def test_resolver_sanitises_unsafe_basename_chars() -> None:
+ r = ProjectResolver()
+ out = r.resolve(_ctx(headers={"x-headroom-project-id": "../etc/passwd; rm -rf /"}))
+ assert out is not None
+ key, _ = out
+ # Path-separators and shell-metas must be neutralised.
+ assert "/" not in key
+ assert ";" not in key
+ assert " " not in key
+
+
+def test_extract_system_prompt_anthropic_string() -> None:
+ assert extract_system_prompt({"system": "hello"}) == "hello"
+
+
+def test_extract_system_prompt_anthropic_blocks() -> None:
+ body = {"system": [{"type": "text", "text": "a"}, {"type": "text", "text": "b"}]}
+ assert extract_system_prompt(body) == "a\nb"
+
+
+def test_extract_system_prompt_openai_messages() -> None:
+ body = {
+ "messages": [
+ {"role": "system", "content": "you are helpful"},
+ {"role": "user", "content": "hi"},
+ ]
+ }
+ assert extract_system_prompt(body) == "you are helpful"
+
+
+def test_extract_system_prompt_missing_returns_empty() -> None:
+ assert extract_system_prompt({"messages": []}) == ""
+
+
+# ---------------------------------------------------------------------------
+# BackendRouter path-layout tests (no real backend I/O — we stub the class).
+# ---------------------------------------------------------------------------
+
+
+class _FakeBackend:
+ def __init__(self, cfg: LocalBackendConfig) -> None:
+ self.cfg = cfg
+
+ async def _ensure_initialized(self) -> None:
+ return
+
+
+def _make_router(
+ tmp_path: Path,
+ mode: MemoryStorageMode,
+ monkeypatch: pytest.MonkeyPatch,
+) -> BackendRouter:
+ # Patch out the real LocalBackend constructor so the router test
+ # doesn't try to load embedders or open SQLite files.
+ monkeypatch.setattr(
+ "headroom.memory.storage_router.LocalBackend",
+ _FakeBackend,
+ )
+ cfg = BackendRouterConfig(
+ mode=mode,
+ root_dir=tmp_path / "memories",
+ global_db_path=tmp_path / "memory.db",
+ max_open_backends=4,
+ backend_config_template=LocalBackendConfig(db_path=str(tmp_path / "memory.db")),
+ )
+ return BackendRouter(cfg)
+
+
+def test_router_project_mode_two_cwds_two_paths(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ router = _make_router(tmp_path, MemoryStorageMode.PROJECT, monkeypatch)
+
+ ctx_a = _ctx(headers={"x-headroom-cwd": "/code/a"})
+ ctx_b = _ctx(headers={"x-headroom-cwd": "/code/b"})
+
+ _, scope_a = router.backend_for(ctx_a)
+ _, scope_b = router.backend_for(ctx_b)
+
+ assert scope_a.mode is MemoryStorageMode.PROJECT
+ assert scope_b.mode is MemoryStorageMode.PROJECT
+ assert scope_a.db_path != scope_b.db_path
+ assert scope_a.display_name == "a"
+ assert scope_b.display_name == "b"
+
+
+def test_router_project_mode_unresolved_falls_back_to_global(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ router = _make_router(tmp_path, MemoryStorageMode.PROJECT, monkeypatch)
+
+ _, scope = router.backend_for(_ctx(system_prompt="no env block"))
+ assert scope.mode is MemoryStorageMode.GLOBAL
+ assert scope.db_path == tmp_path / "memory.db"
+
+
+def test_router_user_mode_partitions_by_user(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ router = _make_router(tmp_path, MemoryStorageMode.USER, monkeypatch)
+
+ _, scope_a = router.backend_for(_ctx(base_user_id="alice"))
+ _, scope_b = router.backend_for(_ctx(base_user_id="bob"))
+
+ assert scope_a.mode is MemoryStorageMode.USER
+ assert scope_b.mode is MemoryStorageMode.USER
+ assert scope_a.db_path != scope_b.db_path
+ assert scope_a.display_name == "alice"
+ assert scope_b.display_name == "bob"
+
+
+def test_router_global_mode_reuses_legacy_path(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ router = _make_router(tmp_path, MemoryStorageMode.GLOBAL, monkeypatch)
+
+ _, scope = router.backend_for(_ctx(headers={"x-headroom-cwd": "/code/anything"}))
+ assert scope.mode is MemoryStorageMode.GLOBAL
+ # GLOBAL mode hits the legacy DB regardless of cwd signals.
+ assert scope.db_path == tmp_path / "memory.db"
+
+
+def test_router_backend_cache_returns_same_instance(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ router = _make_router(tmp_path, MemoryStorageMode.PROJECT, monkeypatch)
+
+ ctx = _ctx(headers={"x-headroom-cwd": "/code/sticky"})
+ b1, _ = router.backend_for(ctx)
+ b2, _ = router.backend_for(ctx)
+ assert b1 is b2
+
+
+def test_router_lru_eviction_drops_oldest(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ # max_open_backends=4 in _make_router. Opening 5 different projects
+ # should evict the first.
+ router = _make_router(tmp_path, MemoryStorageMode.PROJECT, monkeypatch)
+ for i in range(5):
+ router.backend_for(_ctx(headers={"x-headroom-cwd": f"/code/p{i}"}))
+ assert len(router.open_backends()) == 4
diff --git a/tests/test_openai_codex_routing.py b/tests/test_openai_codex_routing.py
index 9c317f08d..251599ce0 100644
--- a/tests/test_openai_codex_routing.py
+++ b/tests/test_openai_codex_routing.py
@@ -303,7 +303,7 @@ def test_handle_openai_responses_memory_timeout_fails_open(monkeypatch):
def __init__(self):
self.config = SimpleNamespace(inject_context=True, inject_tools=False)
- async def search_and_format_context(self, memory_user_id, messages):
+ async def search_and_format_context(self, memory_user_id, messages, **_kwargs):
return "should not be used"
def has_memory_tool_calls(self, response, provider):
diff --git a/tests/test_proxy_openai_responses_bypass.py b/tests/test_proxy_openai_responses_bypass.py
index ceeb9d7fd..f119d435b 100644
--- a/tests/test_proxy_openai_responses_bypass.py
+++ b/tests/test_proxy_openai_responses_bypass.py
@@ -20,7 +20,12 @@ class _MemoryHandler:
self.tool_calls = 0
self.config = SimpleNamespace(inject_context=True, inject_tools=True)
- async def search_and_format_context(self, user_id: str, messages: list[dict[str, Any]]) -> str:
+ async def search_and_format_context(
+ self,
+ user_id: str,
+ messages: list[dict[str, Any]],
+ **_kwargs: Any,
+ ) -> str:
self.search_calls += 1
return "memory context that must not be injected"