Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
590fe89
Stop install-hooks on a settings section of the wrong type
felladrin Nov 5, 2026
e22df62
Read a malformed settings file in doctor like one that is not JSON
felladrin Nov 5, 2026
5564e3c
Merge remote-tracking branch 'origin/main' into reject-malformed-sett…
felladrin Nov 5, 2026
ad36111
Stop install-hooks on a PreToolUse entry Claude Code cannot load
felladrin Nov 5, 2026
1f00690
Merge remote-tracking branch 'origin/reject-malformed-settings-shapes…
felladrin Nov 5, 2026
aeb41d1
Ask claude doctor whether Claude Code applies the settings file
felladrin Nov 5, 2026
70f7c24
Show the hook as not installed next to a PreToolUse entry Claude Code…
felladrin Nov 5, 2026
cdf1fd5
Test the claude doctor verdicts and keep the real claude out of the s…
felladrin Nov 5, 2026
3250846
Merge remote-tracking branch 'origin/doctor-malformed-settings' into …
felladrin Nov 5, 2026
1a31077
Expect a warning from doctor for a settings file it cannot read
felladrin Nov 5, 2026
4e84673
Document that install-hooks and doctor ask claude doctor about the se…
felladrin Nov 5, 2026
5f1e135
Name the npm debug log that claude doctor writes in the home folder
felladrin Nov 5, 2026
49897ad
Point the home tilde at the test folder on Windows too
felladrin Nov 5, 2026
b481eff
Say in the changelog that doctor warns on a settings file it cannot read
felladrin Nov 5, 2026
b65b7d9
Count claude doctor's entry ignored. line as Claude Code dropping onl…
felladrin Nov 6, 2026
dad1e75
Merge remote-tracking branch 'origin/main' into issue-166
felladrin Nov 6, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 21 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,24 @@

## Unreleased

- `keyfence install-hooks claude-code` and `keyfence doctor` reported
the hook as installed in a `settings.json` that Claude Code does not
apply. Claude Code ignores the whole file when one `PreToolUse` entry
in it cannot be loaded, such as one whose `matcher` is not a string or
whose command hook has no `command`. Both now run `claude doctor`:
`install-hooks` stops before it writes when Claude Code reports the
file, and `doctor` fails both Claude Code hook checks for it with the
reason Claude Code gives. A malformed `UserPromptSubmit` entry or deny
value does not count, because Claude Code drops only that entry. When
`claude` is not on `PATH`, times out or prints something keyfence does
not recognise, `doctor` warns that the hook is not confirmed and
`install-hooks` says how to check, instead of printing `ok`. Running
`claude doctor` writes `~/.claude.json`, files under `~/.claude` and a
debug log under `~/.npm/_logs`.
- `keyfence doctor` showed the hook as not installed for a settings file
it could not read, without saying why, and crashed with a
`PermissionError` on one it had no permission to read. It now warns
with the file and the reason.
- `keyfence install-hooks claude-code`, with or without `--remove`,
crashed with an `AttributeError` on a `settings.json` whose `hooks` or
`permissions` was not an object, or whose `PreToolUse`,
Expand All @@ -16,8 +34,9 @@
that entry.
- `keyfence doctor` and `keyfence install-hooks --list` crashed with an
`AttributeError` on the same files. They now read such a file the way
they read one that is not valid JSON: the hook shows as not installed,
and `keyfence install-hooks claude-code` names the key to fix. A
they read one that is not valid JSON: `doctor` warns with the file and
the key to fix, `--list` shows the hook as not installed, and
`keyfence install-hooks claude-code` names the key too. A
`PreToolUse` entry that Claude Code cannot load counts the same way,
so a file keyfence installed into earlier no longer shows the hook as
installed while Claude Code applies none of it.
Expand Down
13 changes: 13 additions & 0 deletions docs/setup.md
Original file line number Diff line number Diff line change
Expand Up @@ -238,6 +238,19 @@ keyfence install-hooks claude-code --remove # takes out only what keyf
keyfence install-hooks claude-code --remove --force # also deny rules an install before 0.5.0 left unrecorded
```

Claude Code applies nothing in a `settings.json` that holds a `PreToolUse`
entry it cannot load, so the hook and the deny rules in that file are off.
keyfence cannot follow Claude Code's schema from release to release, so it
asks Claude Code: before it writes, `install-hooks claude-code` runs
`claude doctor` and stops when it reports that file, and `keyfence doctor`
does the same for each scope that holds the hook and fails the check. When
`claude` is not on `PATH`, does not answer within 10 seconds, or prints
something keyfence does not recognise, both say the file is not confirmed
and point at `claude doctor`. `claude doctor` writes `~/.claude.json`, a
backup of it under `~/.claude/backups`, telemetry files under
`~/.claude/telemetry` and a debug log under `~/.npm/_logs`, so running
either keyfence command touches those.

The same hook ships as a Claude Code plugin, together with `/keyfence:status`
and `/keyfence:setup`. In the plugin the hook is a self-contained Python 3
file, so it protects you even before keyfence itself is installed. Inside
Expand Down
8 changes: 8 additions & 0 deletions keyfence/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -325,6 +325,11 @@ def cmd_install_hooks(args) -> int:
path = hooks.settings_path(args.project)
if args.remove:
return _remove_claude_code(path, args.force)
verdict, reason = doctor.claude_verdicts([path])[path]
if verdict == doctor.FAIL:
print(f"error: Claude Code does not apply {path}: {reason}; fix or remove that entry, then run this again",
file=sys.stderr)
return 1
changed = hooks.install(path, hooks.keyfence_path())
scope = "this project" if args.project else "all projects"
if changed:
Expand All @@ -343,6 +348,9 @@ def cmd_install_hooks(args) -> int:
else:
print(f"Hook already present in {path}.")
_print_deny_rule_versions()
if verdict == doctor.WARN:
print(f"Could not confirm that Claude Code applies {path} ({reason}); claude doctor in {Path.cwd()} lists "
"the settings files it does not apply.")
return 0


Expand Down
141 changes: 123 additions & 18 deletions keyfence/doctor.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,11 @@
from .vault import Vault, VaultError

OK, INFO, WARN, FAIL = "ok", "info", "warn", "fail"
CLAUDE_TIMEOUT = 10
CLAUDE_DOCTOR_HEADER = "Claude Code doctor"
CLAUDE_REJECTS = "nothing it sits in is applied"
CLAUDE_DROPS_ONLY = ("matcher ignored.", "was removed", "This field was ignored.", "entry ignored.")
REASON_LIMIT = 200


@dataclass
Expand Down Expand Up @@ -214,26 +219,89 @@ def check_local_mode(run: Callable = _run) -> Check:
return Check(WARN, "--local capture", "network extension waiting for approval in System Settings > General > Login Items & Extensions > Network Extensions")


def claude_doctor(cwd: Path | None = None, which: Callable = shutil.which) -> tuple[int, str] | str:
claude = which("claude")
if claude is None:
return "claude is not on PATH"
try:
done = subprocess.run([claude, "doctor"], capture_output=True, text=True, timeout=CLAUDE_TIMEOUT,
cwd=cwd, stdin=subprocess.DEVNULL)
except subprocess.TimeoutExpired:
return f"claude doctor did not finish in {CLAUDE_TIMEOUT}s"
except OSError as exc:
return f"claude doctor did not start: {exc.strerror or exc}"
return done.returncode, done.stdout + done.stderr


def _capped(text: str) -> str:
return text if len(text) <= REASON_LIMIT else text[:REASON_LIMIT - 3] + "..."


def _same_file(shown: str, path: Path) -> bool:
return os.path.normcase(os.path.realpath(os.path.expanduser(shown))) == os.path.normcase(os.path.realpath(path))


def _claude_verdict(path: Path, output: str) -> tuple[str, str]:
found = []
for line in output.splitlines():
if not line.startswith("- "):
continue
shown, sep, text = line[2:].partition(" › ")
if not sep:
shown, sep, text = line[2:].partition(": ")
if sep and _same_file(shown, path):
found.append(text.strip())
rejected = [text for text in found if CLAUDE_REJECTS in text]
if rejected:
return FAIL, _capped(rejected[0].split(" — ")[0])
unknown = [text for text in found if not text.endswith(CLAUDE_DROPS_ONLY)]
if unknown:
return WARN, f'claude doctor reports "{_capped(unknown[0])}" for {path}, which keyfence does not recognise'
return OK, ""


def claude_verdicts(paths: list[Path], cwd: Path | None = None) -> dict[Path, tuple[str, str]]:
answer = claude_doctor(cwd)
if isinstance(answer, str):
return {path: (WARN, answer) for path in paths}
code, output = answer
if code != 0:
return {path: (WARN, f"claude doctor exited {code}") for path in paths}
if CLAUDE_DOCTOR_HEADER not in (line.strip() for line in output.splitlines()):
return {path: (WARN, "keyfence does not recognise what claude doctor printed") for path in paths}
return {path: _claude_verdict(path, output) for path in paths}


def settings_problem(path: Path) -> str | None:
try:
hooks._read_settings(path)
except OSError as exc:
return f"cannot read {path}: {exc.strerror or exc}"
except ValueError as exc:
return str(exc) if str(path) in str(exc) else f"cannot read {path}: {exc}"
return None


def hook_installed(path: Path) -> bool:
try:
data = hooks._read_settings(path)
except ValueError:
except (OSError, ValueError):
return False
return any(hooks._is_ours(e) for e in data.get("hooks", {}).get("PreToolUse", []))


def prompt_hook_installed(path: Path) -> bool:
try:
data = hooks._read_settings(path)
except ValueError:
except (OSError, ValueError):
return False
return any(hooks._is_ours(e) for e in data.get("hooks", {}).get("UserPromptSubmit", []))


def keyfence_hook(path: Path, event: str) -> dict | None:
try:
data = hooks._read_settings(path)
except ValueError:
except (OSError, ValueError):
return None
for entry in data.get("hooks", {}).get(event, []):
if hooks._is_ours(entry):
Expand Down Expand Up @@ -286,9 +354,39 @@ def prompt_hook_scopes(agent: str, cwd: Path | None = None) -> list[tuple[str, P
for scope, path in (("global", hooks.settings_path(False)), ("project", hooks.settings_path(True, cwd)))]


def check_hook(cwd: Path | None = None) -> Check:
scopes = []
def _claude_hook_check(label: str, found: list[tuple[str, Path]], unreadable: list[str], missing: Check,
cwd: Path | None, verdicts: dict[Path, tuple[str, str]] | None) -> Check:
if not found:
if unreadable:
return Check(WARN, label, f"{unreadable[0]}; keyfence cannot tell whether its hook is in it")
return missing
scopes = ", ".join(scope for scope, _ in found)
if verdicts is None:
verdicts = claude_verdicts([path for _, path in found], cwd)
unconfirmed = []
for scope, path in found:
status, reason = verdicts[path]
if status == FAIL:
return Check(FAIL, label, f"installed ({scope}) but Claude Code does not apply {path}: {reason}; the hooks "
"and deny rules in that file are off until that entry is fixed or removed")
if status == WARN:
unconfirmed.append(reason)
if unreadable:
return Check(WARN, label, f"installed ({scopes}), but {unreadable[0]}; keyfence cannot tell whether its hook is in it")
if unconfirmed:
return Check(WARN, label, f"installed ({scopes}), not confirmed: {unconfirmed[0]}; claude doctor in "
f"{cwd or Path.cwd()} lists any settings file Claude Code does not apply under "
"\"Invalid settings\"")
return Check(OK, label, f"installed ({scopes})")


def check_hook(cwd: Path | None = None, verdicts: dict[Path, tuple[str, str]] | None = None) -> Check:
scopes, unreadable = [], []
for scope, path in (("global", hooks.settings_path(False)), ("project", hooks.settings_path(True, cwd))):
problem = settings_problem(path)
if problem:
unreadable.append(problem)
continue
if not hook_installed(path):
continue
hook = keyfence_hook(path, "PreToolUse")
Expand All @@ -301,15 +399,19 @@ def check_hook(cwd: Path | None = None) -> Check:
return Check(FAIL, "Claude Code hook",
f"installed ({scope}) but the {scope} hook calls {_hook_display(hook)}, which {problem}; every Claude Code "
"tool call is refused until keyfence install-hooks claude-code runs again")
scopes.append(scope)
if scopes:
return Check(OK, "Claude Code hook", "installed (" + ", ".join(scopes) + ")")
return Check(INFO, "Claude Code hook", "not installed; keyfence install-hooks claude-code stops Claude Code from reading secret files")
scopes.append((scope, path))
return _claude_hook_check("Claude Code hook", scopes, unreadable, Check(
INFO, "Claude Code hook", "not installed; keyfence install-hooks claude-code stops Claude Code from reading secret files"),
cwd, verdicts)


def check_prompt_hook(cwd: Path | None = None) -> Check:
scopes = []
def check_prompt_hook(cwd: Path | None = None, verdicts: dict[Path, tuple[str, str]] | None = None) -> Check:
scopes, unreadable = [], []
for scope, path in (("global", hooks.settings_path(False)), ("project", hooks.settings_path(True, cwd))):
problem = settings_problem(path)
if problem:
unreadable.append(problem)
continue
if not prompt_hook_installed(path):
continue
hook = keyfence_hook(path, "UserPromptSubmit")
Expand All @@ -322,11 +424,11 @@ def check_prompt_hook(cwd: Path | None = None) -> Check:
return Check(FAIL, "Claude Code prompt hook",
f"installed ({scope}) but the {scope} hook calls {_hook_display(hook)}, which {problem}; every submitted prompt "
"is refused until keyfence install-hooks claude-code runs again")
scopes.append(scope)
if scopes:
return Check(OK, "Claude Code prompt hook", "installed (" + ", ".join(scopes) + ")")
return Check(INFO, "Claude Code prompt hook",
f"not installed; keyfence install-hooks claude-code adds it (needs Claude Code v{hooks.PROMPT_HOOK_MIN_CLAUDE_CODE}+)")
scopes.append((scope, path))
return _claude_hook_check("Claude Code prompt hook", scopes, unreadable, Check(
INFO, "Claude Code prompt hook",
f"not installed; keyfence install-hooks claude-code adds it (needs Claude Code v{hooks.PROMPT_HOOK_MIN_CLAUDE_CODE}+)"),
cwd, verdicts)


def check_pi_extension(cwd: Path | None = None) -> Check:
Expand Down Expand Up @@ -365,6 +467,9 @@ def check_audit() -> Check:

def run_checks(port: int, cwd: Path | None = None) -> list[Check]:
host, target = proxy_endpoint(os.environ, port)
paths = [path for path in (hooks.settings_path(False), hooks.settings_path(True, cwd))
if hook_installed(path) or prompt_hook_installed(path)]
verdicts = claude_verdicts(paths, cwd) if paths else {}
return [
Check(OK, "keyfence", f"{__version__} on Python {sys.version.split()[0]}, {platform.system()}"),
check_mitmdump(),
Expand All @@ -376,8 +481,8 @@ def run_checks(port: int, cwd: Path | None = None) -> list[Check]:
check_proxy(host, target),
check_environment(host, target),
check_local_mode(),
check_hook(cwd),
check_prompt_hook(cwd),
check_hook(cwd, verdicts),
check_prompt_hook(cwd, verdicts),
check_pi_extension(cwd),
check_audit(),
]
Expand Down
14 changes: 14 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,20 @@
os.environ.pop("KEYFENCE_ENV_VAULT", None)

import pytest # noqa: E402
from keyfence import doctor # noqa: E402

CLAUDE_DOCTOR = doctor.claude_doctor
CLAUDE_DOCTOR_CLEAN = "Claude Code doctor\n\nRunning: package-manager (2.1.311)\n\nNo installation issues found.\n"


@pytest.fixture(autouse=True)
def no_real_claude(monkeypatch):
monkeypatch.setattr(doctor, "claude_doctor", lambda cwd=None: (0, CLAUDE_DOCTOR_CLEAN))


@pytest.fixture
def claude_doctor():
return CLAUDE_DOCTOR


@pytest.fixture
Expand Down
55 changes: 55 additions & 0 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -569,6 +569,61 @@ def test_install_hooks_prints_the_claude_code_versions_when_the_hook_is_already_
assert all(version in out for version in cli.DENY_RULE_MIN_CLAUDE_CODE.values())


@pytest.mark.parametrize("entry, reason", [
({"matcher": 5, "hooks": [{"type": "command", "command": "true"}]},
"hooks.PreToolUse.0: Invalid hook matcher (matcher: Invalid input: expected string, received number)"),
({"matcher": "Read", "hooks": [{"type": "command"}]},
"hooks.PreToolUse.0.hooks.0: Invalid command hook (command: Invalid input: expected string, received undefined)"),
])
def test_install_hooks_refuses_a_settings_file_claude_code_does_not_apply_and_leaves_it_alone(home, tmp_path, monkeypatch,
capsys, entry, reason):
monkeypatch.chdir(tmp_path)
settings = tmp_path / ".claude" / "settings.json"
settings.parent.mkdir()
settings.write_text(json.dumps({"hooks": {"PreToolUse": [entry]}}))
before = settings.read_bytes()
output = (f"Claude Code doctor\n\nInvalid settings\n- {settings.resolve()} › {reason} — a PreToolUse/PermissionRequest "
"hook that cannot be loaded may be what guards the permissions declared beside it, so nothing it sits in "
"is applied until the entry is fixed or removed.\n")
monkeypatch.setattr(cli.doctor, "claude_doctor", lambda cwd=None: (0, output))
for _ in range(2):
assert cli.main(["install-hooks", "claude-code", "--project"]) == 1
captured = capsys.readouterr()
assert captured.out == ""
assert captured.err == (f"error: Claude Code does not apply {settings}: {reason}; fix or remove that entry, "
"then run this again\n")
assert settings.read_bytes() == before
assert not (tmp_path / ".claude" / "keyfence-deny-rules.json").exists()


def test_install_hooks_says_how_to_check_when_claude_cannot_confirm_the_file(home, tmp_path, monkeypatch, capsys):
monkeypatch.chdir(tmp_path)
monkeypatch.setattr(cli.doctor, "claude_doctor", lambda cwd=None: "claude is not on PATH")
settings = tmp_path / ".claude" / "settings.json"
hint = (f"Could not confirm that Claude Code applies {settings} (claude is not on PATH); claude doctor in {tmp_path} "
"lists the settings files it does not apply.")
assert cli.main(["install-hooks", "claude-code", "--project"]) == 0
out = capsys.readouterr().out
assert "Hook installed" in out and out.splitlines()[-1] == hint
assert cli.main(["install-hooks", "claude-code", "--project"]) == 0
out = capsys.readouterr().out
assert "Hook already present" in out and out.splitlines()[-1] == hint


def test_install_hooks_adds_no_hint_when_claude_code_applies_the_file(home, tmp_path, monkeypatch, capsys):
monkeypatch.chdir(tmp_path)
assert cli.main(["install-hooks", "claude-code", "--project"]) == 0
assert "Could not confirm" not in capsys.readouterr().out


def test_install_hooks_remove_does_not_ask_claude(home, tmp_path, monkeypatch, capsys):
monkeypatch.chdir(tmp_path)
assert cli.main(["install-hooks", "claude-code", "--project"]) == 0
monkeypatch.setattr(cli.doctor, "claude_doctor", lambda cwd=None: pytest.fail("claude doctor ran"))
assert cli.main(["install-hooks", "claude-code", "--project", "--remove"]) == 0
assert "Hook removed" in capsys.readouterr().out


def test_install_hooks_remove_does_not_print_the_claude_code_versions(home, tmp_path, monkeypatch, capsys):
monkeypatch.chdir(tmp_path)
assert cli.main(["install-hooks", "claude-code", "--project"]) == 0
Expand Down
Loading
Loading