claude-dev-env 8.117.5 → 8.118.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,168 @@
1
+ """Find the hooks that nested checkouts declare for one event.
2
+
3
+ A session directory can hold several checkouts, each with its own settings::
4
+
5
+ session directory
6
+ |-- checkout-a/.claude/settings.json PreToolUse "Bash" -> ./gate.sh
7
+ `-- checkout-b/.claude/settings.json SessionStart -> ./start.sh
8
+
9
+ For a PreToolUse call on ``Bash`` this module returns one ``NestedHook`` for
10
+ ``./gate.sh`` in checkout-a. The forwarder in ``nested_project_hooks`` runs it.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ import re
17
+ from dataclasses import dataclass
18
+ from pathlib import Path
19
+
20
+ from hooks_constants.nested_project_hooks_constants import (
21
+ ALL_MATCH_EVERYTHING_MATCHERS,
22
+ CHECKOUT_MARKER_NAME,
23
+ COMMAND_HOOK_TYPE,
24
+ COMMAND_KEY,
25
+ DEFAULT_HOOK_TIMEOUT_SECONDS,
26
+ HOOK_TYPE_KEY,
27
+ HOOKS_KEY,
28
+ MATCHER_KEY,
29
+ SETTINGS_DIRECTORY_NAME,
30
+ SETTINGS_ENCODING,
31
+ SETTINGS_FILE_NAME,
32
+ TIMEOUT_KEY,
33
+ )
34
+
35
+
36
+ @dataclass(frozen=True)
37
+ class NestedHook:
38
+ """One command hook a nested checkout declares for the current event."""
39
+
40
+ project_directory: Path
41
+ command: str
42
+ timeout_seconds: float
43
+
44
+
45
+ def _settings_path(directory: Path) -> Path:
46
+ return directory / SETTINGS_DIRECTORY_NAME / SETTINGS_FILE_NAME
47
+
48
+
49
+ def find_nested_projects(session_directory: Path) -> list[Path]:
50
+ """Return the child checkouts whose project hooks Claude Code skipped.
51
+
52
+ Args:
53
+ session_directory: The directory the session started in.
54
+
55
+ Returns:
56
+ Each immediate child holding both a ``.git`` entry and a
57
+ ``.claude/settings.json`` file, sorted by name. Empty when the
58
+ session directory is a checkout or has settings of its own.
59
+ """
60
+ if (session_directory / CHECKOUT_MARKER_NAME).exists():
61
+ return []
62
+ if _settings_path(session_directory).is_file():
63
+ return []
64
+ try:
65
+ all_children = sorted(session_directory.iterdir())
66
+ except OSError:
67
+ return []
68
+ return [
69
+ each_child
70
+ for each_child in all_children
71
+ if each_child.is_dir()
72
+ and (each_child / CHECKOUT_MARKER_NAME).exists()
73
+ and _settings_path(each_child).is_file()
74
+ ]
75
+
76
+
77
+ def _read_hook_groups(project_directory: Path, event_name: str) -> list[object]:
78
+ try:
79
+ settings_text = _settings_path(project_directory).read_text(encoding=SETTINGS_ENCODING)
80
+ settings = json.loads(settings_text)
81
+ except (OSError, json.JSONDecodeError):
82
+ return []
83
+ if not isinstance(settings, dict):
84
+ return []
85
+ hooks_by_event = settings.get(HOOKS_KEY)
86
+ if not isinstance(hooks_by_event, dict):
87
+ return []
88
+ all_groups = hooks_by_event.get(event_name)
89
+ if not isinstance(all_groups, list):
90
+ return []
91
+ return all_groups
92
+
93
+
94
+ def matcher_selects(matcher: object, match_target: str) -> bool:
95
+ """Report whether a settings matcher selects this event's target.
96
+
97
+ Args:
98
+ matcher: The ``matcher`` value of one hook group, possibly absent.
99
+ match_target: The tool name for PreToolUse, the start source for
100
+ SessionStart.
101
+
102
+ Returns:
103
+ True for an absent, empty, or ``*`` matcher, and for a matcher whose
104
+ pattern matches the whole target. An invalid pattern matches only
105
+ its exact text.
106
+ """
107
+ if matcher is None:
108
+ return True
109
+ if not isinstance(matcher, str):
110
+ return False
111
+ if matcher in ALL_MATCH_EVERYTHING_MATCHERS:
112
+ return True
113
+ try:
114
+ return re.fullmatch(matcher, match_target) is not None
115
+ except re.error:
116
+ return matcher == match_target
117
+
118
+
119
+ def _command_hook(project_directory: Path, hook_fields: object) -> NestedHook | None:
120
+ if not isinstance(hook_fields, dict):
121
+ return None
122
+ if hook_fields.get(HOOK_TYPE_KEY) != COMMAND_HOOK_TYPE:
123
+ return None
124
+ command = hook_fields.get(COMMAND_KEY)
125
+ if not isinstance(command, str) or not command.strip():
126
+ return None
127
+ timeout_value = hook_fields.get(TIMEOUT_KEY)
128
+ timeout_seconds = DEFAULT_HOOK_TIMEOUT_SECONDS
129
+ if isinstance(timeout_value, (int, float)) and timeout_value > 0:
130
+ timeout_seconds = float(timeout_value)
131
+ return NestedHook(project_directory, command, timeout_seconds)
132
+
133
+
134
+ def _selected_hook_entries(
135
+ project_directory: Path, event_name: str, match_target: str
136
+ ) -> list[object]:
137
+ all_hook_entries: list[object] = []
138
+ for each_group in _read_hook_groups(project_directory, event_name):
139
+ if not isinstance(each_group, dict):
140
+ continue
141
+ if not matcher_selects(each_group.get(MATCHER_KEY), match_target):
142
+ continue
143
+ all_group_hooks = each_group.get(HOOKS_KEY)
144
+ if isinstance(all_group_hooks, list):
145
+ all_hook_entries.extend(all_group_hooks)
146
+ return all_hook_entries
147
+
148
+
149
+ def collect_nested_hooks(
150
+ session_directory: Path, event_name: str, match_target: str
151
+ ) -> list[NestedHook]:
152
+ """Return every nested command hook that this event selects, in order.
153
+
154
+ Args:
155
+ session_directory: The directory the session started in.
156
+ event_name: The hook event being handled.
157
+ match_target: The value the event's matchers compare against.
158
+
159
+ Returns:
160
+ The selected command hooks, checkout by checkout in name order and
161
+ in declaration order inside each checkout.
162
+ """
163
+ all_candidates = (
164
+ _command_hook(each_project, each_entry)
165
+ for each_project in find_nested_projects(session_directory)
166
+ for each_entry in _selected_hook_entries(each_project, event_name, match_target)
167
+ )
168
+ return [each_candidate for each_candidate in all_candidates if each_candidate is not None]
@@ -547,3 +547,44 @@ def test_should_allow_and_write_one_line_for_each_child_the_time_limit_cuts_off(
547
547
  "beta",
548
548
  "gamma",
549
549
  ]
550
+
551
+
552
+ def test_should_run_a_collected_hook_in_its_checkout_and_return_its_output(
553
+ tmp_path: pathlib.Path,
554
+ ) -> None:
555
+ checkout_directory = _make_checkout(
556
+ tmp_path,
557
+ "alpha",
558
+ {"PreToolUse": [_command_group("Bash", 'read -r payload; echo "$CLAUDE_PROJECT_DIR|$payload"')]},
559
+ )
560
+ (nested_hook,) = nested_project_hooks.collect_nested_hooks(tmp_path, "PreToolUse", "Bash")
561
+
562
+ completed_process = nested_project_hooks.run_nested_hook(nested_hook, '{"tool_name": "Bash"}')
563
+
564
+ assert completed_process is not None
565
+ project_directory, payload_text = completed_process.stdout.strip().split("|")
566
+ assert pathlib.Path(project_directory).resolve() == checkout_directory.resolve()
567
+ assert payload_text == '{"tool_name": "Bash"}'
568
+
569
+
570
+ def test_should_join_plain_and_json_session_start_output_into_one_context() -> None:
571
+ all_results = [
572
+ subprocess.CompletedProcess(["alpha"], 0, "alpha is ready\n", "alpha warned\n"),
573
+ subprocess.CompletedProcess(
574
+ ["beta"],
575
+ 0,
576
+ json.dumps({"hookSpecificOutput": {"additionalContext": "beta loaded its rules"}}),
577
+ "",
578
+ ),
579
+ ]
580
+
581
+ verdict = nested_project_hooks.session_start_verdict(all_results)
582
+
583
+ assert verdict.exit_code == 0
584
+ assert json.loads(verdict.stdout_text) == {
585
+ "hookSpecificOutput": {
586
+ "hookEventName": "SessionStart",
587
+ "additionalContext": "alpha is ready\n\nbeta loaded its rules",
588
+ }
589
+ }
590
+ assert verdict.stderr_text == "alpha warned"
@@ -0,0 +1,164 @@
1
+ """Behavior tests for finding the hooks that nested checkouts declare.
2
+
3
+ Each case builds a session directory with child checkouts on disk and reads
4
+ which checkouts and which command hooks the discovery functions return.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import pathlib
11
+
12
+ import pytest
13
+
14
+ from lifecycle.nested_project_hooks_discovery import (
15
+ NestedHook,
16
+ collect_nested_hooks,
17
+ find_nested_projects,
18
+ matcher_selects,
19
+ )
20
+
21
+ DEFAULT_TIMEOUT_SECONDS = 600.0
22
+
23
+
24
+ def _make_checkout(
25
+ session_directory: pathlib.Path,
26
+ checkout_name: str,
27
+ all_hook_groups_by_event: dict[str, list[dict[str, object]]],
28
+ ) -> pathlib.Path:
29
+ checkout_directory = session_directory / checkout_name
30
+ (checkout_directory / ".git").mkdir(parents=True)
31
+ settings_directory = checkout_directory / ".claude"
32
+ settings_directory.mkdir()
33
+ (settings_directory / "settings.json").write_text(
34
+ json.dumps({"hooks": all_hook_groups_by_event}), encoding="utf-8"
35
+ )
36
+ return checkout_directory
37
+
38
+
39
+ def test_should_find_each_child_checkout_with_settings_in_name_order(
40
+ tmp_path: pathlib.Path,
41
+ ) -> None:
42
+ beta_directory = _make_checkout(tmp_path, "beta", {})
43
+ alpha_directory = _make_checkout(tmp_path, "alpha", {})
44
+ (tmp_path / "no-git" / ".claude").mkdir(parents=True)
45
+ (tmp_path / "no-git" / ".claude" / "settings.json").write_text("{}", encoding="utf-8")
46
+ (tmp_path / "no-settings" / ".git").mkdir(parents=True)
47
+ (tmp_path / "loose-file.txt").write_text("not a checkout", encoding="utf-8")
48
+
49
+ assert find_nested_projects(tmp_path) == [alpha_directory, beta_directory]
50
+
51
+
52
+ def test_should_find_no_child_when_the_session_directory_is_a_checkout(
53
+ tmp_path: pathlib.Path,
54
+ ) -> None:
55
+ (tmp_path / ".git").mkdir()
56
+ _make_checkout(tmp_path, "alpha", {})
57
+
58
+ assert find_nested_projects(tmp_path) == []
59
+
60
+
61
+ def test_should_find_no_child_when_the_session_directory_has_its_own_settings(
62
+ tmp_path: pathlib.Path,
63
+ ) -> None:
64
+ (tmp_path / ".claude").mkdir()
65
+ (tmp_path / ".claude" / "settings.json").write_text("{}", encoding="utf-8")
66
+ _make_checkout(tmp_path, "alpha", {})
67
+
68
+ assert find_nested_projects(tmp_path) == []
69
+
70
+
71
+ def test_should_find_no_child_when_the_session_directory_is_missing(
72
+ tmp_path: pathlib.Path,
73
+ ) -> None:
74
+ assert find_nested_projects(tmp_path / "gone") == []
75
+
76
+
77
+ @pytest.mark.parametrize(
78
+ ("matcher", "match_target", "is_selected"),
79
+ [
80
+ (None, "Bash", True),
81
+ ("", "Bash", True),
82
+ ("*", "Bash", True),
83
+ ("Write|Edit", "Edit", True),
84
+ ("Write|Edit", "Bash", False),
85
+ ("Bas", "Bash", False),
86
+ ("[", "[", True),
87
+ ("[", "Bash", False),
88
+ (7, "Bash", False),
89
+ ],
90
+ )
91
+ def test_should_select_a_target_only_when_the_matcher_covers_all_of_it(
92
+ matcher: object, match_target: str, is_selected: bool
93
+ ) -> None:
94
+ assert matcher_selects(matcher, match_target) is is_selected
95
+
96
+
97
+ def test_should_collect_command_hooks_by_checkout_then_declaration_order(
98
+ tmp_path: pathlib.Path,
99
+ ) -> None:
100
+ alpha_directory = _make_checkout(
101
+ tmp_path,
102
+ "alpha",
103
+ {
104
+ "PreToolUse": [
105
+ {"matcher": "Bash", "hooks": [{"type": "command", "command": "./first.sh"}]},
106
+ {
107
+ "matcher": "Bash",
108
+ "hooks": [{"type": "command", "command": "./second.sh", "timeout": 5}],
109
+ },
110
+ ]
111
+ },
112
+ )
113
+ beta_directory = _make_checkout(
114
+ tmp_path,
115
+ "beta",
116
+ {"PreToolUse": [{"hooks": [{"type": "command", "command": "./third.sh"}]}]},
117
+ )
118
+
119
+ assert collect_nested_hooks(tmp_path, "PreToolUse", "Bash") == [
120
+ NestedHook(alpha_directory, "./first.sh", DEFAULT_TIMEOUT_SECONDS),
121
+ NestedHook(alpha_directory, "./second.sh", 5.0),
122
+ NestedHook(beta_directory, "./third.sh", DEFAULT_TIMEOUT_SECONDS),
123
+ ]
124
+
125
+
126
+ def test_should_skip_entries_that_are_not_runnable_command_hooks(
127
+ tmp_path: pathlib.Path,
128
+ ) -> None:
129
+ alpha_directory = _make_checkout(
130
+ tmp_path,
131
+ "alpha",
132
+ {
133
+ "PreToolUse": [
134
+ {"matcher": "Edit", "hooks": [{"type": "command", "command": "./edit-only.sh"}]},
135
+ "not a group",
136
+ {
137
+ "matcher": "Bash",
138
+ "hooks": [
139
+ {"type": "prompt", "prompt": "check the call"},
140
+ {"type": "command", "command": " "},
141
+ {"type": "command", "command": "./zero-timeout.sh", "timeout": 0},
142
+ "not a hook",
143
+ ],
144
+ },
145
+ ],
146
+ "SessionStart": [{"hooks": [{"type": "command", "command": "./start.sh"}]}],
147
+ },
148
+ )
149
+
150
+ assert collect_nested_hooks(tmp_path, "PreToolUse", "Bash") == [
151
+ NestedHook(alpha_directory, "./zero-timeout.sh", DEFAULT_TIMEOUT_SECONDS),
152
+ ]
153
+
154
+
155
+ @pytest.mark.parametrize("unreadable_settings", ["{not json", "[]", '{"hooks": []}'])
156
+ def test_should_collect_nothing_from_settings_that_cannot_be_read(
157
+ tmp_path: pathlib.Path, unreadable_settings: str
158
+ ) -> None:
159
+ checkout_directory = _make_checkout(tmp_path, "alpha", {})
160
+ (checkout_directory / ".claude" / "settings.json").write_text(
161
+ unreadable_settings, encoding="utf-8"
162
+ )
163
+
164
+ assert collect_nested_hooks(tmp_path, "PreToolUse", "Bash") == []
@@ -82,6 +82,32 @@ def _log_hook_crash(hook_script_path: str, error: Exception) -> None:
82
82
  sys.stderr.flush()
83
83
 
84
84
 
85
+ def _run_hook_script(hook_script_path: str) -> tuple[bool, int]:
86
+ """Run one hook script under ``__main__`` and return whether it crashed and its exit code.
87
+
88
+ ::
89
+
90
+ the script calls sys.exit(2) -> (False, 2)
91
+ the script ends without an exit -> (False, 0)
92
+ the script calls sys.exit("text") -> (False, 0)
93
+ the script raises ValueError -> (True, 0), and the crash is logged
94
+
95
+ Args:
96
+ hook_script_path: Absolute path of the hook script to run.
97
+
98
+ Returns:
99
+ The crash flag, then the integer the hook passed to SystemExit, else 0.
100
+ """
101
+ try:
102
+ runpy.run_path(hook_script_path, run_name="__main__")
103
+ except SystemExit as exit_signal:
104
+ return False, exit_signal.code if isinstance(exit_signal.code, int) else 0
105
+ except Exception as error:
106
+ _log_hook_crash(hook_script_path, error)
107
+ return True, 0
108
+ return False, 0
109
+
110
+
85
111
  def run_hosted_hook(
86
112
  hook_script_path: str,
87
113
  all_hook_arguments: list[str],
@@ -113,19 +139,12 @@ def run_hosted_hook(
113
139
  original_stdout = sys.stdout
114
140
  original_argv = sys.argv
115
141
  captured_output = io.StringIO()
116
- hook_did_crash = False
117
- hook_exit_code = 0
118
142
 
119
143
  try:
120
144
  sys.stdin = io.StringIO(payload_text)
121
145
  sys.stdout = captured_output
122
146
  sys.argv = [hook_script_path, *all_hook_arguments]
123
- runpy.run_path(hook_script_path, run_name="__main__")
124
- except SystemExit as exit_signal:
125
- hook_exit_code = exit_signal.code if isinstance(exit_signal.code, int) else 0
126
- except Exception as error:
127
- _log_hook_crash(hook_script_path, error)
128
- hook_did_crash = True
147
+ hook_did_crash, hook_exit_code = _run_hook_script(hook_script_path)
129
148
  finally:
130
149
  sys.stdin = original_stdin
131
150
  sys.stdout = original_stdout
@@ -411,3 +411,54 @@ def test_should_pass_a_hosted_hook_exit_two_to_the_host_with_its_stderr(
411
411
  assert (raised_exit.value.code or 0) == expected_exit_code
412
412
  assert "probe child says stop" in capsys.readouterr().err
413
413
  assert later_marker.exists()
414
+
415
+
416
+ @pytest.mark.parametrize(
417
+ ("probe_source", "expected_outcome"),
418
+ [
419
+ ("import sys\nsys.exit(2)\n", (False, 2)),
420
+ ("marker = 1\n", (False, 0)),
421
+ ("import sys\nsys.exit('stop')\n", (False, 0)),
422
+ ("raise ValueError('probe broke')\n", (True, 0)),
423
+ ],
424
+ )
425
+ def test_should_report_the_crash_flag_and_exit_code_of_a_hosted_hook(
426
+ tmp_path: Path,
427
+ capsys: pytest.CaptureFixture[str],
428
+ probe_source: str,
429
+ expected_outcome: tuple[bool, int],
430
+ ) -> None:
431
+ dispatcher_module = sys.modules[aggregate_post_hosted_hook_results.__module__]
432
+ probe_path = tmp_path / "probe.py"
433
+ probe_path.write_text(probe_source, encoding="utf-8")
434
+
435
+ hosted_result = dispatcher_module.run_hosted_hook(
436
+ str(probe_path), [], "", is_blocking=True
437
+ )
438
+
439
+ assert (hosted_result.did_crash, hosted_result.exit_code) == expected_outcome
440
+ did_crash = expected_outcome[0]
441
+ assert ("probe broke" in capsys.readouterr().err) is did_crash
442
+
443
+
444
+ def test_should_restore_stdin_stdout_and_argv_after_a_hosted_hook_crashes(
445
+ tmp_path: Path,
446
+ ) -> None:
447
+ dispatcher_module = sys.modules[aggregate_post_hosted_hook_results.__module__]
448
+ probe_path = tmp_path / "crash_probe.py"
449
+ probe_path.write_text(
450
+ "import sys\nprint(sys.argv[1] + sys.stdin.read())\nraise ValueError('probe broke')\n",
451
+ encoding="utf-8",
452
+ )
453
+ stdin_before, stdout_before, argv_before = sys.stdin, sys.stdout, sys.argv
454
+
455
+ hosted_result = dispatcher_module.run_hosted_hook(
456
+ str(probe_path), ["tail"], "payload", is_blocking=True
457
+ )
458
+
459
+ assert sys.stdin is stdin_before
460
+ assert sys.stdout is stdout_before
461
+ assert sys.argv is argv_before
462
+ assert hosted_result == PostHostedHookResult(
463
+ captured_stdout="tailpayload\n", did_crash=True, is_blocking=True, exit_code=0
464
+ )
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-dev-env",
3
- "version": "8.117.5",
3
+ "version": "8.118.1",
4
4
  "description": "Claude Code development standards — rules, hooks, agents, commands, and skills",
5
5
  "type": "module",
6
6
  "bin": {
@@ -134,6 +134,7 @@ def _names_exempt_registration_path(registered_string: str) -> bool:
134
134
  hooks/blocking/issue_close_handoff_gate.py -> exempt
135
135
  hooks/blocking/verify_before_acting.py -> exempt
136
136
  hooks/blocking/session_title_format_gate.py -> exempt
137
+ hooks/blocking/task_subject_outcome_gate.py -> exempt
137
138
  hooks/blocking/artifact_dark_mode_gate.py -> exempt
138
139
  hooks/blocking/send_user_file_worktree_root_gate.py -> exempt
139
140
  hooks/blocking/question_brief_gate.py -> exempt
@@ -176,6 +177,10 @@ def _names_exempt_registration_path(registered_string: str) -> bool:
176
177
  The session title format gate denies a malformed title. It decides the
177
178
  shape of a title and no code or safety policy.
178
179
 
180
+ The task subject gate denies a task list subject that starts with a
181
+ procedure step label or holds a code-formatted name. It decides the
182
+ wording the user reads and no code or safety policy.
183
+
179
184
  The artifact page gate denies a page publish whose text is unreadable in
180
185
  dark mode. It decides how a page renders and no code or safety policy.
181
186
 
@@ -71,6 +71,7 @@ ALL_ACTION_BOUNDARY_EXEMPT_REGISTRATION_PATHS = (
71
71
  "blocking/issue_close_handoff_gate.py",
72
72
  "blocking/verify_before_acting.py",
73
73
  "blocking/session_title_format_gate.py",
74
+ "blocking/task_subject_outcome_gate.py",
74
75
  "blocking/image_read_size_gate.py",
75
76
  "blocking/artifact_dark_mode_gate.py",
76
77
  "blocking/send_user_file_worktree_root_gate.py",
@@ -130,6 +130,14 @@ def test_new_session_title_gate_registration_is_clean(tmp_path: Path) -> None:
130
130
  assert adapters.hook_configuration_diagnostics(current_document, tmp_path) == ()
131
131
 
132
132
 
133
+ def test_new_task_subject_outcome_gate_registration_is_clean(tmp_path: Path) -> None:
134
+ current_document = _hook_document(
135
+ ["hooks/blocking/task_subject_outcome_gate.py"],
136
+ '{"hooks": {}}',
137
+ )
138
+ assert adapters.hook_configuration_diagnostics(current_document, tmp_path) == ()
139
+
140
+
133
141
  def test_new_task_subject_gate_registration_is_clean(tmp_path: Path) -> None:
134
142
  current_document = _hook_document(
135
143
  ["hooks/blocking/task_subject_length_gate.py"],