Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 44 additions & 7 deletions host-setup/agent-safety/claude/install.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,9 @@

HERE = pathlib.Path(__file__).resolve().parent

# Each hook's file name, and the substring identifying its registration in settings.json.
# Named once, since a registration written under one spelling and searched for under another is reported absent forever.
# The guard was spelled by hand on the search side and by position on the deploy side, which is that same drift one rename away.
# NAME serves both the writer (DEPLOYED_HOOKS, hook_dst/sweep_dst) and the reader (`names_hook`).
# A rename made on one side and not the other reports the registration absent forever.
# STEM is read by the test suite alone now, as a substring convenience over a real command.
GUARD_NAME = "gh-write-guard.py"
GUARD_STEM = "gh-write-guard"
SWEEP_NAME = "stray-process-sweep.py"
Expand Down Expand Up @@ -116,6 +116,39 @@ def runs_hook(command, path):
)


def names_hook(command, name):
"""Whether `command` runs a file whose own name is exactly `name` (e.g. GUARD_NAME), at any path.

Matched with `runs_hook`'s own boundary characters rather than by tokenizing the command.
A command `runs_hook` already treats as running the deployed hook, such as one wrapped in
`bash -c "..."`, in `(...)`, or followed by `; true`, carries those wrapping characters
attached to the path with no separating space, which `shlex.split` folds into the token and
a plain whitespace split (its own fallback on an unbalanced quote) leaves attached to a quote
character, so neither reads the trailing path segment as `name` alone.

Matched as a trailing path segment rather than a bare substring, so a maintainer's own hook
whose file name merely contains this kit's stem, such as `my-gh-write-guard-audit.sh`
containing `gh-write-guard`, is not claimed: the character right after the stem there is
`-`, not one of the boundary characters this match requires.

A quoted path is read to its closing quote rather than through the same boundary characters,
since those are literal there: `"/c/Program Files (x86)/hooks/gh-write-guard.py"` is a path
`runs_hook` accepts whole, and the bare-word boundary class below cannot cross the space or
the parentheses inside it to reach the deployed name.

Known gap, not chased further here: an unquoted path whose own directory holds one of the
bare-word boundary characters, and a handful of shell compositions `runs_hook` itself only
accepts because it is handed the exact literal path rather than discovering one (a backtick,
a no-space redirect, a quote escaped inside an outer quote). Closing those needs `runs_hook`
widened too, which is a design change on its own rather than a local match.
"""
text = str(command).replace("\\", "/")
escaped = re.escape(name)
quoted = rf'"(?:[^"]*/)?{escaped}"' + "|" + rf"'(?:[^']*/)?{escaped}'"
bare = rf"(?:^|[\s\"'(])(?:[^\s\"'()|&;]*/)?{escaped}(?=$|[\s\"')|&;])"
return re.search(quoted, text) is not None or re.search(bare, text) is not None


def matcher_sees_bash(matcher):
"""Whether a PreToolUse matcher group receives a Bash call.

Expand Down Expand Up @@ -577,7 +610,7 @@ def event_groups(event):
if not isinstance(group, dict):
continue
for hook in group.get("hooks") or []:
if not isinstance(hook, dict) or GUARD_STEM not in str(hook.get("command", "")):
if not isinstance(hook, dict) or not names_hook(hook.get("command", ""), GUARD_NAME):
continue
named += 1
if not runs_hook(hook.get("command"), guard_path) or hook.get("type") != "command":
Expand Down Expand Up @@ -612,7 +645,7 @@ def event_groups(event):
continue
sweep_path = claude_home / "hooks" / SWEEP_NAME
for hook in group.get("hooks") or []:
if not isinstance(hook, dict) or SWEEP_STEM not in str(hook.get("command", "")):
if not isinstance(hook, dict) or not names_hook(hook.get("command", ""), SWEEP_NAME):
continue
sweeps_named += 1
if not runs_hook(hook.get("command"), sweep_path) or hook.get("type") != "command":
Expand Down Expand Up @@ -971,7 +1004,9 @@ def reject(where, held, want):
for g in pre:
hooks_list = g.get("hooks")
if isinstance(hooks_list, list):
hooks_list[:] = [h for h in hooks_list if GUARD_STEM not in str(h.get("command", ""))]
hooks_list[:] = [
h for h in hooks_list if not names_hook(h.get("command", ""), GUARD_NAME)
]
group = next((g for g in pre if g.get("matcher") == "Bash"), None)
if group is None:
group = {"matcher": "Bash", "hooks": []}
Expand All @@ -985,7 +1020,9 @@ def reject(where, held, want):
for g in ends:
hooks_list = g.get("hooks")
if isinstance(hooks_list, list):
hooks_list[:] = [h for h in hooks_list if SWEEP_STEM not in str(h.get("command", ""))]
hooks_list[:] = [
h for h in hooks_list if not names_hook(h.get("command", ""), SWEEP_NAME)
]
end_group = next((g for g in ends if matcher_covers_every_exit_reason(g.get("matcher"))), None)
if end_group is None:
end_group = {"hooks": []}
Expand Down
52 changes: 45 additions & 7 deletions host-setup/agent-safety/claude/test_install.py
Original file line number Diff line number Diff line change
Expand Up @@ -504,7 +504,7 @@ def test_a_decoy_command_naming_the_sweep_is_not_a_registration(self):
for label, entry, expected in (
(
"decoy",
{"type": "command", "command": "echo stray-process-sweep"},
{"type": "command", "command": "echo /tmp/stray-process-sweep.py"},
"does not run the deployed one",
),
("timeout", dict(good, timeout=1), "carries timeout 1"),
Expand Down Expand Up @@ -596,15 +596,14 @@ def test_one_group_defect_is_reported_once_however_many_entries(self):
matcher_lines = [p for p in problems if "matcher" in p and event in p]
self.assertEqual(len(matcher_lines), 1, problems)

def test_the_guard_is_deployed_and_searched_for_under_one_name(self):
"""The sweep routes both halves through a constant, and the guard spelled one half by hand."""
def test_the_guard_is_deployed_and_registered_under_one_name(self):
"""The deployed file and the registered command both name GUARD_NAME, or a rename on
one side and not the other reports the registration absent forever."""
self.install()
self.assertTrue(install.GUARD_NAME.startswith(install.GUARD_STEM))
live = self.home / "hooks" / install.GUARD_NAME
self.assertTrue(live.is_file(), "the deployed name is not what the installer wrote")
self.assertIn(
install.GUARD_STEM, self._settings()["hooks"]["PreToolUse"][0]["hooks"][0]["command"]
)
registered = self._settings()["hooks"]["PreToolUse"][0]["hooks"][0]["command"]
self.assertTrue(install.names_hook(registered, install.GUARD_NAME))

def test_a_longer_sweep_timeout_is_not_reported_as_a_defect(self):
"""A budget larger than this installer writes is better than it, not worse."""
Expand Down Expand Up @@ -715,6 +714,45 @@ def test_reinstalling_clears_an_unregistered_hook(self):
self.install()
self.assertEqual(run(self.home, "--report").returncode, 0)

def test_a_wrapper_merely_containing_a_stem_is_not_the_kits_registration(self):
"""A maintainer's own hook whose command merely contains a stem, such as
`my-gh-write-guard-audit.sh`, is neither counted by `--report` as this kit's registration
nor removed by a re-run. A substring test on the whole command claimed both; judging
ownership by the file name a token names does neither."""
for event, wrapper_name in (
("PreToolUse", "my-gh-write-guard-audit.sh"),
("SessionEnd", "my-stray-process-sweep-audit.sh"),
):
with self.subTest(event=event):
self.install()
data = self._settings()
wrapper = {"type": "command", "command": f"bash /usr/local/bin/{wrapper_name}"}
data["hooks"][event][0]["hooks"].append(wrapper)
self._write(data)
self.assertEqual(install.registration_problems(self.home), [])
self.install()
hooks = self._settings()["hooks"][event][0]["hooks"]
self.assertIn(wrapper, hooks, "the wrapper was removed by a re-run")

def test_names_hook_agrees_with_runs_hook_on_every_shape_it_accepts(self):
"""A command `runs_hook` already treats as running the deployed hook must count as
named too, or a re-run leaves a duplicate registration in place while `--report` calls
the hook absent."""
plain = pathlib.Path("/home/vscode/.claude/hooks/gh-write-guard.py")
metachars = pathlib.Path("/opt/Program Files (x86)/a&b;c|d/gh-write-guard.py")
for label, path, command in (
("bare", plain, f'"python3" "{plain}"'),
("trailing-semicolon", plain, f'"python3" "{plain}"; true'),
("parenthesized", plain, f"(python3 {plain})"),
("bash-c", plain, f'bash -c "python3 {plain} --x"'),
("unbalanced-quote-comment", plain, f'"python3" "{plain}" # it\'s'),
("double-quoted-metacharacters", metachars, f'"python3" "{metachars}"'),
("single-quoted-metacharacters", metachars, f"'python3' '{metachars}'"),
):
with self.subTest(shape=label):
self.assertTrue(install.runs_hook(command, path), command)
self.assertTrue(install.names_hook(command, install.GUARD_NAME), command)


class TestContainmentPrefix(StampCase):
"""The shell prefix is set where the host can contain a command, and owned only while it names ours."""
Expand Down
Loading