Skip to content

Commit 84c0a3b

Browse files
cdeustclaude
andauthored
feat(hooks): a console entry point runs any lifecycle hook from the wheel (#605)
* feat(hooks): a console entry point runs any lifecycle hook from the wheel (#605) A Codex plugin ships only its own directory, so it cannot reach this repository's scripts/launcher.py the way the Claude Code plugin does. mcp_server/hooks/entry.py, backed by the new hypermnesia-mcp-hook console script, validates its module argument against the ten hook names .claude-plugin/plugin.json wires, resolves the storage backend the same way mcp_server/__main__.py does for the server, and dispatches to the named hook's own __main__ unchanged, so its headless guard and composition-root wiring keep running exactly as under scripts/launcher.py. A Codex plugin can then call uvx --from "hypermnesia-mcp[postgresql,sqlite]" hypermnesia-mcp-hook <module> directly. Parity tests run every allowlisted module against both entry points on a benign event and assert equal exit codes and stdout. Co-Authored-By: Claude Sonnet 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Cz7A6goxVzfKL9NT7k4zDH * fix(hooks): entry.py wires the composition root, fix tomllib on 3.10 (#605) CI on PR #605 found two gaps the parity-only test subset masked. First, tests_py/scripts/test_composition_root_wiring_coverage.py:: test_every_hook_with_a_main_block_wires_the_composition_root failed: scripts/launcher.py calls wire_composition_root() before run_module (issue number 560), and entry.py skipped that call, relying only on each hook's own __main__ block to re-wire, which the static guard does not accept as equivalent. entry.py:main now wires the composition root itself between prepare_environment and runpy.run_module, the same seam scripts/launcher.py uses. Second, tests_py/hooks/test_entry.py imported tomllib unconditionally, which does not exist on Python 3.10 (requires-python is >=3.10); the test now falls back to the tomli backport on 3.10, the same package build/hatchling already pull in for that Python version per uv.lock. Also corrected "ten hook modules" to "eleven" in entry.py, the test docstring and the CHANGELOG entry; the allowlist has eleven names. Co-Authored-By: Claude Sonnet 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Cz7A6goxVzfKL9NT7k4zDH --------- Co-authored-by: Claude Sonnet 5 <[email protected]>
1 parent bba138a commit 84c0a3b

4 files changed

Lines changed: 294 additions & 0 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,19 @@ adheres to [Semantic Versioning](https://semver.org/).
88

99
### Added
1010

11+
- **A console entry point runs any Cortex lifecycle hook from the installed
12+
wheel (#605).** A Codex plugin ships only its own directory, so it cannot
13+
reach this repository's `scripts/launcher.py` the way the Claude Code
14+
plugin does. `hypermnesia-mcp-hook`, a new `[project.scripts]` entry
15+
backed by `mcp_server/hooks/entry.py`, validates its module argument
16+
against the eleven hook names `.claude-plugin/plugin.json` wires,
17+
resolves the storage backend the same way the server does, wires the
18+
composition root the same way `scripts/launcher.py` does, and dispatches
19+
to the named hook's own `__main__` unchanged. A Codex plugin can then call
20+
`uvx --from "hypermnesia-mcp[postgresql,sqlite]" hypermnesia-mcp-hook
21+
<module>` directly. This changes nothing for the Claude Code plugin,
22+
which keeps using `scripts/launcher.py`.
23+
1124
- **The host-contract verifier counts the tools the server registers
1225
(ADR-1077).** `scripts/verify_mcp_hosts.py` held its own floor of 52 with a
1326
ceiling three above, so it stayed right through the move to 54 (ADR-1066)

‎mcp_server/hooks/entry.py‎

Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
"""Console entry point that runs a Cortex lifecycle hook from the wheel.
2+
3+
A Codex plugin ships only its own directory, not this repository and not
4+
``scripts/launcher.py``. It calls the console script this module backs
5+
(``hypermnesia-mcp-hook``, declared in ``pyproject.toml``, source: this
6+
module's CHANGELOG entry) as
7+
``uvx --from "hypermnesia-mcp[postgresql,sqlite]" hypermnesia-mcp-hook
8+
<module>``. ``main()`` validates ``<module>`` against the allowlist below,
9+
resolves the storage backend the way ``mcp_server/__main__.py`` does for
10+
the server, wires the composition root the way ``scripts/launcher.py``
11+
does before dispatching (issue number 560), and dispatches to the named
12+
hook's own ``__main__`` block via ``runpy`` -- unchanged, so its headless
13+
guard and its own re-wiring still run exactly as they do under
14+
``scripts/launcher.py``.
15+
16+
No ``chdir`` (uvx does not need one), no dependency installation (uvx owns
17+
dependencies), no capture preflight (``post_tool_capture.py`` already
18+
applies its own skip check).
19+
"""
20+
21+
from __future__ import annotations
22+
23+
import os
24+
import runpy
25+
import sys
26+
from pathlib import Path
27+
from typing import MutableMapping
28+
29+
from mcp_server.infrastructure.backend_marker import apply_backend_resolution
30+
31+
# The eleven hook modules the Claude Code plugin manifest wires
32+
# (.claude-plugin/plugin.json), verified against that file. Anything else
33+
# is refused.
34+
HOOK_MODULES = frozenset(
35+
{
36+
"session_start",
37+
"auto_recall",
38+
"decision_gate",
39+
"no_deps_gate",
40+
"post_tool_capture",
41+
"preemptive_context",
42+
"pipeline_impact_bump",
43+
"post_commit_reindex",
44+
"session_lifecycle",
45+
"compaction_checkpoint",
46+
"agent_briefing",
47+
}
48+
)
49+
50+
# source: scripts/launcher.py:139 -- the same local default, PostgreSQL only.
51+
_DEFAULT_DATABASE_URL = "postgresql://localhost:5432/cortex"
52+
53+
54+
def prepare_environment(
55+
environ: MutableMapping[str, str], marker_path: Path | None = None
56+
) -> None:
57+
"""Resolve the storage backend and the PostgreSQL DATABASE_URL default.
58+
59+
Precondition: ``environ`` is mutable (normally ``os.environ``).
60+
Postcondition: ``CORTEX_MEMORY_STORE_BACKEND`` carries whatever
61+
``apply_backend_resolution`` resolves (mirrors ``mcp_server/__main__.py``
62+
line 22 for the server). ``DATABASE_URL`` is set to the local default
63+
only when it was unset AND the resolved backend is not ``sqlite``
64+
(mirrors ``scripts/launcher.py`` lines 135-139) -- on the SQLite backend
65+
the URL is unused, and injecting a PostgreSQL default would make every
66+
hook invocation attempt a doomed connection.
67+
"""
68+
apply_backend_resolution(environ, marker_path)
69+
backend = environ.get("CORTEX_MEMORY_STORE_BACKEND", "")
70+
if "DATABASE_URL" not in environ and backend != "sqlite":
71+
environ["DATABASE_URL"] = _DEFAULT_DATABASE_URL
72+
73+
74+
def _print_usage() -> None:
75+
names = ", ".join(sorted(HOOK_MODULES))
76+
print(
77+
f"Usage: hypermnesia-mcp-hook <module>\nAllowed modules: {names}",
78+
file=sys.stderr,
79+
)
80+
81+
82+
def main() -> None:
83+
"""Validate argv[1] against the allowlist, then dispatch to the hook.
84+
85+
Precondition: none (argv may be missing its module argument).
86+
Postcondition: exits 2 with nothing on stdout when argv[1] is absent or
87+
not in HOOK_MODULES; otherwise wires every core/ injection seam
88+
(issue number 560, mirroring ``scripts/launcher.py`` lines 150-155 --
89+
the hook's own ``__main__`` re-wires too, but a hook body can run
90+
before that block returns control here), then runs
91+
``mcp_server.hooks.<module>`` as ``__main__`` and exits with that
92+
hook's own exit code, or 1 on any exception the hook itself did not
93+
turn into a SystemExit (mirrors ``scripts/launcher.py`` lines
94+
159-167).
95+
"""
96+
name = sys.argv[1] if len(sys.argv) > 1 else None
97+
if name not in HOOK_MODULES:
98+
_print_usage()
99+
sys.exit(2)
100+
101+
prepare_environment(os.environ)
102+
103+
from mcp_server.hooks.wiring import wire_composition_root # noqa: PLC0415 - issue number 560, same seam as scripts/launcher.py:153
104+
105+
wire_composition_root()
106+
107+
module = f"mcp_server.hooks.{name}"
108+
sys.argv = [module]
109+
try:
110+
runpy.run_module(module, run_name="__main__", alter_sys=True)
111+
except SystemExit:
112+
raise
113+
except Exception as exc: # noqa: BLE001 - dispatch boundary; reported, never crashes
114+
print(f"[hypermnesia-mcp-hook] Failed to run {module}: {exc}", file=sys.stderr)
115+
sys.exit(1)
116+
117+
118+
if __name__ == "__main__":
119+
main()

‎pyproject.toml‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,9 @@ Repository = "https://github.com/cdeust/Cortex"
7777
#
7878
cortex-doctor = "mcp_server.doctor:run"
7979
hypermnesia-mcp = "mcp_server.__main__:main"
80+
# source: CHANGELOG.md Unreleased, ADR number 0874 uses this same interim
81+
# form for the two scripts above until the console-entry-point ADR lands
82+
hypermnesia-mcp-hook = "mcp_server.hooks.entry:main"
8083

8184
[project.optional-dependencies]
8285
postgresql = [

‎tests_py/hooks/test_entry.py‎

Lines changed: 159 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,159 @@
1+
"""Tests for the console entry point that runs any Cortex lifecycle hook
2+
from the installed wheel, without the repository or scripts/launcher.py.
3+
4+
Source: this PR's specification (Codex plugin wave, PR 1). A Codex plugin
5+
ships only its own directory and calls
6+
``uvx --from "hypermnesia-mcp[postgresql,sqlite]" hypermnesia-mcp-hook
7+
<module>``, so the eleven hook modules the Claude Code plugin manifest
8+
wires (.claude-plugin/plugin.json) must be runnable without
9+
scripts/launcher.py.
10+
11+
Parity: mcp_server.hooks.entry must behave exactly like scripts/launcher.py
12+
for every allowlisted module on a benign event, because both are meant to
13+
run the same hook the same way -- the Codex plugin is not a second
14+
implementation of hook dispatch, it is a second caller of the same one.
15+
"""
16+
17+
from __future__ import annotations
18+
19+
import json
20+
import os
21+
import subprocess
22+
import sys
23+
from pathlib import Path
24+
25+
import pytest
26+
27+
# tomllib is 3.11+; requires-python is >=3.10 (pyproject.toml), so the
28+
# fallback backport is used on 3.10, exactly like build/hatchling's own
29+
# dependency on it (uv.lock: tomli, marker python_full_version < "3.11").
30+
if sys.version_info >= (3, 11):
31+
import tomllib
32+
else:
33+
import tomli as tomllib
34+
35+
REPO_ROOT = Path(__file__).resolve().parents[2]
36+
LAUNCHER_PATH = REPO_ROOT / "scripts" / "launcher.py"
37+
38+
HOOK_MODULES = (
39+
"session_start",
40+
"auto_recall",
41+
"decision_gate",
42+
"no_deps_gate",
43+
"post_tool_capture",
44+
"preemptive_context",
45+
"pipeline_impact_bump",
46+
"post_commit_reindex",
47+
"session_lifecycle",
48+
"compaction_checkpoint",
49+
"agent_briefing",
50+
)
51+
52+
53+
def _benign_event(tmp_path: Path) -> str:
54+
target = tmp_path / "seen.txt"
55+
target.write_text("hello\n", encoding="utf-8")
56+
return json.dumps(
57+
{
58+
"session_id": "t",
59+
"cwd": str(tmp_path),
60+
"tool_name": "Read",
61+
"tool_input": {"file_path": str(target)},
62+
"tool_response": "",
63+
}
64+
)
65+
66+
67+
def _isolated_env(tmp_path: Path) -> dict[str, str]:
68+
home = tmp_path / "home"
69+
home.mkdir(exist_ok=True)
70+
claude_dir = tmp_path / "claude-dir"
71+
claude_dir.mkdir(exist_ok=True)
72+
env = dict(os.environ)
73+
env["HOME"] = str(home)
74+
env["CORTEX_CLAUDE_DIR"] = str(claude_dir)
75+
env["CORTEX_MEMORY_STORE_BACKEND"] = "sqlite"
76+
env["CLAUDE_PLUGIN_ROOT"] = str(REPO_ROOT)
77+
env.pop("DATABASE_URL", None)
78+
return env
79+
80+
81+
@pytest.mark.parametrize("module", HOOK_MODULES)
82+
def test_entry_matches_launcher_on_benign_event(module: str, tmp_path: Path) -> None:
83+
event = _benign_event(tmp_path)
84+
env = _isolated_env(tmp_path)
85+
86+
via_entry = subprocess.run(
87+
[sys.executable, "-m", "mcp_server.hooks.entry", module],
88+
input=event,
89+
capture_output=True,
90+
text=True,
91+
env=env,
92+
cwd=REPO_ROOT,
93+
)
94+
via_launcher = subprocess.run(
95+
[sys.executable, str(LAUNCHER_PATH), f"mcp_server.hooks.{module}"],
96+
input=event,
97+
capture_output=True,
98+
text=True,
99+
env=env,
100+
cwd=REPO_ROOT,
101+
)
102+
103+
assert via_entry.returncode == via_launcher.returncode, (
104+
via_entry.stderr,
105+
via_launcher.stderr,
106+
)
107+
assert via_entry.stdout == via_launcher.stdout
108+
109+
110+
def test_entry_refuses_a_module_outside_the_allowlist(tmp_path: Path) -> None:
111+
env = _isolated_env(tmp_path)
112+
result = subprocess.run(
113+
[
114+
sys.executable,
115+
"-m",
116+
"mcp_server.hooks.entry",
117+
"mcp_server.handlers.remember",
118+
],
119+
input="",
120+
capture_output=True,
121+
text=True,
122+
env=env,
123+
cwd=REPO_ROOT,
124+
)
125+
assert result.returncode == 2
126+
assert result.stdout == ""
127+
128+
129+
def test_prepare_environment_marker_selects_sqlite_and_skips_database_url(
130+
tmp_path: Path,
131+
) -> None:
132+
from mcp_server.hooks.entry import prepare_environment
133+
134+
marker = tmp_path / "backend.json"
135+
marker.write_text(json.dumps({"backend": "sqlite"}), encoding="utf-8")
136+
environ: dict[str, str] = {}
137+
138+
prepare_environment(environ, marker_path=marker)
139+
140+
assert environ["CORTEX_MEMORY_STORE_BACKEND"] == "sqlite"
141+
assert "DATABASE_URL" not in environ
142+
143+
144+
def test_prepare_environment_no_marker_postgresql_sets_default_database_url(
145+
tmp_path: Path,
146+
) -> None:
147+
from mcp_server.hooks.entry import prepare_environment
148+
149+
environ: dict[str, str] = {"CORTEX_MEMORY_STORE_BACKEND": "postgresql"}
150+
151+
prepare_environment(environ, marker_path=tmp_path / "absent.json")
152+
153+
assert environ["DATABASE_URL"] == "postgresql://localhost:5432/cortex"
154+
155+
156+
def test_pyproject_declares_the_console_script() -> None:
157+
data = tomllib.loads((REPO_ROOT / "pyproject.toml").read_text(encoding="utf-8"))
158+
scripts = data["project"]["scripts"]
159+
assert scripts["hypermnesia-mcp-hook"] == "mcp_server.hooks.entry:main"

0 commit comments

Comments
 (0)