mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-08-27 14:17:10 -04:00
## Description Stop `headroom wrap codex --memory` from pinning the global `headroom_memory` MCP server to one absolute SQLite path. Today the wrapper writes `--db <wrap-cwd>/.headroom/memory.db` into `~/.codex/config.toml`, which makes later Codex sessions either reopen a stale project-local DB or fail with `unable to open database file` when that original path disappears. This change lets the MCP server use its existing per-cwd default again, so each Codex session resolves `.headroom/memory.db` from the active project instead of a serialized past cwd. Closes #1147 The current Codex-memory config surface was shaped by https://github.com/chopratejas/headroom/issues/462 and https://github.com/chopratejas/headroom/issues/730; this PR keeps that surface project-scoped again instead of globally pinning one DB. ## Type of Change - [x] Bug fix (non-breaking change that fixes an issue) - [ ] New feature (non-breaking change that adds functionality) - [ ] Breaking change (fix or feature that would cause existing functionality to change) - [ ] Documentation update - [ ] Performance improvement - [ ] Code refactoring (no functional changes) ## Changes Made - remove the injected `--db` argument from the global `headroom_memory` Codex MCP block while keeping `--user` intact - preserve the wrap-time local `.headroom/memory.db` setup and Claude-memory import path for the current project - treat only wrap-owned Codex markers as snapshot-suppression and unwrap-cleanup signals, so pre-existing named MCP blocks still back up and restore - log a startup diagnostic from `headroom.memory.mcp_server` that records the configured DB path, config source, cwd/project root, resolved storage scope, path existence/readability, and whether the path was static or cwd-derived - add a shared MCP SDK test stub so both the memory MCP and CCR MCP test surfaces still run in CI when `mcp` is absent - make the shared MCP stub re-import target modules under the stubbed dependency set and restore any pre-existing target module object plus dotted parent-package attribute state after cleanup - add focused regressions and guard coverage for the persisted Codex config shape, named-MCP marker backup and restore, the no-backup memory-only unwrap path, the wrap-memory-then-unwrap cleanup path, the failed-wrap memory-only cleanup path, the startup-diagnostic path classification, the shared-store CCR retrieval path, and the shared MCP stub import lifecycle - add a `CHANGELOG.md` entry for the user-visible Codex memory scoping fix ## Testing - [x] Unit tests pass (`pytest`) - [x] Linting passes (`ruff check .`) - [ ] Type checking passes (`uv run mypy headroom`) - [x] New tests added for new functionality - [ ] Manual testing performed ### Test Output ```text uv run pytest tests/test_ccr_mcp_server.py tests/test_memory/test_mcp_server.py tests/test_cli/test_wrap_codex.py tests/test_mcp_stub.py ======================== 78 passed, 1 warning in 5.96s ======================== Pytest warning: PytestConfigWarning: Unknown config option: asyncio_mode Pytest post-success atexit noise: PermissionError: [WinError 5] Access is denied: 'C:\Users\Rod\AppData\Local\Temp\pytest-of-Rod\pytest-current' uv run ruff check headroom/cli/wrap.py headroom/memory/mcp_server.py tests/_mcp_stub.py tests/test_ccr_mcp_server.py tests/test_cli/test_wrap_codex.py tests/test_mcp_stub.py tests/test_memory/test_mcp_server.py All checks passed! uv run ruff format headroom/cli/wrap.py headroom/memory/mcp_server.py tests/_mcp_stub.py tests/test_ccr_mcp_server.py tests/test_cli/test_wrap_codex.py tests/test_mcp_stub.py tests/test_memory/test_mcp_server.py --check 7 files already formatted ``` ## Real Behavior Proof - Environment: isolated temp project directories, a temp Codex home, the real `wrap codex` and `unwrap codex` CLI commands under pytest, a mocked missing-`codex` launch path for the failed-wrap cleanup case, and shared MCP-SDK stubs for the memory MCP and CCR MCP test modules so CI still exercises those paths without a real `mcp` install. - Exact command / steps: run `uv run pytest tests/test_ccr_mcp_server.py tests/test_memory/test_mcp_server.py tests/test_cli/test_wrap_codex.py tests/test_mcp_stub.py`; prove the persisted config shape with `TestCodexMemoryMcpConfig::test_inject_omits_db_and_replaces_existing_memory_block`; prove prepare-only wrap cleanup with `test_wrap_codex_memory_prepare_only_unwrap_removes_memory_mcp_without_prior_config`; prove failed-wrap cleanup with `test_wrap_codex_memory_launch_failure_unwrap_cleans_memory_only_config`; guard pre-existing named Codex MCP preservation with `test_memory_only_wrap_restores_preexisting_named_mcp_block` and `test_memory_only_wrap_without_backup_preserves_named_mcp_block`; prove the startup diagnostic classifications with `test_memory_mcp_startup_context_reports_dynamic_project_db` and `test_memory_mcp_startup_context_reports_static_external_db`; prove the shared-store CCR retrieval path with `test_mcp_uses_shared_singleton_store` and `test_mcp_retrieves_proxy_stored_content`; prove stub import cleanup with `test_import_module_with_mcp_stub_imports_target_and_cleans_up`, `test_import_module_with_mcp_stub_reimports_target_and_restores_originals`, and `test_import_module_with_mcp_stub_cleans_up_dotted_target_attribute`. - Observed result: the persisted global `headroom_memory` block now keeps `--user` but omits `--db`; prepare-only memory setup still bootstraps the current project's `.headroom/memory.db`; `headroom unwrap codex --no-stop-proxy` now removes both the prepare-only generated config and the failed-wrap memory-only config instead of leaving `[mcp_servers.headroom_memory]` behind; pre-existing named Codex MCP blocks remain restorable across both normal and no-backup memory-only unwrap paths because only wrap-owned markers suppress backups or trigger named-block cleanup; the memory MCP server now logs whether its DB path came from the cwd default or an explicit static path, along with the resolved path and scope it will open; CI can exercise both MCP test modules even when the `mcp` package is absent from the shard environment, and the shared stub now re-imports target modules under the stubbed SDK while restoring both dependency and dotted parent-package target-module import state after cleanup. - Not tested: full end-to-end interactive Codex CLI launch. ## Review Readiness - [x] I have performed a self-review - [x] This PR is ready for human review ## Checklist - [x] My code follows the project's style guidelines - [x] I have performed a self-review of my code - [ ] I have commented my code, particularly in hard-to-understand areas - [x] I have made corresponding changes to the documentation - [ ] My changes generate no new warnings - [x] I have added tests that prove my fix is effective or that my feature works - [x] New and existing unit tests pass locally with my changes - [x] I have updated the CHANGELOG.md if applicable ## Additional Notes The code change stays narrowly scoped to Codex memory config persistence, cleanup, and startup observability. It does not widen into larger memory-routing redesign or startup-failure recovery logic.
96 lines
3 KiB
Python
96 lines
3 KiB
Python
from __future__ import annotations
|
|
|
|
import importlib
|
|
import sys
|
|
from types import ModuleType
|
|
|
|
_MCP_MODULE_NAMES = (
|
|
"mcp",
|
|
"mcp.server",
|
|
"mcp.server.stdio",
|
|
"mcp.types",
|
|
)
|
|
|
|
|
|
def _build_mcp_sdk_stub() -> dict[str, ModuleType]:
|
|
mcp_module = type(sys)("mcp")
|
|
mcp_server_module = type(sys)("mcp.server")
|
|
mcp_stdio_module = type(sys)("mcp.server.stdio")
|
|
mcp_types_module = type(sys)("mcp.types")
|
|
|
|
class DummyServer:
|
|
def __init__(self, name: str) -> None:
|
|
self.name = name
|
|
|
|
def list_tools(self):
|
|
return lambda fn: fn
|
|
|
|
def call_tool(self):
|
|
return lambda fn: fn
|
|
|
|
def create_initialization_options(self):
|
|
return {}
|
|
|
|
class DummyTool:
|
|
def __init__(self, **kwargs) -> None:
|
|
self.kwargs = kwargs
|
|
|
|
class DummyTextContent:
|
|
def __init__(self, **kwargs) -> None:
|
|
self.kwargs = kwargs
|
|
|
|
async def dummy_stdio_server():
|
|
raise RuntimeError("stdio_server should not run in unit tests")
|
|
|
|
mcp_server_module.Server = DummyServer
|
|
mcp_stdio_module.stdio_server = dummy_stdio_server
|
|
mcp_types_module.TextContent = DummyTextContent
|
|
mcp_types_module.Tool = DummyTool
|
|
|
|
return {
|
|
"mcp": mcp_module,
|
|
"mcp.server": mcp_server_module,
|
|
"mcp.server.stdio": mcp_stdio_module,
|
|
"mcp.types": mcp_types_module,
|
|
}
|
|
|
|
|
|
def import_module_with_mcp_stub(module_name: str):
|
|
original_target_module = sys.modules.get(module_name)
|
|
parent_name, _, child_name = module_name.rpartition(".")
|
|
original_parent_module = sys.modules.get(parent_name) if parent_name else None
|
|
original_parent_attr_exists = bool(
|
|
original_parent_module and child_name and hasattr(original_parent_module, child_name)
|
|
)
|
|
original_parent_attr = (
|
|
getattr(original_parent_module, child_name) if original_parent_attr_exists else None
|
|
)
|
|
original_modules = {name: sys.modules.get(name) for name in _MCP_MODULE_NAMES}
|
|
stub_modules = _build_mcp_sdk_stub()
|
|
|
|
sys.modules.pop(module_name, None)
|
|
for name, module in stub_modules.items():
|
|
sys.modules[name] = module
|
|
|
|
try:
|
|
return importlib.import_module(module_name)
|
|
finally:
|
|
if original_target_module is None:
|
|
sys.modules.pop(module_name, None)
|
|
else:
|
|
sys.modules[module_name] = original_target_module
|
|
if child_name:
|
|
current_parent_module = sys.modules.get(parent_name) or original_parent_module
|
|
if current_parent_module is not None:
|
|
if original_parent_attr_exists:
|
|
setattr(current_parent_module, child_name, original_parent_attr)
|
|
else:
|
|
try:
|
|
delattr(current_parent_module, child_name)
|
|
except AttributeError:
|
|
pass
|
|
for name, original_module in original_modules.items():
|
|
if original_module is None:
|
|
sys.modules.pop(name, None)
|
|
else:
|
|
sys.modules[name] = original_module
|