claude-dev-env 8.118.0 → 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,174 @@
1
+ import pytest
2
+
3
+ from open_tasks_transcript_records import (
4
+ claude_prompt_text,
5
+ codex_prompt_text,
6
+ is_assistant_record,
7
+ is_codex_question_call,
8
+ is_codex_read_call,
9
+ is_codex_work_call,
10
+ is_read_tool_name,
11
+ is_work_tool_name,
12
+ normalized_text,
13
+ parsed_object,
14
+ send_call_file_paths,
15
+ )
16
+
17
+
18
+ def codex_record(payload: object) -> dict[str, object]:
19
+ return {"type": "response_item", "payload": payload}
20
+
21
+
22
+ def test_should_lowercase_text_and_collapse_each_whitespace_run() -> None:
23
+ assert normalized_text(" Fix\tThe\n\n Login BUG ") == "fix the login bug"
24
+ assert normalized_text("") == ""
25
+
26
+
27
+ def test_should_return_only_a_json_object_from_text() -> None:
28
+ assert parsed_object('{"plan": [1, 2]}') == {"plan": [1, 2]}
29
+ assert parsed_object('"just a string"') is None
30
+ assert parsed_object('{"truncated": ') is None
31
+
32
+
33
+ @pytest.mark.parametrize(
34
+ ("record", "expected_text"),
35
+ [
36
+ (
37
+ {
38
+ "role": "user",
39
+ "message": {
40
+ "content": [
41
+ {"type": "text", "text": "Refactor"},
42
+ {"type": "text", "text": "the cache"},
43
+ ]
44
+ },
45
+ },
46
+ "Refactor the cache",
47
+ ),
48
+ ({"message": {"role": "user", "content": "Port the parser"}}, "Port the parser"),
49
+ (
50
+ {
51
+ "type": "user",
52
+ "message": {
53
+ "content": [
54
+ {"type": "text", "text": "<system-reminder>r</system-reminder>"},
55
+ {"type": "image"},
56
+ ]
57
+ },
58
+ },
59
+ "<system-reminder>r</system-reminder>",
60
+ ),
61
+ ({"type": "user", "isSidechain": True, "message": {"content": "Side task"}}, None),
62
+ ({"type": "user", "isCompactSummary": True, "message": {"content": "Summary"}}, None),
63
+ ({"type": "user", "message": {"content": " "}}, None),
64
+ ({"type": "user", "message": {"content": " Stop hook feedback: hold"}}, None),
65
+ ],
66
+ )
67
+ def test_should_read_prompt_text_from_each_user_record_shape(
68
+ record: dict[str, object], expected_text: str | None
69
+ ) -> None:
70
+ assert claude_prompt_text(record) == expected_text
71
+
72
+
73
+ def test_should_read_codex_user_text_from_a_string_or_its_text_blocks() -> None:
74
+ assert (
75
+ codex_prompt_text(
76
+ codex_record({"type": "message", "role": "user", "content": "Remove the flag"})
77
+ )
78
+ == "Remove the flag"
79
+ )
80
+ block_message = {
81
+ "type": "message",
82
+ "role": "user",
83
+ "content": ["skip", {"type": "input_text", "text": "Ship"}, {"text": "it"}],
84
+ }
85
+ assert codex_prompt_text(codex_record(block_message)) == "Ship it"
86
+ assert (
87
+ codex_prompt_text(codex_record({"type": "function_call", "role": "user", "content": "x"}))
88
+ is None
89
+ )
90
+ assert (
91
+ codex_prompt_text(
92
+ {"type": "event_msg", "payload": {"type": "message", "role": "user", "content": "x"}}
93
+ )
94
+ is None
95
+ )
96
+
97
+
98
+ def test_should_count_each_codex_call_type_as_work_except_the_plan_and_question_calls() -> None:
99
+ assert (
100
+ is_codex_work_call(codex_record({"type": "custom_tool_call", "name": "apply_patch"}))
101
+ is True
102
+ )
103
+ assert is_codex_work_call(codex_record({"type": "message", "name": "shell"})) is False
104
+ assert (
105
+ is_codex_work_call(codex_record({"type": "function_call", "name": "update_plan"})) is False
106
+ )
107
+ assert is_codex_work_call(codex_record("not a payload")) is False
108
+
109
+
110
+ def test_should_recognize_a_codex_question_card_call() -> None:
111
+ assert (
112
+ is_codex_question_call(
113
+ codex_record({"type": "custom_tool_call", "name": "request_user_input"})
114
+ )
115
+ is True
116
+ )
117
+ assert (
118
+ is_codex_question_call(
119
+ codex_record({"type": "function_call", "name": "request_user_input_async"})
120
+ )
121
+ is True
122
+ )
123
+ assert is_codex_question_call(codex_record({"type": "function_call", "name": "shell"})) is False
124
+ assert (
125
+ is_codex_question_call(codex_record({"type": "message", "name": "request_user_input"}))
126
+ is False
127
+ )
128
+ assert (
129
+ is_codex_question_call(
130
+ {"type": "user", "payload": {"type": "function_call", "name": "request_user_input"}}
131
+ )
132
+ is False
133
+ )
134
+
135
+
136
+ def test_should_treat_lookup_tools_as_non_work_and_other_names_as_work() -> None:
137
+ assert is_work_tool_name("TaskList") is False
138
+ assert is_work_tool_name("TaskGet") is False
139
+ assert is_work_tool_name("ToolSearch") is False
140
+ assert is_work_tool_name("AskUserQuestion") is False
141
+ assert is_work_tool_name("Edit") is True
142
+ assert is_work_tool_name(7) is True
143
+
144
+
145
+ def test_should_find_the_assistant_role_on_the_message_when_the_record_says_user() -> None:
146
+ assert is_assistant_record({"role": "user", "message": {"role": "assistant"}}) is True
147
+ assert is_assistant_record({"message": "assistant"}) is False
148
+ assert is_assistant_record({"type": "response_item", "role": "tool"}) is False
149
+
150
+
151
+ @pytest.mark.parametrize(
152
+ ("tool_name", "expected_is_read"),
153
+ [
154
+ ("PowerShell", True),
155
+ ("mcp__x__v2Read", True),
156
+ ("mcp__get_server__publish", False),
157
+ ("ToolSearch", False),
158
+ ("mcp__drive__list_and_delete", False),
159
+ ],
160
+ )
161
+ def test_should_judge_a_read_tool_by_the_words_after_the_server_name(tool_name: str, expected_is_read: bool) -> None:
162
+ assert is_read_tool_name(tool_name) is expected_is_read
163
+
164
+
165
+ def test_should_keep_every_sent_path_in_order_and_ignore_a_call_without_files() -> None:
166
+ assert send_call_file_paths("SendUserFile", {"files": ["b.md", "a.md", "b.md"]}) == ["b.md", "a.md", "b.md"]
167
+ assert send_call_file_paths("SendUserFile", {"message": "here"}) == []
168
+
169
+
170
+ def test_should_count_a_codex_call_as_a_read_by_its_type_and_tool_name() -> None:
171
+ assert is_codex_read_call(codex_record({"type": "custom_tool_call", "name": "view_image"})) is True
172
+ assert is_codex_read_call(codex_record({"type": "function_call", "name": "apply_patch"})) is False
173
+ assert is_codex_read_call(codex_record({"type": "message", "name": "shell"})) is False
174
+ assert is_codex_read_call({"type": "event_msg", "payload": {"type": "local_shell_call"}}) is False
@@ -11,6 +11,7 @@ import pytest
11
11
 
12
12
  import turn_review_gate
13
13
  import turn_review_snapshot
14
+ import turn_review_state
14
15
  from pii_prevention_blocker_parts import repository_exemption
15
16
 
16
17
  GATE_PATH = Path(turn_review_gate.__file__)
@@ -1020,6 +1021,24 @@ def test_should_pass_the_stop_quietly_when_the_lock_stays_busy_after_the_review(
1020
1021
  assert "Stop left the review state alone" in turn_review_log(isolated_home)
1021
1022
 
1022
1023
 
1024
+ def test_should_keep_the_review_state_in_the_file_the_state_module_names(
1025
+ project: Path, gate_environment: dict[str, str], monkeypatch: pytest.MonkeyPatch
1026
+ ) -> None:
1027
+ monkeypatch.setattr(turn_review_state, "STATE_FILE_TEMPLATE", "moved-review-{session_id}.json")
1028
+ state_directory = Path(gate_environment["TMPDIR"])
1029
+ _run_gate_in_process(monkeypatch, gate_environment, "UserPromptSubmit")
1030
+ drop_retry(project)
1031
+
1032
+ stop_exit_code = _run_gate_in_process(monkeypatch, gate_environment, "Stop")
1033
+
1034
+ assert list(state_directory.glob("turn-review-*.json")) == []
1035
+ [moved_state_file] = state_directory.glob("moved-review-*.json")
1036
+ moved_state = json.loads(moved_state_file.read_text())
1037
+ assert stop_exit_code == 2
1038
+ assert moved_state["blocks_in_a_row"] == 1
1039
+ assert moved_state["findings"]["TR-1"]["status"] == "open"
1040
+
1041
+
1023
1042
  def test_should_review_both_turns_when_two_prompts_in_a_row_beat_their_stops(
1024
1043
  project: Path, gate_environment: dict[str, str]
1025
1044
  ) -> None:
@@ -25,7 +25,7 @@ Preconditions:
25
25
 
26
26
  - Run each command from the repository root with Python and pytest available. The tests and direct cache probe use disposable directories.
27
27
 
28
- - **Nested checkout hooks.** Input is a session started above a child checkout with its own hooks. Run `python -m pytest packages/claude-dev-env/hooks/lifecycle/test_nested_project_hooks.py -q`. The adjacent test observes the child hook running in its checkout.
28
+ - **Nested checkout hooks.** Input is a session started above a child checkout with its own hooks. Run `python -m pytest packages/claude-dev-env/hooks/lifecycle/test_nested_project_hooks.py packages/claude-dev-env/hooks/lifecycle/test_nested_project_hooks_discovery.py -q`. The adjacent test observes the child hook running in its checkout. The discovery test observes which checkouts and command hooks `lifecycle/nested_project_hooks_discovery.py` selects.
29
29
  - **Worktree fetch.** Input is an `EnterWorktree` call without a path. Run `python -m pytest packages/claude-dev-env/hooks/lifecycle/test_enter_worktree_origin_prefetch.py -q`. The adjacent test observes a fetch attempt and a zero exit even when a remote is absent.
30
30
  - **Session-end cache.** Input is an aged `claude-ctx-` cache file in a disposable directory. Run `python -c 'import os, runpy, tempfile; from pathlib import Path; directory=tempfile.TemporaryDirectory(); root=Path(directory.name); entry=root/"claude-ctx-old.json"; entry.write_text("{}"); os.utime(entry,(0,0)); module=runpy.run_path("packages/claude-dev-env/hooks/lifecycle/session_end_cleanup.py"); module["purge_old_entries"](str(root),7); assert not entry.exists(); directory.cleanup(); print("stale cache entry removed")'`. The command prints `stale cache entry removed`. This script has no adjacent behavior test.
31
31
  - **Plugin data cleanup.** Input is an empty plugin data directory. Run `python -m pytest packages/claude-dev-env/hooks/session/test_plugin_data_dir_cleanup.py -q`. The adjacent test observes its removal and preserves directories with files.
@@ -34,7 +34,6 @@ from __future__ import annotations
34
34
 
35
35
  import json
36
36
  import os
37
- import re
38
37
  import shutil
39
38
  import subprocess
40
39
  import sys
@@ -49,19 +48,11 @@ if _hooks_dir not in sys.path:
49
48
  from hooks_constants.nested_project_hooks_constants import (
50
49
  ADDITIONAL_CONTEXT_KEY,
51
50
  ALL_FORWARDED_PERMISSION_DECISIONS,
52
- ALL_MATCH_EVERYTHING_MATCHERS,
53
51
  BLOCKING_EXIT_CODE,
54
- CHECKOUT_MARKER_NAME,
55
- COMMAND_HOOK_TYPE,
56
- COMMAND_KEY,
57
52
  CONTEXT_SECTION_SEPARATOR,
58
- DEFAULT_HOOK_TIMEOUT_SECONDS,
59
53
  DENY_PERMISSION_DECISION,
60
54
  HOOK_EVENT_NAME_KEY,
61
- HOOK_TYPE_KEY,
62
- HOOKS_KEY,
63
55
  ALL_MATCH_TARGET_KEYS_BY_EVENT,
64
- MATCHER_KEY,
65
56
  PRE_TOOL_USE_EVENT,
66
57
  PROJECT_DIRECTORY_ENVIRONMENT_VARIABLE,
67
58
  ALL_RUN_BUDGET_SECONDS_BY_EVENT,
@@ -69,12 +60,8 @@ from hooks_constants.nested_project_hooks_constants import (
69
60
  NOT_STARTED_OUTCOME,
70
61
  STOPPED_OUTCOME_TEMPLATE,
71
62
  SESSION_START_EVENT,
72
- SETTINGS_DIRECTORY_NAME,
73
- SETTINGS_ENCODING,
74
- SETTINGS_FILE_NAME,
75
63
  SHELL_COMMAND_FLAG,
76
64
  ALL_SHELL_PROGRAM_NAMES,
77
- TIMEOUT_KEY,
78
65
  )
79
66
  from hooks_constants.hook_specific_output_keys import (
80
67
  HOOK_EVENT_NAME_KEY as HOOK_EVENT_NAME_OUTPUT_KEY,
@@ -84,15 +71,7 @@ from hooks_constants.hook_specific_output_keys import (
84
71
  )
85
72
  from hooks_constants.hook_time_budget import call_timeout, time_budget
86
73
  from hooks_constants.subprocess_window import hidden_window_creation_flags
87
-
88
-
89
- @dataclass(frozen=True)
90
- class NestedHook:
91
- """One command hook a nested checkout declares for the current event."""
92
-
93
- project_directory: Path
94
- command: str
95
- timeout_seconds: float
74
+ from lifecycle.nested_project_hooks_discovery import NestedHook, collect_nested_hooks
96
75
 
97
76
 
98
77
  @dataclass(frozen=True)
@@ -104,132 +83,6 @@ class HookVerdict:
104
83
  stderr_text: str
105
84
 
106
85
 
107
- def _settings_path(directory: Path) -> Path:
108
- return directory / SETTINGS_DIRECTORY_NAME / SETTINGS_FILE_NAME
109
-
110
-
111
- def find_nested_projects(session_directory: Path) -> list[Path]:
112
- """Return the child checkouts whose project hooks Claude Code skipped.
113
-
114
- Args:
115
- session_directory: The directory the session started in.
116
-
117
- Returns:
118
- Each immediate child holding both a ``.git`` entry and a
119
- ``.claude/settings.json`` file, sorted by name. Empty when the
120
- session directory is a checkout or has settings of its own.
121
- """
122
- if (session_directory / CHECKOUT_MARKER_NAME).exists():
123
- return []
124
- if _settings_path(session_directory).is_file():
125
- return []
126
- try:
127
- all_children = sorted(session_directory.iterdir())
128
- except OSError:
129
- return []
130
- return [
131
- each_child
132
- for each_child in all_children
133
- if each_child.is_dir()
134
- and (each_child / CHECKOUT_MARKER_NAME).exists()
135
- and _settings_path(each_child).is_file()
136
- ]
137
-
138
-
139
- def _read_hook_groups(project_directory: Path, event_name: str) -> list[object]:
140
- try:
141
- settings_text = _settings_path(project_directory).read_text(encoding=SETTINGS_ENCODING)
142
- settings = json.loads(settings_text)
143
- except (OSError, json.JSONDecodeError):
144
- return []
145
- if not isinstance(settings, dict):
146
- return []
147
- hooks_by_event = settings.get(HOOKS_KEY)
148
- if not isinstance(hooks_by_event, dict):
149
- return []
150
- all_groups = hooks_by_event.get(event_name)
151
- if not isinstance(all_groups, list):
152
- return []
153
- return all_groups
154
-
155
-
156
- def matcher_selects(matcher: object, match_target: str) -> bool:
157
- """Report whether a settings matcher selects this event's target.
158
-
159
- Args:
160
- matcher: The ``matcher`` value of one hook group, possibly absent.
161
- match_target: The tool name for PreToolUse, the start source for
162
- SessionStart.
163
-
164
- Returns:
165
- True for an absent, empty, or ``*`` matcher, and for a matcher whose
166
- pattern matches the whole target. An invalid pattern matches only
167
- its exact text.
168
- """
169
- if matcher is None:
170
- return True
171
- if not isinstance(matcher, str):
172
- return False
173
- if matcher in ALL_MATCH_EVERYTHING_MATCHERS:
174
- return True
175
- try:
176
- return re.fullmatch(matcher, match_target) is not None
177
- except re.error:
178
- return matcher == match_target
179
-
180
-
181
- def _command_hook(project_directory: Path, hook_fields: object) -> NestedHook | None:
182
- if not isinstance(hook_fields, dict):
183
- return None
184
- if hook_fields.get(HOOK_TYPE_KEY) != COMMAND_HOOK_TYPE:
185
- return None
186
- command = hook_fields.get(COMMAND_KEY)
187
- if not isinstance(command, str) or not command.strip():
188
- return None
189
- timeout_value = hook_fields.get(TIMEOUT_KEY)
190
- timeout_seconds = DEFAULT_HOOK_TIMEOUT_SECONDS
191
- if isinstance(timeout_value, (int, float)) and timeout_value > 0:
192
- timeout_seconds = float(timeout_value)
193
- return NestedHook(project_directory, command, timeout_seconds)
194
-
195
-
196
- def _selected_hook_entries(
197
- project_directory: Path, event_name: str, match_target: str
198
- ) -> list[object]:
199
- all_hook_entries: list[object] = []
200
- for each_group in _read_hook_groups(project_directory, event_name):
201
- if not isinstance(each_group, dict):
202
- continue
203
- if not matcher_selects(each_group.get(MATCHER_KEY), match_target):
204
- continue
205
- all_group_hooks = each_group.get(HOOKS_KEY)
206
- if isinstance(all_group_hooks, list):
207
- all_hook_entries.extend(all_group_hooks)
208
- return all_hook_entries
209
-
210
-
211
- def collect_nested_hooks(
212
- session_directory: Path, event_name: str, match_target: str
213
- ) -> list[NestedHook]:
214
- """Return every nested command hook that this event selects, in order.
215
-
216
- Args:
217
- session_directory: The directory the session started in.
218
- event_name: The hook event being handled.
219
- match_target: The value the event's matchers compare against.
220
-
221
- Returns:
222
- The selected command hooks, checkout by checkout in name order and
223
- in declaration order inside each checkout.
224
- """
225
- all_candidates = (
226
- _command_hook(each_project, each_entry)
227
- for each_project in find_nested_projects(session_directory)
228
- for each_entry in _selected_hook_entries(each_project, event_name, match_target)
229
- )
230
- return [each_candidate for each_candidate in all_candidates if each_candidate is not None]
231
-
232
-
233
86
  def _shell_program() -> str | None:
234
87
  for each_name in ALL_SHELL_PROGRAM_NAMES:
235
88
  found_path = shutil.which(each_name)
@@ -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"