Add config-health monitor and install wiring

- Add the config-health skill: a read-only monitor for hook wiring, rule references, and rule staleness; every mode exits 0.
- Ship its own SessionStart hook asset so installing the module registers the monitor; keep PreToolUse opt-in.
- Keep one install-state record per hook source, so hooks-runtime and config-health can share settings.json and uninstall removes both.
- Split the monitor into a CLI entry plus constants, paths, and scan modules; split scan_command and the hook contract suite. All files are under 800 lines and no function body reaches 50 lines.
This commit is contained in:
YuhaoLin2005 committed 2026-11-02 22:53:30 +08:00
1 parent e83576fe7d
commit 95bf86c348
20 files changed
+1752 -1249

No files matched your search

+98 -585
View File
@@ -80,581 +80,46 @@ try:
except (AttributeError, OSError):
pass # Python <3.7 or stdout is not a TTY/stream
WARN_PREFIX = '[config-health] WARN: '
# Sessions of rule-health history to look back for guard staleness.
STALENESS_WINDOW = 5
# Minimum tool calls for a session to be "complex enough" to expect rule markers.
MIN_TOOL_CALLS_FOR_CHECK = 5
# Rule-health log written by the earlier Stop-hook monitor (read-only here).
# Relative to the Claude data root, which is CLAUDE_CONFIG_DIR or ~/.claude.
RULE_HEALTH_LOG = 'session-data/rule-health.jsonl'
# Metadata keys in each rule-health record, not rule counters.
NON_RULE_KEYS = {'ts', 'date', 'time', 'tool_calls', 'edits'}
# Matches a script path inside one shell word: ~/.claude/scripts/x.py,
# scripts/x.js, C:/path/x.py, ./hooks/x.py, ${CLAUDE_PLUGIN_ROOT}/hooks/x.js.
# Applied per shell word (see _split_shell_words) rather than to the raw
# command, so a quoted path containing a space stays one token.
#
# The trailing lookahead is load-bearing. Without it `archive.js.bak` matches
# as `archive.js`, and the monitor warns about a file that does not exist
# while the file the shell actually opens does.
SCRIPT_TOKEN = re.compile(
r'([^\s"\']+\.(?:py|js|mjs|cjs|sh))(?![A-Za-z0-9_.~-])'
)
# A quoted shell word that ends in a script extension is one argument
# verbatim, spaces included: "C:\Program Files\ecc\hooks\guard.py". Spaces
# inside it are part of the path, not separators.
WHOLE_WORD_SCRIPT_RE = re.compile(r'[^"\']*\.(?:py|js|mjs|cjs|sh)\Z')
# A finding never quotes a whole command. The whole-word rule above can pick
# up an argument that is itself a command line, and a hook command can be
# very long; a monitor that prints 200KB of somebody's settings file has
# stopped being a monitor.
MAX_REPORTED_PATH = 160
# $NAME / ${NAME} in a hook command.
PLACEHOLDER_RE = re.compile(r'\$\{?([A-Za-z_][A-Za-z0-9_]*)\}?')
# Interpreters whose -e / -c argument is a program body rather than a script
# path. The two kinds of payload are not the same thing:
# - a shell's -c payload is a command line, so it is scanned again as one
# - a node/python -e payload is source in another language, where a string
# is a string: p.join(r,'scripts/hooks/x.js') is assembled at runtime and
# is not a file the shell will open
SHELL_INTERPRETERS = frozenset(('sh', 'bash', 'zsh'))
JS_INTERPRETERS = frozenset((
'node', 'nodejs', 'python', 'python3', 'pythonw', 'py',
))
INTERPRETERS = SHELL_INTERPRETERS | JS_INTERPRETERS
# Long and short spellings of "the next word is a program body", plus the
# bundled short forms a shell accepts (`bash -lc "..."`).
PROGRAM_FLAG_LONG = frozenset(('--eval', '--command'))
# Options of the interpreters above whose value is the *next* word. Without
# these, `bash -o pipefail -c "..."` orphans the -c: pipefail looks like a
# command, so the payload after it is read as a path and the whole hook body
# gets printed as a missing file.
OPTION_TAKES_NEXT_WORD = frozenset(('-o', '-O', '-W', '-X', '--options'))
SHELL_SEPARATORS = (';', '&&', '||', '|', '&', '\n')
# A backslash only escapes what a shell would let it escape. Everything else
# after a backslash is literal, because on Windows — where this script also
# runs — a backslash is a path separator, not an escape. Notably absent: `\\`
# (a UNC prefix is two backslashes, not an escaped one), `$` and a backtick
# (C:\$Recycle.Bin is a directory, not an escape).
ESCAPABLE_BACKSLASH = frozenset((' ', '\t', '"', "'", ';', '&', '|',
'<', '>', '(', ')'))
# How deep a `sh -c "sh -c ..."` chain is followed before giving up. A command
# nested past this is not something a settings file should contain, and an
# unbounded recursion on attacker-shaped input is worse than a missed check.
MAX_PAYLOAD_DEPTH = 3
# Root of the installed plugin, when running from a plugin install. Claude Code
# sets this for plugin-style hooks; it is the only provider placeholder this
# monitor resolves, because every other placeholder is provider-specific and
# guessing at it would turn a real signal into a false warning.
PLUGIN_ROOT_ENV = 'CLAUDE_PLUGIN_ROOT'
# Pin the plugin root explicitly. The provider sets CLAUDE_PLUGIN_ROOT to the
# root of the plugin that is *running*, so with more than one plugin installed
# a settings line wired for a different one is judged against the wrong
# directory. One value cannot describe two plugins; this override is the
# honest escape hatch, and --check names the root it used.
PLUGIN_ROOT_OVERRIDE_ENV = 'CONFIG_HEALTH_PLUGIN_ROOT'
# Cap on hook input we are willing to drain. This is a bound on bytes buffered,
# not on time: sys.stdin.read(n) returns on n characters or EOF, whichever
# comes first, so a hook that hangs is stopped by the `timeout` in its wiring,
# not by this cap.
STDIN_DRAIN_LIMIT = 64 * 1024
# audit_hook_wiring verdicts.
AUDIT_OK = 'ok' # at least one candidate path exists
AUDIT_MISSING = 'missing' # no candidate path exists — report the token
AUDIT_SKIP = 'skip' # no path could be built — say nothing
# This monitor is read-only: importing its helper modules must not leave a
# __pycache__ directory inside the plugin install.
sys.dont_write_bytecode = True
def _split_shell_words(command):
"""Split `command` into (word, single_quoted) pairs, POSIX-quote aware.
A hook command is a shell command line, so a path containing a space has
to survive as one word. Splitting naively on whitespace turns
``python3 "C:\\Program Files\\ecc\\hooks\\guard.py"`` into the token
``Files\\ecc\\hooks\\guard.py``, which does not exist — a false alarm
manufactured by the tokenizer.
Args:
command (`str`): A raw hook command.
Returns:
`list[tuple[str, bool, bool]] | None`: Each shell word, whether any
part of it was quoted (a quoted word is one argument verbatim,
spaces included), and whether any part of it was single-quoted (a
single-quoted placeholder is not expanded by the shell, so it
cannot be resolved from here). `None` when a quote is left open:
the command is not parseable as written, and what a broken quote
swallows next is a guess.
"""
words = []
chars = []
quote = None
started = False
quoted = False
single = False
i = 0
length = len(command)
while i < length:
ch = command[i]
if quote == "'":
if ch == "'":
quote = None
else:
chars.append(ch)
elif quote == '"':
if ch == '\\' and i + 1 < length \
and command[i + 1] in ESCAPABLE_BACKSLASH:
chars.append(command[i + 1])
i += 1
elif ch == '"':
quote = None
else:
chars.append(ch)
elif ch in '\'"':
quote = ch
quoted = True
single = single or ch == "'"
started = True
elif ch.isspace():
if started:
words.append((''.join(chars), quoted, single))
chars = []
quoted = False
single = False
started = False
elif ch == '\\' and i + 1 < length \
and command[i + 1] in ESCAPABLE_BACKSLASH:
chars.append(command[i + 1])
started = True
i += 1
else:
chars.append(ch)
started = True
i += 1
if quote is not None:
return None
if started:
words.append((''.join(chars), quoted, single))
return words
def _is_interpreter(word):
"""Whether `word` names a shell interpreter rather than a file."""
name = word.replace('\\', '/').rsplit('/', 1)[-1].lower()
return name in INTERPRETERS
def _is_program_flag(word, shell):
"""Whether `word` is an option whose next word is a program body.
Covers the long spellings, the plain short ones, and the bundled short
forms a shell accepts — `bash -lc "..."` is the same thing as `bash -c
"..."` and used to be read as two ordinary words.
The letter is interpreter-specific, and getting it wrong is a false
warning: `sh -e script.sh` is errexit, not a program body, so treating `-e`
as one hides the script the shell will run.
"""
if word in PROGRAM_FLAG_LONG:
return True
if word.startswith('--') or not word.startswith('-') or len(word) < 2:
return False
wanted = 'c' if shell else 'e'
return wanted in word[1:]
def _is_separator(word):
"""Whether `word` contains a shell command separator."""
return any(sep in word for sep in SHELL_SEPARATORS)
def scan_command(command, depth=0):
"""Return (tokens, unparsed, bodies, too_deep) for `command`.
`tokens` is a list of (token, single_quoted). `unparsed` is True when the
command could not be split as written — an unclosed quote. `bodies` counts
the interpreter program bodies that were skipped: source in another
language, where this monitor cannot tell a path from a string, so nothing
inside was judged. `too_deep` is True when a `sh -c` chain went past
`MAX_PAYLOAD_DEPTH`; the tokens found before that point are still returned,
because a missing script on the outer command does not stop being one.
Every reason this function declines to judge something is returned rather
than swallowed, because `--check` prints the counts and a silent drop with
no count is the failure this whole design is built against.
Three things need more than a regex over the raw command:
- a quoted word is one argument verbatim, so a path with a space in it has
to be taken whole rather than cut at the space;
- an interpreter's program body is not a script path. A shell's `-c`
payload is itself a command line and is scanned again; a `node -e` or
`python -c` payload is source in another language, where a string is a
string — `p.join(r,'scripts/hooks/x.js')` is assembled at runtime and is
not a file anything will open, so it is skipped;
- a backslash only escapes what a shell would let it escape. Treating
every backslash as an escape turns `C:\\Users\\me\\guard.py` into
`C:Usersmeguard.py`, which is a false alarm on the platform this script
is developed on.
Args:
command (`str`): A raw hook command.
depth (`int`): Current `sh -c` nesting.
Returns:
`tuple[list[tuple[str, bool]], bool, int, bool]`: The tokens, whether
the command was unparseable, how many program bodies were skipped,
and whether nesting ran out.
"""
words = _split_shell_words(command)
if words is None:
return [], True, 0, False
tokens = []
bodies = 0
too_deep = False
index = 0
total = len(words)
interpreter = None
option_arg = False
while index < total:
word, quoted, single = words[index]
# A separator only separates when the shell can see it. Inside quotes
# it is part of the name, and `python3 "weird;name.py"` is a file.
if not quoted and _is_separator(word):
interpreter = None
option_arg = False
index += 1
continue
if _is_interpreter(word):
interpreter = word
option_arg = False
index += 1
continue
if interpreter and _is_program_flag(word, _is_shell_interpreter(interpreter)):
if quoted:
# The body is glued to the flag, as in `node -e"..."`. Nothing
# after this word belongs to the program, and nothing inside
# it was judged — so it counts like any other skipped body.
bodies += 1
index += 1
continue
payload_at = index + 1
payload = words[payload_at][0] if payload_at < total else None
payload_quoted = words[payload_at][1] if payload_at < total else False
if payload is None:
index = total
continue
if _is_shell_interpreter(interpreter):
if depth >= MAX_PAYLOAD_DEPTH:
# Too deep to follow. Counted, and the tokens collected
# so far are kept — a missing script on the outer command
# is still a missing script. Reported as its own thing,
# not as an unclosed quote, which it is not.
return tokens, False, bodies, True
# A shell payload is a command line: scan it again rather
# than hide a real reference behind the -c.
if payload_quoted:
sub, sub_unparsed, sub_bodies, sub_deep = scan_command(
payload, depth + 1)
if sub_unparsed:
return tokens, True, bodies, too_deep
tokens.extend(sub)
bodies += sub_bodies
too_deep = too_deep or sub_deep
index = payload_at + 1
continue
chunk = []
cursor = payload_at
while cursor < total and not _is_separator(words[cursor][0]):
chunk.append(words[cursor][0])
cursor += 1
sub, sub_unparsed, sub_bodies, sub_deep = scan_command(
' '.join(chunk), depth + 1)
if sub_unparsed:
return tokens, True, bodies, too_deep
tokens.extend(sub)
bodies += sub_bodies
too_deep = too_deep or sub_deep
index = cursor
continue
# Source in another language: skip the body. Quoted, that is one
# word; unquoted, the shell hands node every word up to the next
# separator as the program, so all of them go. Counted, because
# nothing inside it was judged and `--check` should say so.
bodies += 1
if not payload_quoted:
while payload_at < total \
and not _is_separator(words[payload_at][0]):
payload_at += 1
else:
payload_at += 1
index = payload_at
interpreter = None
continue
if interpreter and word.startswith('-') and len(word) > 1:
# An option of the interpreter seen a moment ago. Options run
# until the first non-option word, so `bash -x -c "..."` still
# has a program body waiting. Some of them take their value as
# the next word, which is an option too.
option_arg = not quoted and word in OPTION_TAKES_NEXT_WORD
index += 1
continue
if option_arg:
option_arg = False
index += 1
continue
interpreter = None
candidate = word
if (quoted or ' ' in word) and not word.startswith('-'):
# `"python3 scripts/hooks/guard.js"` is one shell word, but it is
# an interpreter and its argument, not one long path. Reporting
# the word verbatim would quote the whole command back.
head, _, tail = word.partition(' ')
if tail and _is_interpreter(head):
candidate = tail
if not candidate.startswith('-') and (quoted or ' ' in candidate) \
and WHOLE_WORD_SCRIPT_RE.match(candidate):
tokens.append((candidate, single))
else:
tokens.extend((m.group(1), single)
for m in SCRIPT_TOKEN.finditer(candidate))
index += 1
return tokens, False, bodies, too_deep
def _is_shell_interpreter(word):
"""Whether `word` names an interpreter whose -c payload is a command."""
name = word.replace('\\', '/').rsplit('/', 1)[-1].lower()
return name in SHELL_INTERPRETERS
def resolve_dirs():
"""Return (user_home, project_dir) honoring env overrides for determinism."""
user_home = os.environ.get('CONFIG_HEALTH_USER_HOME') or os.path.expanduser('~')
project_dir = os.environ.get('CLAUDE_PROJECT_DIR') or os.getcwd()
return user_home, project_dir
def claude_data_dir(user_home):
"""Claude's user data root: CLAUDE_CONFIG_DIR when set, else ~/.claude.
Claude Code reads user settings from this directory, and launchers move it
with CLAUDE_CONFIG_DIR. Reading ~/.claude unconditionally would audit a
file the harness is not loading, which is worse than not auditing at all.
"""
configured = os.environ.get('CLAUDE_CONFIG_DIR')
if configured:
return os.path.abspath(os.path.expanduser(configured))
return os.path.join(user_home, '.claude')
def read_text(path):
"""Read a file defensively; return None on any read/decode error."""
if not os.path.exists(path):
return None
try:
with open(path, 'r', encoding='utf-8') as f:
return f.read()
except (OSError, UnicodeDecodeError):
return None
def read_json(path):
"""Parse a JSON file defensively; return None if missing or malformed."""
text = read_text(path)
if text is None:
return None
try:
return json.loads(text)
except (ValueError, TypeError):
return None
def placeholder_env(project_dir, user_home):
"""Explicit map of the placeholders this monitor is willing to resolve.
Deliberately an allowlist rather than a copy of ``os.environ``: a hook
command can contain a provider placeholder we cannot judge, and resolving
an arbitrary one from ambient shell state would make findings depend on
unrelated environment. The two provider names below are the exception,
and only because a plugin install cannot be audited without them — both
are overridable so an audit can be pinned rather than inherited.
``$HOME`` / ``$USERPROFILE`` resolve to ``user_home``, the same value
``~`` resolves to, so ``$HOME/x.py`` and ``~/x.py`` are judged alike.
Args:
project_dir (`str`): Absolute project directory.
user_home (`str`): Absolute user home directory.
Returns:
`dict`: Placeholder name to absolute directory.
"""
env = {
'CLAUDE_PROJECT_DIR': project_dir,
'HOME': user_home,
'USERPROFILE': user_home,
}
plugin_root = (
os.environ.get(PLUGIN_ROOT_OVERRIDE_ENV)
or os.environ.get(PLUGIN_ROOT_ENV)
# The helper modules are imported behind the same non-blocking contract as the
# rest of the script: a broken install (missing module) or an interpreter fault
# during import must exit 0 without a traceback, because a hook that crashes
# degrades the session it is meant to be watching.
try:
from config_health_constants import (
AUDIT_MISSING,
AUDIT_OK,
AUDIT_SKIP,
MAX_PAYLOAD_DEPTH,
MAX_REPORTED_PATH,
MIN_TOOL_CALLS_FOR_CHECK,
NON_RULE_KEYS,
PLUGIN_ROOT_ENV,
RULE_HEALTH_LOG,
STALENESS_WINDOW,
STDIN_DRAIN_LIMIT,
WARN_PREFIX,
)
if plugin_root:
# abspath(expanduser(...)): the audited roots are normalized against
# the process cwd, so a `~`-prefixed or relative plugin root would
# silently stop being the plugin root at the containment check.
env[PLUGIN_ROOT_ENV] = os.path.abspath(os.path.expanduser(plugin_root))
return env
def audit_roots(project_dir, user_home, env):
"""Directories a resolved hook script is allowed to live under.
Normalized once per audit: the roots do not change within a run, and
re-normalizing them per token is what made the first cut of this
containment check measurably slower than the audit it replaced.
"""
roots = [project_dir, user_home]
plugin_root = env.get(PLUGIN_ROOT_ENV)
if plugin_root:
roots.append(plugin_root)
return [_normalize(r) for r in roots]
def _normalize(path):
"""Absolute, separator-normalized, case-normalized form of `path`."""
if not os.path.isabs(path):
path = os.path.join(os.getcwd(), path)
return os.path.normcase(os.path.normpath(path))
def is_within(path, roots):
"""Whether `path` is one of `roots` or lives under one of them."""
target = _normalize(path)
for base in roots:
if target == base:
return True
if target.startswith(base.rstrip(os.sep) + os.sep):
return True
return False
def expand_placeholders(raw, env, single_quoted=False):
"""Expand the placeholders present in `env`, leaving the rest intact.
Args:
raw (`str`): A script token from a hook command.
env (`dict`): Placeholder name to replacement, from
:func:`placeholder_env`.
single_quoted (`bool`): Whether the token sat inside single quotes.
The shell does not expand those, so no path can be built from
them and the token is treated as unresolvable.
Returns:
`tuple[str, list[str], bool]`: The expanded token, the names of any
placeholders that could not be resolved, and whether anything was
actually substituted. A token carrying an unresolved placeholder is
skipped rather than reported as missing — we cannot tell a missing
script from a path we failed to build.
"""
unresolved = []
def _replace(match):
name = match.group(1)
if name not in env or single_quoted:
unresolved.append(name)
return match.group(0)
return env[name]
expanded = PLACEHOLDER_RE.sub(_replace, raw)
return expanded, unresolved, expanded != raw
def resolve_script_path(raw, project_dir, user_home, env, roots,
single_quoted=False):
"""Turn a token from a hook command into the paths we are willing to judge.
`~` resolves against CONFIG_HEALTH_USER_HOME when set (the same override
used for the user settings path), else the real home — so tests stay
deterministic without affecting real users.
The containment check applies to substituted paths only. A bare relative
path is not confined to the audited roots: a hook command does not say
which directory it runs from (plugin commands run from the plugin root,
project wiring from the project), so such a token is resolved under every
audited root and reported only when it is missing from all of them. An
absolute or `~` path outside the roots is still reported — that is a real
path to a real file, and the monitor has no reason to stay quiet about it.
Args:
raw (`str`): A script token from a hook command.
project_dir (`str`): Absolute project directory.
user_home (`str`): Absolute user home directory.
env (`dict`): Supported placeholder replacements.
roots (`list[str]`): Pre-normalized audited roots, from
:func:`audit_roots`.
single_quoted (`bool`): Whether the token sat inside single quotes.
Returns:
`tuple[list[str], str, bool]`: The candidate paths, a status (see
:data:`AUDIT_OK`, :data:`AUDIT_MISSING`, :data:`AUDIT_SKIP`), and
whether the token was a bare relative path judged against every
root. That last flag is what lets `--check` name the one case where
"healthy" and "the project copy is missing" look identical.
``'ok'`` — at least one candidate exists on disk.
``'missing'`` — no candidate exists; report the token.
``'skip'`` — no path could be built (an unresolvable or
single-quoted placeholder, or a substituted path
outside the audited roots). Reporting these is
how a plugin install turns into a false-warning
flood, and a monitor that cries wolf is worse than
no monitor.
"""
expanded, unresolved, changed = expand_placeholders(
raw, env, single_quoted,
from config_health_paths import (
_normalize,
audit_roots,
claude_data_dir,
placeholder_env,
read_json,
read_text,
resolve_dirs,
resolve_script_path,
)
if unresolved:
return [], AUDIT_SKIP, False
from config_health_scan import scan_command
except Exception:
if __name__ == '__main__':
sys.exit(0)
raise
if expanded.startswith('~'):
override = os.environ.get('CONFIG_HEALTH_USER_HOME')
base = override if override else os.path.expanduser('~')
candidates = [os.path.join(base, expanded[1:].lstrip('/\\'))]
relative = False
elif os.path.isabs(expanded):
candidates = [expanded]
relative = False
else:
candidates = [os.path.join(root, expanded) for root in roots]
relative = True
if changed and not all(is_within(c, roots) for c in candidates):
return [], AUDIT_SKIP, relative
existing = []
for candidate in candidates:
if os.path.exists(candidate):
existing.append(candidate)
break
if existing:
return existing, AUDIT_OK, relative
return candidates, AUDIT_MISSING, relative
def iter_hook_commands(settings):
@@ -775,13 +240,20 @@ def _dedupe_key(status, paths, raw):
def audit_rule_references(project_dir):
"""Verify rule files referenced by CLAUDE.md exist on disk."""
"""Verify rule files referenced by CLAUDE.md exist on disk.
Rule paths may be nested: ECC installs rules under namespaced
subdirectories such as `rules/ecc/common/security.md`, and a pattern that
stopped at one path segment silently skipped every one of those.
"""
findings = []
for base in ('CLAUDE.md', os.path.join('.claude', 'CLAUDE.md')):
content = read_text(os.path.join(project_dir, base))
if content is None:
continue
for ref in re.finditer(r'(?:\.claude/)?rules/[A-Za-z0-9_.-]+\.md', content):
for ref in re.finditer(
r'(?:\.claude/)?rules/(?:[A-Za-z0-9_.-]+/)*[A-Za-z0-9_.-]+\.md',
content):
rel = ref.group(0)
fp = os.path.join(project_dir, rel)
if not os.path.exists(fp):
@@ -828,10 +300,17 @@ def audit_guard_staleness(claude_dir):
]
if not complex_sessions:
continue
if all(rec.get(rule, 0) == 0 for rec in complex_sessions):
findings.append(
f'rule "{rule}" last fired {STALENESS_WINDOW}+ sessions ago → may be dead'
)
# Any positive count inside the window means the rule did fire in one
# of the recent sessions — including a short session the complexity
# filter leaves out of the judgment. Reporting "not fired in the last
# five sessions" while a counter in one of those five is positive
# sends the user to investigate a rule that worked.
if any(rec.get(rule, 0) > 0 for rec in recent):
continue
findings.append(
f'rule "{rule}" has not fired in the last '
f'{STALENESS_WINDOW} sessions → may be dead'
)
return findings
@@ -861,8 +340,40 @@ def read_settings(path, stats=None, label='settings'):
return parsed, False
def hook_sources(user_home, project_dir, env):
"""Every file that can declare a live hook, in the order Claude loads them.
Settings are not the only source. Claude Code also loads
`.claude/settings.local.json` (which wins over both settings files) and a
plugin's own `hooks/hooks.json`, both of which run hooks no settings file
mentions. Auditing only `settings.json` gives a missing script declared
solely in one of those a clean report — the failure mode this monitor
exists to catch.
Args:
user_home (`str`): Absolute user home.
project_dir (`str`): Absolute project directory.
env (`dict`): Placeholder environment from :func:`placeholder_env`.
Returns:
`list[tuple[str, str]]`: `(label, path)` pairs. A label is what
`--check` prints when the file exists but cannot be parsed.
"""
sources = [
('user', os.path.join(claude_data_dir(user_home), 'settings.json')),
('project', os.path.join(project_dir, '.claude', 'settings.json')),
('project-local',
os.path.join(project_dir, '.claude', 'settings.local.json')),
]
plugin_root = env.get(PLUGIN_ROOT_ENV)
if plugin_root:
sources.append(
('plugin', os.path.join(plugin_root, 'hooks', 'hooks.json')))
return sources
def audit_hook_settings(user_home, project_dir, stats=None):
"""Run the hook-wiring audit over both settings files.
"""Run the hook-wiring audit over every hook source.
Returns:
`tuple[dict, list[str]]`: The placeholder environment, and findings.
@@ -870,14 +381,11 @@ def audit_hook_settings(user_home, project_dir, stats=None):
env = placeholder_env(project_dir, user_home)
findings = []
claude_dir = claude_data_dir(user_home)
user_settings, _ = read_settings(
os.path.join(claude_dir, 'settings.json'), stats, 'user')
project_settings, _ = read_settings(
os.path.join(project_dir, '.claude', 'settings.json'), stats, 'project')
# Both settings may be absent or malformed — each is handled independently
# Each source may be absent or malformed — each is handled independently
# and never blocks. A malformed file yields no findings (nothing to audit)
# rather than a crash.
for settings in (user_settings, project_settings):
# and is counted, rather than a crash or a silent clean verdict.
for label, path in hook_sources(user_home, project_dir, env):
settings, _ = read_settings(path, stats, label)
if settings is not None:
findings.extend(
audit_hook_wiring(settings, project_dir, user_home, env, stats)
@@ -961,6 +469,12 @@ def check_mode():
for finding in findings:
print(' ' + WARN_PREFIX + finding)
_print_audit_counts(stats)
sys.exit(0)
def _print_audit_counts(stats):
"""Print the counts behind a --check verdict."""
# A monitor that decided not to look has to say so: unjudged paths are
# otherwise indistinguishable from healthy ones, and a blind spot that
# is invisible cannot be fixed. Printed here only, never per tool call.
@@ -1012,7 +526,6 @@ def check_mode():
# what makes a wrong-root false positive diagnosable.
print('config-health: [info] $CLAUDE_PLUGIN_ROOT resolved to '
+ plugin_root)
sys.exit(0)
def main():
+101
View File
@@ -0,0 +1,101 @@
"""Constants shared by the config-health monitor."""
import re
WARN_PREFIX = '[config-health] WARN: '
# Sessions of rule-health history to look back for guard staleness.
STALENESS_WINDOW = 5
# Minimum tool calls for a session to be "complex enough" to expect rule markers.
MIN_TOOL_CALLS_FOR_CHECK = 5
# Rule-health log written by the earlier Stop-hook monitor (read-only here).
# Relative to the Claude data root, which is CLAUDE_CONFIG_DIR or ~/.claude.
RULE_HEALTH_LOG = 'session-data/rule-health.jsonl'
# Metadata keys in each rule-health record, not rule counters.
NON_RULE_KEYS = {'ts', 'date', 'time', 'tool_calls', 'edits'}
# Matches a script path inside one shell word: ~/.claude/scripts/x.py,
# scripts/x.js, C:/path/x.py, ./hooks/x.py, ${CLAUDE_PLUGIN_ROOT}/hooks/x.js.
# Applied per shell word (see _split_shell_words) rather than to the raw
# command, so a quoted path containing a space stays one token.
#
# The trailing lookahead is load-bearing. Without it `archive.js.bak` matches
# as `archive.js`, and the monitor warns about a file that does not exist
# while the file the shell actually opens does.
SCRIPT_TOKEN = re.compile(
r'([^\s"\']+\.(?:py|js|mjs|cjs|sh))(?![A-Za-z0-9_.~-])'
)
# A quoted shell word that ends in a script extension is one argument
# verbatim, spaces included: "C:\Program Files\ecc\hooks\guard.py". Spaces
# inside it are part of the path, not separators.
WHOLE_WORD_SCRIPT_RE = re.compile(r'[^"\']*\.(?:py|js|mjs|cjs|sh)\Z')
# A finding never quotes a whole command. The whole-word rule above can pick
# up an argument that is itself a command line, and a hook command can be
# very long; a monitor that prints 200KB of somebody's settings file has
# stopped being a monitor.
MAX_REPORTED_PATH = 160
# $NAME / ${NAME} in a hook command.
PLACEHOLDER_RE = re.compile(r'\$\{?([A-Za-z_][A-Za-z0-9_]*)\}?')
# Interpreters whose -e / -c argument is a program body rather than a script
# path. The two kinds of payload are not the same thing:
# - a shell's -c payload is a command line, so it is scanned again as one
# - a node/python -e payload is source in another language, where a string
# is a string: p.join(r,'scripts/hooks/x.js') is assembled at runtime and
# is not a file the shell will open
SHELL_INTERPRETERS = frozenset(('sh', 'bash', 'zsh'))
JS_INTERPRETERS = frozenset((
'node', 'nodejs', 'python', 'python3', 'pythonw', 'py',
))
INTERPRETERS = SHELL_INTERPRETERS | JS_INTERPRETERS
# Long and short spellings of "the next word is a program body", plus the
# bundled short forms a shell accepts (`bash -lc "..."`).
PROGRAM_FLAG_LONG = frozenset(('--eval', '--command'))
# Options of the interpreters above whose value is the *next* word. Without
# these, `bash -o pipefail -c "..."` orphans the -c: pipefail looks like a
# command, so the payload after it is read as a path and the whole hook body
# gets printed as a missing file.
OPTION_TAKES_NEXT_WORD = frozenset(('-o', '-O', '-W', '-X', '--options'))
SHELL_SEPARATORS = (';', '&&', '||', '|', '&', '\n')
# A backslash only escapes what a shell would let it escape. Everything else
# after a backslash is literal, because on Windows — where this script also
# runs — a backslash is a path separator, not an escape. Notably absent: `\\`
# (a UNC prefix is two backslashes, not an escaped one), `$` and a backtick
# (C:\$Recycle.Bin is a directory, not an escape).
ESCAPABLE_BACKSLASH = frozenset((' ', '\t', '"', "'", ';', '&', '|',
'<', '>', '(', ')'))
# How deep a `sh -c "sh -c ..."` chain is followed before giving up. A command
# nested past this is not something a settings file should contain, and an
# unbounded recursion on attacker-shaped input is worse than a missed check.
MAX_PAYLOAD_DEPTH = 3
# Root of the installed plugin, when running from a plugin install. Claude Code
# sets this for plugin-style hooks; it is the only provider placeholder this
# monitor resolves, because every other placeholder is provider-specific and
# guessing at it would turn a real signal into a false warning.
PLUGIN_ROOT_ENV = 'CLAUDE_PLUGIN_ROOT'
# Pin the plugin root explicitly. The provider sets CLAUDE_PLUGIN_ROOT to the
# root of the plugin that is *running*, so with more than one plugin installed
# a settings line wired for a different one is judged against the wrong
# directory. One value cannot describe two plugins; this override is the
# honest escape hatch, and --check names the root it used.
PLUGIN_ROOT_OVERRIDE_ENV = 'CONFIG_HEALTH_PLUGIN_ROOT'
# Cap on hook input we are willing to drain. This is a bound on bytes buffered,
# not on time: sys.stdin.read(n) returns on n characters or EOF, whichever
# comes first, so a hook that hangs is stopped by the `timeout` in its wiring,
# not by this cap.
STDIN_DRAIN_LIMIT = 64 * 1024
# audit_hook_wiring verdicts.
AUDIT_OK = 'ok' # at least one candidate path exists
AUDIT_MISSING = 'missing' # no candidate path exists — report the token
AUDIT_SKIP = 'skip' # no path could be built — say nothing
+227
View File
@@ -0,0 +1,227 @@
"""Path resolution and defensive reads for the config-health monitor."""
import json
import os
from config_health_constants import (
AUDIT_MISSING,
AUDIT_OK,
AUDIT_SKIP,
PLACEHOLDER_RE,
PLUGIN_ROOT_ENV,
PLUGIN_ROOT_OVERRIDE_ENV,
)
def resolve_dirs():
"""Return (user_home, project_dir) honoring env overrides for determinism."""
user_home = os.environ.get('CONFIG_HEALTH_USER_HOME') or os.path.expanduser('~')
project_dir = os.environ.get('CLAUDE_PROJECT_DIR') or os.getcwd()
return user_home, project_dir
def claude_data_dir(user_home):
"""Claude's user data root: CLAUDE_CONFIG_DIR when set, else ~/.claude.
Claude Code reads user settings from this directory, and launchers move it
with CLAUDE_CONFIG_DIR. Reading ~/.claude unconditionally would audit a
file the harness is not loading, which is worse than not auditing at all.
"""
configured = os.environ.get('CLAUDE_CONFIG_DIR')
if configured:
return os.path.abspath(os.path.expanduser(configured))
return os.path.join(user_home, '.claude')
def read_text(path):
"""Read a file defensively; return None on any read/decode error."""
if not os.path.exists(path):
return None
try:
with open(path, 'r', encoding='utf-8') as f:
return f.read()
except (OSError, UnicodeDecodeError):
return None
def read_json(path):
"""Parse a JSON file defensively; return None if missing or malformed."""
text = read_text(path)
if text is None:
return None
try:
return json.loads(text)
except (ValueError, TypeError):
return None
def placeholder_env(project_dir, user_home):
"""Explicit map of the placeholders this monitor is willing to resolve.
Deliberately an allowlist rather than a copy of ``os.environ``: a hook
command can contain a provider placeholder we cannot judge, and resolving
an arbitrary one from ambient shell state would make findings depend on
unrelated environment. The two provider names below are the exception,
and only because a plugin install cannot be audited without them — both
are overridable so an audit can be pinned rather than inherited.
``$HOME`` / ``$USERPROFILE`` resolve to ``user_home``, the same value
``~`` resolves to, so ``$HOME/x.py`` and ``~/x.py`` are judged alike.
Args:
project_dir (`str`): Absolute project directory.
user_home (`str`): Absolute user home directory.
Returns:
`dict`: Placeholder name to absolute directory.
"""
env = {
'CLAUDE_PROJECT_DIR': project_dir,
'HOME': user_home,
'USERPROFILE': user_home,
}
plugin_root = (
os.environ.get(PLUGIN_ROOT_OVERRIDE_ENV)
or os.environ.get(PLUGIN_ROOT_ENV)
)
if plugin_root:
# abspath(expanduser(...)): the audited roots are normalized against
# the process cwd, so a `~`-prefixed or relative plugin root would
# silently stop being the plugin root at the containment check.
env[PLUGIN_ROOT_ENV] = os.path.abspath(os.path.expanduser(plugin_root))
return env
def audit_roots(project_dir, user_home, env):
"""Directories a resolved hook script is allowed to live under.
Normalized once per audit: the roots do not change within a run, and
re-normalizing them per token is what made the first cut of this
containment check measurably slower than the audit it replaced.
"""
roots = [project_dir, user_home]
plugin_root = env.get(PLUGIN_ROOT_ENV)
if plugin_root:
roots.append(plugin_root)
return [_normalize(r) for r in roots]
def _normalize(path):
"""Absolute, separator-normalized, case-normalized form of `path`."""
if not os.path.isabs(path):
path = os.path.join(os.getcwd(), path)
return os.path.normcase(os.path.normpath(path))
def is_within(path, roots):
"""Whether `path` is one of `roots` or lives under one of them."""
target = _normalize(path)
for base in roots:
if target == base:
return True
if target.startswith(base.rstrip(os.sep) + os.sep):
return True
return False
def expand_placeholders(raw, env, single_quoted=False):
"""Expand the placeholders present in `env`, leaving the rest intact.
Args:
raw (`str`): A script token from a hook command.
env (`dict`): Placeholder name to replacement, from
:func:`placeholder_env`.
single_quoted (`bool`): Whether the token sat inside single quotes.
The shell does not expand those, so no path can be built from
them and the token is treated as unresolvable.
Returns:
`tuple[str, list[str], bool]`: The expanded token, the names of any
placeholders that could not be resolved, and whether anything was
actually substituted. A token carrying an unresolved placeholder is
skipped rather than reported as missing — we cannot tell a missing
script from a path we failed to build.
"""
unresolved = []
def _replace(match):
name = match.group(1)
if name not in env or single_quoted:
unresolved.append(name)
return match.group(0)
return env[name]
expanded = PLACEHOLDER_RE.sub(_replace, raw)
return expanded, unresolved, expanded != raw
def resolve_script_path(raw, project_dir, user_home, env, roots,
single_quoted=False):
"""Turn a token from a hook command into the paths we are willing to judge.
`~` resolves against CONFIG_HEALTH_USER_HOME when set (the same override
used for the user settings path), else the real home — so tests stay
deterministic without affecting real users.
The containment check applies to substituted paths only. A bare relative
path is not confined to the audited roots: a hook command does not say
which directory it runs from (plugin commands run from the plugin root,
project wiring from the project), so such a token is resolved under every
audited root and reported only when it is missing from all of them. An
absolute or `~` path outside the roots is still reported — that is a real
path to a real file, and the monitor has no reason to stay quiet about it.
Args:
raw (`str`): A script token from a hook command.
project_dir (`str`): Absolute project directory.
user_home (`str`): Absolute user home directory.
env (`dict`): Supported placeholder replacements.
roots (`list[str]`): Pre-normalized audited roots, from
:func:`audit_roots`.
single_quoted (`bool`): Whether the token sat inside single quotes.
Returns:
`tuple[list[str], str, bool]`: The candidate paths, a status (see
:data:`AUDIT_OK`, :data:`AUDIT_MISSING`, :data:`AUDIT_SKIP`), and
whether the token was a bare relative path judged against every
root. That last flag is what lets `--check` name the one case where
"healthy" and "the project copy is missing" look identical.
``'ok'`` — at least one candidate exists on disk.
``'missing'`` — no candidate exists; report the token.
``'skip'`` — no path could be built (an unresolvable or
single-quoted placeholder, or a substituted path
outside the audited roots). Reporting these is
how a plugin install turns into a false-warning
flood, and a monitor that cries wolf is worse than
no monitor.
"""
expanded, unresolved, changed = expand_placeholders(
raw, env, single_quoted,
)
if unresolved:
return [], AUDIT_SKIP, False
if expanded.startswith('~'):
override = os.environ.get('CONFIG_HEALTH_USER_HOME')
base = override if override else os.path.expanduser('~')
candidates = [os.path.join(base, expanded[1:].lstrip('/\\'))]
relative = False
elif os.path.isabs(expanded):
candidates = [expanded]
relative = False
else:
candidates = [os.path.join(root, expanded) for root in roots]
relative = True
if changed and not all(is_within(c, roots) for c in candidates):
return [], AUDIT_SKIP, relative
existing = []
for candidate in candidates:
if os.path.exists(candidate):
existing.append(candidate)
break
if existing:
return existing, AUDIT_OK, relative
return candidates, AUDIT_MISSING, relative
+251
View File
@@ -0,0 +1,251 @@
"""Shell-command tokenising for the config-health monitor."""
from config_health_constants import (
ESCAPABLE_BACKSLASH,
INTERPRETERS,
MAX_PAYLOAD_DEPTH,
OPTION_TAKES_NEXT_WORD,
PROGRAM_FLAG_LONG,
SCRIPT_TOKEN,
SHELL_INTERPRETERS,
SHELL_SEPARATORS,
WHOLE_WORD_SCRIPT_RE,
)
def _split_shell_words(command):
"""Split `command` into (word, single_quoted) pairs, POSIX-quote aware.
A hook command is a shell command line, so a path containing a space has
to survive as one word. Splitting naively on whitespace turns
``python3 "C:\\Program Files\\ecc\\hooks\\guard.py"`` into the token
``Files\\ecc\\hooks\\guard.py``, which does not exist — a false alarm
manufactured by the tokenizer.
Args:
command (`str`): A raw hook command.
Returns:
`list[tuple[str, bool, bool]] | None`: Each shell word, whether any
part of it was quoted (a quoted word is one argument verbatim,
spaces included), and whether any part of it was single-quoted (a
single-quoted placeholder is not expanded by the shell, so it
cannot be resolved from here). `None` when a quote is left open:
the command is not parseable as written, and what a broken quote
swallows next is a guess.
"""
words = []
chars = []
quote = None
started = False
quoted = False
single = False
i = 0
while i < len(command):
ch = command[i]
if quote == "'":
if ch == "'":
quote = None
else:
chars.append(ch)
elif quote == '"':
if ch == '\\' and i + 1 < len(command) \
and command[i + 1] in ESCAPABLE_BACKSLASH:
chars.append(command[i + 1])
i += 1
elif ch == '"':
quote = None
else:
chars.append(ch)
elif ch in '\'"':
quote = ch
quoted = True
single = single or ch == "'"
started = True
elif ch.isspace():
if started:
words.append((''.join(chars), quoted, single))
chars = []
quoted = False
single = False
started = False
elif ch == '\\' and i + 1 < len(command) \
and command[i + 1] in ESCAPABLE_BACKSLASH:
chars.append(command[i + 1])
started = True
i += 1
else:
chars.append(ch)
started = True
i += 1
if quote is not None:
return None
if started:
words.append((''.join(chars), quoted, single))
return words
def _is_interpreter(word):
"""Whether `word` names a shell interpreter rather than a file."""
name = word.replace('\\', '/').rsplit('/', 1)[-1].lower()
return name in INTERPRETERS
def _is_program_flag(word, shell):
"""Whether `word` is an option whose next word is a program body.
Covers the long spellings, the plain short ones, and the bundled short
forms a shell accepts — `bash -lc "..."` is the same thing as `bash -c
"..."` and used to be read as two ordinary words.
The letter is interpreter-specific, and getting it wrong is a false
warning: `sh -e script.sh` is errexit, not a program body, so treating `-e`
as one hides the script the shell will run.
"""
if word in PROGRAM_FLAG_LONG:
return True
if word.startswith('--') or not word.startswith('-') or len(word) < 2:
return False
wanted = 'c' if shell else 'e'
return wanted in word[1:]
def _is_separator(word):
"""Whether `word` contains a shell command separator."""
return any(sep in word for sep in SHELL_SEPARATORS)
# scan_command returns (tokens, unparsed, bodies, too_deep). `tokens` is a
# list of (token, single_quoted); `unparsed` is True when the command could
# not be split as written (an unclosed quote); `bodies` counts interpreter
# program bodies that were skipped because they are source in another
# language; `too_deep` is True when a `sh -c` chain passed
# MAX_PAYLOAD_DEPTH, with the tokens found so far still returned. Every
# reason to decline judgement is counted rather than swallowed, because
# `--check` reports the counts.
#
# Three things need more than a regex over the raw command: a quoted word is
# one argument verbatim (a path with a space stays whole); an interpreter's
# program body is not a script path (a shell's -c payload is scanned again,
# a node/python payload is skipped); and a backslash only escapes what a
# shell would let it escape (treating every backslash as an escape mangles
# C:\Users\me\guard.py).
def scan_command(command, depth=0):
"""Return (tokens, unparsed, bodies, too_deep) for `command`."""
words = _split_shell_words(command)
if words is None:
return [], True, 0, False
tokens = []
bodies = 0
too_deep = False
index = 0
interpreter = None
option_arg = False
while index < len(words):
word, quoted, single = words[index]
# A separator only separates when the shell can see it. Inside quotes
# it is part of the name, and `python3 "weird;name.py"` is a file.
if not quoted and _is_separator(word):
interpreter = None
option_arg = False
index += 1
continue
if _is_interpreter(word):
interpreter = word
option_arg = False
index += 1
continue
if interpreter and _is_program_flag(
word, _is_shell_interpreter(interpreter)):
(index, added, stop, unparsed,
deep, reset) = _scan_program_body(
interpreter, quoted, words, index, depth, tokens)
bodies += added
too_deep = too_deep or deep
interpreter = None if reset else interpreter
if stop:
return tokens, unparsed, bodies, too_deep
continue
if interpreter and word.startswith('-') and len(word) > 1:
# An interpreter option; some take the next word as their value.
option_arg = not quoted and word in OPTION_TAKES_NEXT_WORD
index += 1
continue
if option_arg:
option_arg = False
index += 1
continue
interpreter = None
tokens.extend(_word_tokens(word, quoted, single))
index += 1
return tokens, False, bodies, too_deep
def _scan_program_body(interpreter, quoted, words, index, depth, tokens):
"""Handle an interpreter program flag at `index`.
Returns (next_index, bodies_added, stop, unparsed, too_deep,
reset_interpreter). `stop` means the whole scan must end now, with
`unparsed`/`too_deep` describing why.
"""
total = len(words)
if quoted:
# The body is glued to the flag, as in `node -e"..."`. Nothing after
# this word belongs to the program, and nothing inside it was judged,
# so it counts like any other skipped body.
return index + 1, 1, False, False, False, False
payload_at = index + 1
if payload_at >= total:
return total, 0, False, False, False, False
payload, payload_quoted, _ = words[payload_at]
if _is_shell_interpreter(interpreter):
if depth >= MAX_PAYLOAD_DEPTH:
# Too deep to follow. Counted, and the tokens collected so far
# are kept — a missing script on the outer command is still one.
return total, 0, True, False, True, False
if payload_quoted:
sub = scan_command(payload, depth + 1)
if sub[1]:
return total, 0, True, True, False, False
tokens.extend(sub[0])
return payload_at + 1, sub[2], False, False, sub[3], False
cursor = payload_at
chunk = []
while cursor < total and not _is_separator(words[cursor][0]):
chunk.append(words[cursor][0])
cursor += 1
sub = scan_command(' '.join(chunk), depth + 1)
if sub[1]:
return total, 0, True, True, False, False
tokens.extend(sub[0])
return cursor, sub[2], False, False, sub[3], False
# Source in another language: skip the body. Quoted, that is one word;
# unquoted, the shell hands node every word up to the next separator as
# the program, so all of them go. Counted, because nothing inside was
# judged and `--check` should say so.
if payload_quoted:
return payload_at + 1, 1, False, False, False, True
while payload_at < total and not _is_separator(words[payload_at][0]):
payload_at += 1
return payload_at, 1, False, False, False, True
def _word_tokens(word, quoted, single):
"""Turn one shell word into script-path tokens."""
candidate = word
if (quoted or ' ' in word) and not word.startswith('-'):
# `"python3 scripts/hooks/guard.js"` is one shell word, but it is an
# interpreter and its argument, not one long path.
head, _, tail = word.partition(' ')
if tail and _is_interpreter(head):
candidate = tail
if not candidate.startswith('-') and (quoted or ' ' in candidate) \
and WHOLE_WORD_SCRIPT_RE.match(candidate):
return [(candidate, single)]
return [(m.group(1), single) for m in SCRIPT_TOKEN.finditer(candidate)]
def _is_shell_interpreter(word):
"""Whether `word` names an interpreter whose -c payload is a command."""
name = word.replace('\\', '/').rsplit('/', 1)[-1].lower()
return name in SHELL_INTERPRETERS
+8 -4
View File
@@ -1626,10 +1626,14 @@ function collectRepairOperations(operationHealth, desiredPlan) {
&& !isDeepStrictEqual(operation.previousManagedHooks, operation.managedHooks)
))
.map(operation => ({ ...operation })),
].filter((operation, index, items) => items.findIndex(candidate => (
candidate.kind === operation.kind
&& candidate.destinationPath === operation.destinationPath
)) === index);
].filter((operation, index, items) => items.findIndex(candidate => {
if (candidate.kind !== operation.kind) return false;
if (candidate.destinationPath !== operation.destinationPath) return false;
// One settings file holds hooks shipped by several modules; each module's
// record must survive the dedupe so repair rewrites every contribution.
if (operation.kind !== 'update-claude-settings') return true;
return (candidate.sourceRelativePath || '') === (operation.sourceRelativePath || '');
}) === index);
}
function executeGuardedRepairOperation(repair, plan, operation, repairedPaths) {
+21 -5
View File
@@ -5,6 +5,14 @@ const {
validateRecordedManagedHooks,
} = require('./install/claude-settings');
// A module may only own the settings merge for the hook config it ships. The
// install state is the record of what the installer did, so this map is what
// keeps one module from claiming another module's hook source.
const CLAUDE_HOOKS_CONFIG_OWNERS = Object.freeze({
'hooks-runtime': CLAUDE_HOOKS_CONFIG_PATH,
'config-health': 'manifests/install-assets/config-health-hooks.json',
});
// Dependency-free, self-contained validation. The installer closure must not
// require any non-builtin package (enterprise supply-chain vetting: the vetted
// bytes must be the installed bytes). install-state is validated by the
@@ -218,11 +226,19 @@ function createFallbackValidator() {
if (!['claude', 'claude-project'].includes(state.target && state.target.target)) {
pushError(`${instancePath}/kind`, 'is only valid for Claude targets');
}
if (operation.moduleId !== 'hooks-runtime') {
pushError(`${instancePath}/moduleId`, 'must equal hooks-runtime');
}
if (String(operation.sourceRelativePath).replace(/\\/g, '/') !== CLAUDE_HOOKS_CONFIG_PATH) {
pushError(`${instancePath}/sourceRelativePath`, 'must equal hooks/hooks.json');
const expectedSource = CLAUDE_HOOKS_CONFIG_OWNERS[operation.moduleId];
if (!expectedSource) {
pushError(
`${instancePath}/moduleId`,
`must be a module that ships its own hooks (${Object.keys(CLAUDE_HOOKS_CONFIG_OWNERS).join(', ')})`
);
} else if (
String(operation.sourceRelativePath).replace(/\\/g, '/') !== expectedSource
) {
pushError(
`${instancePath}/sourceRelativePath`,
`must equal ${expectedSource} for module "${operation.moduleId}"`
);
}
if (
isNonEmptyString(state.target && state.target.root)
+22 -1
View File
@@ -11,8 +11,14 @@ const {
planClaudeHooksOperations,
convertWindowsPathToWSL,
} = require('./helpers');
const { getClaudeSettingsPath } = require('../install/claude-settings');
const CLAUDE_ECC_NAMESPACE = 'ecc';
// config-health ships its own SessionStart hook. It is a separate config from
// hooks/hooks.json because installing the module without hooks-runtime must
// not register every ECC hook, and installing hooks-runtime must not register
// this one without the module that provides the script.
const CONFIG_HEALTH_HOOKS_CONFIG_PATH = 'manifests/install-assets/config-health-hooks.json';
function getClaudeManagedDestinationPath(adapter, sourceRelativePath, input) {
const normalizedSourcePath = normalizeRelativePath(sourceRelativePath);
@@ -112,7 +118,7 @@ module.exports = createInstallTargetAdapter({
const operations = modules.flatMap(module => {
const paths = Array.isArray(module.paths) ? module.paths : [];
return paths
const moduleOperations = paths
.filter(p => !isForeignPlatformPath(p, adapter.target) && !adapter.excludesSourcePath(p))
.flatMap(sourceRelativePath => {
if (
@@ -140,6 +146,21 @@ module.exports = createInstallTargetAdapter({
return [adapter.createScaffoldOperation(module.id, sourceRelativePath, planningInput)];
});
if (module.id !== 'config-health') {
return moduleOperations;
}
// The skill promises a SessionStart hook by default. Copying the skill
// and the script is not that promise: without this settings merge the
// installed monitor is never invoked by an ordinary session. PreToolUse
// stays opt-in and is deliberately absent from this config.
return [...moduleOperations, createRemappedOperation(
adapter,
module.id,
CONFIG_HEALTH_HOOKS_CONFIG_PATH,
getClaudeSettingsPath(adapter.resolveRoot(planningInput)),
{ kind: 'update-claude-settings', strategy: 'merge-hook-ids' }
)];
});
if (!operations.some(operation => operation.moduleId === 'commands-core'
&& normalizeRelativePath(operation.sourceRelativePath).startsWith('scripts/'))) return operations;
+20 -2
View File
@@ -7,9 +7,13 @@ const {
normalizeRelativePath,
planClaudeHooksOperations,
} = require('./helpers');
const { getClaudeSettingsPath } = require('../install/claude-settings');
const CLAUDE_ECC_NAMESPACE = 'ecc';
const CLAUDE_PROJECT_COMMONJS_PACKAGE = 'manifests/install-assets/claude-project-scripts-package.json';
// config-health ships its own SessionStart hook; see claude-home.js for why
// this is not part of hooks/hooks.json.
const CONFIG_HEALTH_HOOKS_CONFIG_PATH = 'manifests/install-assets/config-health-hooks.json';
function getClaudeManagedDestinationPath(adapter, sourceRelativePath, input) {
const normalizedSourcePath = normalizeRelativePath(sourceRelativePath);
@@ -95,8 +99,22 @@ module.exports = createInstallTargetAdapter({
return [adapter.createScaffoldOperation(module.id, sourceRelativePath, planningInput)];
});
// The skill promises a SessionStart hook by default. Copying the skill
// and the script is not that promise: without this settings merge the
// installed monitor is never invoked by an ordinary session. PreToolUse
// stays opt-in and is deliberately absent from this config.
const withModuleHooks = module.id === 'config-health'
? [...moduleOperations, createRemappedOperation(
adapter,
module.id,
CONFIG_HEALTH_HOOKS_CONFIG_PATH,
getClaudeSettingsPath(adapter.resolveRoot(planningInput)),
{ kind: 'update-claude-settings', strategy: 'merge-hook-ids' }
)]
: moduleOperations;
if (module.id !== 'hooks-runtime') {
return moduleOperations;
return withModuleHooks;
}
return [
@@ -107,7 +125,7 @@ module.exports = createInstallTargetAdapter({
path.join(adapter.resolveRoot(planningInput), 'scripts', directory, 'package.json'),
{ strategy: 'preserve-relative-path' }
)),
...moduleOperations,
...withModuleHooks,
];
});
if (!operations.some(operation => operation.moduleId === 'commands-core'
+5
View File
@@ -611,9 +611,14 @@ function findPreviousManagedHooks(previousState, plan, operation) {
return null;
}
// Settings files collect hooks from more than one module, so the recorded
// operation is identified by its source as well; matching on the destination
// alone hands one module the other module's managed hooks.
const previousOperation = (previousState.operations || []).find(candidate => (
candidate.kind === operation.kind
&& comparablePath(candidate.destinationPath) === comparablePath(operation.destinationPath)
&& (operation.kind !== 'update-claude-settings'
|| (candidate.sourceRelativePath || '') === (operation.sourceRelativePath || ''))
));
if (!previousOperation || !previousOperation.managedHooks) {
return null;
+12 -3
View File
@@ -135,9 +135,18 @@ function isManagedOperation(operation) {
function uniqueOperations(operations) {
const byDestination = new Map();
for (const operation of operations) {
// A target path has one current owner. Later operations come from the
// newest plan and replace stale metadata for the same destination.
byDestination.set(comparablePath(operation.destinationPath), operation);
// A target path has one current owner — except a settings file, which
// takes contributions from every module that ships hooks. Keyed by the
// destination alone, the last settings operation would replace the
// earlier records, and uninstall would leave their managed hooks behind.
const isSettingsOperation = operation.kind === 'update-claude-settings'
|| operation.kind === 'remove-claude-settings-hooks';
const key = isSettingsOperation
? `${operation.kind}\0${comparablePath(operation.destinationPath)}\0${operation.sourceRelativePath || ''}`
: comparablePath(operation.destinationPath);
// Later operations come from the newest plan and replace stale metadata
// for the same destination and source.
byDestination.set(key, operation);
}
return [...byDestination.values()];
}