mirror of
https://github.com/affaan-m/ECC.git
synced 2026-11-17 05:22:17 +00:00
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:
20 files changed
+1752
-1249
No files matched your search
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"hooks": {
|
||||
"SessionStart": [
|
||||
{
|
||||
"id": "config-health:session-start",
|
||||
"matcher": ".*",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "python3 \"${CLAUDE_PLUGIN_ROOT}/scripts/config-health.py\" --startup",
|
||||
"timeout": 10
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -956,7 +956,10 @@
|
||||
"description": "Runtime configuration integrity monitoring for Claude Code (Claude-only; SessionStart by default, PreToolUse opt-in).",
|
||||
"paths": [
|
||||
"skills/config-health",
|
||||
"scripts/config-health.py"
|
||||
"scripts/config-health.py",
|
||||
"scripts/config_health_constants.py",
|
||||
"scripts/config_health_paths.py",
|
||||
"scripts/config_health_scan.py"
|
||||
],
|
||||
"targets": [
|
||||
"claude",
|
||||
|
||||
@@ -113,6 +113,9 @@
|
||||
"scripts/agent-convert.js",
|
||||
"scripts/catalog.js",
|
||||
"scripts/config-health.py",
|
||||
"scripts/config_health_constants.py",
|
||||
"scripts/config_health_paths.py",
|
||||
"scripts/config_health_scan.py",
|
||||
"scripts/ci/scan-supply-chain-iocs.js",
|
||||
"scripts/ci/supply-chain-advisory-sources.js",
|
||||
"scripts/ci/validate-skill-host-compat.js",
|
||||
|
||||
@@ -246,10 +246,22 @@
|
||||
},
|
||||
"then": {
|
||||
"required": ["managedHooks"],
|
||||
"properties": {
|
||||
"moduleId": { "const": "hooks-runtime" },
|
||||
"sourceRelativePath": { "const": "hooks/hooks.json" }
|
||||
}
|
||||
"anyOf": [
|
||||
{
|
||||
"properties": {
|
||||
"moduleId": { "const": "hooks-runtime" },
|
||||
"sourceRelativePath": { "const": "hooks/hooks.json" }
|
||||
}
|
||||
},
|
||||
{
|
||||
"properties": {
|
||||
"moduleId": { "const": "config-health" },
|
||||
"sourceRelativePath": {
|
||||
"const": "manifests/install-assets/config-health-hooks.json"
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
|
||||
+98
-585
@@ -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():
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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) {
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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'
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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()];
|
||||
}
|
||||
|
||||
@@ -114,9 +114,11 @@ the root of the plugin that is *running*, so a settings line wired for a second
|
||||
plugin is judged against the wrong directory. One variable cannot describe two
|
||||
plugins; set `CONFIG_HEALTH_PLUGIN_ROOT` explicitly in that case.
|
||||
|
||||
**Standalone install?** `cp scripts/config-health.py ~/.claude/scripts/` puts it
|
||||
where no plugin root is in its environment. Two things follow, and both are
|
||||
worth acting on rather than ignoring:
|
||||
**Standalone install?** Copy the entry point **and its three helper modules**
|
||||
(`config_health_constants.py`, `config_health_paths.py`, `config_health_scan.py`)
|
||||
into the same directory as `config-health.py`; the entry imports them by name.
|
||||
That puts it where no plugin root is in its environment. Two things follow, and
|
||||
both are worth acting on rather than ignoring:
|
||||
|
||||
- `${CLAUDE_PLUGIN_ROOT}/…` lines become unresolvable, so they are skipped —
|
||||
silence, not verification;
|
||||
@@ -178,9 +180,10 @@ Dead rule reference:
|
||||
`CLAUDE.md references missing rule file: rules/ghost.md` → exit 0.
|
||||
|
||||
Rule staleness:
|
||||
`rule "双池强制触发" last fired 5+ sessions ago → may be dead` — the count is
|
||||
fixed at the five most recent complex sessions, not an arbitrary number of
|
||||
sessions back.
|
||||
`rule "双池强制触发" has not fired in the last 5 sessions → may be dead` — the
|
||||
window is the five most recent complex sessions, not an arbitrary number of
|
||||
sessions back. Any positive count inside that window keeps the rule alive, even
|
||||
in a short session: a count above zero means the rule did fire.
|
||||
|
||||
Healthy plugin install:
|
||||
`python3 "${CLAUDE_PLUGIN_ROOT}/scripts/hooks/guard.py"` with the plugin
|
||||
@@ -189,19 +192,31 @@ one finding, still exit 0 — **provided `CLAUDE_PLUGIN_ROOT` (or
|
||||
`CONFIG_HEALTH_PLUGIN_ROOT`) is set in the monitor's own environment.** Without
|
||||
it the token is unresolvable and there is no finding either way.
|
||||
|
||||
What this monitor reads: `settings.json` (user and project), `CLAUDE.md` (in
|
||||
the project dir), and `$CLAUDE_CONFIG_DIR/session-data/rule-health.jsonl`
|
||||
(default `~/.claude/session-data/rule-health.jsonl`). It reads no documentation
|
||||
to find references, and it does not count how many places a script is wired.
|
||||
What this monitor reads: the hook-wired settings files — `settings.json` in the
|
||||
user dir, in the project dir, and `.claude/settings.local.json` in the project
|
||||
dir; plus the plugin's own `hooks/hooks.json` when `CLAUDE_PLUGIN_ROOT` (or
|
||||
`CONFIG_HEALTH_PLUGIN_ROOT`) is set — `CLAUDE.md` (in the project dir), and
|
||||
`$CLAUDE_CONFIG_DIR/session-data/rule-health.jsonl` (default
|
||||
`~/.claude/session-data/rule-health.jsonl`). It reads no documentation to find
|
||||
references, and it does not count how many places a script is wired.
|
||||
|
||||
## Install
|
||||
|
||||
**ECC users:** install the `config-health` module (`npx ecc-install --modules config-health` or the `full` profile). It is a **Claude-only** module with a SessionStart hook by default; PreToolUse is opt-in. It does not target other harnesses, so it stays isolated from shared 13-harness modules.
|
||||
**ECC users:** install the `config-health` module (`npx ecc-universal install --modules config-health` or the `full` profile). It is a **Claude-only** module with a SessionStart hook by default; PreToolUse is opt-in. It does not target other harnesses, so it stays isolated from shared 13-harness modules.
|
||||
|
||||
**Standalone:** copy `scripts/config-health.py` to
|
||||
`${CLAUDE_CONFIG_DIR:-~/.claude}/scripts/config-health.py` and verify it exists
|
||||
before enabling. If your launcher sets `CLAUDE_CONFIG_DIR`, use that path in the
|
||||
hook command; `~/.claude` is not the file Claude loads in that setup.
|
||||
The module ships its own hook config (`manifests/install-assets/config-health-hooks.json`), merged into `settings.json` at install time with the install root substituted for `${CLAUDE_PLUGIN_ROOT}` — so a home install points at `~/.claude/scripts/config-health.py` and a project install at `<project>/.claude/scripts/config-health.py`. Because that merge is a settings write, it is gated by hook consent:
|
||||
|
||||
- `npx ecc-universal install --modules config-health --enable-hooks` wires the SessionStart hook.
|
||||
- `npx ecc-universal install --modules config-health --no-hooks` installs the script and skill only; nothing is written to `settings.json`, and you wire it yourself from the JSON below.
|
||||
|
||||
Uninstall removes the hook entry along with the files.
|
||||
|
||||
**Standalone:** copy `scripts/config-health.py` and the three helper modules
|
||||
(`config_health_constants.py`, `config_health_paths.py`, `config_health_scan.py`)
|
||||
to `${CLAUDE_CONFIG_DIR:-~/.claude}/scripts/` and verify the entry point exists
|
||||
before enabling. The helpers must sit in the same directory as the entry point.
|
||||
If your launcher sets `CLAUDE_CONFIG_DIR`, use that path in the hook command;
|
||||
`~/.claude` is not the file Claude loads in that setup.
|
||||
|
||||
**Important:** Merge these hook entries into your existing `hooks` object — do not replace it, or you will lose hooks like delivery-gate.
|
||||
|
||||
@@ -243,4 +258,7 @@ Write; not recommended by default):
|
||||
|
||||
| File | Purpose | Hook |
|
||||
|------|---------|------|
|
||||
| scripts/config-health.py | Rule health, hook audit, staleness | SessionStart; PreToolUse opt-in |
|
||||
| scripts/config-health.py | CLI entry: startup, pre-tool, check | SessionStart; PreToolUse opt-in |
|
||||
| scripts/config_health_constants.py | Constants, regexes, audit sets | — |
|
||||
| scripts/config_health_paths.py | Path resolution and defensive reads | — |
|
||||
| scripts/config_health_scan.py | Shell-command tokenising and scanning | — |
|
||||
@@ -0,0 +1,163 @@
|
||||
/**
|
||||
* Shared harness for the config-health hook-contract tests.
|
||||
*
|
||||
* The suites were split out of one 1389-line file. Everything that spawns the
|
||||
* monitor, builds a disposable home, or writes settings lives here so both
|
||||
* suites exercise the same process contract.
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
const { spawnSync } = require('child_process');
|
||||
const fs = require('fs');
|
||||
const os = require('os');
|
||||
const path = require('path');
|
||||
|
||||
const SCRIPT = path.join(__dirname, '..', '..', 'scripts', 'config-health.py');
|
||||
|
||||
// Resolve a working python. On Windows, missing interpreters surface as
|
||||
// status 9009 (not a spawn error), so probe both name and exit status.
|
||||
function resolvePython() {
|
||||
const probe = (name) => {
|
||||
const r = spawnSync(name, ['--version'], { stdio: 'ignore' });
|
||||
return !r.error && r.status === 0;
|
||||
};
|
||||
if (process.env.CONFIG_HEALTH_PYTHON) return process.env.CONFIG_HEALTH_PYTHON;
|
||||
if (probe('python3')) return 'python3';
|
||||
if (probe('python')) return 'python';
|
||||
throw new Error('No python interpreter found (tried CONFIG_HEALTH_PYTHON, python3, python)');
|
||||
}
|
||||
|
||||
const PYTHON = resolvePython();
|
||||
|
||||
// ---- helpers ---------------------------------------------------------------
|
||||
|
||||
function test(name, fn) {
|
||||
try {
|
||||
fn();
|
||||
console.log(` ✓ ${name}`);
|
||||
return true;
|
||||
} catch (err) {
|
||||
console.log(` ✗ ${name}`);
|
||||
console.log(` Error: ${err.message}`);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function makeFixture() {
|
||||
// Returns { home, proj, root } — a throwaway sandbox under os.tmpdir().
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'config-health-'));
|
||||
const home = path.join(root, 'home');
|
||||
const proj = path.join(root, 'proj');
|
||||
fs.mkdirSync(path.join(home, '.claude'), { recursive: true });
|
||||
fs.mkdirSync(path.join(proj, '.claude'), { recursive: true });
|
||||
return { root, home, proj };
|
||||
}
|
||||
|
||||
function run(mode, { home, proj }, stdin = '', extraEnv = {}) {
|
||||
return spawnSync(PYTHON, [SCRIPT, mode], {
|
||||
env: {
|
||||
...process.env,
|
||||
CONFIG_HEALTH_USER_HOME: home,
|
||||
CLAUDE_PROJECT_DIR: proj,
|
||||
CLAUDE_CONFIG_DIR: '',
|
||||
...extraEnv,
|
||||
},
|
||||
input: stdin,
|
||||
encoding: 'utf8',
|
||||
});
|
||||
}
|
||||
|
||||
function writeSettings(home, content) {
|
||||
fs.writeFileSync(path.join(home, '.claude', 'settings.json'), content, 'utf8');
|
||||
}
|
||||
|
||||
// Install-lifecycle fixture: a disposable HOME and Claude data root, so the
|
||||
// real installer/repair/uninstaller run without touching the user's config.
|
||||
function makeInstallFixture() {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'config-health-install-'));
|
||||
const home = path.join(root, 'home');
|
||||
const config = path.join(root, 'claude');
|
||||
const proj = path.join(root, 'proj');
|
||||
fs.mkdirSync(home, { recursive: true });
|
||||
fs.mkdirSync(config, { recursive: true });
|
||||
fs.mkdirSync(proj, { recursive: true });
|
||||
return { root, home, config, proj };
|
||||
}
|
||||
|
||||
function installEnv(fx, extraEnv = {}) {
|
||||
return {
|
||||
HOME: fx.home,
|
||||
USERPROFILE: fx.home,
|
||||
CLAUDE_CONFIG_DIR: fx.config,
|
||||
CONFIG_HEALTH_USER_HOME: fx.home,
|
||||
CLAUDE_PROJECT_DIR: fx.proj,
|
||||
...extraEnv,
|
||||
};
|
||||
}
|
||||
|
||||
function runNode(scriptRel, args, env) {
|
||||
return spawnSync(process.execPath, [path.join(__dirname, '..', '..', scriptRel), ...args], {
|
||||
cwd: path.join(__dirname, '..', '..'),
|
||||
env: { ...process.env, ...env },
|
||||
encoding: 'utf8',
|
||||
timeout: 120000,
|
||||
});
|
||||
}
|
||||
|
||||
function runInstalled(mode, fx, extraEnv = {}) {
|
||||
return spawnSync(PYTHON, [path.join(fx.config, 'scripts', 'config-health.py'), mode], {
|
||||
env: { ...process.env, ...installEnv(fx, extraEnv) },
|
||||
encoding: 'utf8',
|
||||
timeout: 120000,
|
||||
});
|
||||
}
|
||||
|
||||
function runInstalledWithInput(mode, fx, input, extraEnv = {}) {
|
||||
return spawnSync(PYTHON, [path.join(fx.config, 'scripts', 'config-health.py'), mode], {
|
||||
env: { ...process.env, ...installEnv(fx, extraEnv) },
|
||||
input,
|
||||
encoding: 'utf8',
|
||||
timeout: 120000,
|
||||
});
|
||||
}
|
||||
|
||||
const HOOKS_JSON = (scriptPath) => JSON.stringify({
|
||||
hooks: {
|
||||
SessionStart: [{ hooks: [{ type: 'command', command: `python3 ${scriptPath} --start`, timeout: 5000 }] }],
|
||||
PreToolUse: [{ matcher: 'Edit|Write', hooks: [{ type: 'command', command: `python3 ${scriptPath} --pretool`, timeout: 3000 }] }],
|
||||
},
|
||||
});
|
||||
|
||||
// A single command hook, for pinning one parser or resolution rule at a time
|
||||
// instead of the two-shape fixture above.
|
||||
const ONE_HOOK = (command, event = 'PreToolUse') => JSON.stringify({
|
||||
hooks: { [event]: [{ hooks: [{ type: 'command', command, timeout: 5 }] }] },
|
||||
});
|
||||
|
||||
// A plugin install wires its hooks against $CLAUDE_PLUGIN_ROOT, which is a
|
||||
// directory the monitor must expand rather than treat as project-relative.
|
||||
const PLUGIN_HOOKS_JSON = (relPath) => JSON.stringify({
|
||||
hooks: {
|
||||
SessionStart: [{ hooks: [{ type: 'command', command: `python3 "\${CLAUDE_PLUGIN_ROOT}/${relPath}" --start`, timeout: 5000 }] }],
|
||||
PreToolUse: [{ matcher: 'Edit|Write', hooks: [{ type: 'command', command: `python3 "\${CLAUDE_PLUGIN_ROOT}/${relPath}" --pretool`, timeout: 3000 }] }],
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
module.exports = {
|
||||
SCRIPT,
|
||||
PYTHON,
|
||||
test,
|
||||
makeFixture,
|
||||
run,
|
||||
writeSettings,
|
||||
makeInstallFixture,
|
||||
installEnv,
|
||||
runNode,
|
||||
runInstalled,
|
||||
runInstalledWithInput,
|
||||
HOOKS_JSON,
|
||||
ONE_HOOK,
|
||||
PLUGIN_HOOKS_JSON,
|
||||
};
|
||||
@@ -0,0 +1,570 @@
|
||||
/**
|
||||
* config-health tests for shell parsing, finding accounting, and the install
|
||||
* lifecycle.
|
||||
*
|
||||
* Run with: node tests/hooks/config-health-parser.test.js
|
||||
* (also picked up by `node tests/run-all.js`)
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
const assert = require('assert');
|
||||
const { spawnSync } = require('child_process');
|
||||
const fs = require('fs');
|
||||
const os = require('os');
|
||||
const path = require('path');
|
||||
|
||||
const {
|
||||
SCRIPT,
|
||||
PYTHON,
|
||||
test,
|
||||
makeFixture,
|
||||
run,
|
||||
writeSettings,
|
||||
makeInstallFixture,
|
||||
installEnv,
|
||||
runNode,
|
||||
runInstalled,
|
||||
runInstalledWithInput,
|
||||
HOOKS_JSON,
|
||||
ONE_HOOK,
|
||||
PLUGIN_HOOKS_JSON,
|
||||
} = require('./config-health-helpers');
|
||||
|
||||
function runTests() {
|
||||
console.log('\n=== Testing config-health.py parser, accounting, and install lifecycle ===\n');
|
||||
let passed = 0;
|
||||
let total = 0;
|
||||
|
||||
const t = (name, fn) => { total += 1; if (test(name, fn)) passed += 1; };
|
||||
|
||||
// --- a blind spot nobody can see is not a health check -------------------
|
||||
|
||||
t('--check reports how many hook paths it did not audit', () => {
|
||||
const fx = makeFixture();
|
||||
writeSettings(fx.home, ONE_HOOK('python3 "${CLAUDE_ENV_FILE}/hooks/x.py"'));
|
||||
const r = run('--check', fx, '', { CLAUDE_ENV_FILE: '' });
|
||||
assert.ok(r.stdout.includes('not audited'),
|
||||
`the blind spot must be visible, got: ${r.stdout.trim()}`);
|
||||
});
|
||||
|
||||
t('--check names the plugin root it judged against', () => {
|
||||
const fx = makeFixture();
|
||||
const pluginRoot = path.join(fx.root, 'plugin');
|
||||
fs.mkdirSync(pluginRoot, { recursive: true });
|
||||
const r = run('--check', fx, '', { CLAUDE_PLUGIN_ROOT: pluginRoot });
|
||||
assert.ok(r.stdout.includes(pluginRoot),
|
||||
`a wrong-root false positive must be diagnosable, got: ${r.stdout.trim()}`);
|
||||
});
|
||||
|
||||
// --- program bodies, quoting, and the backslash -------------------------
|
||||
// A second adversarial pass found that the first fix of these introduced a
|
||||
// Windows regression: treating every backslash as a shell escape turned
|
||||
// C:\Users\me\guard.py into C:Usersmeguard.py, a false alarm on the
|
||||
// platform this script is developed on. These pin the corrected rules.
|
||||
|
||||
t('an unquoted Windows path keeps its backslashes', () => {
|
||||
const fx = makeFixture();
|
||||
const dir = path.join(fx.home, 'back', 'slash');
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
const present = path.join(dir, 'win.py');
|
||||
fs.writeFileSync(present, '', 'utf8');
|
||||
writeSettings(fx.home, ONE_HOOK(`python3 ${present}`));
|
||||
const ok = run('--startup', fx);
|
||||
assert.ok(!ok.stdout.includes('missing script'),
|
||||
`a Windows path must not be unescaped into nonsense, got: ${ok.stdout.trim()}`);
|
||||
|
||||
writeSettings(fx.home, ONE_HOOK(`python3 ${path.join(dir, 'gone.py')}`));
|
||||
const missing = run('--startup', fx);
|
||||
assert.ok(missing.stdout.includes('gone.py'),
|
||||
`and the missing case must still be reported, got: ${missing.stdout.trim()}`);
|
||||
});
|
||||
|
||||
t('a shell -c body is scanned as a command line again', () => {
|
||||
const fx = makeFixture();
|
||||
const cmd = `sh -c "python3 ${path.join(fx.root, 'nowhere', 'ghost.py')}"`;
|
||||
writeSettings(fx.home, ONE_HOOK(cmd));
|
||||
const r = run('--startup', fx);
|
||||
assert.ok(r.stdout.includes('ghost.py'),
|
||||
`the shell will open that file, so it must be reported, got: ${r.stdout.trim()}`);
|
||||
});
|
||||
|
||||
t('bundled and long-form program flags are recognised', () => {
|
||||
const fx = makeFixture();
|
||||
for (const flag of ['-c', '-lc', '--command']) {
|
||||
writeSettings(fx.home, ONE_HOOK(`bash ${flag} "python3 .claude/scripts/ghost.py"`));
|
||||
const r = run('--startup', fx);
|
||||
assert.ok(r.stdout.includes('ghost.py'),
|
||||
`${flag} takes a command body and must not hide the reference, got: ${r.stdout.trim()}`);
|
||||
}
|
||||
});
|
||||
|
||||
t('a node -e body is skipped, and the argument after it is not', () => {
|
||||
const fx = makeFixture();
|
||||
for (const cmd of [
|
||||
'node -e "const s=p.join(r,\'scripts/hooks/never-created.js\')" node scripts/hooks/ghost.js',
|
||||
'node --eval "const s=1" node scripts/hooks/ghost.js',
|
||||
'node -e const s = p.join(r, "scripts/hooks/never-created.js") ; node scripts/hooks/ghost.js',
|
||||
]) {
|
||||
writeSettings(fx.home, ONE_HOOK(cmd));
|
||||
const r = run('--startup', fx);
|
||||
assert.ok(r.stdout.includes('ghost.js'),
|
||||
`the real argument must survive the body, got: ${r.stdout.trim()}`);
|
||||
assert.ok(!r.stdout.includes('never-created.js'),
|
||||
`a string inside the body is not a file, got: ${r.stdout.trim()}`);
|
||||
}
|
||||
});
|
||||
|
||||
t('an unclosed quote is skipped, counted, and reported by --check', () => {
|
||||
const fx = makeFixture();
|
||||
writeSettings(fx.home, ONE_HOOK('python3 ".claude/scripts/ghost.py --start'));
|
||||
const r = run('--check', fx);
|
||||
assert.strictEqual(r.status, 0, `expected exit 0, got ${r.status}`);
|
||||
assert.ok(!r.stdout.includes('missing script'),
|
||||
`an unparseable command must not produce a guess, got: ${r.stdout.trim()}`);
|
||||
assert.ok(/unclosed quote/.test(r.stdout),
|
||||
`but it must not be invisible either, got: ${r.stdout.trim()}`);
|
||||
});
|
||||
|
||||
t('a relative hook satisfied only outside the project is disclosed', () => {
|
||||
const fx = makeFixture();
|
||||
fs.mkdirSync(path.join(fx.home, '.claude', 'scripts'), { recursive: true });
|
||||
fs.writeFileSync(path.join(fx.home, '.claude', 'scripts', 'home-only.py'), '', 'utf8');
|
||||
writeSettings(fx.home, HOOKS_JSON('.claude/scripts/home-only.py'));
|
||||
const r = run('--check', fx);
|
||||
assert.ok(r.stdout.includes('satisfied by the user home or plugin root'),
|
||||
`the cross-root trade must be visible, got: ${r.stdout.trim()}`);
|
||||
});
|
||||
|
||||
t('an option between the interpreter and -c does not orphan the body', () => {
|
||||
const fx = makeFixture();
|
||||
// The payload is chosen per interpreter: a shell body is a command line
|
||||
// and is rescanned, a python body is source and is not a file reference.
|
||||
const cases = [
|
||||
['bash -x -c "python3 .claude/scripts/ghost.py"', 'ghost.py'],
|
||||
['bash -o pipefail -c "python3 .claude/scripts/ghost.py"', 'ghost.py'],
|
||||
['sh -lc "python3 .claude/scripts/ghost.py"', 'ghost.py'],
|
||||
['bash -x -lc "python3 .claude/scripts/ghost.py"', 'ghost.py'],
|
||||
['python3 -u -c "print(1)" .claude/scripts/ghost.py', 'ghost.py'],
|
||||
];
|
||||
for (const [cmd, expected] of cases) {
|
||||
writeSettings(fx.home, ONE_HOOK(cmd));
|
||||
const r = run('--startup', fx);
|
||||
assert.ok(r.stdout.includes(expected),
|
||||
`${cmd} must still reach the reference, got: ${r.stdout.trim()}`);
|
||||
assert.ok(!r.stdout.includes('python3 .claude/scripts/ghost.py'),
|
||||
`a whole payload must never be printed as a path, got: ${r.stdout.trim()}`);
|
||||
}
|
||||
});
|
||||
|
||||
t('a separator inside quotes is part of the name, not a separator', () => {
|
||||
const fx = makeFixture();
|
||||
for (const name of ['weird;name.py', 'a|b.py', 'a&b.py']) {
|
||||
writeSettings(fx.home, ONE_HOOK(`python3 ".claude/scripts/${name}"`));
|
||||
const r = run('--startup', fx);
|
||||
assert.ok(r.stdout.includes(name),
|
||||
`${name} is a legal filename, got: ${r.stdout.trim()}`);
|
||||
}
|
||||
});
|
||||
|
||||
t('an unclosed quote inside a payload is counted, not dropped', () => {
|
||||
const fx = makeFixture();
|
||||
writeSettings(fx.home, ONE_HOOK('sh -c "python3 .claude/scripts/ghost.py && echo \\"oops"'));
|
||||
const r = run('--check', fx);
|
||||
assert.strictEqual(r.status, 0, `expected exit 0, got ${r.status}`);
|
||||
assert.ok(!r.stdout.includes('missing script'),
|
||||
`an unparseable payload must not produce a guess, got: ${r.stdout.trim()}`);
|
||||
assert.ok(/unclosed quote/.test(r.stdout),
|
||||
`and the outer command must be reported as unparsed, got: ${r.stdout.trim()}`);
|
||||
});
|
||||
|
||||
t('Windows paths a POSIX escaper would mangle survive intact', () => {
|
||||
const fx = makeFixture();
|
||||
// A UNC prefix is two backslashes, not an escaped one. Collapsing it to
|
||||
// \server\share invents a rooted path that was never written.
|
||||
writeSettings(fx.home, ONE_HOOK(String.raw`python3 \\server\share\ghost.py`));
|
||||
const unc = run('--startup', fx);
|
||||
assert.ok(unc.stdout.includes(String.raw`\\server\share\ghost.py`),
|
||||
`a UNC path must be reported whole, got: ${unc.stdout.trim()}`);
|
||||
|
||||
// C:\$Recycle.Bin: the $ reads as a shell placeholder, so the token is
|
||||
// skipped — but skipped and counted, not escaped into C:Recycle.Bin.
|
||||
writeSettings(fx.home, ONE_HOOK(String.raw`python3 C:\$Recycle.Bin\ghost.py`));
|
||||
const dollar = run('--check', fx);
|
||||
assert.ok(!dollar.stdout.includes('C:Recycle.Bin'),
|
||||
`a backslash must not escape the dollar, got: ${dollar.stdout.trim()}`);
|
||||
assert.ok(/not audited/.test(dollar.stdout),
|
||||
`and the skip must be counted, got: ${dollar.stdout.trim()}`);
|
||||
});
|
||||
|
||||
t('a skipped program body is counted, not dropped silently', () => {
|
||||
const fx = makeFixture();
|
||||
// A file named inside a node -e body is a string in another language and
|
||||
// cannot be checked. Silence is right; silence with no count is not.
|
||||
writeSettings(fx.home, ONE_HOOK(
|
||||
'node -e "const s=p.join(r,\'.claude/scripts/ghost.js\')" node .claude/scripts/real.py'));
|
||||
const r = run('--check', fx);
|
||||
assert.ok(!r.stdout.includes('ghost.js'),
|
||||
`a string inside a JS body is not a file, got: ${r.stdout.trim()}`);
|
||||
assert.ok(/program body/.test(r.stdout),
|
||||
`but the unjudged body must be visible, got: ${r.stdout.trim()}`);
|
||||
});
|
||||
|
||||
t('the repo\'s own hook wiring is fully accounted for', () => {
|
||||
const repoRoot = path.join(__dirname, '..', '..');
|
||||
const real = fs.readFileSync(path.join(repoRoot, 'hooks', 'hooks.json'), 'utf8');
|
||||
const fx = makeFixture();
|
||||
writeSettings(fx.home, real);
|
||||
const r = run('--check', fx, '', { CLAUDE_PLUGIN_ROOT: repoRoot });
|
||||
assert.ok(r.stdout.includes('[ok] normal'),
|
||||
`a healthy install must be healthy, got: ${r.stdout.trim()}`);
|
||||
// Every one of the 23 commands hides a program body, and every relative
|
||||
// reference resolves through the plugin root. If those two counts ever go
|
||||
// to zero, the numbers below are no longer describing anything.
|
||||
const bodies = Number((r.stdout.match(/(\d+) interpreter program body/) || [])[1]);
|
||||
const other = Number((r.stdout.match(/(\d+) relative hook path/) || [])[1]);
|
||||
assert.ok(bodies >= 20, `expected ~23 skipped bodies, got ${bodies}`);
|
||||
assert.ok(other >= 10, `expected plugin-root-satisfied paths, got ${other}`);
|
||||
});
|
||||
|
||||
t('a longer name whose prefix is a script name is not truncated to it', () => {
|
||||
const fx = makeFixture();
|
||||
const dir = path.join(fx.proj, 'scripts', 'hooks');
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
// The shell opens these files. A regex without an end guard matches the
|
||||
// prefix and warns about a file that does not exist.
|
||||
for (const name of ['archive.js.bak', 'buf.py.map', 'guard.pyc', 'ok.py~']) {
|
||||
fs.writeFileSync(path.join(dir, name), '', 'utf8');
|
||||
writeSettings(fx.home, ONE_HOOK(`python3 scripts/hooks/${name}`));
|
||||
const r = run('--startup', fx);
|
||||
assert.ok(!r.stdout.includes('missing script'),
|
||||
`${name} exists; a prefix match would warn about a different file, got: ${r.stdout.trim()}`);
|
||||
}
|
||||
fs.writeFileSync(path.join(dir, 'gone.js.bak'), '', 'utf8');
|
||||
writeSettings(fx.home, ONE_HOOK('python3 scripts/hooks/absent.js.bak'));
|
||||
const missing = run('--startup', fx);
|
||||
assert.ok(!missing.stdout.includes('missing script'),
|
||||
`and an absent one is not a script reference either, got: ${missing.stdout.trim()}`);
|
||||
});
|
||||
|
||||
t('sh -e is errexit, not a program body', () => {
|
||||
const fx = makeFixture();
|
||||
writeSettings(fx.home, ONE_HOOK('sh -e .claude/scripts/ghost.py'));
|
||||
const r = run('--startup', fx);
|
||||
assert.ok(r.stdout.includes('ghost.py'),
|
||||
`sh -e runs the next word as a script, got: ${r.stdout.trim()}`);
|
||||
});
|
||||
|
||||
t('a one-word quoted command is not reported as one long path', () => {
|
||||
const fx = makeFixture();
|
||||
writeSettings(fx.home, ONE_HOOK('"python3 .claude/scripts/ghost.js"'));
|
||||
const r = run('--startup', fx);
|
||||
assert.ok(r.stdout.includes('missing script: .claude/scripts/ghost.js'),
|
||||
`the interpreter must be stripped, got: ${r.stdout.trim()}`);
|
||||
assert.ok(!r.stdout.includes('missing script: python3'),
|
||||
`a finding must never quote a whole command, got: ${r.stdout.trim()}`);
|
||||
});
|
||||
|
||||
t('a very long token is clipped rather than printed in full', () => {
|
||||
const fx = makeFixture();
|
||||
const long = 'a'.repeat(5000) + '.py';
|
||||
writeSettings(fx.home, ONE_HOOK(`python3 ${long}`));
|
||||
const r = run('--startup', fx);
|
||||
const line = (r.stdout.split('\n').find((l) => l.includes('missing script')) || '');
|
||||
assert.ok(line.length > 0, 'expected a finding');
|
||||
assert.ok(line.length < 300, `a finding must stay readable, got ${line.length} chars`);
|
||||
assert.ok(/chars total/.test(line), 'clipping must say it clipped');
|
||||
});
|
||||
|
||||
t('a settings file that cannot be read is not reported as healthy', () => {
|
||||
const fx = makeFixture();
|
||||
for (const junk of ['{ not valid json', '[1,2,3]', '{"hooks": 42}', '']) {
|
||||
writeSettings(fx.home, junk);
|
||||
const r = run('--check', fx);
|
||||
assert.strictEqual(r.status, 0, `expected exit 0 for ${JSON.stringify(junk)}`);
|
||||
assert.ok(!r.stdout.includes('[ok] normal'),
|
||||
`an unreadable settings file must not read as healthy, got: ${r.stdout.trim()}`);
|
||||
assert.ok(/could not be read/.test(r.stdout),
|
||||
`and it must say which file, got: ${r.stdout.trim()}`);
|
||||
}
|
||||
});
|
||||
|
||||
t('a settings file that is simply absent is not a finding', () => {
|
||||
const fx = makeFixture();
|
||||
const r = run('--check', fx);
|
||||
assert.ok(r.stdout.includes('[ok] normal'),
|
||||
`no settings file means nothing to audit, got: ${r.stdout.trim()}`);
|
||||
});
|
||||
|
||||
t('deep sh -c nesting is counted without losing the outer findings', () => {
|
||||
const fx = makeFixture();
|
||||
// MAX_PAYLOAD_DEPTH is 3, so four levels is the first that runs out. The
|
||||
// flag has to survive the recursion, not just the level that trips it.
|
||||
const payload = 'sh -c '.repeat(6) + 'true';
|
||||
writeSettings(fx.home, ONE_HOOK(`python3 .claude/scripts/early.py && ${payload}`));
|
||||
const r = run('--check', fx);
|
||||
assert.ok(r.stdout.includes('early.py'),
|
||||
`a missing script before the deep part is still missing, got: ${r.stdout.trim()}`);
|
||||
assert.ok(/nested sh -c deeper/.test(r.stdout),
|
||||
`and the depth limit must be disclosed, got: ${r.stdout.trim()}`);
|
||||
assert.ok(!/unclosed quote/.test(r.stdout),
|
||||
`balanced quotes are not a typo, got: ${r.stdout.trim()}`);
|
||||
});
|
||||
|
||||
t('nesting inside the limit is not reported as too deep', () => {
|
||||
const fx = makeFixture();
|
||||
writeSettings(fx.home, ONE_HOOK('python3 .claude/scripts/early.py && sh -c sh -c true'));
|
||||
const r = run('--check', fx);
|
||||
assert.ok(!/nested sh -c deeper/.test(r.stdout),
|
||||
`two levels is ordinary, got: ${r.stdout.trim()}`);
|
||||
});
|
||||
|
||||
// --- unchanged vs changed settings --------------------------------------
|
||||
|
||||
t('an unchanged settings file yields the same finding on repeat runs', () => {
|
||||
const fx = makeFixture();
|
||||
writeSettings(fx.home, HOOKS_JSON('~/.claude/scripts/missing-again.py'));
|
||||
const first = run('--startup', fx);
|
||||
const second = run('--startup', fx);
|
||||
assert.strictEqual(first.stdout, second.stdout,
|
||||
'deterministic: same config must give byte-identical output');
|
||||
});
|
||||
|
||||
t('changing settings changes the finding', () => {
|
||||
const fx = makeFixture();
|
||||
writeSettings(fx.home, HOOKS_JSON('~/.claude/scripts/missing-again.py'));
|
||||
const before = run('--startup', fx);
|
||||
assert.ok(before.stdout.includes('missing-again.py'), 'expected the first finding');
|
||||
fs.mkdirSync(path.join(fx.home, '.claude', 'scripts'), { recursive: true });
|
||||
fs.writeFileSync(path.join(fx.home, '.claude', 'scripts', 'missing-again.py'), '', 'utf8');
|
||||
const after = run('--startup', fx);
|
||||
assert.ok(!after.stdout.includes('missing script'),
|
||||
`repairing the file must clear the finding, got: ${after.stdout.trim()}`);
|
||||
});
|
||||
|
||||
t('a duplicate reference is reported once per event', () => {
|
||||
const fx = makeFixture();
|
||||
writeSettings(fx.home, JSON.stringify({
|
||||
hooks: {
|
||||
SessionStart: [{ hooks: [
|
||||
{ type: 'command', command: 'python3 ~/.claude/scripts/dup.py --a' },
|
||||
{ type: 'command', command: 'python3 ~/.claude/scripts/dup.py --b' },
|
||||
] }],
|
||||
},
|
||||
}));
|
||||
const r = run('--startup', fx);
|
||||
const hits = (r.stdout.match(/dup\.py/g) || []).length;
|
||||
assert.strictEqual(hits, 1, `expected one finding for a repeated token, got ${hits}`);
|
||||
});
|
||||
|
||||
t('CLAUDE_CONFIG_DIR moves the audited user settings file', () => {
|
||||
const fx = makeFixture();
|
||||
const configDir = path.join(fx.root, 'config');
|
||||
fs.mkdirSync(configDir, { recursive: true });
|
||||
fs.writeFileSync(
|
||||
path.join(configDir, 'settings.json'),
|
||||
ONE_HOOK('python3 ~/.claude/scripts/from-config.py'),
|
||||
'utf8'
|
||||
);
|
||||
writeSettings(fx.home, ONE_HOOK('python3 ~/.claude/scripts/from-home.py'));
|
||||
|
||||
const r = run('--startup', fx, '', { CLAUDE_CONFIG_DIR: configDir });
|
||||
assert.strictEqual(r.status, 0, `expected exit 0, got ${r.status}`);
|
||||
assert.ok(r.stdout.includes('from-config.py'),
|
||||
`expected the settings in $CLAUDE_CONFIG_DIR to be audited, got: ${r.stdout.trim()}`);
|
||||
assert.ok(!r.stdout.includes('from-home.py'),
|
||||
'settings under ~/.claude must not be audited when CLAUDE_CONFIG_DIR is set');
|
||||
|
||||
const check = run('--check', fx, '', { CLAUDE_CONFIG_DIR: configDir });
|
||||
assert.ok(check.stdout.includes('$CLAUDE_CONFIG_DIR resolved to'),
|
||||
'--check must name the non-default data root it resolved');
|
||||
});
|
||||
|
||||
t('CLAUDE_CONFIG_DIR moves the rule-health log', () => {
|
||||
const fx = makeFixture();
|
||||
const configDir = path.join(fx.root, 'config');
|
||||
const dataDir = path.join(configDir, 'session-data');
|
||||
fs.mkdirSync(dataDir, { recursive: true });
|
||||
const records = Array.from({ length: 5 }, (_, index) => JSON.stringify({
|
||||
ts: `2026-10-2${index}T00:00:00Z`,
|
||||
tool_calls: 6,
|
||||
configured_rule: 0,
|
||||
}));
|
||||
fs.writeFileSync(path.join(dataDir, 'rule-health.jsonl'), records.join('\n') + '\n', 'utf8');
|
||||
|
||||
const homeData = path.join(fx.home, '.claude', 'session-data');
|
||||
fs.mkdirSync(homeData, { recursive: true });
|
||||
fs.writeFileSync(
|
||||
path.join(homeData, 'rule-health.jsonl'),
|
||||
records.map(line => line.replace('configured_rule', 'home_rule')).join('\n') + '\n',
|
||||
'utf8'
|
||||
);
|
||||
|
||||
const r = run('--startup', fx, '', { CLAUDE_CONFIG_DIR: configDir });
|
||||
assert.strictEqual(r.status, 0, `expected exit 0, got ${r.status}`);
|
||||
assert.ok(r.stdout.includes('configured_rule'),
|
||||
`expected staleness to be read from $CLAUDE_CONFIG_DIR, got: ${r.stdout.trim()}`);
|
||||
assert.ok(!r.stdout.includes('home_rule'),
|
||||
'the rule-health log under ~/.claude must not be read when CLAUDE_CONFIG_DIR is set');
|
||||
});
|
||||
|
||||
t('installed module survives install, startup, repair, and uninstall in a disposable home', () => {
|
||||
const fx = makeInstallFixture();
|
||||
const env = installEnv(fx);
|
||||
const installedScript = path.join(fx.config, 'scripts', 'config-health.py');
|
||||
const installedSkill = path.join(fx.config, 'skills', 'config-health', 'SKILL.md');
|
||||
const settingsPath = path.join(fx.config, 'settings.json');
|
||||
|
||||
const install = runNode('scripts/install-apply.js',
|
||||
['--target', 'claude', '--modules', 'config-health', '--enable-hooks', '--json'], env);
|
||||
assert.strictEqual(install.status, 0,
|
||||
`install failed: ${(install.stderr || install.stdout).trim()}`);
|
||||
assert.ok(fs.existsSync(installedScript),
|
||||
`installed script missing at ${installedScript}`);
|
||||
assert.ok(fs.existsSync(installedSkill),
|
||||
`installed skill missing at ${installedSkill}`);
|
||||
|
||||
const installedSettings = fs.existsSync(settingsPath)
|
||||
? fs.readFileSync(settingsPath, 'utf8')
|
||||
: '';
|
||||
// Copying the script is not the SessionStart promise the skill makes: the
|
||||
// installed monitor only runs if the installer also registers it.
|
||||
const parsedSettings = JSON.parse(installedSettings);
|
||||
const sessionEntries = parsedSettings.hooks && parsedSettings.hooks.SessionStart;
|
||||
assert.ok(Array.isArray(sessionEntries) && sessionEntries.length > 0,
|
||||
`the default install must register a SessionStart hook, got: ${installedSettings}`);
|
||||
const sessionCommands = sessionEntries
|
||||
.flatMap(entry => (entry.hooks || []).map(hook => hook.command));
|
||||
assert.ok(sessionCommands.some(command => (
|
||||
command.includes('config-health.py') && command.includes('--startup')
|
||||
)), `the SessionStart hook must run the installed monitor: ${sessionCommands.join(' | ')}`);
|
||||
assert.ok(!installedSettings.includes('config-health.py --pretool'),
|
||||
'the default install must not add a per-tool hook');
|
||||
|
||||
// The opt-in pre-tool path must work from the disposable project install,
|
||||
// not only from the in-repo fixture.
|
||||
fs.writeFileSync(settingsPath,
|
||||
ONE_HOOK(`python3 "${installedScript}" --pretool`), 'utf8');
|
||||
const pretoolProject = runInstalledWithInput('--pretool', fx, '{"tool_name":"Edit"}');
|
||||
assert.strictEqual(pretoolProject.status, 0,
|
||||
`installed project pre-tool must exit 0, got ${pretoolProject.status}`);
|
||||
assert.strictEqual(pretoolProject.stdout, '',
|
||||
`installed project pre-tool stdout must stay clean: ${pretoolProject.stdout.trim()}`);
|
||||
assert.ok(!pretoolProject.stderr.includes('references missing script'),
|
||||
`installed project pre-tool must not warn: ${pretoolProject.stderr.trim()}`);
|
||||
|
||||
// The same pre-tool path with a plugin-root command, from the same
|
||||
// disposable install.
|
||||
const pluginRoot = path.join(fx.root, 'plugin');
|
||||
fs.mkdirSync(path.join(pluginRoot, 'scripts', 'hooks'), { recursive: true });
|
||||
fs.writeFileSync(path.join(pluginRoot, 'scripts', 'hooks', 'guard.py'), '', 'utf8');
|
||||
fs.writeFileSync(settingsPath, PLUGIN_HOOKS_JSON('scripts/hooks/guard.py'), 'utf8');
|
||||
const pretoolPlugin = runInstalledWithInput('--pretool', fx, '{"tool_name":"Edit"}',
|
||||
{ CLAUDE_PLUGIN_ROOT: pluginRoot });
|
||||
assert.strictEqual(pretoolPlugin.status, 0,
|
||||
`installed plugin pre-tool must exit 0, got ${pretoolPlugin.status}`);
|
||||
assert.strictEqual(pretoolPlugin.stdout, '',
|
||||
`installed plugin pre-tool stdout must stay clean: ${pretoolPlugin.stdout.trim()}`);
|
||||
assert.ok(!pretoolPlugin.stderr.includes('references missing script'),
|
||||
`installed plugin pre-tool must not warn: ${pretoolPlugin.stderr.trim()}`);
|
||||
|
||||
fs.writeFileSync(settingsPath, PLUGIN_HOOKS_JSON('scripts/ghost.py'), 'utf8');
|
||||
const startup = runInstalled('--startup', fx, { CLAUDE_PLUGIN_ROOT: pluginRoot });
|
||||
assert.strictEqual(startup.status, 0,
|
||||
`startup must stay non-blocking, got ${startup.status}`);
|
||||
assert.ok(startup.stdout.includes('references missing script'),
|
||||
`a real missing plugin script must warn, got: ${startup.stdout.trim()}`);
|
||||
assert.ok(startup.stdout.includes('ghost.py'),
|
||||
'the warning must name the missing plugin script');
|
||||
|
||||
fs.writeFileSync(settingsPath,
|
||||
ONE_HOOK('python3 "${CONFIG_HEALTH_TEST_UNSET_ROOT}/scripts/x.py"'), 'utf8');
|
||||
const check = runInstalled('--check', fx);
|
||||
assert.strictEqual(check.status, 0, `--check exits 0, got ${check.status}`);
|
||||
assert.ok(check.stdout.includes('hook path(s) not audited'),
|
||||
`an unresolved provider root must be reported as unjudged, got: ${check.stdout.trim()}`);
|
||||
assert.ok(!check.stdout.includes('references missing script'),
|
||||
'an unresolved provider root must not be reported as a missing script');
|
||||
|
||||
fs.unlinkSync(installedScript);
|
||||
const repair = runNode('scripts/repair.js', ['--target', 'claude', '--json'], env);
|
||||
assert.strictEqual(repair.status, 0,
|
||||
`repair failed: ${(repair.stderr || repair.stdout).trim()}`);
|
||||
assert.ok(fs.existsSync(installedScript), 'repair must restore the installed script');
|
||||
|
||||
const uninstall = runNode('scripts/uninstall.js', ['--target', 'claude', '--json'], env);
|
||||
assert.strictEqual(uninstall.status, 0,
|
||||
`uninstall failed: ${(uninstall.stderr || uninstall.stdout).trim()}`);
|
||||
assert.ok(!fs.existsSync(installedScript), 'uninstall must remove the installed script');
|
||||
assert.ok(!fs.existsSync(installedSkill), 'uninstall must remove the installed skill');
|
||||
const remainingSettings = fs.existsSync(settingsPath)
|
||||
? fs.readFileSync(settingsPath, 'utf8')
|
||||
: '';
|
||||
assert.ok(!remainingSettings.includes('config-health.py'),
|
||||
'uninstall must remove the SessionStart hook it registered');
|
||||
});
|
||||
|
||||
t('--no-hooks installs the payload without registering the monitor', () => {
|
||||
const fx = makeInstallFixture();
|
||||
const env = installEnv(fx);
|
||||
const installedScript = path.join(fx.config, 'scripts', 'config-health.py');
|
||||
const settingsPath = path.join(fx.config, 'settings.json');
|
||||
|
||||
const install = runNode('scripts/install-apply.js',
|
||||
['--target', 'claude', '--modules', 'config-health', '--no-hooks', '--json'], env);
|
||||
assert.strictEqual(install.status, 0,
|
||||
`install failed: ${(install.stderr || install.stdout).trim()}`);
|
||||
assert.ok(fs.existsSync(installedScript),
|
||||
`--no-hooks must still install the script at ${installedScript}`);
|
||||
const installedSettings = fs.existsSync(settingsPath)
|
||||
? fs.readFileSync(settingsPath, 'utf8')
|
||||
: '';
|
||||
assert.ok(!installedSettings.includes('config-health.py'),
|
||||
'--no-hooks must not wire a hook the user declined');
|
||||
});
|
||||
|
||||
t('project install runs the pre-tool workflow from a disposable project', () => {
|
||||
const fx = makeInstallFixture();
|
||||
const env = installEnv(fx);
|
||||
const installScript = path.join(__dirname, '..', '..', 'scripts', 'install-apply.js');
|
||||
|
||||
const install = spawnSync(process.execPath,
|
||||
[installScript, '--target', 'claude-project', '--modules', 'config-health', '--enable-hooks', '--json'],
|
||||
{ cwd: fx.proj, env: { ...process.env, ...env }, encoding: 'utf8', timeout: 120000 });
|
||||
assert.strictEqual(install.status, 0,
|
||||
`project install failed: ${(install.stderr || install.stdout).trim()}`);
|
||||
|
||||
const installedScript = path.join(fx.proj, '.claude', 'scripts', 'config-health.py');
|
||||
const settingsPath = path.join(fx.proj, '.claude', 'settings.json');
|
||||
assert.ok(fs.existsSync(installedScript),
|
||||
`project install must place the script at ${installedScript}`);
|
||||
|
||||
const projectSettings = JSON.parse(fs.readFileSync(settingsPath, 'utf8'));
|
||||
const sessionCommands = (projectSettings.hooks && projectSettings.hooks.SessionStart || [])
|
||||
.flatMap(entry => (entry.hooks || []).map(hook => hook.command));
|
||||
assert.ok(sessionCommands.some(command => (
|
||||
command.includes('config-health.py') && command.includes('--startup')
|
||||
)), `project install must register the monitor at project scope: ${sessionCommands.join(' | ')}`);
|
||||
|
||||
fs.writeFileSync(settingsPath,
|
||||
ONE_HOOK('python3 .claude/scripts/config-health.py --pretool'), 'utf8');
|
||||
const pretool = spawnSync(PYTHON, [installedScript, '--pretool'], {
|
||||
cwd: fx.proj,
|
||||
env: { ...process.env, ...env, CLAUDE_PROJECT_DIR: fx.proj },
|
||||
input: '{"tool_name":"Edit"}',
|
||||
encoding: 'utf8',
|
||||
timeout: 120000,
|
||||
});
|
||||
assert.strictEqual(pretool.status, 0,
|
||||
`project pre-tool must exit 0, got ${pretool.status}`);
|
||||
assert.strictEqual(pretool.stdout, '',
|
||||
`project pre-tool stdout must stay clean: ${pretool.stdout.trim()}`);
|
||||
assert.ok(!pretool.stderr.includes('references missing script'),
|
||||
`project pre-tool must not warn: ${pretool.stderr.trim()}`);
|
||||
});
|
||||
|
||||
console.log(`\n ${passed}/${total} passed`);
|
||||
if (passed !== total) process.exit(1);
|
||||
}
|
||||
|
||||
runTests();
|
||||
+105
-623
@@ -1,10 +1,6 @@
|
||||
/**
|
||||
* Hook-contract tests for scripts/config-health.py
|
||||
*
|
||||
* Verifies the contract haelyra asked for: present & missing scripts,
|
||||
* malformed & absent settings, absent rule dirs, and warning behavior —
|
||||
* every diagnostic must stay non-blocking (exit 0), exit cleanly, and never
|
||||
* echo raw hook input or secrets.
|
||||
* Hook-contract tests for scripts/config-health.py: resolution, wording, and
|
||||
* non-blocking behavior.
|
||||
*
|
||||
* Run with: node tests/hooks/config-health.test.js
|
||||
* (also picked up by `node tests/run-all.js`)
|
||||
@@ -18,141 +14,25 @@ const fs = require('fs');
|
||||
const os = require('os');
|
||||
const path = require('path');
|
||||
|
||||
const SCRIPT = path.join(__dirname, '..', '..', 'scripts', 'config-health.py');
|
||||
|
||||
// Resolve a working python. On Windows, missing interpreters surface as
|
||||
// status 9009 (not a spawn error), so probe both name and exit status.
|
||||
function resolvePython() {
|
||||
const probe = (name) => {
|
||||
const r = spawnSync(name, ['--version'], { stdio: 'ignore' });
|
||||
return !r.error && r.status === 0;
|
||||
};
|
||||
if (process.env.CONFIG_HEALTH_PYTHON) return process.env.CONFIG_HEALTH_PYTHON;
|
||||
if (probe('python3')) return 'python3';
|
||||
if (probe('python')) return 'python';
|
||||
throw new Error('No python interpreter found (tried CONFIG_HEALTH_PYTHON, python3, python)');
|
||||
}
|
||||
|
||||
const PYTHON = resolvePython();
|
||||
|
||||
// ---- helpers ---------------------------------------------------------------
|
||||
|
||||
function test(name, fn) {
|
||||
try {
|
||||
fn();
|
||||
console.log(` ✓ ${name}`);
|
||||
return true;
|
||||
} catch (err) {
|
||||
console.log(` ✗ ${name}`);
|
||||
console.log(` Error: ${err.message}`);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function makeFixture() {
|
||||
// Returns { home, proj, root } — a throwaway sandbox under os.tmpdir().
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'config-health-'));
|
||||
const home = path.join(root, 'home');
|
||||
const proj = path.join(root, 'proj');
|
||||
fs.mkdirSync(path.join(home, '.claude'), { recursive: true });
|
||||
fs.mkdirSync(path.join(proj, '.claude'), { recursive: true });
|
||||
return { root, home, proj };
|
||||
}
|
||||
|
||||
function run(mode, { home, proj }, stdin = '', extraEnv = {}) {
|
||||
return spawnSync(PYTHON, [SCRIPT, mode], {
|
||||
env: {
|
||||
...process.env,
|
||||
CONFIG_HEALTH_USER_HOME: home,
|
||||
CLAUDE_PROJECT_DIR: proj,
|
||||
CLAUDE_CONFIG_DIR: '',
|
||||
...extraEnv,
|
||||
},
|
||||
input: stdin,
|
||||
encoding: 'utf8',
|
||||
});
|
||||
}
|
||||
|
||||
function writeSettings(home, content) {
|
||||
fs.writeFileSync(path.join(home, '.claude', 'settings.json'), content, 'utf8');
|
||||
}
|
||||
|
||||
// Install-lifecycle fixture: a disposable HOME and Claude data root, so the
|
||||
// real installer/repair/uninstaller run without touching the user's config.
|
||||
function makeInstallFixture() {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'config-health-install-'));
|
||||
const home = path.join(root, 'home');
|
||||
const config = path.join(root, 'claude');
|
||||
const proj = path.join(root, 'proj');
|
||||
fs.mkdirSync(home, { recursive: true });
|
||||
fs.mkdirSync(config, { recursive: true });
|
||||
fs.mkdirSync(proj, { recursive: true });
|
||||
return { root, home, config, proj };
|
||||
}
|
||||
|
||||
function installEnv(fx, extraEnv = {}) {
|
||||
return {
|
||||
HOME: fx.home,
|
||||
USERPROFILE: fx.home,
|
||||
CLAUDE_CONFIG_DIR: fx.config,
|
||||
CONFIG_HEALTH_USER_HOME: fx.home,
|
||||
CLAUDE_PROJECT_DIR: fx.proj,
|
||||
...extraEnv,
|
||||
};
|
||||
}
|
||||
|
||||
function runNode(scriptRel, args, env) {
|
||||
return spawnSync(process.execPath, [path.join(__dirname, '..', '..', scriptRel), ...args], {
|
||||
cwd: path.join(__dirname, '..', '..'),
|
||||
env: { ...process.env, ...env },
|
||||
encoding: 'utf8',
|
||||
timeout: 120000,
|
||||
});
|
||||
}
|
||||
|
||||
function runInstalled(mode, fx, extraEnv = {}) {
|
||||
return spawnSync(PYTHON, [path.join(fx.config, 'scripts', 'config-health.py'), mode], {
|
||||
env: { ...process.env, ...installEnv(fx, extraEnv) },
|
||||
encoding: 'utf8',
|
||||
timeout: 120000,
|
||||
});
|
||||
}
|
||||
|
||||
function runInstalledWithInput(mode, fx, input, extraEnv = {}) {
|
||||
return spawnSync(PYTHON, [path.join(fx.config, 'scripts', 'config-health.py'), mode], {
|
||||
env: { ...process.env, ...installEnv(fx, extraEnv) },
|
||||
input,
|
||||
encoding: 'utf8',
|
||||
timeout: 120000,
|
||||
});
|
||||
}
|
||||
|
||||
const HOOKS_JSON = (scriptPath) => JSON.stringify({
|
||||
hooks: {
|
||||
SessionStart: [{ hooks: [{ type: 'command', command: `python3 ${scriptPath} --start`, timeout: 5000 }] }],
|
||||
PreToolUse: [{ matcher: 'Edit|Write', hooks: [{ type: 'command', command: `python3 ${scriptPath} --pretool`, timeout: 3000 }] }],
|
||||
},
|
||||
});
|
||||
|
||||
// A single command hook, for pinning one parser or resolution rule at a time
|
||||
// instead of the two-shape fixture above.
|
||||
const ONE_HOOK = (command, event = 'PreToolUse') => JSON.stringify({
|
||||
hooks: { [event]: [{ hooks: [{ type: 'command', command, timeout: 5 }] }] },
|
||||
});
|
||||
|
||||
// A plugin install wires its hooks against $CLAUDE_PLUGIN_ROOT, which is a
|
||||
// directory the monitor must expand rather than treat as project-relative.
|
||||
const PLUGIN_HOOKS_JSON = (relPath) => JSON.stringify({
|
||||
hooks: {
|
||||
SessionStart: [{ hooks: [{ type: 'command', command: `python3 "\${CLAUDE_PLUGIN_ROOT}/${relPath}" --start`, timeout: 5000 }] }],
|
||||
PreToolUse: [{ matcher: 'Edit|Write', hooks: [{ type: 'command', command: `python3 "\${CLAUDE_PLUGIN_ROOT}/${relPath}" --pretool`, timeout: 3000 }] }],
|
||||
},
|
||||
});
|
||||
|
||||
// ---- suite -----------------------------------------------------------------
|
||||
const {
|
||||
SCRIPT,
|
||||
PYTHON,
|
||||
test,
|
||||
makeFixture,
|
||||
run,
|
||||
writeSettings,
|
||||
makeInstallFixture,
|
||||
installEnv,
|
||||
runNode,
|
||||
runInstalled,
|
||||
runInstalledWithInput,
|
||||
HOOKS_JSON,
|
||||
ONE_HOOK,
|
||||
PLUGIN_HOOKS_JSON,
|
||||
} = require('./config-health-helpers');
|
||||
|
||||
function runTests() {
|
||||
console.log('\n=== Testing config-health.py hook contract ===\n');
|
||||
console.log('\n=== Testing config-health.py hook contract: resolution and wording ===\n');
|
||||
let passed = 0;
|
||||
let total = 0;
|
||||
|
||||
@@ -213,6 +93,92 @@ function runTests() {
|
||||
assert.ok(r.stdout.includes('missing rule file'), 'expected a dead-rule warning');
|
||||
});
|
||||
|
||||
// ECC installs rules under nested namespaces; a flat-only pattern missed
|
||||
// every one of those, so a missing nested reference reported healthy.
|
||||
t('startup warns on a missing nested rule reference', () => {
|
||||
const fx = makeFixture();
|
||||
fs.writeFileSync(path.join(fx.proj, 'CLAUDE.md'),
|
||||
'see rules/ecc/common/security.md and .claude/rules/ecc/common/style.md\n', 'utf8');
|
||||
const r = run('--startup', fx);
|
||||
assert.strictEqual(r.status, 0, `expected exit 0, got ${r.status}`);
|
||||
assert.ok(r.stdout.includes('rules/ecc/common/security.md'),
|
||||
`expected the nested reference to be audited, got: ${r.stdout.trim()}`);
|
||||
assert.ok(r.stdout.includes('rules/ecc/common/style.md'),
|
||||
`expected the .claude-prefixed nested reference to be audited, got: ${r.stdout.trim()}`);
|
||||
});
|
||||
|
||||
t('a nested rule reference that exists is not reported', () => {
|
||||
const fx = makeFixture();
|
||||
fs.mkdirSync(path.join(fx.proj, 'rules', 'ecc', 'common'), { recursive: true });
|
||||
fs.writeFileSync(path.join(fx.proj, 'rules', 'ecc', 'common', 'security.md'), '# x\n', 'utf8');
|
||||
fs.writeFileSync(path.join(fx.proj, 'CLAUDE.md'),
|
||||
'see rules/ecc/common/security.md\n', 'utf8');
|
||||
const r = run('--startup', fx);
|
||||
assert.strictEqual(r.status, 0, `expected exit 0, got ${r.status}`);
|
||||
assert.ok(!r.stdout.includes('missing rule file'),
|
||||
`an existing nested rule must stay silent, got: ${r.stdout.trim()}`);
|
||||
});
|
||||
|
||||
// settings.local.json wins over both settings files, so a hook declared only
|
||||
// there is live. Not reading it turns a broken hook into a clean report.
|
||||
t('a missing hook declared only in settings.local.json is reported', () => {
|
||||
const fx = makeFixture();
|
||||
fs.writeFileSync(path.join(fx.proj, '.claude', 'settings.local.json'),
|
||||
ONE_HOOK('python3 .claude/scripts/ghost-local.py'), 'utf8');
|
||||
const r = run('--startup', fx);
|
||||
assert.strictEqual(r.status, 0, `expected exit 0, got ${r.status}`);
|
||||
assert.ok(r.stdout.includes('ghost-local.py'),
|
||||
`expected the local settings hook to be audited, got: ${r.stdout.trim()}`);
|
||||
});
|
||||
|
||||
// A plugin's own hooks/hooks.json runs without any settings file naming it.
|
||||
t('a missing hook declared only in plugin hooks/hooks.json is reported', () => {
|
||||
const fx = makeFixture();
|
||||
const pluginRoot = path.join(fx.root, 'plugin');
|
||||
fs.mkdirSync(path.join(pluginRoot, 'hooks'), { recursive: true });
|
||||
fs.writeFileSync(path.join(pluginRoot, 'hooks', 'hooks.json'),
|
||||
PLUGIN_HOOKS_JSON('scripts/hooks/ghost-plugin.py'), 'utf8');
|
||||
const r = run('--startup', fx, '', { CLAUDE_PLUGIN_ROOT: pluginRoot });
|
||||
assert.strictEqual(r.status, 0, `expected exit 0, got ${r.status}`);
|
||||
assert.ok(r.stdout.includes('ghost-plugin.py'),
|
||||
`expected the plugin hook source to be audited, got: ${r.stdout.trim()}`);
|
||||
});
|
||||
|
||||
// A positive count in a short session is still a firing. The complexity
|
||||
// filter decides whether a rule *should* fire, not whether it did.
|
||||
t('a rule that fired in a short recent session is not called dead', () => {
|
||||
const fx = makeFixture();
|
||||
const dataDir = path.join(fx.home, '.claude', 'session-data');
|
||||
fs.mkdirSync(dataDir, { recursive: true });
|
||||
const records = [
|
||||
...Array.from({ length: 4 }, (_, index) => JSON.stringify({
|
||||
ts: `2026-10-2${index}T00:00:00Z`, tool_calls: 10, live_rule: 0,
|
||||
})),
|
||||
JSON.stringify({ ts: '2026-10-30T00:00:00Z', tool_calls: 1, live_rule: 3 }),
|
||||
];
|
||||
fs.writeFileSync(path.join(dataDir, 'rule-health.jsonl'),
|
||||
records.join('\n') + '\n', 'utf8');
|
||||
const r = run('--startup', fx);
|
||||
assert.strictEqual(r.status, 0, `expected exit 0, got ${r.status}`);
|
||||
assert.ok(!r.stdout.includes('live_rule'),
|
||||
`a rule that fired inside the window must not be called dead: ${r.stdout.trim()}`);
|
||||
});
|
||||
|
||||
t('a rule with zero counts across five complex sessions is reported stale', () => {
|
||||
const fx = makeFixture();
|
||||
const dataDir = path.join(fx.home, '.claude', 'session-data');
|
||||
fs.mkdirSync(dataDir, { recursive: true });
|
||||
const records = Array.from({ length: 5 }, (_, index) => JSON.stringify({
|
||||
ts: `2026-10-2${index}T00:00:00Z`, tool_calls: 10, dead_rule: 0,
|
||||
}));
|
||||
fs.writeFileSync(path.join(dataDir, 'rule-health.jsonl'),
|
||||
records.join('\n') + '\n', 'utf8');
|
||||
const r = run('--startup', fx);
|
||||
assert.strictEqual(r.status, 0, `expected exit 0, got ${r.status}`);
|
||||
assert.ok(r.stdout.includes('dead_rule') && r.stdout.includes('has not fired'),
|
||||
`expected the stale rule to be named, got: ${r.stdout.trim()}`);
|
||||
});
|
||||
|
||||
// --pretool must NEVER echo stdin (raw hook input / secrets).
|
||||
t('pretool never echoes raw hook input or secrets to stdout', () => {
|
||||
const fx = makeFixture();
|
||||
@@ -769,490 +735,6 @@ function runTests() {
|
||||
assert.strictEqual(r.stdout, '', `${mode} must not print a half-finished report`);
|
||||
}
|
||||
});
|
||||
|
||||
// --- a blind spot nobody can see is not a health check -------------------
|
||||
|
||||
t('--check reports how many hook paths it did not audit', () => {
|
||||
const fx = makeFixture();
|
||||
writeSettings(fx.home, ONE_HOOK('python3 "${CLAUDE_ENV_FILE}/hooks/x.py"'));
|
||||
const r = run('--check', fx, '', { CLAUDE_ENV_FILE: '' });
|
||||
assert.ok(r.stdout.includes('not audited'),
|
||||
`the blind spot must be visible, got: ${r.stdout.trim()}`);
|
||||
});
|
||||
|
||||
t('--check names the plugin root it judged against', () => {
|
||||
const fx = makeFixture();
|
||||
const pluginRoot = path.join(fx.root, 'plugin');
|
||||
fs.mkdirSync(pluginRoot, { recursive: true });
|
||||
const r = run('--check', fx, '', { CLAUDE_PLUGIN_ROOT: pluginRoot });
|
||||
assert.ok(r.stdout.includes(pluginRoot),
|
||||
`a wrong-root false positive must be diagnosable, got: ${r.stdout.trim()}`);
|
||||
});
|
||||
|
||||
// --- program bodies, quoting, and the backslash -------------------------
|
||||
// A second adversarial pass found that the first fix of these introduced a
|
||||
// Windows regression: treating every backslash as a shell escape turned
|
||||
// C:\Users\me\guard.py into C:Usersmeguard.py, a false alarm on the
|
||||
// platform this script is developed on. These pin the corrected rules.
|
||||
|
||||
t('an unquoted Windows path keeps its backslashes', () => {
|
||||
const fx = makeFixture();
|
||||
const dir = path.join(fx.home, 'back', 'slash');
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
const present = path.join(dir, 'win.py');
|
||||
fs.writeFileSync(present, '', 'utf8');
|
||||
writeSettings(fx.home, ONE_HOOK(`python3 ${present}`));
|
||||
const ok = run('--startup', fx);
|
||||
assert.ok(!ok.stdout.includes('missing script'),
|
||||
`a Windows path must not be unescaped into nonsense, got: ${ok.stdout.trim()}`);
|
||||
|
||||
writeSettings(fx.home, ONE_HOOK(`python3 ${path.join(dir, 'gone.py')}`));
|
||||
const missing = run('--startup', fx);
|
||||
assert.ok(missing.stdout.includes('gone.py'),
|
||||
`and the missing case must still be reported, got: ${missing.stdout.trim()}`);
|
||||
});
|
||||
|
||||
t('a shell -c body is scanned as a command line again', () => {
|
||||
const fx = makeFixture();
|
||||
const cmd = `sh -c "python3 ${path.join(fx.root, 'nowhere', 'ghost.py')}"`;
|
||||
writeSettings(fx.home, ONE_HOOK(cmd));
|
||||
const r = run('--startup', fx);
|
||||
assert.ok(r.stdout.includes('ghost.py'),
|
||||
`the shell will open that file, so it must be reported, got: ${r.stdout.trim()}`);
|
||||
});
|
||||
|
||||
t('bundled and long-form program flags are recognised', () => {
|
||||
const fx = makeFixture();
|
||||
for (const flag of ['-c', '-lc', '--command']) {
|
||||
writeSettings(fx.home, ONE_HOOK(`bash ${flag} "python3 .claude/scripts/ghost.py"`));
|
||||
const r = run('--startup', fx);
|
||||
assert.ok(r.stdout.includes('ghost.py'),
|
||||
`${flag} takes a command body and must not hide the reference, got: ${r.stdout.trim()}`);
|
||||
}
|
||||
});
|
||||
|
||||
t('a node -e body is skipped, and the argument after it is not', () => {
|
||||
const fx = makeFixture();
|
||||
for (const cmd of [
|
||||
'node -e "const s=p.join(r,\'scripts/hooks/never-created.js\')" node scripts/hooks/ghost.js',
|
||||
'node --eval "const s=1" node scripts/hooks/ghost.js',
|
||||
'node -e const s = p.join(r, "scripts/hooks/never-created.js") ; node scripts/hooks/ghost.js',
|
||||
]) {
|
||||
writeSettings(fx.home, ONE_HOOK(cmd));
|
||||
const r = run('--startup', fx);
|
||||
assert.ok(r.stdout.includes('ghost.js'),
|
||||
`the real argument must survive the body, got: ${r.stdout.trim()}`);
|
||||
assert.ok(!r.stdout.includes('never-created.js'),
|
||||
`a string inside the body is not a file, got: ${r.stdout.trim()}`);
|
||||
}
|
||||
});
|
||||
|
||||
t('an unclosed quote is skipped, counted, and reported by --check', () => {
|
||||
const fx = makeFixture();
|
||||
writeSettings(fx.home, ONE_HOOK('python3 ".claude/scripts/ghost.py --start'));
|
||||
const r = run('--check', fx);
|
||||
assert.strictEqual(r.status, 0, `expected exit 0, got ${r.status}`);
|
||||
assert.ok(!r.stdout.includes('missing script'),
|
||||
`an unparseable command must not produce a guess, got: ${r.stdout.trim()}`);
|
||||
assert.ok(/unclosed quote/.test(r.stdout),
|
||||
`but it must not be invisible either, got: ${r.stdout.trim()}`);
|
||||
});
|
||||
|
||||
t('a relative hook satisfied only outside the project is disclosed', () => {
|
||||
const fx = makeFixture();
|
||||
fs.mkdirSync(path.join(fx.home, '.claude', 'scripts'), { recursive: true });
|
||||
fs.writeFileSync(path.join(fx.home, '.claude', 'scripts', 'home-only.py'), '', 'utf8');
|
||||
writeSettings(fx.home, HOOKS_JSON('.claude/scripts/home-only.py'));
|
||||
const r = run('--check', fx);
|
||||
assert.ok(r.stdout.includes('satisfied by the user home or plugin root'),
|
||||
`the cross-root trade must be visible, got: ${r.stdout.trim()}`);
|
||||
});
|
||||
|
||||
t('an option between the interpreter and -c does not orphan the body', () => {
|
||||
const fx = makeFixture();
|
||||
// The payload is chosen per interpreter: a shell body is a command line
|
||||
// and is rescanned, a python body is source and is not a file reference.
|
||||
const cases = [
|
||||
['bash -x -c "python3 .claude/scripts/ghost.py"', 'ghost.py'],
|
||||
['bash -o pipefail -c "python3 .claude/scripts/ghost.py"', 'ghost.py'],
|
||||
['sh -lc "python3 .claude/scripts/ghost.py"', 'ghost.py'],
|
||||
['bash -x -lc "python3 .claude/scripts/ghost.py"', 'ghost.py'],
|
||||
['python3 -u -c "print(1)" .claude/scripts/ghost.py', 'ghost.py'],
|
||||
];
|
||||
for (const [cmd, expected] of cases) {
|
||||
writeSettings(fx.home, ONE_HOOK(cmd));
|
||||
const r = run('--startup', fx);
|
||||
assert.ok(r.stdout.includes(expected),
|
||||
`${cmd} must still reach the reference, got: ${r.stdout.trim()}`);
|
||||
assert.ok(!r.stdout.includes('python3 .claude/scripts/ghost.py'),
|
||||
`a whole payload must never be printed as a path, got: ${r.stdout.trim()}`);
|
||||
}
|
||||
});
|
||||
|
||||
t('a separator inside quotes is part of the name, not a separator', () => {
|
||||
const fx = makeFixture();
|
||||
for (const name of ['weird;name.py', 'a|b.py', 'a&b.py']) {
|
||||
writeSettings(fx.home, ONE_HOOK(`python3 ".claude/scripts/${name}"`));
|
||||
const r = run('--startup', fx);
|
||||
assert.ok(r.stdout.includes(name),
|
||||
`${name} is a legal filename, got: ${r.stdout.trim()}`);
|
||||
}
|
||||
});
|
||||
|
||||
t('an unclosed quote inside a payload is counted, not dropped', () => {
|
||||
const fx = makeFixture();
|
||||
writeSettings(fx.home, ONE_HOOK('sh -c "python3 .claude/scripts/ghost.py && echo \\"oops"'));
|
||||
const r = run('--check', fx);
|
||||
assert.strictEqual(r.status, 0, `expected exit 0, got ${r.status}`);
|
||||
assert.ok(!r.stdout.includes('missing script'),
|
||||
`an unparseable payload must not produce a guess, got: ${r.stdout.trim()}`);
|
||||
assert.ok(/unclosed quote/.test(r.stdout),
|
||||
`and the outer command must be reported as unparsed, got: ${r.stdout.trim()}`);
|
||||
});
|
||||
|
||||
t('Windows paths a POSIX escaper would mangle survive intact', () => {
|
||||
const fx = makeFixture();
|
||||
// A UNC prefix is two backslashes, not an escaped one. Collapsing it to
|
||||
// \server\share invents a rooted path that was never written.
|
||||
writeSettings(fx.home, ONE_HOOK(String.raw`python3 \\server\share\ghost.py`));
|
||||
const unc = run('--startup', fx);
|
||||
assert.ok(unc.stdout.includes(String.raw`\\server\share\ghost.py`),
|
||||
`a UNC path must be reported whole, got: ${unc.stdout.trim()}`);
|
||||
|
||||
// C:\$Recycle.Bin: the $ reads as a shell placeholder, so the token is
|
||||
// skipped — but skipped and counted, not escaped into C:Recycle.Bin.
|
||||
writeSettings(fx.home, ONE_HOOK(String.raw`python3 C:\$Recycle.Bin\ghost.py`));
|
||||
const dollar = run('--check', fx);
|
||||
assert.ok(!dollar.stdout.includes('C:Recycle.Bin'),
|
||||
`a backslash must not escape the dollar, got: ${dollar.stdout.trim()}`);
|
||||
assert.ok(/not audited/.test(dollar.stdout),
|
||||
`and the skip must be counted, got: ${dollar.stdout.trim()}`);
|
||||
});
|
||||
|
||||
t('a skipped program body is counted, not dropped silently', () => {
|
||||
const fx = makeFixture();
|
||||
// A file named inside a node -e body is a string in another language and
|
||||
// cannot be checked. Silence is right; silence with no count is not.
|
||||
writeSettings(fx.home, ONE_HOOK(
|
||||
'node -e "const s=p.join(r,\'.claude/scripts/ghost.js\')" node .claude/scripts/real.py'));
|
||||
const r = run('--check', fx);
|
||||
assert.ok(!r.stdout.includes('ghost.js'),
|
||||
`a string inside a JS body is not a file, got: ${r.stdout.trim()}`);
|
||||
assert.ok(/program body/.test(r.stdout),
|
||||
`but the unjudged body must be visible, got: ${r.stdout.trim()}`);
|
||||
});
|
||||
|
||||
t('the repo\'s own hook wiring is fully accounted for', () => {
|
||||
const repoRoot = path.join(__dirname, '..', '..');
|
||||
const real = fs.readFileSync(path.join(repoRoot, 'hooks', 'hooks.json'), 'utf8');
|
||||
const fx = makeFixture();
|
||||
writeSettings(fx.home, real);
|
||||
const r = run('--check', fx, '', { CLAUDE_PLUGIN_ROOT: repoRoot });
|
||||
assert.ok(r.stdout.includes('[ok] normal'),
|
||||
`a healthy install must be healthy, got: ${r.stdout.trim()}`);
|
||||
// Every one of the 23 commands hides a program body, and every relative
|
||||
// reference resolves through the plugin root. If those two counts ever go
|
||||
// to zero, the numbers below are no longer describing anything.
|
||||
const bodies = Number((r.stdout.match(/(\d+) interpreter program body/) || [])[1]);
|
||||
const other = Number((r.stdout.match(/(\d+) relative hook path/) || [])[1]);
|
||||
assert.ok(bodies >= 20, `expected ~23 skipped bodies, got ${bodies}`);
|
||||
assert.ok(other >= 10, `expected plugin-root-satisfied paths, got ${other}`);
|
||||
});
|
||||
|
||||
t('a longer name whose prefix is a script name is not truncated to it', () => {
|
||||
const fx = makeFixture();
|
||||
const dir = path.join(fx.proj, 'scripts', 'hooks');
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
// The shell opens these files. A regex without an end guard matches the
|
||||
// prefix and warns about a file that does not exist.
|
||||
for (const name of ['archive.js.bak', 'buf.py.map', 'guard.pyc', 'ok.py~']) {
|
||||
fs.writeFileSync(path.join(dir, name), '', 'utf8');
|
||||
writeSettings(fx.home, ONE_HOOK(`python3 scripts/hooks/${name}`));
|
||||
const r = run('--startup', fx);
|
||||
assert.ok(!r.stdout.includes('missing script'),
|
||||
`${name} exists; a prefix match would warn about a different file, got: ${r.stdout.trim()}`);
|
||||
}
|
||||
fs.writeFileSync(path.join(dir, 'gone.js.bak'), '', 'utf8');
|
||||
writeSettings(fx.home, ONE_HOOK('python3 scripts/hooks/absent.js.bak'));
|
||||
const missing = run('--startup', fx);
|
||||
assert.ok(!missing.stdout.includes('missing script'),
|
||||
`and an absent one is not a script reference either, got: ${missing.stdout.trim()}`);
|
||||
});
|
||||
|
||||
t('sh -e is errexit, not a program body', () => {
|
||||
const fx = makeFixture();
|
||||
writeSettings(fx.home, ONE_HOOK('sh -e .claude/scripts/ghost.py'));
|
||||
const r = run('--startup', fx);
|
||||
assert.ok(r.stdout.includes('ghost.py'),
|
||||
`sh -e runs the next word as a script, got: ${r.stdout.trim()}`);
|
||||
});
|
||||
|
||||
t('a one-word quoted command is not reported as one long path', () => {
|
||||
const fx = makeFixture();
|
||||
writeSettings(fx.home, ONE_HOOK('"python3 .claude/scripts/ghost.js"'));
|
||||
const r = run('--startup', fx);
|
||||
assert.ok(r.stdout.includes('missing script: .claude/scripts/ghost.js'),
|
||||
`the interpreter must be stripped, got: ${r.stdout.trim()}`);
|
||||
assert.ok(!r.stdout.includes('missing script: python3'),
|
||||
`a finding must never quote a whole command, got: ${r.stdout.trim()}`);
|
||||
});
|
||||
|
||||
t('a very long token is clipped rather than printed in full', () => {
|
||||
const fx = makeFixture();
|
||||
const long = 'a'.repeat(5000) + '.py';
|
||||
writeSettings(fx.home, ONE_HOOK(`python3 ${long}`));
|
||||
const r = run('--startup', fx);
|
||||
const line = (r.stdout.split('\n').find((l) => l.includes('missing script')) || '');
|
||||
assert.ok(line.length > 0, 'expected a finding');
|
||||
assert.ok(line.length < 300, `a finding must stay readable, got ${line.length} chars`);
|
||||
assert.ok(/chars total/.test(line), 'clipping must say it clipped');
|
||||
});
|
||||
|
||||
t('a settings file that cannot be read is not reported as healthy', () => {
|
||||
const fx = makeFixture();
|
||||
for (const junk of ['{ not valid json', '[1,2,3]', '{"hooks": 42}', '']) {
|
||||
writeSettings(fx.home, junk);
|
||||
const r = run('--check', fx);
|
||||
assert.strictEqual(r.status, 0, `expected exit 0 for ${JSON.stringify(junk)}`);
|
||||
assert.ok(!r.stdout.includes('[ok] normal'),
|
||||
`an unreadable settings file must not read as healthy, got: ${r.stdout.trim()}`);
|
||||
assert.ok(/could not be read/.test(r.stdout),
|
||||
`and it must say which file, got: ${r.stdout.trim()}`);
|
||||
}
|
||||
});
|
||||
|
||||
t('a settings file that is simply absent is not a finding', () => {
|
||||
const fx = makeFixture();
|
||||
const r = run('--check', fx);
|
||||
assert.ok(r.stdout.includes('[ok] normal'),
|
||||
`no settings file means nothing to audit, got: ${r.stdout.trim()}`);
|
||||
});
|
||||
|
||||
t('deep sh -c nesting is counted without losing the outer findings', () => {
|
||||
const fx = makeFixture();
|
||||
// MAX_PAYLOAD_DEPTH is 3, so four levels is the first that runs out. The
|
||||
// flag has to survive the recursion, not just the level that trips it.
|
||||
const payload = 'sh -c '.repeat(6) + 'true';
|
||||
writeSettings(fx.home, ONE_HOOK(`python3 .claude/scripts/early.py && ${payload}`));
|
||||
const r = run('--check', fx);
|
||||
assert.ok(r.stdout.includes('early.py'),
|
||||
`a missing script before the deep part is still missing, got: ${r.stdout.trim()}`);
|
||||
assert.ok(/nested sh -c deeper/.test(r.stdout),
|
||||
`and the depth limit must be disclosed, got: ${r.stdout.trim()}`);
|
||||
assert.ok(!/unclosed quote/.test(r.stdout),
|
||||
`balanced quotes are not a typo, got: ${r.stdout.trim()}`);
|
||||
});
|
||||
|
||||
t('nesting inside the limit is not reported as too deep', () => {
|
||||
const fx = makeFixture();
|
||||
writeSettings(fx.home, ONE_HOOK('python3 .claude/scripts/early.py && sh -c sh -c true'));
|
||||
const r = run('--check', fx);
|
||||
assert.ok(!/nested sh -c deeper/.test(r.stdout),
|
||||
`two levels is ordinary, got: ${r.stdout.trim()}`);
|
||||
});
|
||||
|
||||
// --- unchanged vs changed settings --------------------------------------
|
||||
|
||||
t('an unchanged settings file yields the same finding on repeat runs', () => {
|
||||
const fx = makeFixture();
|
||||
writeSettings(fx.home, HOOKS_JSON('~/.claude/scripts/missing-again.py'));
|
||||
const first = run('--startup', fx);
|
||||
const second = run('--startup', fx);
|
||||
assert.strictEqual(first.stdout, second.stdout,
|
||||
'deterministic: same config must give byte-identical output');
|
||||
});
|
||||
|
||||
t('changing settings changes the finding', () => {
|
||||
const fx = makeFixture();
|
||||
writeSettings(fx.home, HOOKS_JSON('~/.claude/scripts/missing-again.py'));
|
||||
const before = run('--startup', fx);
|
||||
assert.ok(before.stdout.includes('missing-again.py'), 'expected the first finding');
|
||||
fs.mkdirSync(path.join(fx.home, '.claude', 'scripts'), { recursive: true });
|
||||
fs.writeFileSync(path.join(fx.home, '.claude', 'scripts', 'missing-again.py'), '', 'utf8');
|
||||
const after = run('--startup', fx);
|
||||
assert.ok(!after.stdout.includes('missing script'),
|
||||
`repairing the file must clear the finding, got: ${after.stdout.trim()}`);
|
||||
});
|
||||
|
||||
t('a duplicate reference is reported once per event', () => {
|
||||
const fx = makeFixture();
|
||||
writeSettings(fx.home, JSON.stringify({
|
||||
hooks: {
|
||||
SessionStart: [{ hooks: [
|
||||
{ type: 'command', command: 'python3 ~/.claude/scripts/dup.py --a' },
|
||||
{ type: 'command', command: 'python3 ~/.claude/scripts/dup.py --b' },
|
||||
] }],
|
||||
},
|
||||
}));
|
||||
const r = run('--startup', fx);
|
||||
const hits = (r.stdout.match(/dup\.py/g) || []).length;
|
||||
assert.strictEqual(hits, 1, `expected one finding for a repeated token, got ${hits}`);
|
||||
});
|
||||
|
||||
t('CLAUDE_CONFIG_DIR moves the audited user settings file', () => {
|
||||
const fx = makeFixture();
|
||||
const configDir = path.join(fx.root, 'config');
|
||||
fs.mkdirSync(configDir, { recursive: true });
|
||||
fs.writeFileSync(
|
||||
path.join(configDir, 'settings.json'),
|
||||
ONE_HOOK('python3 ~/.claude/scripts/from-config.py'),
|
||||
'utf8'
|
||||
);
|
||||
writeSettings(fx.home, ONE_HOOK('python3 ~/.claude/scripts/from-home.py'));
|
||||
|
||||
const r = run('--startup', fx, '', { CLAUDE_CONFIG_DIR: configDir });
|
||||
assert.strictEqual(r.status, 0, `expected exit 0, got ${r.status}`);
|
||||
assert.ok(r.stdout.includes('from-config.py'),
|
||||
`expected the settings in $CLAUDE_CONFIG_DIR to be audited, got: ${r.stdout.trim()}`);
|
||||
assert.ok(!r.stdout.includes('from-home.py'),
|
||||
'settings under ~/.claude must not be audited when CLAUDE_CONFIG_DIR is set');
|
||||
|
||||
const check = run('--check', fx, '', { CLAUDE_CONFIG_DIR: configDir });
|
||||
assert.ok(check.stdout.includes('$CLAUDE_CONFIG_DIR resolved to'),
|
||||
'--check must name the non-default data root it resolved');
|
||||
});
|
||||
|
||||
t('CLAUDE_CONFIG_DIR moves the rule-health log', () => {
|
||||
const fx = makeFixture();
|
||||
const configDir = path.join(fx.root, 'config');
|
||||
const dataDir = path.join(configDir, 'session-data');
|
||||
fs.mkdirSync(dataDir, { recursive: true });
|
||||
const records = Array.from({ length: 5 }, (_, index) => JSON.stringify({
|
||||
ts: `2026-10-2${index}T00:00:00Z`,
|
||||
tool_calls: 6,
|
||||
configured_rule: 0,
|
||||
}));
|
||||
fs.writeFileSync(path.join(dataDir, 'rule-health.jsonl'), records.join('\n') + '\n', 'utf8');
|
||||
|
||||
const homeData = path.join(fx.home, '.claude', 'session-data');
|
||||
fs.mkdirSync(homeData, { recursive: true });
|
||||
fs.writeFileSync(
|
||||
path.join(homeData, 'rule-health.jsonl'),
|
||||
records.map(line => line.replace('configured_rule', 'home_rule')).join('\n') + '\n',
|
||||
'utf8'
|
||||
);
|
||||
|
||||
const r = run('--startup', fx, '', { CLAUDE_CONFIG_DIR: configDir });
|
||||
assert.strictEqual(r.status, 0, `expected exit 0, got ${r.status}`);
|
||||
assert.ok(r.stdout.includes('configured_rule'),
|
||||
`expected staleness to be read from $CLAUDE_CONFIG_DIR, got: ${r.stdout.trim()}`);
|
||||
assert.ok(!r.stdout.includes('home_rule'),
|
||||
'the rule-health log under ~/.claude must not be read when CLAUDE_CONFIG_DIR is set');
|
||||
});
|
||||
|
||||
t('installed module survives install, startup, repair, and uninstall in a disposable home', () => {
|
||||
const fx = makeInstallFixture();
|
||||
const env = installEnv(fx);
|
||||
const installedScript = path.join(fx.config, 'scripts', 'config-health.py');
|
||||
const installedSkill = path.join(fx.config, 'skills', 'config-health', 'SKILL.md');
|
||||
const settingsPath = path.join(fx.config, 'settings.json');
|
||||
|
||||
const install = runNode('scripts/install-apply.js',
|
||||
['--target', 'claude', '--modules', 'config-health', '--json'], env);
|
||||
assert.strictEqual(install.status, 0,
|
||||
`install failed: ${(install.stderr || install.stdout).trim()}`);
|
||||
assert.ok(fs.existsSync(installedScript),
|
||||
`installed script missing at ${installedScript}`);
|
||||
assert.ok(fs.existsSync(installedSkill),
|
||||
`installed skill missing at ${installedSkill}`);
|
||||
|
||||
const installedSettings = fs.existsSync(settingsPath)
|
||||
? fs.readFileSync(settingsPath, 'utf8')
|
||||
: '';
|
||||
assert.ok(!installedSettings.includes('config-health.py --pretool'),
|
||||
'the default install must not add a per-tool hook');
|
||||
|
||||
// The opt-in pre-tool path must work from the disposable project install,
|
||||
// not only from the in-repo fixture.
|
||||
fs.writeFileSync(settingsPath,
|
||||
ONE_HOOK(`python3 "${installedScript}" --pretool`), 'utf8');
|
||||
const pretoolProject = runInstalledWithInput('--pretool', fx, '{"tool_name":"Edit"}');
|
||||
assert.strictEqual(pretoolProject.status, 0,
|
||||
`installed project pre-tool must exit 0, got ${pretoolProject.status}`);
|
||||
assert.strictEqual(pretoolProject.stdout, '',
|
||||
`installed project pre-tool stdout must stay clean: ${pretoolProject.stdout.trim()}`);
|
||||
assert.ok(!pretoolProject.stderr.includes('references missing script'),
|
||||
`installed project pre-tool must not warn: ${pretoolProject.stderr.trim()}`);
|
||||
|
||||
// The same pre-tool path with a plugin-root command, from the same
|
||||
// disposable install.
|
||||
const pluginRoot = path.join(fx.root, 'plugin');
|
||||
fs.mkdirSync(path.join(pluginRoot, 'scripts', 'hooks'), { recursive: true });
|
||||
fs.writeFileSync(path.join(pluginRoot, 'scripts', 'hooks', 'guard.py'), '', 'utf8');
|
||||
fs.writeFileSync(settingsPath, PLUGIN_HOOKS_JSON('scripts/hooks/guard.py'), 'utf8');
|
||||
const pretoolPlugin = runInstalledWithInput('--pretool', fx, '{"tool_name":"Edit"}',
|
||||
{ CLAUDE_PLUGIN_ROOT: pluginRoot });
|
||||
assert.strictEqual(pretoolPlugin.status, 0,
|
||||
`installed plugin pre-tool must exit 0, got ${pretoolPlugin.status}`);
|
||||
assert.strictEqual(pretoolPlugin.stdout, '',
|
||||
`installed plugin pre-tool stdout must stay clean: ${pretoolPlugin.stdout.trim()}`);
|
||||
assert.ok(!pretoolPlugin.stderr.includes('references missing script'),
|
||||
`installed plugin pre-tool must not warn: ${pretoolPlugin.stderr.trim()}`);
|
||||
|
||||
fs.writeFileSync(settingsPath, PLUGIN_HOOKS_JSON('scripts/ghost.py'), 'utf8');
|
||||
const startup = runInstalled('--startup', fx, { CLAUDE_PLUGIN_ROOT: pluginRoot });
|
||||
assert.strictEqual(startup.status, 0,
|
||||
`startup must stay non-blocking, got ${startup.status}`);
|
||||
assert.ok(startup.stdout.includes('references missing script'),
|
||||
`a real missing plugin script must warn, got: ${startup.stdout.trim()}`);
|
||||
assert.ok(startup.stdout.includes('ghost.py'),
|
||||
'the warning must name the missing plugin script');
|
||||
|
||||
fs.writeFileSync(settingsPath,
|
||||
ONE_HOOK('python3 "${CONFIG_HEALTH_TEST_UNSET_ROOT}/scripts/x.py"'), 'utf8');
|
||||
const check = runInstalled('--check', fx);
|
||||
assert.strictEqual(check.status, 0, `--check exits 0, got ${check.status}`);
|
||||
assert.ok(check.stdout.includes('hook path(s) not audited'),
|
||||
`an unresolved provider root must be reported as unjudged, got: ${check.stdout.trim()}`);
|
||||
assert.ok(!check.stdout.includes('references missing script'),
|
||||
'an unresolved provider root must not be reported as a missing script');
|
||||
|
||||
fs.unlinkSync(installedScript);
|
||||
const repair = runNode('scripts/repair.js', ['--target', 'claude', '--json'], env);
|
||||
assert.strictEqual(repair.status, 0,
|
||||
`repair failed: ${(repair.stderr || repair.stdout).trim()}`);
|
||||
assert.ok(fs.existsSync(installedScript), 'repair must restore the installed script');
|
||||
|
||||
const uninstall = runNode('scripts/uninstall.js', ['--target', 'claude', '--json'], env);
|
||||
assert.strictEqual(uninstall.status, 0,
|
||||
`uninstall failed: ${(uninstall.stderr || uninstall.stdout).trim()}`);
|
||||
assert.ok(!fs.existsSync(installedScript), 'uninstall must remove the installed script');
|
||||
assert.ok(!fs.existsSync(installedSkill), 'uninstall must remove the installed skill');
|
||||
});
|
||||
|
||||
t('project install runs the pre-tool workflow from a disposable project', () => {
|
||||
const fx = makeInstallFixture();
|
||||
const env = installEnv(fx);
|
||||
const installScript = path.join(__dirname, '..', '..', 'scripts', 'install-apply.js');
|
||||
|
||||
const install = spawnSync(process.execPath,
|
||||
[installScript, '--target', 'claude-project', '--modules', 'config-health', '--json'],
|
||||
{ cwd: fx.proj, env: { ...process.env, ...env }, encoding: 'utf8', timeout: 120000 });
|
||||
assert.strictEqual(install.status, 0,
|
||||
`project install failed: ${(install.stderr || install.stdout).trim()}`);
|
||||
|
||||
const installedScript = path.join(fx.proj, '.claude', 'scripts', 'config-health.py');
|
||||
const settingsPath = path.join(fx.proj, '.claude', 'settings.json');
|
||||
assert.ok(fs.existsSync(installedScript),
|
||||
`project install must place the script at ${installedScript}`);
|
||||
|
||||
fs.writeFileSync(settingsPath,
|
||||
ONE_HOOK('python3 .claude/scripts/config-health.py --pretool'), 'utf8');
|
||||
const pretool = spawnSync(PYTHON, [installedScript, '--pretool'], {
|
||||
cwd: fx.proj,
|
||||
env: { ...process.env, ...env, CLAUDE_PROJECT_DIR: fx.proj },
|
||||
input: '{"tool_name":"Edit"}',
|
||||
encoding: 'utf8',
|
||||
timeout: 120000,
|
||||
});
|
||||
assert.strictEqual(pretool.status, 0,
|
||||
`project pre-tool must exit 0, got ${pretool.status}`);
|
||||
assert.strictEqual(pretool.stdout, '',
|
||||
`project pre-tool stdout must stay clean: ${pretool.stdout.trim()}`);
|
||||
assert.ok(!pretool.stderr.includes('references missing script'),
|
||||
`project pre-tool must not warn: ${pretool.stderr.trim()}`);
|
||||
});
|
||||
|
||||
console.log(`\n ${passed}/${total} passed`);
|
||||
if (passed !== total) process.exit(1);
|
||||
}
|
||||
|
||||
@@ -550,12 +550,22 @@ function runTests() {
|
||||
const settingsOperations = parsed.plan.operations.filter(operation => (
|
||||
operation.kind === 'update-claude-settings'
|
||||
));
|
||||
assert.strictEqual(settingsOperations.length, 1);
|
||||
assert.strictEqual(
|
||||
settingsOperations[0].destinationPath,
|
||||
path.join(homeDir, '.claude', 'settings.json')
|
||||
// Two modules ship hooks: the runtime, and config-health's own
|
||||
// SessionStart registration. Both merge into the same settings file.
|
||||
assert.strictEqual(settingsOperations.length, 2);
|
||||
for (const operation of settingsOperations) {
|
||||
assert.strictEqual(
|
||||
operation.destinationPath,
|
||||
path.join(homeDir, '.claude', 'settings.json')
|
||||
);
|
||||
assert.ok(operation.managedHooks.SessionStart);
|
||||
}
|
||||
assert.deepStrictEqual(
|
||||
settingsOperations
|
||||
.map(operation => String(operation.sourceRelativePath).replace(/\\/g, '/'))
|
||||
.sort(),
|
||||
['hooks/hooks.json', 'manifests/install-assets/config-health-hooks.json']
|
||||
);
|
||||
assert.ok(settingsOperations[0].managedHooks.SessionStart);
|
||||
assert.ok(!parsed.plan.operations.some(operation => (
|
||||
operation.kind === 'copy-file'
|
||||
&& String(operation.sourceRelativePath || '').replace(/\\/g, '/') === 'hooks/hooks.json'
|
||||
|
||||
@@ -132,6 +132,66 @@ function runTests() {
|
||||
}
|
||||
})) passed++; else failed++;
|
||||
|
||||
if (test('uninstall removes every managed hook when two modules share settings.json', () => {
|
||||
const homeDir = createTempDir('uninstall-shared-settings-home-');
|
||||
const projectRoot = createTempDir('uninstall-shared-settings-project-');
|
||||
const claudeRoot = path.join(homeDir, '.claude');
|
||||
const settingsPath = path.join(claudeRoot, 'settings.json');
|
||||
const statePath = path.join(claudeRoot, 'ecc', 'install-state.json');
|
||||
|
||||
try {
|
||||
execFileSync(
|
||||
'node',
|
||||
[INSTALL_SCRIPT, '--target', 'claude', '--modules', 'hooks-runtime,config-health', '--enable-hooks'],
|
||||
{
|
||||
cwd: projectRoot,
|
||||
env: { ...process.env, HOME: homeDir, USERPROFILE: homeDir },
|
||||
encoding: 'utf8',
|
||||
stdio: ['pipe', 'pipe', 'pipe'],
|
||||
timeout: CLI_TIMEOUT_MS,
|
||||
}
|
||||
);
|
||||
const state = JSON.parse(fs.readFileSync(statePath, 'utf8'));
|
||||
const settingsOperations = state.operations.filter(operation => (
|
||||
operation.kind === 'update-claude-settings'
|
||||
));
|
||||
// Each module's settings contribution must keep its own record; keyed by
|
||||
// destination alone, one overwrites the other and its hooks leak.
|
||||
assert.strictEqual(settingsOperations.length, 2,
|
||||
`expected one settings record per hook-shipping module, got ${JSON.stringify(
|
||||
settingsOperations.map(operation => operation.moduleId)
|
||||
)}`);
|
||||
const managedIds = new Set(settingsOperations
|
||||
.flatMap(operation => Object.values(operation.managedHooks || {}))
|
||||
.flat()
|
||||
.map(entry => entry.id));
|
||||
assert.ok(managedIds.has('config-health:session-start'),
|
||||
'the config-health hook must be recorded');
|
||||
assert.ok(managedIds.has('session:start'),
|
||||
'the runtime SessionStart hook must be recorded');
|
||||
|
||||
const uninstallResult = run(['--target', 'claude'], {
|
||||
cwd: projectRoot,
|
||||
homeDir,
|
||||
});
|
||||
assert.strictEqual(uninstallResult.code, 0, uninstallResult.stderr);
|
||||
assert.ok(!fs.existsSync(statePath), 'uninstall must remove the install-state record');
|
||||
|
||||
const settings = fs.existsSync(settingsPath)
|
||||
? JSON.parse(fs.readFileSync(settingsPath, 'utf8'))
|
||||
: {};
|
||||
const remainingIds = Object.values(settings.hooks || {})
|
||||
.flat()
|
||||
.map(entry => entry.id);
|
||||
const leaked = remainingIds.filter(id => managedIds.has(id));
|
||||
assert.deepStrictEqual(leaked, [],
|
||||
`uninstall left managed hooks behind in settings.json: ${leaked.join(', ')}`);
|
||||
} finally {
|
||||
cleanup(homeDir);
|
||||
cleanup(projectRoot);
|
||||
}
|
||||
})) passed++; else failed++;
|
||||
|
||||
if (test('uninstalls the project hook module boundary and preserves user Claude package data', () => {
|
||||
const homeDir = createTempDir('uninstall-claude-project-esm-home-');
|
||||
const projectRoot = createTempDir('uninstall-claude-project-esm-');
|
||||
|
||||
Reference in new issue
Block a user