Skip to content

Ask claude doctor whether Claude Code applies the settings file - #167

Merged
felladrin merged 16 commits into
mainfrom
issue-166
Nov 6, 2026
Merged

felladrin merged 16 commits into
mainfrom
issue-166

Conversation

@felladrin

@felladrin felladrin commented Nov 5, 2026 •

Copy link
Copy Markdown
Collaborator

Currently, keyfence install-hooks claude-code and keyfence doctor report the hook as installed once keyfence's entry is in settings.json, even when Claude Code applies nothing in that file. Claude Code drops the whole file when one PreToolUse entry in it cannot be loaded (for example a matcher that is not a string, or a command hook without command), 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-code runs claude doctor before it writes. When Claude Code reports the file, it stops with Claude Code's reason and leaves the file alone.
  • doctor runs claude doctor once, only when a scope holds the keyfence hook. A file Claude Code does not apply fails both Claude Code hook checks, with the reason.
  • A malformed UserPromptSubmit entry or deny value does not count: Claude Code drops only that entry, and both checks stay ok.
  • When claude is not on PATH, does not answer in 10 seconds, or prints something keyfence does not recognise, doctor shows warn ... not confirmed (never ok) and install-hooks adds a line that says how to check.
  • doctor now 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. Each claude doctor run writes ~/.claude.json, a backup of it under ~/.claude/backups, telemetry files under ~/.claude/telemetry (with CLAUDE_CONFIG_DIR set, 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 ~/.claude stays untouched (~/.npm/_logs still gets a debug log per run):

  1. export CLAUDE_CONFIG_DIR=$(mktemp -d), then cd "$(mktemp -d)" && mkdir .claude.
  2. printf '{"hooks":{"PreToolUse":[{"matcher":5,"hooks":[{"type":"command","command":"true"}]}]}}' > .claude/settings.json
  3. keyfence install-hooks claude-code --project stops with exit 1 and error: Claude Code does not apply .../.claude/settings.json: hooks.PreToolUse.0: Invalid hook matcher (...). The file is unchanged.
  4. Change the entry to {"matcher":"Read","hooks":[{"type":"command","command":"true"}]} and run step 3 again: the hook installs. keyfence doctor shows ok for both Claude Code hooks.
  5. Put 5 back as the matcher in the file by hand and run keyfence doctor: both Claude Code hooks show FAIL ... Claude Code does not apply ..., and the exit code is 1.
  6. Run PATH=/usr/bin:/bin "$(command -v keyfence)" doctor: both show warn ... not confirmed: claude is not on PATH.
  7. chmod 000 .claude/settings.json and run keyfence doctor: both show warn ... cannot read ...: Permission denied, with no traceback.

Not changed here

  • keyfence writes the global hook to ~/.claude/settings.json and ignores CLAUDE_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.
  • The path format of claude doctor on Windows is not measured. The Windows CI job runs the path-matching tests (through realpath, normcase and expanduser), but with the line format measured on macOS, not with real Windows output.
Implementation record

What changed

File Change
keyfence/doctor.py claude_doctor() runs claude doctor (stdin /dev/null, cwd, 10 s timeout) and returns (code, output) or why it could not. claude_verdicts() maps each settings path to ok, fail with Claude Code's reason, or warn with why it is not confirmed. settings_problem() names an unreadable file. check_hook and check_prompt_hook share _claude_hook_check(); run_checks runs claude once for both. The three _read_settings wrappers also catch OSError.
keyfence/cli.py install-hooks claude-code asks before it writes: refuses on fail, adds the hint on warn. --remove does not ask.
tests/conftest.py Autouse fixture replaces doctor.claude_doctor with a stub that reports a clean file; claude_doctor fixture hands the real function to the tests that need it.
tests/test_doctor.py 23 new test cases; INFO to WARN in test_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_installed and test_installed_scopes_names_both_locations_for_each_agent.
tests/test_cli.py 5 new test cases for install-hooks.
CHANGELOG.md, docs/setup.md Entries, and a paragraph on the check and the files claude doctor writes.

keyfence/hooks.py and plugin/hooks/guard.py are 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):

  • Exit code is 0 in every case, including a rejected file. Only the text carries the verdict.
  • Each problem is a line - <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 through realpath (and expanduser, for a ~ form).
  • A line for the path with nothing it sits in is applied => fail; the reason is the text before —, capped at 200 characters.
  • Lines ending in matcher ignored., was removed, This field was ignored. or entry ignored. => ignored (Claude Code drops only that value).
  • Any other line for the path => warn, quoting it. No line for the path => ok.
  • No Claude Code doctor header line, a non-zero exit, a timeout or claude missing => warn for 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

Verification

  • env -u <proxy and CA vars> ./.venv/bin/pytest on b481eff at 2026-11-05T20:05Z: exit 0, 1317 passed, coverage 98.75%.
  • The test for a settings file without read permission is skipped on Windows and when running as root. On Windows, chmod sets only the read-only flag, so the file stays readable; root reads a file whatever its mode.
  • The first Windows CI run failed the ~ path test: it set only HOME, and os.path.expanduser reads USERPROFILE on Windows. The test now sets both. Claude Code also takes the home folder from USERPROFILE there, so the code did not change.
  • Each new test proven able to fail: 15 mutations of the guarded code (rejection phrase ignored, dropped-only lines counted, path compared verbatim, no-answer read as ok, exit code ignored, header not required, no cap, OSError not caught, stdin inherited, claude run with no hook, path named twice, unreadable scope hidden, no refusal, no hint, --remove asking), each red, then restored with an empty git diff. Replacing settings_problem with None turns the 16 updated or new unreadable-file tests red.
  • The stub keeps the real binary out: with the autouse stub disabled and a logging claude shim first on PATH, the doctor, cli and version tests made 27 claude doctor calls (without the shim they go to /opt/homebrew/bin/claude). With the stub, 0.
  • End to end with the real claude 2.1.311, CLAUDE_CONFIG_DIR and HOME in temp folders: the steps above, plus the command shape (refused) and a malformed UserPromptSubmit entry (installed, both ok).

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 aminueza left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 claude installed.
  • No false ok: making the no-answer path return ok, 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.

Base automatically changed from doctor-malformed-settings to main November 6, 2026 16:34
# Conflicts:
#	CHANGELOG.md
#	keyfence/doctor.py
#	tests/test_doctor.py
@felladrin

Copy link
Copy Markdown
Collaborator Author

Done. entry ignored. is in the drop-only tuple now, with the line added to the parametrize list of test_an_entry_claude_code_drops_on_its_own_leaves_both_hooks_ok (dad1e75). Full suite green locally: 1318 passed, one more than your run because of the new case.

By the way, #164 and #165 are merged now, so the PR targets main and I updated the body to match.

@felladrin
felladrin requested a review from aminueza November 6, 2026 16:36

@aminueza aminueza left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-verified at dad1e75. The change I asked for is in, and nothing else is outstanding.

  • CLAUDE_DROPS_ONLY now includes entry ignored.. The new parametrize line matches, character for character, what claude doctor prints on 2.1.269 and 2.1.317 for a null hook entry.
  • I reverted only that suffix and the new case fails (AssertionError at tests/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 null inside keyfence's UserPromptSubmit entry now gives ok on both hooks. It gave warn … not confirmed before.
    • matcher: 5 in PreToolUse still gives FAIL on both hooks. That holds after install, through a 222-character symlinked path, and from inside a Claude Code session. install-hooks still refuses and leaves the file byte-identical.
    • Without claude on PATH, both commands still warn and never report ok.
  • 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.

@felladrin
felladrin merged commit 59cd051 into main Nov 6, 2026
11 checks passed
@felladrin
felladrin deleted the issue-166 branch November 6, 2026 17:38
@felladrin felladrin mentioned this pull request Nov 16, 2026
aminueza pushed a commit that referenced this pull request Nov 16, 2026
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

install-hooks and doctor report the Claude Code hook as installed when Claude Code does not apply the settings file

2 participants