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,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
@@ -0,0 +1,129 @@
1
+ import io
2
+ import json
3
+ from pathlib import Path
4
+
5
+ import pytest
6
+
7
+ import task_subject_outcome_gate
8
+
9
+
10
+ def run_gate(
11
+ monkeypatch: pytest.MonkeyPatch,
12
+ capsys: pytest.CaptureFixture[str],
13
+ tool_name: str,
14
+ tool_input: object,
15
+ ) -> tuple[int, str]:
16
+ hook_input = {"hook_event_name": "PreToolUse", "tool_name": tool_name, "tool_input": tool_input}
17
+ monkeypatch.setattr(
18
+ "sys.stdin", io.TextIOWrapper(io.BytesIO(json.dumps(hook_input).encode("utf-8")))
19
+ )
20
+ exit_code = task_subject_outcome_gate.main()
21
+ return exit_code, capsys.readouterr().err
22
+
23
+
24
+ @pytest.fixture(autouse=True)
25
+ def isolated_home(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
26
+ monkeypatch.setenv("HOME", str(tmp_path))
27
+ monkeypatch.setenv("USERPROFILE", str(tmp_path))
28
+
29
+
30
+ @pytest.mark.parametrize("tool_name", ["TaskCreate", "TaskUpdate"])
31
+ @pytest.mark.parametrize(
32
+ "subject",
33
+ [
34
+ "Task names in the list read as outcomes",
35
+ "PR 2347 merged with checks green",
36
+ "PR 12: checks green",
37
+ "Issue 7: closed with the fix linked",
38
+ "Merge PR #2347 once review is clean",
39
+ "Feature flag removed from the settings page",
40
+ "Step notes turn off when the user asks",
41
+ "Phase 2.0 released to all users",
42
+ ],
43
+ )
44
+ def test_should_allow_a_plain_outcome_subject(
45
+ monkeypatch: pytest.MonkeyPatch,
46
+ capsys: pytest.CaptureFixture[str],
47
+ tool_name: str,
48
+ subject: str,
49
+ ) -> None:
50
+ assert run_gate(monkeypatch, capsys, tool_name, {"subject": subject}) == (0, "")
51
+
52
+
53
+ @pytest.mark.parametrize(
54
+ "subject",
55
+ [
56
+ "Feature 1: Investigate the affected subsystem",
57
+ "Feature 3: Write the throughput checkpoint",
58
+ "Feature 6-8: Rebase into small ordered commits, run Opening a PR",
59
+ "Step 3: run the tests",
60
+ "phase 2) migrate callers",
61
+ "Bug fix 4. Reproduce first",
62
+ "Bug fix 5: Reproduce first",
63
+ ],
64
+ )
65
+ def test_should_deny_a_subject_that_starts_with_a_procedure_step_label(
66
+ monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], subject: str
67
+ ) -> None:
68
+ exit_code, stderr_text = run_gate(monkeypatch, capsys, "TaskCreate", {"subject": subject})
69
+ assert exit_code == 2
70
+ assert "procedure step label" in stderr_text
71
+ assert "by its outcome in the user's words" in stderr_text
72
+ assert "private checklist" in stderr_text
73
+
74
+
75
+ def test_should_deny_a_subject_with_a_code_formatted_name(
76
+ monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
77
+ ) -> None:
78
+ exit_code, stderr_text = run_gate(
79
+ monkeypatch, capsys, "TaskUpdate", {"taskId": "3", "subject": "Run `how` over the hooks"}
80
+ )
81
+ assert exit_code == 2
82
+ assert "code-formatted name" in stderr_text
83
+
84
+
85
+ def test_should_deny_a_todo_write_item_that_carries_a_marker(
86
+ monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
87
+ ) -> None:
88
+ all_todos = [
89
+ {"content": "Hook refuses procedure step names", "status": "completed"},
90
+ {"content": "Step 2: push the branch", "status": "pending"},
91
+ ]
92
+ exit_code, stderr_text = run_gate(monkeypatch, capsys, "TodoWrite", {"todos": all_todos})
93
+ assert exit_code == 2
94
+ assert "Step 2: push the branch" in stderr_text
95
+
96
+
97
+ def test_should_allow_todo_write_items_that_read_as_outcomes(
98
+ monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
99
+ ) -> None:
100
+ all_todos = [{"content": "Hook refuses procedure step names", "status": "in_progress"}]
101
+ assert run_gate(monkeypatch, capsys, "TodoWrite", {"todos": all_todos}) == (0, "")
102
+
103
+
104
+ @pytest.mark.parametrize(
105
+ ("tool_name", "tool_input"),
106
+ [
107
+ ("TaskUpdate", {"taskId": "3", "status": "completed"}),
108
+ ("TaskCreate", "Step 1: not a dictionary"),
109
+ ("Bash", {"subject": "Step 1: run"}),
110
+ ("TodoWrite", {"todos": "Step 1: run"}),
111
+ ],
112
+ )
113
+ def test_should_leave_other_tools_and_schemas_alone(
114
+ monkeypatch: pytest.MonkeyPatch,
115
+ capsys: pytest.CaptureFixture[str],
116
+ tool_name: str,
117
+ tool_input: object,
118
+ ) -> None:
119
+ assert run_gate(monkeypatch, capsys, tool_name, tool_input) == (0, "")
120
+
121
+
122
+ def test_task_subject_violation_should_return_none_for_an_outcome() -> None:
123
+ assert task_subject_outcome_gate.task_subject_violation("Hook refuses step names") is None
124
+
125
+
126
+ def test_task_subject_violation_should_name_the_backtick_marker() -> None:
127
+ violation = task_subject_outcome_gate.task_subject_violation("Fix `gate.py`")
128
+ assert violation is not None
129
+ assert "code-formatted name" in violation
@@ -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:
@@ -12,6 +12,7 @@ This family stops a chat reply, edited message, or tool call when its payload br
12
12
  - `blocking/edit_marker_gate.py` rejects strikethrough and edit-note markers in replacement chat text or cards.
13
13
  - `blocking/issue_close_handoff_gate.py` denies an issue comment or issue write that closes the issue and routes a found defect to another issue or epic.
14
14
  - `blocking/session_title_format_gate.py` denies a session title that breaks the `<emoji> <name>` shape or has a name longer than 25 characters.
15
+ - `blocking/task_subject_outcome_gate.py` denies a TaskCreate or TaskUpdate subject, or a TodoWrite item, that starts with a procedure step label (step, phase, stage, part, feature, bug fix, refactoring, or playbook, then a one- or two-digit number or range, then `:`, `)`, or a `.` that no digit follows) or holds a backtick. The reason says to name the item by its outcome in the user's words and keep procedure steps in a private checklist file. A status-only TaskUpdate passes.
15
16
  - `blocking/task_subject_length_gate.py` denies a `TaskCreate` or `TaskUpdate` whose `subject` is over 80 characters, and a `TodoWrite` whose list holds an item `content` over 80 characters, naming the first such item. The reason gives the length and the limit and says to start with who acts (Me, You, or Handed off), say what is left, and put detail in the description.
16
17
  - `blocking/step_note_gate.py` requires a status line before a tool call while its opt-in flag is on.
17
18
  - `blocking/wakeup_cap_gate.py` keeps a self-wakeup inside the 1-hour prompt cache. A wake over the step-down (57 minutes for `send_later` and Routines, 3480 seconds for `ScheduleWakeup`) and at most 60 minutes away runs with its delay rewritten to the step-down. A wake over 60 minutes away, or a cron with more than 57 minutes between wakes, is denied with a reason that says to stack wakes under the cap. A Routine that starts a fresh session on each firing passes.
@@ -36,6 +37,7 @@ This family stops a chat reply, edited message, or tool call when its payload br
36
37
  - `blocking/edit_marker_gate.py` runs on `PreToolUse`, matcher `mcp__.*__update_message`, timeout `10` seconds in `hooks.json`.
37
38
  - `blocking/issue_close_handoff_gate.py` runs on `PreToolUse`, matcher `mcp__.*__(add_issue_comment|issue_write|update_issue_comment)`, timeout `10` seconds in `hooks.json`.
38
39
  - `blocking/session_title_format_gate.py` runs on `PreToolUse`, matcher `mcp__.*__set_session_title`, timeout `10` seconds in `hooks.json`.
40
+ - `blocking/task_subject_outcome_gate.py` runs on `PreToolUse`, matcher `TaskCreate|TaskUpdate|TodoWrite`, timeout `10` seconds in `hooks.json`, after the length gate in the same group. Like the length gate, it runs in Claude Code only.
39
41
  - `blocking/task_subject_length_gate.py` runs on `PreToolUse`, matcher `TaskCreate|TaskUpdate|TodoWrite`, timeout `10` seconds in `hooks.json`. It runs in Claude Code only: the installer gives Codex only the PreToolUse group whose matcher is `multi_agent_v1__spawn_agent`, and gives Cursor only the hooks `bin/install-constants.mjs` names.
40
42
  - `blocking/step_note_gate.py` runs on `PreToolUse`, matcher `*`, timeout `15` seconds in `hooks.json`.
41
43
  - `blocking/question_brief_gate.py` runs on `PreToolUse`, matcher `AskUserQuestion`, timeout `10` seconds in `hooks.json`. Its transcript poll stops at 3 seconds.
@@ -65,6 +67,7 @@ Preconditions:
65
67
  - **Edit marker.** Input is an update message with strikethrough or an edit note. Run `python -m pytest packages/claude-dev-env/hooks/blocking/test_edit_marker_gate.py -q`. The adjacent test observes a denial; clean replacement text passes.
66
68
  - **Handoff close.** Input is an issue comment that says the issue is closed and that the found defect belongs to another issue. Run `python -m pytest packages/claude-dev-env/hooks/blocking/test_issue_close_handoff_gate.py -q`. The adjacent test observes a denial; a close with a plain cross-reference and a routing comment on an open issue both pass.
67
69
  - **Session title.** Input is a set session title call with no leading emoji or a name over 25 characters. Run `python -m pytest packages/claude-dev-env/hooks/blocking/test_session_title_format_gate.py -q`. The adjacent test observes a denial that names the broken rule; a well-formed title passes.
70
+ - **Procedure step names.** Input is a TaskCreate subject `Feature 3: Write the throughput checkpoint`, a TaskUpdate subject with a backtick, and a TodoWrite item `Step 2: push the branch`. Run `python -m pytest packages/claude-dev-env/hooks/blocking/test_task_subject_outcome_gate.py -q`. The adjacent test observes a denial for each; `PR 12: checks green`, `PR 2347 merged with checks green`, and a status-only TaskUpdate pass.
68
71
  - **Task subject.** Input is a `TaskCreate` call whose subject is a 229-character status sentence, then three short subjects that start with Me, You, and Handed off. Run `python -m pytest packages/claude-dev-env/hooks/blocking/test_task_subject_length_gate.py -q`. The adjacent test observes a denial that gives the status sentence's length and the limit, the short ones passing, 80 characters passing and 81 denied, a status-only `TaskUpdate` passing, and a `TodoWrite` denial that names its long item.
69
72
  - **First title.** Input is a `UserPromptSubmit` payload with a work prompt, after a transcript that lists the title tool and holds no title call. Run `python -m pytest packages/claude-dev-env/hooks/session/test_tracking_nudge.py -q`. The adjacent test observes one note that names the tool and `⏳ <name>`, exit 0 and empty stderr. A second ask and an ask after a compaction get no such note. A session without the title tool, and a title that shows the hourglass, get no title note.
70
73
  - **Step note.** Input is a tool call after a transcript message without a status line while the flag is on. Run `python -m pytest packages/claude-dev-env/hooks/blocking/test_step_note_gate.py -q`. The adjacent test observes a block until a status line appears.
@@ -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.
package/hooks/hooks.json CHANGED
@@ -236,6 +236,11 @@
236
236
  "type": "command",
237
237
  "command": "python3 ${CLAUDE_PLUGIN_ROOT}/hooks/blocking/task_subject_length_gate.py",
238
238
  "timeout": 10
239
+ },
240
+ {
241
+ "type": "command",
242
+ "command": "python3 ${CLAUDE_PLUGIN_ROOT}/hooks/blocking/task_subject_outcome_gate.py",
243
+ "timeout": 10
239
244
  }
240
245
  ]
241
246
  },
@@ -0,0 +1,37 @@
1
+ """Constants for task_subject_outcome_gate.py."""
2
+
3
+ import re
4
+
5
+ TOOL_NAME_KEY = "tool_name"
6
+ TOOL_INPUT_KEY = "tool_input"
7
+ GATE_EVENT_NAME = "PreToolUse"
8
+ ALLOW_EXIT_CODE = 0
9
+ BLOCK_EXIT_CODE = 2
10
+
11
+ TASK_CREATE_TOOL_NAME = "TaskCreate"
12
+ TASK_UPDATE_TOOL_NAME = "TaskUpdate"
13
+ TODO_WRITE_TOOL_NAME = "TodoWrite"
14
+ ALL_SUBJECT_TOOL_NAMES = frozenset({TASK_CREATE_TOOL_NAME, TASK_UPDATE_TOOL_NAME})
15
+ TASK_SUBJECT_KEY = "subject"
16
+ TODOS_KEY = "todos"
17
+ TODO_CONTENT_KEY = "content"
18
+
19
+ PROCEDURE_STEP_PREFIX_PATTERN = re.compile(
20
+ r"^\s*(?:step|phase|stage|part|feature|bug\s+fix|refactoring|playbook)"
21
+ r"\s*\d{1,2}(?:\s*[-–]\s*\d{1,2})?\s*(?:[:)]|\.(?!\d))",
22
+ re.IGNORECASE,
23
+ )
24
+ CODE_SPAN_MARKER = "`"
25
+
26
+ PROCEDURE_STEP_MESSAGE = (
27
+ "The task subject '{subject}' starts with a procedure step label such as 'Step 3:' or"
28
+ " 'Feature 6-8:'."
29
+ )
30
+ CODE_SPAN_MESSAGE = "The task subject '{subject}' holds a code-formatted name in backticks."
31
+ RETRY_INSTRUCTION = (
32
+ " The user follows the task list to see where the work stands and what is left."
33
+ " Name the item by its outcome in the user's words, such as"
34
+ " 'Task names in the list read as outcomes'."
35
+ " Keep playbook steps, skill names, and other procedure steps in a private checklist"
36
+ " file such as todo.md in the work folder, and call the tool again."
37
+ )
@@ -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)