fix(install): remove only graphify's own hook entries, keep others (#4359)

Hook install/uninstall identified graphify's hooks with
`"graphify" in str(group)` over the whole group dict. That removed a user's
own command sharing graphify's `hooks` array (with the whole group), and any
unrelated group whose command path merely contained the word "graphify" (e.g.
a script under `graphify-notes/`). Uninstall rewrote the settings file with no
backup, and `_strip_graphify_hook` raised AttributeError on a non-dict entry.

Match the individual `hooks[]` entries instead. A graphify entry is a command
hook whose command invokes graphify's own `hook-guard`/`hook-check` subcommands
(current installs) or references `graphify-out/` (the pre-#522 inline bash
guard). Only those entries are removed; a group is dropped only when nothing is
left in it, and non-dict/non-list shapes are passed through. Applies to the
Claude, CodeBuddy, Codex and Gemini install and uninstall filters, keeping them
in step. Uninstall now goes through `_write_settings_with_backup`, so it keeps
a rolling `.graphify-bak` like install already did.

Adds tests covering a user command sharing graphify's group, an unrelated group
whose path contains "graphify", a non-dict entry, and the legacy-bash replacement
plus idempotency for each host.

(cherry picked from commit 41310c256d)
This commit is contained in:
N. Hariharan authored and safishamsi committed 2026-10-12 22:37:54 +01:00
1 parent 804b7933cd
commit c3d537ae4a
2 files changed
+293 -17

No files matched your search

+90 -17
View File
@@ -478,6 +478,71 @@ def _claude_pretooluse_hooks(strict: bool = False, project: bool = False) -> "li
{"matcher": "Read|Glob",
"hooks": [{"type": "command", "command": read_cmd, "timeout": 10}]},
]
# Tokens that only ever appear in a command graphify itself writes: its
# `hook-guard <search|read|gemini>` and `hook-check` subcommands. Legacy
# (pre-#522) installs shipped an inline POSIX bash guard instead, whose command
# always gated on graphify's own output dir, so that marker identifies it too.
_GRAPHIFY_HOOK_SUBCOMMANDS = ("hook-guard", "hook-check")
_GRAPHIFY_LEGACY_HOOK_MARKER = "graphify-out/"
def _is_graphify_hook_command(command: str) -> bool:
"""True when a hook ``command`` string is one graphify installed.
Matches graphify's own guard/check subcommands (current installs) or the
``graphify-out/`` path its pre-#522 inline bash guard gated on (legacy
installs). Deliberately command-scoped: the old ``"graphify" in str(group)``
match also caught an unrelated group whose command path merely contained the
word "graphify" (#4359).
"""
lowered = command.lower()
if "graphify" not in lowered:
return False
if any(sub in lowered for sub in _GRAPHIFY_HOOK_SUBCOMMANDS):
return True
return _GRAPHIFY_LEGACY_HOOK_MARKER in lowered
def _is_graphify_hook_entry(entry: object) -> bool:
"""True when a single ``hooks[]`` element is a graphify command entry.
Non-dict and non-command entries are never graphify's (the old uninstall
filter called ``.get`` on every entry and raised ``AttributeError`` on a
plain string, #4359).
"""
if not isinstance(entry, dict) or entry.get("type") != "command":
return False
command = entry.get("command")
return isinstance(command, str) and _is_graphify_hook_command(command)
def _strip_graphify_hooks(groups: "list") -> "list":
"""Drop graphify's own hook entries from *groups*, keeping everything else.
Only the individual entries graphify installed are removed, so a user
command sharing graphify's group survives and a group is dropped only once
removal leaves it with no hooks. Non-dict groups and non-list ``hooks`` are
passed through untouched, and a group without a graphify entry is never
rewritten. This replaces the old group-level ``"graphify" in str(group)``
filter, which removed whole groups (and other tools' commands in them) and
any unrelated group whose command path happened to contain the word (#4359).
"""
kept: "list" = []
for group in groups:
if not isinstance(group, dict):
kept.append(group)
continue
entries = group.get("hooks")
if not isinstance(entries, list):
kept.append(group)
continue
remaining = [e for e in entries if not _is_graphify_hook_entry(e)]
if len(remaining) == len(entries):
kept.append(group) # nothing of ours in this group
elif remaining:
kept.append({**group, "hooks": remaining})
# else: the group held only graphify commands -- drop it entirely.
return kept
def _skill_registration(skill_path: str = "~/.claude/skills/graphify/SKILL.md") -> str:
# Heading is "# graphify" (H1) to match _SKILL_REGISTRATION_MARKER, which
# _register_always_on_block anchors its idempotent replace-or-append on.
@@ -1008,9 +1073,7 @@ def _install_gemini_hook(project_dir: Path, project: bool = False) -> None:
before_tool = hooks.setdefault("BeforeTool", [])
if not isinstance(before_tool, list):
_refuse_to_modify(settings_path)
hooks["BeforeTool"] = [
h for h in before_tool if "graphify" not in str(h)
]
hooks["BeforeTool"] = _strip_graphify_hooks(before_tool)
hooks["BeforeTool"].append(_gemini_hook(project=project))
_write_settings_with_backup(settings_path, settings)
print(" .gemini/settings.json -> BeforeTool hook registered")
@@ -1023,11 +1086,13 @@ def _uninstall_gemini_hook(project_dir: Path) -> None:
except json.JSONDecodeError:
return
before_tool = settings.get("hooks", {}).get("BeforeTool", [])
filtered = [h for h in before_tool if "graphify" not in str(h)]
if len(filtered) == len(before_tool):
if not isinstance(before_tool, list):
return
filtered = _strip_graphify_hooks(before_tool)
if filtered == before_tool:
return
settings["hooks"]["BeforeTool"] = filtered
settings_path.write_text(json.dumps(settings, indent=2), encoding="utf-8")
_write_settings_with_backup(settings_path, settings)
print(" .gemini/settings.json -> BeforeTool hook removed")
def gemini_uninstall(project_dir: Path | None = None, *, project: bool = False, remove_user_skill: bool | None = None) -> None:
"""Remove the graphify section from GEMINI.md, uninstall hook, and remove skill file.
@@ -1767,7 +1832,7 @@ def _install_codex_hook(project_dir: Path, project: bool = False) -> None:
pre_tool = hooks.setdefault("PreToolUse", [])
if not isinstance(pre_tool, list):
_refuse_to_modify(hooks_path)
hooks["PreToolUse"] = [h for h in pre_tool if "graphify" not in str(h)]
hooks["PreToolUse"] = _strip_graphify_hooks(pre_tool)
hooks["PreToolUse"].extend(hook_entry["hooks"]["PreToolUse"])
_write_settings_with_backup(hooks_path, existing)
print(
@@ -1787,9 +1852,13 @@ def _uninstall_codex_hook(project_dir: Path) -> None:
except json.JSONDecodeError:
return
pre_tool = existing.get("hooks", {}).get("PreToolUse", [])
filtered = [h for h in pre_tool if "graphify" not in str(h)]
if not isinstance(pre_tool, list):
return
filtered = _strip_graphify_hooks(pre_tool)
if filtered == pre_tool:
return
existing["hooks"]["PreToolUse"] = filtered
hooks_path.write_text(json.dumps(existing, indent=2), encoding="utf-8")
_write_settings_with_backup(hooks_path, existing)
print(f" .codex/hooks.json -> PreToolUse hook removed")
def _agents_install(project_dir: Path, platform: str, project: bool = False) -> None:
"""Write the graphify section to the local AGENTS.md for always-on platforms."""
@@ -2075,7 +2144,7 @@ def _install_claude_hook(project_dir: Path, strict: bool = False, project: bool
if not isinstance(pre_tool, list):
_refuse_to_modify(settings_path)
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))]
hooks["PreToolUse"] = _strip_graphify_hooks(pre_tool)
hooks["PreToolUse"].extend(_claude_pretooluse_hooks(strict=strict, project=project))
_write_settings_with_backup(settings_path, settings)
_mode = " (strict)" if strict else ""
@@ -2099,11 +2168,13 @@ def _strip_graphify_hook(settings_path: Path) -> None:
except json.JSONDecodeError:
return
pre_tool = settings.get("hooks", {}).get("PreToolUse", [])
filtered = [h for h in pre_tool if not (h.get("matcher") in ("Glob|Grep", "Bash", "Bash|Grep", "Read|Glob") and "graphify" in str(h))]
if len(filtered) == len(pre_tool):
if not isinstance(pre_tool, list):
return
filtered = _strip_graphify_hooks(pre_tool)
if filtered == pre_tool:
return
settings["hooks"]["PreToolUse"] = filtered
settings_path.write_text(json.dumps(settings, indent=2), encoding="utf-8")
_write_settings_with_backup(settings_path, settings)
print(f" .claude/{settings_path.name} -> PreToolUse hook removed")
@@ -2289,7 +2360,7 @@ def _install_codebuddy_hook(project_dir: Path) -> None:
if not isinstance(pre_tool, list):
_refuse_to_modify(settings_path)
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))]
hooks["PreToolUse"] = _strip_graphify_hooks(pre_tool)
hooks["PreToolUse"].extend(_claude_pretooluse_hooks())
_write_settings_with_backup(settings_path, settings)
print(f" .codebuddy/settings.json -> PreToolUse hooks registered")
@@ -2303,11 +2374,13 @@ def _uninstall_codebuddy_hook(project_dir: Path) -> None:
except json.JSONDecodeError:
return
pre_tool = settings.get("hooks", {}).get("PreToolUse", [])
filtered = [h for h in pre_tool if not (h.get("matcher") in ("Glob|Grep", "Bash", "Bash|Grep", "Read|Glob") and "graphify" in str(h))]
if len(filtered) == len(pre_tool):
if not isinstance(pre_tool, list):
return
filtered = _strip_graphify_hooks(pre_tool)
if filtered == pre_tool:
return
settings["hooks"]["PreToolUse"] = filtered
settings_path.write_text(json.dumps(settings, indent=2), encoding="utf-8")
_write_settings_with_backup(settings_path, settings)
print(f" .codebuddy/settings.json -> PreToolUse hook removed")
def codebuddy_uninstall(project_dir: Path | None = None, *, project: bool = False, remove_user_skill: bool | None = None) -> None:
"""Remove the graphify skill tree (SKILL.md + references/) and the CODEBUDDY.md section.
+203
View File
@@ -0,0 +1,203 @@
"""Hook install/uninstall must remove only graphify's own hook entries (#4359).
Install and uninstall used to identify graphify's hooks with
``"graphify" in str(group)`` over the whole group dict. That removed:
- a user's own command sharing graphify's ``hooks`` array, along with the group;
- an unrelated group whose command path merely contained the word ``graphify``
(e.g. a script under a folder named ``graphify-notes``);
- and, on uninstall, wrote the settings file back with no backup while
``_strip_graphify_hook`` raised ``AttributeError`` on a non-dict entry.
These tests pin the entry-scoped contract: only entries graphify installed go,
a group is dropped only when nothing is left in it, other tools' commands
survive, and uninstall keeps a rolling backup.
"""
from __future__ import annotations
import json
import pytest
from graphify import install as install_mod
# id -> (install, uninstall, settings file relative to project, section key)
_INSTALLERS = {
"claude": (
lambda project: install_mod._install_claude_hook(project),
lambda project: install_mod._uninstall_claude_hook(project),
".claude/settings.json",
"PreToolUse",
),
"codebuddy": (
lambda project: install_mod._install_codebuddy_hook(project),
lambda project: install_mod._uninstall_codebuddy_hook(project),
".codebuddy/settings.json",
"PreToolUse",
),
"codex": (
lambda project: install_mod._install_codex_hook(project),
lambda project: install_mod._uninstall_codex_hook(project),
".codex/hooks.json",
"PreToolUse",
),
"gemini": (
lambda project: install_mod._install_gemini_hook(project),
lambda project: install_mod._uninstall_gemini_hook(project),
".gemini/settings.json",
"BeforeTool",
),
}
def _groups(settings: dict, section: str) -> list:
return settings["hooks"][section]
def _has_graphify(entry: object) -> bool:
return install_mod._is_graphify_hook_entry(entry)
@pytest.mark.parametrize("name", sorted(_INSTALLERS))
def test_uninstall_keeps_user_commands_and_unrelated_groups(tmp_path, name):
install, uninstall, rel, section = _INSTALLERS[name]
project = tmp_path / "proj"
project.mkdir()
install(project)
settings_path = project / rel
settings = json.loads(settings_path.read_text(encoding="utf-8"))
groups = _groups(settings, section)
assert any(
_has_graphify(e) for g in groups if isinstance(g, dict) for e in g.get("hooks", [])
), f"{name} install registered no graphify hook"
# 1) the user adds their own command to graphify's own group;
# 2) an unrelated guard group whose command path contains "graphify".
for group in groups:
if isinstance(group, dict) and any(_has_graphify(e) for e in group.get("hooks", [])):
group["hooks"].append({"type": "command", "command": "python /tools/my-linter.py"})
break
groups.append(
{
"matcher": "Bash",
"hooks": [{"type": "command", "command": "python /tools/graphify-notes/check.py"}],
}
)
settings_path.write_text(json.dumps(settings, indent=2), encoding="utf-8")
uninstall(project)
after = settings_path.read_text(encoding="utf-8")
assert "my-linter" in after, f"{name}: the user's command in graphify's group was removed"
assert "graphify-notes" in after, f"{name}: the unrelated group was removed"
assert "hook-guard" not in after and "hook-check" not in after, (
f"{name}: graphify's own hook commands were not removed"
)
backup = settings_path.with_name(settings_path.name + ".graphify-bak")
assert backup.exists(), f"{name}: uninstall wrote no backup"
@pytest.mark.parametrize("name", sorted(_INSTALLERS))
def test_uninstall_survives_a_non_dict_entry(tmp_path, name):
"""#4359: a plain string in the hook array must not crash uninstall, and must
be preserved (it is not graphify's)."""
install, uninstall, rel, section = _INSTALLERS[name]
project = tmp_path / "proj"
project.mkdir()
install(project)
settings_path = project / rel
settings = json.loads(settings_path.read_text(encoding="utf-8"))
_groups(settings, section).append("a-legacy-string-entry")
settings_path.write_text(json.dumps(settings, indent=2), encoding="utf-8")
uninstall(project) # must not raise
after = json.loads(settings_path.read_text(encoding="utf-8"))
assert "a-legacy-string-entry" in _groups(after, section)
def test_install_removes_legacy_bash_hook_and_stays_idempotent(tmp_path):
"""The pre-#522 inline bash guard is still replaced, without duplicating
graphify's groups on a re-run."""
project = tmp_path / "proj"
settings_path = project / ".claude" / "settings.json"
settings_path.parent.mkdir(parents=True)
settings_path.write_text(
json.dumps(
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "[ -f graphify-out/graph.json ] && echo x || true",
}
],
}
]
}
}
),
encoding="utf-8",
)
install_mod._install_claude_hook(project)
install_mod._install_claude_hook(project)
groups = json.loads(settings_path.read_text(encoding="utf-8"))["hooks"]["PreToolUse"]
assert "graphify-out/graph.json" not in json.dumps(groups), "legacy bash guard survived"
assert len([g for g in groups if "graphify" in json.dumps(g)]) == 2, "not idempotent"
@pytest.mark.parametrize(
"command",
[
"graphify hook-guard search",
'"C:/tools/graphify.EXE" hook-guard read --strict',
"graphify hook-guard gemini",
"graphify hook-check",
"[ -f graphify-out/graph.json ] && echo x || true",
],
)
def test_graphify_commands_are_recognised(command):
assert install_mod._is_graphify_hook_command(command)
@pytest.mark.parametrize(
"command",
[
"python /tools/graphify-notes/check.py",
"python /tools/check.py",
"eslint .",
"",
],
)
def test_other_commands_are_not_recognised(command):
assert not install_mod._is_graphify_hook_command(command)
def test_strip_drops_only_emptied_groups_and_passes_malformed_through():
groups = [
{
"matcher": "Bash|Grep",
"hooks": [
{"type": "command", "command": "graphify hook-guard search"},
{"type": "command", "command": "my-own-command"},
],
},
{"matcher": "Read|Glob", "hooks": [{"type": "command", "command": "graphify hook-guard read"}]},
"not-a-dict",
{"matcher": "Bash", "hooks": "not-a-list"},
]
out = install_mod._strip_graphify_hooks(groups)
assert out == [
{"matcher": "Bash|Grep", "hooks": [{"type": "command", "command": "my-own-command"}]},
"not-a-dict",
{"matcher": "Bash", "hooks": "not-a-list"},
]