Repository navigation
Conversation
install() and uninstall() assumed every section of settings.json had the type Claude Code documents, and raised AttributeError when one did not. uninstall() was worse with a deny object: it iterated the object's keys and, when it removed the hook, wrote them back as a list. Both now read the file through _read_settings(), which checks the top level, hooks, permissions, the two hook events and deny, and raises a ValueError naming the key before anything is written; the CLI already prints a ValueError as "error: ..." and exits 1. There is no safe way to add rules to a deny that is an object, so stopping beats a rewrite. Inside a list of the right type, a hook entry that is not an object, or whose hooks field is not a list, is not keyfence's, so _is_ours() and _sync_command() skip it and it stays in place, as non-string deny entries do.
keyfence doctor and install-hooks --list parsed settings.json with their own json.loads and walked hooks.<event> with .get, so a section of the wrong type (hooks as a list, an event as a string) raised AttributeError. They now read through hooks._read_settings(), whose ValueError they already catch for invalid JSON, and walk an entry's hooks through hooks._entry_hooks(), which skips one that is not an object. Treating the file as unreadable means the hook shows as not installed; install-hooks claude-code then stops with the error that names the key.
A PreToolUse entry that is not an object, has no hooks list, or holds a
hook that is not an object makes Claude Code apply nothing in the file
that holds it ("nothing it sits in is applied", claude doctor on 2.1.311
and 2.1.317). install-hooks left such an entry in place and wrote the
hook and the deny rules beside it, so it and keyfence doctor reported a
protection that was not in effect.
_read_settings now raises a ValueError naming the entry, in the same
wording as the wrong-type section errors, so install and --remove stop
before any write. A malformed UserPromptSubmit entry is still left in
place: Claude Code ignores only that entry there.
…' into doctor-malformed-settings # Conflicts: # CHANGELOG.md
Claude Code ignores a whole settings file when one PreToolUse entry in it cannot be loaded, so keyfence reported a hook and deny rules that were not in force. doctor now runs claude doctor once and fails the hook checks for a file it reports with "nothing it sits in is applied", and install-hooks refuses such a file before it writes. When claude is missing, times out or prints something keyfence does not recognise, both say the hook is not confirmed and point at claude doctor instead of printing ok. doctor also names a settings file it cannot read and why, instead of "not installed", and no longer crashes on one it lacks permission to read.
… cannot load test_keyfence_hook_skips_a_hook_that_is_not_an_object asserted that doctor reports the hook as installed in a file whose PreToolUse list holds an entry that is not an object. Claude Code applies nothing in such a file, and since doctor reads through _read_settings, which now rejects that entry, doctor and install-hooks --list say "not installed" there. Replace it with two tests. A file keyfence installed into, with a malformed PreToolUse entry added (including a null before keyfence's own hook, which crashed doctor before it read through _entry_hooks), shows both hooks as not installed in doctor and in the --list scopes. Malformed UserPromptSubmit entries, and a null inside keyfence's own prompt entry, do not hide the prompt hook, because Claude Code ignores only those.
…uite An autouse fixture replaces the function that runs claude doctor with a stub that reports a clean file, so no test starts the claude binary on the machine running the suite, whose own settings file may hold a keyfence hook. The new tests feed back the lines Claude Code 2.1.311 printed for the matcher and command shapes, the UserPromptSubmit and deny values it drops on their own, and each case where it gives no answer.
doctor now names a settings file it cannot read, and why, as a warning instead of showing the hook as not installed. Update the tests that read invalid JSON, a section of the wrong type, or a PreToolUse entry Claude Code cannot load through check_hook and check_prompt_hook. hook_installed and the install-hooks --list scopes still report such a file as not installed.
The test that matches a "~/..." path from claude doctor set only HOME, but os.path.expanduser reads USERPROFILE on Windows since Python 3.8, so the tilde expanded to the runner's real profile and the verdict was ok instead of fail. Set USERPROFILE as well. Claude Code takes the home folder from USERPROFILE on Windows too, so the code stays as it is.
aminueza
left a comment
There was a problem hiding this comment.
Asking Claude Code instead of copying its schema is the right design, and it holds up against the real binary. One small parsing gap needs fixing before merge.
What holds
I ran it end to end with the real claude on PATH, both 2.1.269 (the one on PATH here) and 2.1.317, with HOME and CLAUDE_CONFIG_DIR in temp folders:
| case | 2.1.269 | 2.1.317 |
|---|---|---|
valid install, then doctor |
ok / ok |
ok / ok |
matcher: 5 added after install |
FAIL both, exit 1 |
FAIL both, exit 1 |
install-hooks on a file with matcher: 5 |
exit 1, file untouched | exit 1, file untouched |
| 222-character project path reached through a symlink | FAIL (path matched) |
FAIL |
run from inside a Claude Code session (its CLAUDE*/ANTHROPIC* env inherited) |
FAIL as expected |
same |
claude not on PATH |
warn … not confirmed, install hint |
same |
- Timing: each command takes 2 to 6 s with
claudeinstalled. - No false
ok: making the no-answer path returnok, dropping the header check, letting an unknown line through, ignoring the exit code, or comparing paths verbatim each fails a test. - Suite: 1317 passed, coverage 98.72%. CI is green.
Side effects. On a copy of a real, long-used ~/.claude.json, claude doctor from either version changed no key: none added, none removed, no value changed. On a fresh file it does run first-start migrations, for example theme and userID, but install-hooks runs only where Claude Code is already in use. The docs paragraph describes this fairly.
Worth fixing: entry ignored. is a drop-only message
Claude Code reports a hook it skips inside a non-PreToolUse entry with ; entry ignored., and applies the rest of the file. The same message appears on both versions:
hooks.UserPromptSubmit.0.hooks.0: Hook entry must be an object; received null; entry ignored.
hooks.UserPromptSubmit.0.hooks.0: Invalid command hook (command: Invalid input: expected string, received undefined); entry ignored.
CLAUDE_DROPS_ONLY does not list it, so these lines fall into "does not recognise". Both hook checks then show warn … not confirmed for a file Claude Code applies. #165 documents the first shape as harmless and tests it, so doctor contradicts that PR on its own case. Adding "entry ignored." to the tuple turns both into ok on both versions, keeps PreToolUse at FAIL, and leaves the suite green. Please also add an entry ignored. line to the parametrize list of test_an_entry_claude_code_drops_on_its_own_leaves_both_hooks_ok.
Other individual drops still read as warn because their message has no stable suffix: an unknown hook event name, a malformed deny rule such as Read(, and model: Expected string. That is the conservative side, and I would leave it.
Not from this PR, for a separate issue
On Windows, shutil.which searches the current directory before PATH unless NoDefaultCurrentDirectoryInExePath is set. The Python 3.14 source confirms this through _win_path_needs_curdir. So keyfence doctor or install-hooks, run in a cloned repository that holds a claude.cmd, would execute that file. This PR adds one more instance of a pattern that keyfence already has for mitmdump (runner.py), the secret-manager CLIs (sources.py) and doctor, so it belongs in one fix across all callers. Two ways to fix it: set NoDefaultCurrentDirectoryInExePath for the lookup, or reject a result that resolves inside the current directory.
# Conflicts: # CHANGELOG.md # keyfence/doctor.py # tests/test_doctor.py
|
Done. By the way, #164 and #165 are merged now, so the PR targets |
aminueza
left a comment
There was a problem hiding this comment.
Re-verified at dad1e75. The change I asked for is in, and nothing else is outstanding.
CLAUDE_DROPS_ONLYnow includesentry ignored.. The new parametrize line matches, character for character, whatclaude doctorprints on 2.1.269 and 2.1.317 for anullhook entry.- I reverted only that suffix and the new case fails (
AssertionErrorattests/test_doctor.py:593). The other four cases still pass, so the test pins the fix. - Ran the real binary again on 2.1.269 and 2.1.317 against this head:
- A
nullinside keyfence'sUserPromptSubmitentry now givesokon both hooks. It gavewarn … not confirmedbefore. matcher: 5inPreToolUsestill givesFAILon both hooks. That holds after install, through a 222-character symlinked path, and from inside a Claude Code session.install-hooksstill refuses and leaves the file byte-identical.- Without
claudeon PATH, both commands stillwarnand never reportok.
- A
- The merge from main (#164 and #165) is clean. Full suite: 1318 passed, coverage 98.72%. CI is green on all three OSes.
The Windows shutil.which lookup from my last review stays out of scope. It will be handled in a separate issue covering every caller.
Step 1 of the three in docs/development.md: __version__ and the plugin manifest to 0.11.0, and the Unreleased heading renamed to 0.11.0 (2026-11-16). The release carries the install-hooks and doctor fixes from #162 to #167. The plugin manifest bump matters this time: keyfence/hooks.py changed since 0.10.2, so the marketplace needs the new version to serve the new guard.py.
Currently,
keyfence install-hooks claude-codeandkeyfence doctorreport the hook as installed once keyfence's entry is insettings.json, even when Claude Code applies nothing in that file. Claude Code drops the whole file when onePreToolUseentry in it cannot be loaded (for example amatcherthat is not a string, or a command hook withoutcommand), so the hook and the 42 deny rules are off and nothing says so. aminueza found this and laid out the options in #166.This PR asks Claude Code itself, instead of copying its schema into keyfence:
install-hooks claude-coderunsclaude doctorbefore it writes. When Claude Code reports the file, it stops with Claude Code's reason and leaves the file alone.doctorrunsclaude doctoronce, only when a scope holds the keyfence hook. A file Claude Code does not apply fails both Claude Code hook checks, with the reason.UserPromptSubmitentry or deny value does not count: Claude Code drops only that entry, and both checks stayok.claudeis not onPATH, does not answer in 10 seconds, or prints something keyfence does not recognise,doctorshowswarn ... not confirmed(neverok) andinstall-hooksadds a line that says how to check.doctornow names a settings file it cannot read, and why, as a warning. Before, it showed "not installed" with no reason, and crashed on a file it had no permission to read.Side effect to know about: both commands now start
claude. Eachclaude doctorrun writes~/.claude.json, a backup of it under~/.claude/backups, telemetry files under~/.claude/telemetry(withCLAUDE_CONFIG_DIRset, those three go to that folder instead), and a debug log under~/.npm/_logs(always in the home folder). It needs no login and no network.Closes #166
How to test manually
Use a throwaway project folder and a throwaway Claude Code config folder, so your own
~/.claudestays untouched (~/.npm/_logsstill gets a debug log per run):export CLAUDE_CONFIG_DIR=$(mktemp -d), thencd "$(mktemp -d)" && mkdir .claude.printf '{"hooks":{"PreToolUse":[{"matcher":5,"hooks":[{"type":"command","command":"true"}]}]}}' > .claude/settings.jsonkeyfence install-hooks claude-code --projectstops with exit 1 anderror: Claude Code does not apply .../.claude/settings.json: hooks.PreToolUse.0: Invalid hook matcher (...). The file is unchanged.{"matcher":"Read","hooks":[{"type":"command","command":"true"}]}and run step 3 again: the hook installs.keyfence doctorshowsokfor both Claude Code hooks.5back as the matcher in the file by hand and runkeyfence doctor: both Claude Code hooks showFAIL ... Claude Code does not apply ..., and the exit code is 1.PATH=/usr/bin:/bin "$(command -v keyfence)" doctor: both showwarn ... not confirmed: claude is not on PATH.chmod 000 .claude/settings.jsonand runkeyfence doctor: both showwarn ... cannot read ...: Permission denied, with no traceback.Not changed here
~/.claude/settings.jsonand ignoresCLAUDE_CONFIG_DIR. With that variable set, Claude Code reads a different file, so the global install is not read at all, and this check finds no line for it.claude doctoron Windows is not measured. The Windows CI job runs the path-matching tests (throughrealpath,normcaseandexpanduser), but with the line format measured on macOS, not with real Windows output.Implementation record
What changed
keyfence/doctor.pyclaude_doctor()runsclaude doctor(stdin/dev/null, cwd, 10 s timeout) and returns(code, output)or why it could not.claude_verdicts()maps each settings path took,failwith Claude Code's reason, orwarnwith why it is not confirmed.settings_problem()names an unreadable file.check_hookandcheck_prompt_hookshare_claude_hook_check();run_checksrunsclaudeonce for both. The three_read_settingswrappers also catchOSError.keyfence/cli.pyinstall-hooks claude-codeasks before it writes: refuses onfail, adds the hint onwarn.--removedoes not ask.tests/conftest.pydoctor.claude_doctorwith a stub that reports a clean file;claude_doctorfixture hands the real function to the tests that need it.tests/test_doctor.pytest_hook_check,test_prompt_hook_check,test_a_settings_section_of_the_wrong_type_reads_like_a_file_that_is_not_json,test_a_pre_tool_use_entry_claude_code_cannot_load_shows_an_installed_file_as_not_installedandtest_installed_scopes_names_both_locations_for_each_agent.tests/test_cli.pyCHANGELOG.md,docs/setup.mdclaude doctorwrites.keyfence/hooks.pyandplugin/hooks/guard.pyare not touched. Code: +131/-18 in two files; tests: +278/-7.How the output is read
Measured on Claude Code 2.1.311 (the issue used 2.1.317; the messages match word for word):
- <path> › <key>: <message>, or- <path>: <message>for a whole-file problem. The user path prints as given, the project path resolved (/var/...vs/private/var/...), so both sides go throughrealpath(andexpanduser, for a~form).nothing it sits in is applied=>fail; the reason is the text before—, capped at 200 characters.matcher ignored.,was removed,This field was ignored.orentry ignored.=> ignored (Claude Code drops only that value).warn, quoting it. No line for the path =>ok.Claude Code doctorheader line, a non-zero exit, a timeout orclaudemissing =>warnfor every path.Timing: 0.59 s to 0.85 s per run, 0.28 s with a refused or blackholed proxy, 0.72 s under a PTY, with no keypress wait and no login.
Decisions
warn, notok, when Claude Code cannot be asked. A user who runs Claude Code without the CLI onPATHsees two warnings;doctorstill exits 0. Dropped:okplus a hint, because it printsokfor a file nobody checked.warn, notfail: keyfence cannot tell whether its hook was meant to be in it. AValueErrormessage that already names the path prints alone, without a secondcannot read <path>:._read_settingsrejects (Stop install-hooks on a malformed settings section or PreToolUse entry #164's shapes) now shows aswarn ... hooks.PreToolUse[0] in <path> is not an object, where Read a malformed settings file in doctor like one that is not JSON #165 showedinfo not installed.hook_installedandinstall-hooks --liststill say not installed.claudeonPATH, those Stop install-hooks on a malformed settings section or PreToolUse entry #164 shapes stopinstall-hookswith Claude Code's message before Stop install-hooks on a malformed settings section or PreToolUse entry #164's own error is reached. Both exit 1 and leave the file alone.Verification
env -u <proxy and CA vars> ./.venv/bin/pyteston b481eff at 2026-11-05T20:05Z: exit 0, 1317 passed, coverage 98.75%.chmodsets only the read-only flag, so the file stays readable; root reads a file whatever its mode.~path test: it set onlyHOME, andos.path.expanduserreadsUSERPROFILEon Windows. The test now sets both. Claude Code also takes the home folder fromUSERPROFILEthere, so the code did not change.ok, exit code ignored, header not required, no cap,OSErrornot caught, stdin inherited,clauderun with no hook, path named twice, unreadable scope hidden, no refusal, no hint,--removeasking), each red, then restored with an emptygit diff. Replacingsettings_problemwithNoneturns the 16 updated or new unreadable-file tests red.claudeshim first onPATH, the doctor, cli and version tests made 27claude doctorcalls (without the shim they go to/opt/homebrew/bin/claude). With the stub, 0.claude2.1.311,CLAUDE_CONFIG_DIRandHOMEin temp folders: the steps above, plus thecommandshape (refused) and a malformedUserPromptSubmitentry (installed, bothok).