Skip to content

Commit 62b44c5

Browse files
committed
fix(codex): preserve receipt identity and minimal hook imports
1 parent 816da67 commit 62b44c5

9 files changed

Lines changed: 98 additions & 60 deletions

‎mcp_server/hooks/agent_briefing.py‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
"""Automatic child briefing for Claude Code and Codex.
33
44
Claude specialists use their task prompt. Codex PreToolUse appends context to
5-
exact spawn arguments; promptless SubagentStart supplies scoped team decisions.
5+
exact spawn arguments; promptless SubagentStart supplies scoped project/role context.
66
Queries and receipt writes honor the configured SQLite/PostgreSQL backend.
77
88
source: ADR-0481
@@ -180,8 +180,8 @@ def _briefing(event, agent, keywords):
180180
target,
181181
[{"memory_id": m["id"]} for m in memories],
182182
channel="agent_briefing",
183-
session_id=event.get("session_id")
184-
or session_id_from_transcript(event.get("transcript_path")),
183+
session_id=session_id_from_transcript(event.get("transcript_path"))
184+
or event.get("session_id"),
185185
)
186186
except Exception as exc: # noqa: BLE001 — hook boundary; visible degradation
187187
_log(f"skip: briefing query failed: {exc}")

‎mcp_server/hooks/preemptive_context.py‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,6 @@
4848
from mcp_server.shared.project_scope import resolve_project_root
4949
from mcp_server.hooks.shell_read_events import completed_shell_read
5050
from mcp_server.infrastructure.file_memory_priming import prime_file_memories
51-
from mcp_server.infrastructure.memory_store import get_shared_store
5251

5352
_LOG_PREFIX = "[cortex-preemptive]"
5453
_HEAT_BOOST = 0.1 # source: ADR-0496 — preserved existing activation increment
@@ -107,6 +106,10 @@ def _prime_file_memories(
107106
"""One atomic boost for all cues in this tool call (source: ADR-1086)."""
108107
paths = [file_path] if isinstance(file_path, str) else file_path
109108
try:
109+
from mcp_server.infrastructure.memory_store import ( # noqa: PLC0415 -- cooldown imports must work without site packages
110+
get_shared_store,
111+
)
112+
110113
return prime_file_memories(get_shared_store(), paths, project, _HEAT_BOOST)
111114
except Exception as exc: # noqa: BLE001 — hook boundary; storage errors are logged
112115
_log(f"prime failed: {exc}")

‎mcp_server/infrastructure/file_memory_priming.py‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,16 @@
77
from __future__ import annotations
88

99
from pathlib import Path
10+
from typing import TYPE_CHECKING, cast
1011

11-
from mcp_server.infrastructure.memory_store import MemoryStore
1212
from mcp_server.infrastructure.pg_scope_clause import directory_scope_clause
1313
from mcp_server.shared.project_scope import project_ancestors
1414

15+
if TYPE_CHECKING:
16+
from typing_extensions import LiteralString
17+
18+
from mcp_server.infrastructure.memory_store import MemoryStore
19+
1520

1621
def _literal_pattern(value: str) -> str:
1722
return "%" + value.replace("!", "!!").replace("%", "!%").replace("_", "!_") + "%"
@@ -39,7 +44,9 @@ def prime_file_memories(
3944
params = (boost, boost, *scope_params, *(_literal_pattern(cue) for cue in cues))
4045
with store.acquire_interactive() as conn:
4146
try:
42-
result = conn.execute(sql, params)
47+
# Query fragments contain only fixed SQL and generated placeholders;
48+
# project paths and content cues are exclusively bound parameters.
49+
result = conn.execute(cast("LiteralString", sql), params)
4350
conn.commit()
4451
return result.rowcount
4552
except Exception:

‎tests_py/hooks/test_agent_briefing_postgres.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,14 +5,15 @@
55
import pytest
66

77
from mcp_server.hooks import agent_briefing as hook
8-
from mcp_server.infrastructure.pg_store import PgMemoryStore
98
from tests_py.conftest import _TEST_DB_URL, _USE_PG
109

1110
pytestmark = pytest.mark.skipif(not _USE_PG, reason="PostgreSQL test database required")
1211

1312

1413
@pytest.fixture
1514
def seeded_store():
15+
from mcp_server.infrastructure.pg_store import PgMemoryStore
16+
1617
store = PgMemoryStore(database_url=_TEST_DB_URL)
1718

1819
def insert(content, **values):

‎tests_py/hooks/test_agent_briefing_sqlite.py‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,8 @@ def test_task_pass_and_promptless_team_pass_are_scoped(connection):
5959
} == {global_id}
6060

6161

62-
def test_native_start_records_exact_receipt(connection, capsys):
62+
@pytest.mark.parametrize("transcript", [None, "/sessions/child-transcript.jsonl"])
63+
def test_native_start_records_exact_receipt(connection, capsys, transcript):
6364
memory = insert(connection, "shared decision", is_team_decision=True)
6465
with (
6566
patch.object(hook, "_connect", return_value=connection),
@@ -71,6 +72,7 @@ def test_native_start_records_exact_receipt(connection, capsys):
7172
"agent_type": "worker",
7273
"cwd": "/project",
7374
"session_id": "child-test",
75+
"transcript_path": transcript,
7476
}
7577
)
7678
assert "shared decision" in capsys.readouterr().out
@@ -81,7 +83,7 @@ def test_native_start_records_exact_receipt(connection, capsys):
8183
receipt = connection.store._conn.execute(
8284
"SELECT * FROM injection_receipts"
8385
).fetchone()
84-
assert receipt["session_id"] == "child-test"
86+
assert receipt["session_id"] == ("child-transcript" if transcript else "child-test")
8587

8688

8789
def test_sqlite_selection_does_not_probe_postgres(connection, monkeypatch):

‎tests_py/hooks/test_hook_database_configuration.py‎

Lines changed: 25 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
"""Hooks must preserve the configured store URL. source: ADR-1085"""
22

3-
from unittest.mock import MagicMock, patch
3+
import sys
4+
from types import ModuleType
5+
from unittest.mock import MagicMock
46

57
import pytest
68

@@ -9,6 +11,21 @@
911
from mcp_server.infrastructure.memory_config import get_memory_settings
1012

1113

14+
@pytest.fixture
15+
def postgres_connection_factory(monkeypatch):
16+
"""Model the optional driver boundary without importing the driver."""
17+
driver = ModuleType("psycopg")
18+
rows = ModuleType("psycopg.rows")
19+
factory = MagicMock()
20+
driver.Connection = factory
21+
driver.Error = RuntimeError
22+
rows.DictRow = dict
23+
rows.dict_row = MagicMock()
24+
monkeypatch.setitem(sys.modules, "psycopg", driver)
25+
monkeypatch.setitem(sys.modules, "psycopg.rows", rows)
26+
return factory
27+
28+
1229
def test_entry_promotes_namespaced_url_without_redirecting_to_default(tmp_path):
1330
environ = {"CORTEX_MEMORY_DATABASE_URL": "postgresql:///briefing_alias_test"}
1431
prepare_environment(environ, tmp_path / "absent-marker.json")
@@ -18,7 +35,7 @@ def test_entry_promotes_namespaced_url_without_redirecting_to_default(tmp_path):
1835
@pytest.mark.parametrize("backend", ["auto", "postgresql"])
1936
@pytest.mark.parametrize("canonical", [None, "postgresql:///canonical_test"])
2037
def test_direct_briefing_uses_settings_url_and_canonical_precedence(
21-
monkeypatch, canonical, backend
38+
monkeypatch, canonical, backend, postgres_connection_factory
2239
):
2340
monkeypatch.setenv("CORTEX_MEMORY_STORE_BACKEND", backend)
2441
monkeypatch.setenv(
@@ -30,12 +47,12 @@ def test_direct_briefing_uses_settings_url_and_canonical_precedence(
3047
get_memory_settings.cache_clear()
3148
connection = MagicMock()
3249
try:
33-
with patch("psycopg.Connection") as factory:
34-
factory.__getitem__.return_value.connect.return_value = connection
35-
assert _connect() is connection
36-
assert factory.__getitem__.return_value.connect.call_args.args[0] == (
37-
canonical or "postgresql:///briefing_alias_test"
38-
)
50+
factory = postgres_connection_factory
51+
factory.__getitem__.return_value.connect.return_value = connection
52+
assert _connect() is connection
53+
assert factory.__getitem__.return_value.connect.call_args.args[0] == (
54+
canonical or "postgresql:///briefing_alias_test"
55+
)
3956
finally:
4057
get_memory_settings.cache_clear()
4158

‎tests_py/hooks/test_preemptive_context.py‎

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -142,7 +142,10 @@ def test_update_cooldown_recovers_from_a_corrupt_file():
142142
def test_prime_passes_paths_and_scope_to_selected_backend():
143143
store = MagicMock()
144144
with (
145-
patch.object(hook, "get_shared_store", return_value=store),
145+
patch(
146+
"mcp_server.infrastructure.memory_store.get_shared_store",
147+
return_value=store,
148+
),
146149
patch.object(hook, "prime_file_memories", return_value=7) as prime,
147150
):
148151
assert hook._prime_file_memories("/repo/store.py", "/repo") == 7
@@ -151,8 +154,9 @@ def test_prime_passes_paths_and_scope_to_selected_backend():
151154

152155

153156
def test_failed_update_is_logged_with_its_cause(capsys):
154-
with patch.object(
155-
hook, "get_shared_store", side_effect=RuntimeError("unavailable")
157+
with patch(
158+
"mcp_server.infrastructure.memory_store.get_shared_store",
159+
side_effect=RuntimeError("unavailable"),
156160
):
157161
assert hook._prime_file_memories("/a.py") is None
158162
assert "prime failed: unavailable" in capsys.readouterr().err
@@ -161,8 +165,9 @@ def test_failed_update_is_logged_with_its_cause(capsys):
161165
def test_storage_failure_does_not_suppress_recovered_read():
162166
event = {"tool_name": "Read", "tool_input": {"file_path": "/a.py"}}
163167
with (
164-
patch.object(
165-
hook, "get_shared_store", side_effect=[RuntimeError("offline"), MagicMock()]
168+
patch(
169+
"mcp_server.infrastructure.memory_store.get_shared_store",
170+
side_effect=[RuntimeError("offline"), MagicMock()],
166171
),
167172
patch.object(hook, "prime_file_memories", return_value=1) as prime,
168173
):

‎tests_py/invariants/test_I2_canonical_writer.py‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
- homeostatic_apply.py _apply_fold (rare amortized fold UPDATE,
1818
per write class since M-D3)
1919
- anchor.py anchor handler (heat_base=1.0, no_decay=TRUE)
20-
- preemptive_context.py _prime_file_memories (heat_base boost on read/edit)
20+
- file_memory_priming.py prime_file_memories (scoped file-cue boost, ADR-1086)
2121
2222
Any new writer outside this list fails this test.
2323
"""
@@ -53,8 +53,8 @@
5353
("handlers/consolidation/homeostatic_apply.py", 184),
5454
# Anchor pin.
5555
("handlers/anchor.py", 145),
56-
# Preemptive boost.
57-
("hooks/preemptive_context.py", 125),
56+
# Atomic project-scoped file-cue boost, moved from the hook in ADR-1086.
57+
("infrastructure/file_memory_priming.py", 37),
5858
# Pipeline-impact boost.
5959
("hooks/pipeline_impact_bump.py", 164),
6060
# CAS-guarded deliberate reheat.

‎tests_py/test_tool_surface.py‎

Lines changed: 38 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@
1414
import sys
1515
import textwrap
1616

17+
import pytest
18+
1719
from mcp.server.mcpserver import MCPServer
1820

1921
from mcp_server.__main__ import register_all
@@ -85,10 +87,10 @@ def test_the_docker_smoke_floor_follows_the_surface() -> None:
8587

8688

8789
def test_the_verifier_imports_without_the_mcp_sdk() -> None:
88-
"""The mcp-host-config CI job installs the host CLIs, not the SDK.
90+
"""The verifier can bootstrap before artifact dependencies are installed.
8991
90-
Importing `mcp_server.tool_surface` at module scope pulled the SDK
91-
through the registries and broke that job (issue #597).
92+
Importing registries at module scope previously broke this boundary
93+
(issue #597); full candidate verification loads them only when needed.
9294
"""
9395
result = subprocess.run(
9496
[sys.executable, "-c", _SDK_FREE_IMPORT_PROBE], capture_output=True, text=True
@@ -98,43 +100,44 @@ def test_the_verifier_imports_without_the_mcp_sdk() -> None:
98100
assert "imported" in result.stdout
99101

100102

101-
def test_the_sdk_less_job_never_binds_a_release_to_this_checkouts_bounds() -> None:
102-
"""Importability is not enough: a full-profile case in the SDK-less job
103-
still *calls* `full_tool_bounds()` and dies on the same missing SDK.
104-
105-
Codex stopped shipping a lean profile (PR #620), so mcp-host-config's
106-
codex-cli case had to move to `--profiles full`, and it broke that way.
107-
`--published-surface` is what keeps the call unreachable there, and it is
108-
correct beyond the SDK: that command resolves a released artifact whose
109-
surface is its own release's, not this checkout's (ADR-1077, revision
110-
2026-09-22).
111-
"""
103+
def test_candidate_job_installs_dependencies_and_checks_its_full_surface() -> None:
104+
"""The candidate wheel supplies the SDK; exact checkout bounds must run."""
112105
import pathlib
113106
import re
114107

115108
workflow = pathlib.Path(".github/workflows/ci.yml").read_text(encoding="utf-8")
116109
job = workflow.split("\n mcp-host-config:\n", 1)
117-
assert len(job) == 2, "the mcp-host-config job is no longer declared as expected"
118-
# Up to the next top-level job key.
110+
assert len(job) == 2
119111
body = re.split(r"\n [a-z][a-z-]*:\n", job[1], maxsplit=1)[0]
120-
121-
# Per invocation, not over the whole job: a second --profiles full case
122-
# added later that legitimately needs no flag would otherwise satisfy a
123-
# job-wide substring check on behalf of the one that does need it.
124-
invocations = [
125-
# From the script name to the `--` that ends the flags.
126-
match.group(0)
127-
for match in re.finditer(
128-
r"verify_mcp_hosts\.py(?:[^\n]*\\\n)*[^\n]*", body, flags=re.MULTILINE
129-
)
130-
]
131-
assert invocations, (
132-
"the job no longer drives the verifier; drop this test or re-point it"
112+
commands = body.replace("\\\n", " ")
113+
invocations = re.findall(
114+
r"uv run[^\n]*scripts/verify_mcp_hosts\.py[^\n]*", commands
133115
)
116+
assert invocations, "candidate verification must install its wheel dependencies"
117+
assert 'uv build --wheel --out-dir "$RUNNER_TEMP/cortex-codex-wheel"' in body
134118
for invocation in invocations:
135-
if "--profiles full" in invocation:
136-
assert "--published-surface" in invocation, (
137-
"this full-profile case in the SDK-less job must pass "
138-
"--published-surface, or it calls full_tool_bounds() and dies "
139-
f"on ModuleNotFoundError: No module named 'mcp':\n{invocation}"
140-
)
119+
assert '--no-project --with "$candidate_wheel" -- env' in invocation
120+
assert 'UV_FIND_LINKS="$RUNNER_TEMP/cortex-codex-wheel"' in invocation
121+
assert "--profiles full" in invocation
122+
assert "--published-surface" not in invocation, (
123+
"candidate bounds cannot be bypassed"
124+
)
125+
assert "--artifact-surface" not in invocation, (
126+
"candidate bounds cannot be bypassed"
127+
)
128+
129+
130+
def test_candidate_verifier_rejects_lean_only_discovery(tmp_path) -> None:
131+
"""A candidate claiming full must fail when only the lean tools survive."""
132+
from mcp_server.tool_profiles import LEAN_TOOL_NAMES
133+
from scripts.mcp_host_client import ContractCase, ContractError
134+
from scripts.verify_mcp_hosts import _verify_tool_surface
135+
136+
case = ContractCase("codex-cli", "full", (), tmp_path, 180, False, "auto")
137+
responses = {2: {"result": {"tools": [{"name": n} for n in LEAN_TOOL_NAMES]}}}
138+
with pytest.raises(ContractError, match="discovered .* full tools; expected"):
139+
_verify_tool_surface(case, responses, published=False)
140+
responses[2]["result"]["tools"] = [{"name": n} for n in standalone_tool_names()]
141+
assert _verify_tool_surface(case, responses, published=False) == len(
142+
standalone_tool_names()
143+
)

0 commit comments

Comments
 (0)