Skip to content

Commit 35c6349

Browse files
davidbhowardsafishamsi
authored andcommitted
fix(install): emit a bare hook command for project-scoped installs (#3129)
A --project (committed/shared) install pinned the absolute interpreter path into the hook command, so the committed hook churned across machines. Emit a bare `graphify <sub>` command for project installs (resolved at hook-run time via the PATH/pin/uv-tool probes), while the global install still emits the absolute path (preserving the Windows VS Code Codex case). Uninstall still strips the bare command.
1 parent b568488 commit 35c6349

2 files changed

Lines changed: 170 additions & 23 deletions

File tree

‎graphify/install.py‎

Lines changed: 47 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -285,12 +285,14 @@ def _print_project_git_add_hint(paths: list[Path]) -> None:
285285
print()
286286
print("Project-scoped install. Add to version control:")
287287
print(f" git add {' '.join(unique)}")
288-
def _claude_pretooluse_hooks(strict: bool = False) -> "list[dict]":
288+
def _claude_pretooluse_hooks(strict: bool = False, project: bool = False) -> "list[dict]":
289289
"""graphify's Claude/Codebuddy PreToolUse hooks, resolved at install time.
290290
291291
The command invokes `graphify hook-guard <search|read>` via the absolute exe
292-
path (`_resolve_graphify_exe`), so it parses under sh, cmd.exe and PowerShell
293-
alike — this is the #522 fix, and mirrors the codex hook. Matchers are
292+
path (`_resolve_graphify_exe`) — or, for a project-scoped install, via the
293+
bare `graphify` command, since that config gets committed (#3129). Either
294+
form parses under sh, cmd.exe and PowerShell alike — this is the #522 fix,
295+
and mirrors the codex hook. Matchers are
294296
"Bash|Grep" and "Read|Glob" and the command always contains "graphify", so the
295297
existing install/uninstall filters find and replace both old bash hooks and
296298
these. "Grep" is in the search matcher because current Claude Code routes
@@ -301,7 +303,7 @@ def _claude_pretooluse_hooks(strict: bool = False) -> "list[dict]":
301303
first raw read per session (Claude Code only). The ``GRAPHIFY_HOOK_STRICT`` env
302304
var can force it on or off at runtime without a reinstall.
303305
"""
304-
exe = _resolve_graphify_exe()
306+
exe = _resolve_graphify_exe(project=project)
305307
if " " in exe and not exe.startswith('"'):
306308
exe = f'"{exe}"'
307309
read_cmd = f"{exe} hook-guard read" + (" --strict" if strict else "")
@@ -689,9 +691,13 @@ def _print_install_usage() -> None:
689691
_CODEBUDDY_MD_MARKER = "## graphify"
690692
_AGENTS_MD_MARKER = "## graphify"
691693
_GEMINI_MD_MARKER = "## graphify"
692-
def _gemini_hook() -> dict:
693-
"""Gemini CLI BeforeTool hook, resolved to a shell-agnostic `graphify` call."""
694-
exe = _resolve_graphify_exe()
694+
def _gemini_hook(project: bool = False) -> dict:
695+
"""Gemini CLI BeforeTool hook, resolved to a shell-agnostic `graphify` call.
696+
697+
A project-scoped install emits the bare command, since .gemini/settings.json
698+
is then committed and an installing machine's path is wrong there (#3129).
699+
"""
700+
exe = _resolve_graphify_exe(project=project)
695701
if " " in exe and not exe.startswith('"'):
696702
exe = f'"{exe}"'
697703
return {
@@ -721,7 +727,7 @@ def gemini_install(project_dir: Path | None = None, *, project: bool = False) ->
721727

722728
# Always re-install the Gemini hook so an older payload (e.g. pre-issue-#580
723729
# wording) is replaced on upgrade.
724-
_install_gemini_hook(project_dir)
730+
_install_gemini_hook(project_dir, project=project)
725731
if project:
726732
_print_project_git_add_hint([_project_scope_root(skill_dst, project_dir), project_dir / "GEMINI.md", project_dir / ".gemini"])
727733
print()
@@ -769,7 +775,7 @@ def _write_settings_with_backup(settings_path: Path, settings: dict) -> None:
769775
backup = settings_path.with_name(settings_path.name + ".graphify-bak")
770776
shutil.copy2(settings_path, backup)
771777
settings_path.write_text(output, encoding="utf-8")
772-
def _install_gemini_hook(project_dir: Path) -> None:
778+
def _install_gemini_hook(project_dir: Path, project: bool = False) -> None:
773779
settings_path = project_dir / ".gemini" / "settings.json"
774780
settings_path.parent.mkdir(parents=True, exist_ok=True)
775781
settings = _read_settings_for_merge(settings_path)
@@ -782,7 +788,7 @@ def _install_gemini_hook(project_dir: Path) -> None:
782788
hooks["BeforeTool"] = [
783789
h for h in before_tool if "graphify" not in str(h)
784790
]
785-
hooks["BeforeTool"].append(_gemini_hook())
791+
hooks["BeforeTool"].append(_gemini_hook(project=project))
786792
_write_settings_with_backup(settings_path, settings)
787793
print(" .gemini/settings.json -> BeforeTool hook registered")
788794
def _uninstall_gemini_hook(project_dir: Path) -> None:
@@ -1397,9 +1403,17 @@ def _uninstall_opencode_plugin(project_dir: Path) -> None:
13971403
config.pop("plugin")
13981404
config_file.write_text(json.dumps(config, indent=2), encoding="utf-8")
13991405
print(f" {_OPENCODE_CONFIG_PATH} -> plugin deregistered")
1400-
def _resolve_graphify_exe() -> str:
1406+
def _resolve_graphify_exe(project: bool = False) -> str:
14011407
"""Return the absolute path to the graphify executable, with forward slashes.
14021408
1409+
With *project* set, return the bare ``graphify`` command instead. A
1410+
project-scoped install writes hook config the installer then tells the user
1411+
to commit, so an absolute path resolved from the installing machine is wrong
1412+
for every other clone: it names a directory that does not exist there, and
1413+
the drive letter and ``.EXE`` casing do not even survive between two Windows
1414+
checkouts. A committed hook refers to ``graphify`` the way it would refer to
1415+
``git`` or ``node``, and PATH resolves it per machine (#3129).
1416+
14031417
Falls back to bare 'graphify' if resolution fails. Using an absolute path
14041418
ensures the hook works in environments where the venv Scripts/ directory is
14051419
not on PATH (e.g. VS Code Codex extension on Windows).
@@ -1413,6 +1427,8 @@ def _resolve_graphify_exe() -> str:
14131427
``.replace`` is a no-op on POSIX where paths already use forward slashes.
14141428
"""
14151429
import shutil
1430+
if project:
1431+
return "graphify"
14161432
found = shutil.which("graphify")
14171433
if not found:
14181434
# Derive from sys.executable: same Scripts/ (Windows) or bin/ (Unix) dir
@@ -1423,14 +1439,18 @@ def _resolve_graphify_exe() -> str:
14231439
found = str(candidate)
14241440
break
14251441
return (found or "graphify").replace("\\", "/")
1426-
def _install_codex_hook(project_dir: Path) -> None:
1427-
"""Add graphify PreToolUse hook to .codex/hooks.json."""
1442+
def _install_codex_hook(project_dir: Path, project: bool = False) -> None:
1443+
"""Add graphify PreToolUse hook to .codex/hooks.json.
1444+
1445+
A project-scoped install emits the bare command, since .codex/hooks.json is
1446+
then committed and an installing machine's path is wrong there (#3129).
1447+
"""
14281448
hooks_path = project_dir / ".codex" / "hooks.json"
14291449
hooks_path.parent.mkdir(parents=True, exist_ok=True)
14301450

14311451
existing = _read_settings_for_merge(hooks_path)
14321452

1433-
graphify_exe = _resolve_graphify_exe()
1453+
graphify_exe = _resolve_graphify_exe(project=project)
14341454
hook_entry = {
14351455
"hooks": {
14361456
"PreToolUse": [
@@ -1472,7 +1492,7 @@ def _uninstall_codex_hook(project_dir: Path) -> None:
14721492
existing["hooks"]["PreToolUse"] = filtered
14731493
hooks_path.write_text(json.dumps(existing, indent=2), encoding="utf-8")
14741494
print(f" .codex/hooks.json -> PreToolUse hook removed")
1475-
def _agents_install(project_dir: Path, platform: str) -> None:
1495+
def _agents_install(project_dir: Path, platform: str, project: bool = False) -> None:
14761496
"""Write the graphify section to the local AGENTS.md for always-on platforms."""
14771497
target = (project_dir or Path(".")) / "AGENTS.md"
14781498

@@ -1491,7 +1511,7 @@ def _agents_install(project_dir: Path, platform: str) -> None:
14911511
print(f"graphify section written to {target.resolve()}")
14921512

14931513
if platform == "codex":
1494-
_install_codex_hook(project_dir or Path("."))
1514+
_install_codex_hook(project_dir or Path("."), project=project)
14951515
elif platform == "opencode":
14961516
_install_opencode_plugin(project_dir or Path("."))
14971517
elif platform == "kilo":
@@ -1555,7 +1575,7 @@ def _project_install(platform_name: str, project_dir: Path | None = None, strict
15551575
platform_name = _canonical_platform(platform_name)
15561576
if platform_name in ("claude", "windows"):
15571577
install(platform=platform_name, project=True, project_dir=project_dir)
1558-
claude_install(project_dir, strict=strict)
1578+
claude_install(project_dir, strict=strict, project=True)
15591579
_print_project_git_add_hint([project_dir / ".claude", project_dir / "CLAUDE.md"])
15601580
elif platform_name == "gemini":
15611581
gemini_install(project_dir, project=True)
@@ -1567,7 +1587,7 @@ def _project_install(platform_name: str, project_dir: Path | None = None, strict
15671587
_print_project_git_add_hint([project_dir / ".kiro"])
15681588
elif platform_name in ("aider", "amp", "codex", "opencode", "claw", "droid", "trae", "trae-cn", "hermes"):
15691589
skill_dst = _copy_skill_file(platform_name, project=True, project_dir=project_dir)
1570-
_agents_install(project_dir, platform_name)
1590+
_agents_install(project_dir, platform_name, project=True)
15711591
hint_paths = [_project_scope_root(skill_dst, project_dir), project_dir / "AGENTS.md"]
15721592
if platform_name == "opencode":
15731593
hint_paths.append(project_dir / ".opencode")
@@ -1708,7 +1728,7 @@ def _kilo_uninstall(project_dir: Path) -> None:
17081728
_agents_uninstall(project_dir or Path("."), platform="kilo")
17091729
removed = _kilo_uninstall_global()
17101730
print("; ".join(removed) if removed else "nothing to remove")
1711-
def claude_install(project_dir: Path | None = None, strict: bool = False) -> None:
1731+
def claude_install(project_dir: Path | None = None, strict: bool = False, project: bool = False) -> None:
17121732
"""Write the graphify section to the local CLAUDE.md."""
17131733
target = (project_dir or Path(".")) / "CLAUDE.md"
17141734

@@ -1728,16 +1748,20 @@ def claude_install(project_dir: Path | None = None, strict: bool = False) -> Non
17281748

17291749
# Always re-install the Claude Code PreToolUse hook so an old hook
17301750
# payload (e.g. pre-issue-#580 wording) is replaced on upgrade.
1731-
_install_claude_hook(project_dir or Path("."), strict=strict)
1751+
_install_claude_hook(project_dir or Path("."), strict=strict, project=project)
17321752

17331753
print()
17341754
print("Claude Code will now check the knowledge graph before answering")
17351755
print("codebase questions and rebuild it after code changes.")
17361756
if strict:
17371757
print("Strict mode: the first raw file read per session is blocked until")
17381758
print("one `graphify query` runs (toggle with GRAPHIFY_HOOK_STRICT=0).")
1739-
def _install_claude_hook(project_dir: Path, strict: bool = False) -> None:
1740-
"""Add graphify PreToolUse hook to .claude/settings.json."""
1759+
def _install_claude_hook(project_dir: Path, strict: bool = False, project: bool = False) -> None:
1760+
"""Add graphify PreToolUse hook to .claude/settings.json.
1761+
1762+
A project-scoped install emits the bare command, since .claude/settings.json
1763+
is then committed and an installing machine's path is wrong there (#3129).
1764+
"""
17411765
settings_path = project_dir / ".claude" / "settings.json"
17421766
settings_path.parent.mkdir(parents=True, exist_ok=True)
17431767

@@ -1751,7 +1775,7 @@ def _install_claude_hook(project_dir: Path, strict: bool = False) -> None:
17511775
_refuse_to_modify(settings_path)
17521776

17531777
hooks["PreToolUse"] = [h for h in pre_tool if not (isinstance(h, dict) and h.get("matcher") in ("Glob|Grep", "Bash", "Bash|Grep", "Read|Glob") and "graphify" in str(h))]
1754-
hooks["PreToolUse"].extend(_claude_pretooluse_hooks(strict=strict))
1778+
hooks["PreToolUse"].extend(_claude_pretooluse_hooks(strict=strict, project=project))
17551779
_write_settings_with_backup(settings_path, settings)
17561780
_mode = " (strict)" if strict else ""
17571781
print(f" .claude/settings.json -> PreToolUse hooks registered (Bash|Grep search + Read/Glob){_mode}")

‎tests/test_install.py‎

Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1218,3 +1218,126 @@ def test_codex_hook_command_is_a_real_cli_subcommand(tmp_path):
12181218
f"codex hook registers {subcommand!r}, which the CLI does not dispatch "
12191219
f"(#2165). Known commands: {sorted(dispatched)}"
12201220
)
1221+
1222+
1223+
# --- #3129: project-scoped installs must not embed a machine-absolute path ----
1224+
#
1225+
# `--project` writes hook config that the installer then tells the user to
1226+
# commit ("Add to version control: git add ..."). An exe path resolved from the
1227+
# installing machine is wrong in every other clone, and the drive letter and
1228+
# .EXE casing do not even survive between two Windows checkouts. The committed
1229+
# hook must name `graphify` and let PATH resolve it, the way the git-hook layer
1230+
# already does with `command -v graphify` (hooks.py). The user-profile install
1231+
# is deliberately left alone: it stays on the machine that wrote it, and an
1232+
# absolute path is what makes the hook work where the venv Scripts/ dir is not
1233+
# on PATH (e.g. the VS Code Codex extension on Windows).
1234+
1235+
_PROJECT_HOOK_FILES = {
1236+
"claude": ".claude/settings.json",
1237+
"codex": ".codex/hooks.json",
1238+
"gemini": ".gemini/settings.json",
1239+
}
1240+
1241+
1242+
def _hook_commands(text: str) -> list:
1243+
"""Every hook command string in a settings/hooks JSON document."""
1244+
import json as _json
1245+
1246+
doc = _json.loads(text)
1247+
found = []
1248+
for groups in doc.get("hooks", {}).values():
1249+
for group in groups:
1250+
for hook in group.get("hooks", []):
1251+
if "command" in hook:
1252+
found.append(hook["command"])
1253+
return found
1254+
1255+
1256+
def _run_project_install(project, home, platform):
1257+
from graphify.__main__ import main
1258+
1259+
with patch("graphify.__main__.Path.home", return_value=home):
1260+
with patch("sys.argv", ["graphify", "install", "--project", "--platform", platform]):
1261+
main()
1262+
1263+
1264+
@pytest.mark.parametrize("platform", sorted(_PROJECT_HOOK_FILES))
1265+
def test_project_install_hook_command_is_portable(tmp_path, monkeypatch, platform):
1266+
"""A committed hook must carry no absolute path, drive letter or .EXE casing."""
1267+
home = tmp_path / "home"
1268+
project = tmp_path / "project"
1269+
project.mkdir()
1270+
monkeypatch.chdir(project)
1271+
# Resolution would otherwise find a real graphify on this machine; pin it so
1272+
# the assertion fails loudly if the project path ever resolves again.
1273+
monkeypatch.setattr("shutil.which", lambda _name: r"C:\Users\installer\graphify.EXE")
1274+
1275+
_run_project_install(project, home, platform)
1276+
1277+
commands = _hook_commands((project / _PROJECT_HOOK_FILES[platform]).read_text(encoding="utf-8"))
1278+
assert commands, f"{platform} project install registered no hook command"
1279+
for command in commands:
1280+
assert command.startswith("graphify "), command
1281+
assert ":" not in command, f"drive letter / absolute path leaked: {command}"
1282+
assert "\\" not in command, f"backslash path leaked: {command}"
1283+
assert ".exe" not in command.lower(), f"platform exe casing leaked: {command}"
1284+
assert "installer" not in command, f"installing user's path leaked: {command}"
1285+
1286+
1287+
@pytest.mark.parametrize("platform", sorted(_PROJECT_HOOK_FILES))
1288+
def test_user_profile_install_still_resolves_absolute_path(tmp_path, monkeypatch, platform):
1289+
"""The non-project install keeps the resolved path (#522/#1987 behaviour)."""
1290+
home = tmp_path / "home"
1291+
project = tmp_path / "project"
1292+
project.mkdir()
1293+
monkeypatch.chdir(project)
1294+
monkeypatch.setattr("shutil.which", lambda _name: r"C:\Users\installer\graphify.EXE")
1295+
1296+
from graphify.__main__ import main
1297+
1298+
with patch("graphify.__main__.Path.home", return_value=home):
1299+
with patch("sys.argv", ["graphify", platform, "install"]):
1300+
main()
1301+
1302+
commands = _hook_commands((project / _PROJECT_HOOK_FILES[platform]).read_text(encoding="utf-8"))
1303+
assert commands, f"{platform} install registered no hook command"
1304+
for command in commands:
1305+
assert command.startswith("C:/Users/installer/graphify.EXE "), command
1306+
1307+
1308+
@pytest.mark.parametrize("platform", sorted(_PROJECT_HOOK_FILES))
1309+
def test_project_install_is_idempotent(tmp_path, monkeypatch, platform):
1310+
"""Installing twice leaves byte-identical config (no churn on re-install)."""
1311+
home = tmp_path / "home"
1312+
project = tmp_path / "project"
1313+
project.mkdir()
1314+
monkeypatch.chdir(project)
1315+
monkeypatch.setattr("shutil.which", lambda _name: r"C:\Users\installer\graphify.EXE")
1316+
target = project / _PROJECT_HOOK_FILES[platform]
1317+
1318+
_run_project_install(project, home, platform)
1319+
first = target.read_text(encoding="utf-8")
1320+
_run_project_install(project, home, platform)
1321+
1322+
assert target.read_text(encoding="utf-8") == first
1323+
1324+
1325+
def test_project_uninstall_removes_the_bare_hook_command(tmp_path, monkeypatch):
1326+
"""The uninstall filter matches on "graphify", so a bare command still goes."""
1327+
from graphify.__main__ import main
1328+
1329+
home = tmp_path / "home"
1330+
project = tmp_path / "project"
1331+
project.mkdir()
1332+
monkeypatch.chdir(project)
1333+
monkeypatch.setattr("shutil.which", lambda _name: r"C:\Users\installer\graphify.EXE")
1334+
1335+
_run_project_install(project, home, "claude")
1336+
settings = project / ".claude" / "settings.json"
1337+
assert any("hook-guard" in c for c in _hook_commands(settings.read_text(encoding="utf-8")))
1338+
1339+
with patch("graphify.__main__.Path.home", return_value=home):
1340+
with patch("sys.argv", ["graphify", "claude", "uninstall", "--project"]):
1341+
main()
1342+
1343+
assert not [c for c in _hook_commands(settings.read_text(encoding="utf-8")) if "graphify" in c]

0 commit comments

Comments
 (0)