Skip to content

Commit 1a7e334

Browse files
cdeustclaude
andcommitted
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
1 parent bba138a commit 1a7e334

4 files changed

Lines changed: 274 additions & 0 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,18 @@ 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 ten hook names `.claude-plugin/plugin.json` wires, resolves
17+
the storage backend the same way the server does, and dispatches to the
18+
named hook's own `__main__` unchanged. A Codex plugin can then call
19+
`uvx --from "hypermnesia-mcp[postgresql,sqlite]" hypermnesia-mcp-hook
20+
<module>` directly. This changes nothing for the Claude Code plugin,
21+
which keeps using `scripts/launcher.py`.
22+
1123
- **The host-contract verifier counts the tools the server registers
1224
(ADR-1077).** `scripts/verify_mcp_hosts.py` held its own floor of 52 with a
1325
ceiling three above, so it stayed right through the move to 54 (ADR-1066)

‎mcp_server/hooks/entry.py‎

Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
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, and dispatches to the named hook's own ``__main__`` block via
11+
``runpy`` -- unchanged, so its headless guard and composition-root wiring
12+
still run exactly as they do under ``scripts/launcher.py``.
13+
14+
No ``chdir`` (uvx does not need one), no dependency installation (uvx owns
15+
dependencies), no capture preflight (``post_tool_capture.py`` already
16+
applies its own skip check).
17+
"""
18+
19+
from __future__ import annotations
20+
21+
import os
22+
import runpy
23+
import sys
24+
from pathlib import Path
25+
from typing import MutableMapping
26+
27+
from mcp_server.infrastructure.backend_marker import apply_backend_resolution
28+
29+
# The ten hook modules the Claude Code plugin manifest wires (.claude-plugin/
30+
# plugin.json), verified against that file. Anything else is refused.
31+
HOOK_MODULES = frozenset(
32+
{
33+
"session_start",
34+
"auto_recall",
35+
"decision_gate",
36+
"no_deps_gate",
37+
"post_tool_capture",
38+
"preemptive_context",
39+
"pipeline_impact_bump",
40+
"post_commit_reindex",
41+
"session_lifecycle",
42+
"compaction_checkpoint",
43+
"agent_briefing",
44+
}
45+
)
46+
47+
# source: scripts/launcher.py:139 -- the same local default, PostgreSQL only.
48+
_DEFAULT_DATABASE_URL = "postgresql://localhost:5432/cortex"
49+
50+
51+
def prepare_environment(
52+
environ: MutableMapping[str, str], marker_path: Path | None = None
53+
) -> None:
54+
"""Resolve the storage backend and the PostgreSQL DATABASE_URL default.
55+
56+
Precondition: ``environ`` is mutable (normally ``os.environ``).
57+
Postcondition: ``CORTEX_MEMORY_STORE_BACKEND`` carries whatever
58+
``apply_backend_resolution`` resolves (mirrors ``mcp_server/__main__.py``
59+
line 22 for the server). ``DATABASE_URL`` is set to the local default
60+
only when it was unset AND the resolved backend is not ``sqlite``
61+
(mirrors ``scripts/launcher.py`` lines 135-139) -- on the SQLite backend
62+
the URL is unused, and injecting a PostgreSQL default would make every
63+
hook invocation attempt a doomed connection.
64+
"""
65+
apply_backend_resolution(environ, marker_path)
66+
backend = environ.get("CORTEX_MEMORY_STORE_BACKEND", "")
67+
if "DATABASE_URL" not in environ and backend != "sqlite":
68+
environ["DATABASE_URL"] = _DEFAULT_DATABASE_URL
69+
70+
71+
def _print_usage() -> None:
72+
names = ", ".join(sorted(HOOK_MODULES))
73+
print(
74+
f"Usage: hypermnesia-mcp-hook <module>\nAllowed modules: {names}",
75+
file=sys.stderr,
76+
)
77+
78+
79+
def main() -> None:
80+
"""Validate argv[1] against the allowlist, then dispatch to the hook.
81+
82+
Precondition: none (argv may be missing its module argument).
83+
Postcondition: exits 2 with nothing on stdout when argv[1] is absent or
84+
not in HOOK_MODULES; otherwise runs ``mcp_server.hooks.<module>``
85+
as ``__main__`` and exits with that hook's own exit code, or 1 on any
86+
exception the hook itself did not turn into a SystemExit (mirrors
87+
``scripts/launcher.py`` lines 159-167).
88+
"""
89+
name = sys.argv[1] if len(sys.argv) > 1 else None
90+
if name not in HOOK_MODULES:
91+
_print_usage()
92+
sys.exit(2)
93+
94+
prepare_environment(os.environ)
95+
96+
module = f"mcp_server.hooks.{name}"
97+
sys.argv = [module]
98+
try:
99+
runpy.run_module(module, run_name="__main__", alter_sys=True)
100+
except SystemExit:
101+
raise
102+
except Exception as exc: # noqa: BLE001 - dispatch boundary; reported, never crashes
103+
print(f"[hypermnesia-mcp-hook] Failed to run {module}: {exc}", file=sys.stderr)
104+
sys.exit(1)
105+
106+
107+
if __name__ == "__main__":
108+
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: 151 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,151 @@
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 ten hook modules the Claude Code plugin manifest wires
8+
(.claude-plugin/plugin.json) must be runnable without scripts/launcher.py.
9+
10+
Parity: mcp_server.hooks.entry must behave exactly like scripts/launcher.py
11+
for every allowlisted module on a benign event, because both are meant to
12+
run the same hook the same way -- the Codex plugin is not a second
13+
implementation of hook dispatch, it is a second caller of the same one.
14+
"""
15+
16+
from __future__ import annotations
17+
18+
import json
19+
import os
20+
import subprocess
21+
import sys
22+
import tomllib
23+
from pathlib import Path
24+
25+
import pytest
26+
27+
REPO_ROOT = Path(__file__).resolve().parents[2]
28+
LAUNCHER_PATH = REPO_ROOT / "scripts" / "launcher.py"
29+
30+
HOOK_MODULES = (
31+
"session_start",
32+
"auto_recall",
33+
"decision_gate",
34+
"no_deps_gate",
35+
"post_tool_capture",
36+
"preemptive_context",
37+
"pipeline_impact_bump",
38+
"post_commit_reindex",
39+
"session_lifecycle",
40+
"compaction_checkpoint",
41+
"agent_briefing",
42+
)
43+
44+
45+
def _benign_event(tmp_path: Path) -> str:
46+
target = tmp_path / "seen.txt"
47+
target.write_text("hello\n", encoding="utf-8")
48+
return json.dumps(
49+
{
50+
"session_id": "t",
51+
"cwd": str(tmp_path),
52+
"tool_name": "Read",
53+
"tool_input": {"file_path": str(target)},
54+
"tool_response": "",
55+
}
56+
)
57+
58+
59+
def _isolated_env(tmp_path: Path) -> dict[str, str]:
60+
home = tmp_path / "home"
61+
home.mkdir(exist_ok=True)
62+
claude_dir = tmp_path / "claude-dir"
63+
claude_dir.mkdir(exist_ok=True)
64+
env = dict(os.environ)
65+
env["HOME"] = str(home)
66+
env["CORTEX_CLAUDE_DIR"] = str(claude_dir)
67+
env["CORTEX_MEMORY_STORE_BACKEND"] = "sqlite"
68+
env["CLAUDE_PLUGIN_ROOT"] = str(REPO_ROOT)
69+
env.pop("DATABASE_URL", None)
70+
return env
71+
72+
73+
@pytest.mark.parametrize("module", HOOK_MODULES)
74+
def test_entry_matches_launcher_on_benign_event(module: str, tmp_path: Path) -> None:
75+
event = _benign_event(tmp_path)
76+
env = _isolated_env(tmp_path)
77+
78+
via_entry = subprocess.run(
79+
[sys.executable, "-m", "mcp_server.hooks.entry", module],
80+
input=event,
81+
capture_output=True,
82+
text=True,
83+
env=env,
84+
cwd=REPO_ROOT,
85+
)
86+
via_launcher = subprocess.run(
87+
[sys.executable, str(LAUNCHER_PATH), f"mcp_server.hooks.{module}"],
88+
input=event,
89+
capture_output=True,
90+
text=True,
91+
env=env,
92+
cwd=REPO_ROOT,
93+
)
94+
95+
assert via_entry.returncode == via_launcher.returncode, (
96+
via_entry.stderr,
97+
via_launcher.stderr,
98+
)
99+
assert via_entry.stdout == via_launcher.stdout
100+
101+
102+
def test_entry_refuses_a_module_outside_the_allowlist(tmp_path: Path) -> None:
103+
env = _isolated_env(tmp_path)
104+
result = subprocess.run(
105+
[
106+
sys.executable,
107+
"-m",
108+
"mcp_server.hooks.entry",
109+
"mcp_server.handlers.remember",
110+
],
111+
input="",
112+
capture_output=True,
113+
text=True,
114+
env=env,
115+
cwd=REPO_ROOT,
116+
)
117+
assert result.returncode == 2
118+
assert result.stdout == ""
119+
120+
121+
def test_prepare_environment_marker_selects_sqlite_and_skips_database_url(
122+
tmp_path: Path,
123+
) -> None:
124+
from mcp_server.hooks.entry import prepare_environment
125+
126+
marker = tmp_path / "backend.json"
127+
marker.write_text(json.dumps({"backend": "sqlite"}), encoding="utf-8")
128+
environ: dict[str, str] = {}
129+
130+
prepare_environment(environ, marker_path=marker)
131+
132+
assert environ["CORTEX_MEMORY_STORE_BACKEND"] == "sqlite"
133+
assert "DATABASE_URL" not in environ
134+
135+
136+
def test_prepare_environment_no_marker_postgresql_sets_default_database_url(
137+
tmp_path: Path,
138+
) -> None:
139+
from mcp_server.hooks.entry import prepare_environment
140+
141+
environ: dict[str, str] = {"CORTEX_MEMORY_STORE_BACKEND": "postgresql"}
142+
143+
prepare_environment(environ, marker_path=tmp_path / "absent.json")
144+
145+
assert environ["DATABASE_URL"] == "postgresql://localhost:5432/cortex"
146+
147+
148+
def test_pyproject_declares_the_console_script() -> None:
149+
data = tomllib.loads((REPO_ROOT / "pyproject.toml").read_text(encoding="utf-8"))
150+
scripts = data["project"]["scripts"]
151+
assert scripts["hypermnesia-mcp-hook"] == "mcp_server.hooks.entry:main"

0 commit comments

Comments
 (0)