claude-dev-env 8.117.3 → 8.117.5
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.
- package/_shared/pr-loop/scripts/pyproject.toml +1 -1
- package/_shared/process-tree/scripts/pyproject.toml +1 -1
- package/bin/cde.mjs +4 -3
- package/bin/cde.test.mjs +87 -1
- package/bin/codex-compat.mjs +4 -3
- package/bin/codex-compat.test.mjs +91 -1
- package/bin/install-plan.mjs +2 -1
- package/bin/install.mjs +24 -7
- package/bin/install.plan.test.mjs +15 -0
- package/bin/install.test.mjs +61 -0
- package/bin/python-probe.mjs +42 -0
- package/bin/python-probe.test.mjs +19 -2
- package/docs/references/advisor-tool.md +2 -0
- package/docs/rule-guides/features-start-with-an-eval.md +3 -3
- package/docs/rule-guides/proof-before-pull-request.md +2 -2
- package/hooks/blocking/bash_pre_tool_use_dispatcher.py +11 -4
- package/hooks/blocking/build_eval_before_eval_write_gate.py +10 -4
- package/hooks/blocking/followup_pr_dedupe.py +381 -64
- package/hooks/blocking/gate_child_process.py +187 -0
- package/hooks/blocking/gate_run_reads.py +116 -35
- package/hooks/blocking/merge_review_gate.py +93 -10
- package/hooks/blocking/merge_review_gate_parts/create_folders.py +346 -0
- package/hooks/blocking/merge_review_gate_parts/create_options.py +86 -0
- package/hooks/blocking/merge_review_gate_parts/folder_state.py +107 -0
- package/hooks/blocking/merge_review_gate_parts/open_request.py +199 -64
- package/hooks/blocking/merge_review_gate_parts/quoted_lines.py +283 -0
- package/hooks/blocking/merge_review_gate_parts/wrapped_creates.py +126 -0
- package/hooks/blocking/pr_lifecycle_skill_gate.py +61 -18
- package/hooks/blocking/pre_tool_use_dispatcher.py +25 -3
- package/hooks/blocking/pull_request_proof.py +5 -51
- package/hooks/blocking/pull_request_proof_edit_gate.py +19 -5
- package/hooks/blocking/test_bash_pre_tool_use_dispatcher.py +54 -0
- package/hooks/blocking/test_build_eval_before_eval_write_gate.py +64 -0
- package/hooks/blocking/test_followup_pr_dedupe.py +464 -1
- package/hooks/blocking/test_gate_child_process.py +64 -0
- package/hooks/blocking/test_gate_run_reads.py +364 -4
- package/hooks/blocking/test_merge_review_gate.py +832 -39
- package/hooks/blocking/test_pr_lifecycle_skill_gate.py +130 -4
- package/hooks/blocking/test_pre_tool_use_dispatcher.py +64 -0
- package/hooks/blocking/test_pull_request_proof.py +16 -0
- package/hooks/blocking/test_pull_request_proof_edit_gate.py +60 -0
- package/hooks/blocking/tests/test_create_folders.py +290 -0
- package/hooks/blocking/tests/test_create_options.py +34 -0
- package/hooks/blocking/tests/test_folder_state.py +40 -0
- package/hooks/blocking/tests/test_open_request.py +350 -44
- package/hooks/blocking/tests/test_quoted_lines.py +86 -0
- package/hooks/blocking/tests/test_wrapped_creates.py +42 -0
- package/hooks/features/bash-dispatchers.md +1 -1
- package/hooks/features/conduct-gates.md +7 -7
- package/hooks/features/session-context.md +3 -3
- package/hooks/features/write-edit-blocking.md +3 -3
- package/hooks/hooks_constants/advisor_rules_prompt_constants.py +14 -6
- package/hooks/hooks_constants/build_eval_before_eval_write_gate_constants.py +5 -0
- package/hooks/hooks_constants/followup_pr_dedupe_constants.py +34 -1
- package/hooks/hooks_constants/gate_fault.py +52 -0
- package/hooks/hooks_constants/gate_fault_constants.py +13 -0
- package/hooks/hooks_constants/gate_run_reads_constants.py +9 -1
- package/hooks/hooks_constants/merge_review_gate_constants.py +94 -1
- package/hooks/hooks_constants/piped_pytest_blocker_constants.py +2 -0
- package/hooks/hooks_constants/pr_lifecycle_skill_gate_constants.py +6 -1
- package/hooks/hooks_constants/pre_tool_use_stdin.py +23 -3
- package/hooks/hooks_constants/shell_command_pipeline.py +68 -8
- package/hooks/hooks_constants/shell_command_segments.py +2 -2
- package/hooks/hooks_constants/shell_command_wrappers.py +3 -2
- package/hooks/hooks_constants/test_followup_pr_dedupe_constants.py +7 -0
- package/hooks/hooks_constants/test_gate_fault.py +41 -0
- package/hooks/hooks_constants/test_piped_pytest_blocker_constants.py +5 -0
- package/hooks/hooks_constants/test_pr_lifecycle_skill_gate_constants.py +10 -0
- package/hooks/hooks_constants/test_pre_tool_use_stdin.py +97 -0
- package/hooks/hooks_constants/test_shell_command_pipeline.py +55 -0
- package/hooks/hooks_constants/test_shell_command_segments.py +15 -0
- package/hooks/hooks_constants/test_shell_command_wrappers.py +6 -0
- package/hooks/hooks_constants/transcript_skill_scan_constants.py +6 -0
- package/hooks/pyproject.toml +2 -3
- package/hooks/session/advisor_rules_prompt.py +53 -9
- package/hooks/session/test_advisor_rules_prompt.py +70 -4
- package/hooks/test_python_floor.py +197 -0
- package/hooks/test_transcript_skill_scan.py +324 -0
- package/hooks/transcript_skill_scan.py +233 -2
- package/package.json +1 -1
|
@@ -16,7 +16,7 @@ program verdict compose on top of these segments.
|
|
|
16
16
|
from __future__ import annotations
|
|
17
17
|
|
|
18
18
|
import shlex
|
|
19
|
-
from typing import NamedTuple
|
|
19
|
+
from typing import NamedTuple, cast
|
|
20
20
|
|
|
21
21
|
from hooks_constants.piped_pytest_blocker_constants import (
|
|
22
22
|
ALL_OPERATOR_TOKENS_LONGEST_FIRST,
|
|
@@ -39,6 +39,7 @@ from hooks_constants.piped_pytest_blocker_constants import (
|
|
|
39
39
|
HEREDOC_TERMINATOR_GROUP,
|
|
40
40
|
LINE_CONTINUATION_JOIN,
|
|
41
41
|
LINE_CONTINUATION_PATTERN,
|
|
42
|
+
LINEAR_TIME_LEXER_MINIMUM_LENGTH,
|
|
42
43
|
NO_FOLLOWING_OPERATOR,
|
|
43
44
|
PAREN_GROUP_LINE_JOIN,
|
|
44
45
|
PUNCTUATION_ONLY_TOKEN_PATTERN,
|
|
@@ -55,6 +56,7 @@ __all__ = [
|
|
|
55
56
|
"command_line_without_comment",
|
|
56
57
|
"join_line_continuations",
|
|
57
58
|
"live_command_lines",
|
|
59
|
+
"operator_aware_tokens",
|
|
58
60
|
"paren_group_joined_lines",
|
|
59
61
|
"pending_heredoc_opened_by",
|
|
60
62
|
"pipeline_segments_for_command",
|
|
@@ -63,6 +65,47 @@ __all__ = [
|
|
|
63
65
|
]
|
|
64
66
|
|
|
65
67
|
|
|
68
|
+
class _TokenPieces:
|
|
69
|
+
"""The characters of the token ``shlex`` is reading, kept as a list so each addition costs one step."""
|
|
70
|
+
|
|
71
|
+
def __init__(self, first_piece: str) -> None:
|
|
72
|
+
self.all_pieces = [first_piece]
|
|
73
|
+
self.length = len(first_piece)
|
|
74
|
+
|
|
75
|
+
def __iadd__(self, piece: str) -> _TokenPieces:
|
|
76
|
+
self.all_pieces.append(piece)
|
|
77
|
+
self.length += len(piece)
|
|
78
|
+
return self
|
|
79
|
+
|
|
80
|
+
def __bool__(self) -> bool:
|
|
81
|
+
return self.length > 0
|
|
82
|
+
|
|
83
|
+
def __eq__(self, other: object) -> bool:
|
|
84
|
+
return isinstance(other, str) and str(self) == other
|
|
85
|
+
|
|
86
|
+
def __hash__(self) -> int:
|
|
87
|
+
return hash(str(self))
|
|
88
|
+
|
|
89
|
+
def __str__(self) -> str:
|
|
90
|
+
return "".join(self.all_pieces)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
class _LinearTimeLexer(shlex.shlex):
|
|
94
|
+
"""The stdlib lexer with its token held as ``_TokenPieces``, so a long quoted word reads in linear time."""
|
|
95
|
+
|
|
96
|
+
@property
|
|
97
|
+
def token(self) -> str:
|
|
98
|
+
return cast(str, self.token_pieces)
|
|
99
|
+
|
|
100
|
+
@token.setter
|
|
101
|
+
def token(self, value: str) -> None:
|
|
102
|
+
self.token_pieces = value if isinstance(value, _TokenPieces) else _TokenPieces(value)
|
|
103
|
+
|
|
104
|
+
def read_token(self) -> str | None:
|
|
105
|
+
token = super().read_token()
|
|
106
|
+
return None if token is None else str(token)
|
|
107
|
+
|
|
108
|
+
|
|
66
109
|
class PendingHeredoc(NamedTuple):
|
|
67
110
|
"""The word an open heredoc closes on, and how its opener lets that word be indented."""
|
|
68
111
|
|
|
@@ -108,18 +151,35 @@ def all_operator_aware_tokenizations(command: str) -> list[list[str]]:
|
|
|
108
151
|
"""
|
|
109
152
|
all_tokenizations: list[list[str]] = []
|
|
110
153
|
for each_posix_mode in (True, False):
|
|
111
|
-
|
|
112
|
-
lexer.whitespace_split = True
|
|
113
|
-
lexer.commenters = DISABLED_LEXER_COMMENTERS
|
|
114
|
-
try:
|
|
115
|
-
all_tokens = list(lexer)
|
|
116
|
-
except ValueError:
|
|
117
|
-
continue
|
|
154
|
+
all_tokens = operator_aware_tokens(command, each_posix_mode)
|
|
118
155
|
if all_tokens:
|
|
119
156
|
all_tokenizations.append(all_tokens)
|
|
120
157
|
return all_tokenizations
|
|
121
158
|
|
|
122
159
|
|
|
160
|
+
def operator_aware_tokens(command: str, is_posix: bool) -> list[str] | None:
|
|
161
|
+
"""Return one quote-aware tokenization that carries operators as their own tokens, or None.
|
|
162
|
+
|
|
163
|
+
::
|
|
164
|
+
|
|
165
|
+
'cd "a b" && git push', POSIX -> ["cd", "a b", "&&", "git", "push"]
|
|
166
|
+
'cd "a b" && git push', raw -> ["cd", '"a b"', "&&", "git", "push"]
|
|
167
|
+
'echo "open', either mode -> None
|
|
168
|
+
|
|
169
|
+
Args:
|
|
170
|
+
command: One logical Bash command line (continuations already joined).
|
|
171
|
+
is_posix: True for the POSIX reading, False for the raw one that keeps quotes and backslashes.
|
|
172
|
+
"""
|
|
173
|
+
lexer_type = _LinearTimeLexer if len(command) > LINEAR_TIME_LEXER_MINIMUM_LENGTH else shlex.shlex
|
|
174
|
+
lexer = lexer_type(command, posix=is_posix, punctuation_chars=True)
|
|
175
|
+
lexer.whitespace_split = True
|
|
176
|
+
lexer.commenters = DISABLED_LEXER_COMMENTERS
|
|
177
|
+
try:
|
|
178
|
+
return list(lexer)
|
|
179
|
+
except ValueError:
|
|
180
|
+
return None
|
|
181
|
+
|
|
182
|
+
|
|
123
183
|
def _trailing_operator_token(token: str) -> str | None:
|
|
124
184
|
"""Return the longest control operator the token ends with, or None."""
|
|
125
185
|
for each_operator in ALL_OPERATOR_TOKENS_LONGEST_FIRST:
|
|
@@ -40,7 +40,7 @@ ALL_SHELL_CONTROL_OPERATOR_TOKENS: frozenset[str] = frozenset(
|
|
|
40
40
|
{"&&", "||", ";", "|", "&", "|&"}
|
|
41
41
|
)
|
|
42
42
|
CONTROL_OPERATOR_SPLIT_PATTERN = re.compile(r"(&&|\|\||;|\|&|\||(?<!>)&(?!>))")
|
|
43
|
-
LEADING_ASSIGNMENT_PATTERN = re.compile(r"^[A-Za-z_][A-Za-z0-9_]
|
|
43
|
+
LEADING_ASSIGNMENT_PATTERN = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*\+?=")
|
|
44
44
|
LAUNCHER_DURATION_PATTERN = re.compile(r"^\d+[a-z]*$", re.IGNORECASE)
|
|
45
45
|
|
|
46
46
|
|
|
@@ -75,7 +75,7 @@ def split_into_segments(all_command_tokens: list[str]) -> list[list[str]]:
|
|
|
75
75
|
def effective_leading_program(all_segment_tokens: list[str]) -> str | None:
|
|
76
76
|
"""Return the effective program token after assignments and launcher wrappers.
|
|
77
77
|
|
|
78
|
-
Skips ``VAR=value`` prefixes and known launchers (``timeout``, ``env``, …)
|
|
78
|
+
Skips ``VAR=value`` and ``VAR+=value`` prefixes and known launchers (``timeout``, ``env``, …)
|
|
79
79
|
plus their flags and duration arguments. Returns None when no program token
|
|
80
80
|
remains.
|
|
81
81
|
"""
|
|
@@ -70,6 +70,7 @@ __all__ = [
|
|
|
70
70
|
"all_wrapped_command_segments",
|
|
71
71
|
"all_command_substitution_texts",
|
|
72
72
|
"evaluated_inner_command",
|
|
73
|
+
"quoted_line_breaks_joined",
|
|
73
74
|
]
|
|
74
75
|
|
|
75
76
|
|
|
@@ -293,7 +294,7 @@ def evaluated_inner_command(all_segment_tokens: list[str]) -> str | None:
|
|
|
293
294
|
return None
|
|
294
295
|
|
|
295
296
|
|
|
296
|
-
def
|
|
297
|
+
def quoted_line_breaks_joined(command: str) -> str:
|
|
297
298
|
"""Return a copy of the command that holds a space at each quoted line break.
|
|
298
299
|
|
|
299
300
|
The pipeline parser splits a command at every line break, so a quoted
|
|
@@ -320,7 +321,7 @@ def _inner_commands(command: str, all_command_segments: list[list[str]]) -> list
|
|
|
320
321
|
|
|
321
322
|
A copy of the command with its quoted line breaks joined comes last when it differs.
|
|
322
323
|
"""
|
|
323
|
-
joined_command =
|
|
324
|
+
joined_command = quoted_line_breaks_joined(command)
|
|
324
325
|
all_inner_commands = [
|
|
325
326
|
joined_command if joined_command != command else None,
|
|
326
327
|
*(string_exec_inner_command(each_segment) for each_segment in all_command_segments),
|
|
@@ -6,3 +6,10 @@ from hooks_constants import followup_pr_dedupe_constants as constants
|
|
|
6
6
|
def test_parent_pattern_reads_both_spellings_and_stops_at_the_number() -> None:
|
|
7
7
|
assert re.search(constants.FOLLOWUP_PARENT_PATTERN, "followup to #12", re.IGNORECASE)
|
|
8
8
|
assert re.search(constants.FOLLOWUP_PARENT_PATTERN, "Follow-up to #1731", re.IGNORECASE).group(1) == "1731"
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def test_python_program_pattern_should_read_versioned_and_launcher_names_only() -> None:
|
|
12
|
+
for each_name in ("python", "python3", "python3.11", "python3.13", "pythonw", "py", "pyw"):
|
|
13
|
+
assert re.fullmatch(constants.PYTHON_PROGRAM_NAME_PATTERN, each_name)
|
|
14
|
+
for each_name in ("pytest", "pyright", "python-config", "ipython"):
|
|
15
|
+
assert re.fullmatch(constants.PYTHON_PROGRAM_NAME_PATTERN, each_name) is None
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
"""Tests for the wording a gate gives when one of its checks raises."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from hooks_constants.gate_fault import gate_fault_reason, gate_fault_system_message
|
|
6
|
+
from hooks_constants.gate_fault_constants import GATE_FAULT_TEXT_CHARACTER_LIMIT
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def test_reason_names_the_gate_the_error_type_and_the_text() -> None:
|
|
10
|
+
reason = gate_fault_reason("merge review", KeyError("head"))
|
|
11
|
+
assert reason.startswith("The merge review gate hit a fault")
|
|
12
|
+
assert "KeyError: 'head'" in reason
|
|
13
|
+
assert "refused" in reason
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def test_reason_caps_the_error_text() -> None:
|
|
17
|
+
reason = gate_fault_reason(
|
|
18
|
+
"merge review", ValueError("x" * (GATE_FAULT_TEXT_CHARACTER_LIMIT * 3))
|
|
19
|
+
)
|
|
20
|
+
assert "x" * GATE_FAULT_TEXT_CHARACTER_LIMIT in reason
|
|
21
|
+
assert "x" * (GATE_FAULT_TEXT_CHARACTER_LIMIT + 1) not in reason
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def test_system_message_names_the_script_the_error_and_that_the_call_was_not_checked() -> None:
|
|
25
|
+
message = gate_fault_system_message("verify_before_commit_gate.py", RuntimeError("probe broke"))
|
|
26
|
+
assert "verify_before_commit_gate.py" in message
|
|
27
|
+
assert "RuntimeError: probe broke" in message
|
|
28
|
+
assert "did not check this call" in message
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def test_system_message_does_not_say_the_call_is_refused() -> None:
|
|
32
|
+
message = gate_fault_system_message("verify_before_commit_gate.py", RuntimeError("probe broke"))
|
|
33
|
+
assert "refused" not in message
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def test_system_message_caps_the_error_text() -> None:
|
|
37
|
+
message = gate_fault_system_message(
|
|
38
|
+
"merge_review_gate.py", ValueError("y" * (GATE_FAULT_TEXT_CHARACTER_LIMIT * 3))
|
|
39
|
+
)
|
|
40
|
+
assert "y" * GATE_FAULT_TEXT_CHARACTER_LIMIT in message
|
|
41
|
+
assert "y" * (GATE_FAULT_TEXT_CHARACTER_LIMIT + 1) not in message
|
|
@@ -23,3 +23,8 @@ def test_shell_keywords_and_builtins_step_to_the_command_they_run() -> None:
|
|
|
23
23
|
)
|
|
24
24
|
assert "-a" in constants.ALL_WRAPPER_OPTION_GRAMMARS_BY_NAME["exec"].all_value_taking_options
|
|
25
25
|
assert "-p" in constants.ALL_WRAPPER_OPTION_GRAMMARS_BY_NAME["command"].all_flag_options
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def test_linear_time_lexer_starts_past_a_typed_command_length() -> None:
|
|
29
|
+
assert constants.LINEAR_TIME_LEXER_MINIMUM_LENGTH == 4096
|
|
30
|
+
assert constants.LINEAR_TIME_LEXER_MINIMUM_LENGTH > len("git push origin head " * 100)
|
|
@@ -10,3 +10,13 @@ def test_gate_targets_the_named_skill_and_pre_tool_use() -> None:
|
|
|
10
10
|
def test_gate_covers_shells_and_pull_request_tools() -> None:
|
|
11
11
|
assert constants.SHELL_TOOL_NAMES == {"Bash", "PowerShell"}
|
|
12
12
|
assert len(constants.ALL_GITHUB_MCP_TOOL_SUFFIXES) == 4
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def test_scan_sentence_should_join_a_deny_reason_and_name_both_repairs() -> None:
|
|
16
|
+
assert constants.SCAN_RAN_OUT_SENTENCE.startswith(" ")
|
|
17
|
+
assert "loading the skill again" in constants.SCAN_RAN_OUT_SENTENCE
|
|
18
|
+
assert "build-eval again" in constants.SCAN_RAN_OUT_SENTENCE
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def test_gate_name_should_read_as_a_noun_phrase_in_the_fault_reason() -> None:
|
|
22
|
+
assert constants.GATE_NAME == "pull request lifecycle"
|
|
@@ -6,9 +6,11 @@ import inspect
|
|
|
6
6
|
import io
|
|
7
7
|
import json
|
|
8
8
|
import sys
|
|
9
|
+
from collections.abc import Callable
|
|
9
10
|
from unittest.mock import patch
|
|
10
11
|
|
|
11
12
|
from hooks_constants import pre_tool_use_stdin
|
|
13
|
+
from hooks_constants.gate_fault_constants import GATE_FAULT_TEXT_CHARACTER_LIMIT
|
|
12
14
|
from hooks_constants.pre_tool_use_stdin import read_hook_input_dictionary_from_stdin
|
|
13
15
|
|
|
14
16
|
|
|
@@ -101,3 +103,98 @@ def test_read_returns_none_for_an_integer_past_the_digit_limit() -> None:
|
|
|
101
103
|
oversized_payload = '{"tool_name": "Bash", "tool_use_id": ' + "7" * 6000 + "}"
|
|
102
104
|
with patch("sys.stdin", io.StringIO(oversized_payload)):
|
|
103
105
|
assert read_hook_input_dictionary_from_stdin() is None
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _raise_from_check(payload: dict[str, object]) -> dict[str, object] | None:
|
|
109
|
+
raise RuntimeError("probe broke on " + str(payload["tool_name"]))
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _run_with_raising_check(
|
|
113
|
+
error_check: Callable[[dict[str, object]], dict[str, object] | None] = _raise_from_check,
|
|
114
|
+
) -> tuple[int, str, str]:
|
|
115
|
+
captured_stdout = io.StringIO()
|
|
116
|
+
error_output = io.StringIO()
|
|
117
|
+
with (
|
|
118
|
+
patch("sys.stdin", io.StringIO('{"tool_name": "Bash"}')),
|
|
119
|
+
patch("sys.stdout", captured_stdout),
|
|
120
|
+
patch("sys.stderr", error_output),
|
|
121
|
+
patch("sys.argv", ["/plugin/hooks/blocking/verify_before_commit_gate.py"]),
|
|
122
|
+
):
|
|
123
|
+
exit_code = pre_tool_use_stdin.print_decision_from_stdin(error_check)
|
|
124
|
+
return exit_code, captured_stdout.getvalue(), error_output.getvalue()
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def test_print_decision_from_stdin_returns_zero_when_the_check_raises() -> None:
|
|
128
|
+
exit_code, _, _ = _run_with_raising_check()
|
|
129
|
+
assert exit_code == 0
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def test_print_decision_from_stdin_prints_one_system_message_line_when_the_check_raises() -> None:
|
|
133
|
+
_, standard_output, _ = _run_with_raising_check()
|
|
134
|
+
all_lines = standard_output.splitlines()
|
|
135
|
+
assert len(all_lines) == 1
|
|
136
|
+
decision = json.loads(all_lines[0])
|
|
137
|
+
assert set(decision) == {"systemMessage"}
|
|
138
|
+
assert "hookSpecificOutput" not in decision
|
|
139
|
+
assert "permissionDecision" not in standard_output
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def test_print_decision_from_stdin_fault_message_names_the_script_file_and_the_error() -> None:
|
|
143
|
+
_, standard_output, _ = _run_with_raising_check()
|
|
144
|
+
message = json.loads(standard_output)["systemMessage"]
|
|
145
|
+
assert "verify_before_commit_gate.py" in message
|
|
146
|
+
assert "/plugin/hooks/blocking" not in message
|
|
147
|
+
assert "RuntimeError: probe broke on Bash" in message
|
|
148
|
+
assert "did not check this call" in message
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def test_print_decision_from_stdin_fault_message_caps_the_error_text() -> None:
|
|
152
|
+
long_text = "z" * (GATE_FAULT_TEXT_CHARACTER_LIMIT * 3)
|
|
153
|
+
|
|
154
|
+
def raise_long_error(payload: dict[str, object]) -> dict[str, object] | None:
|
|
155
|
+
raise ValueError(long_text)
|
|
156
|
+
|
|
157
|
+
_, standard_output, _ = _run_with_raising_check(raise_long_error)
|
|
158
|
+
message = json.loads(standard_output)["systemMessage"]
|
|
159
|
+
assert "z" * GATE_FAULT_TEXT_CHARACTER_LIMIT in message
|
|
160
|
+
assert "z" * (GATE_FAULT_TEXT_CHARACTER_LIMIT + 1) not in message
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def test_print_decision_from_stdin_writes_the_traceback_to_standard_error() -> None:
|
|
164
|
+
_, _, standard_error = _run_with_raising_check()
|
|
165
|
+
assert "Traceback" in standard_error
|
|
166
|
+
assert standard_error.rstrip().splitlines()[-1] == "RuntimeError: probe broke on Bash"
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def test_print_decision_from_stdin_writes_a_returned_deny_unchanged() -> None:
|
|
170
|
+
deny_decision = {
|
|
171
|
+
"hookSpecificOutput": {
|
|
172
|
+
"hookEventName": "PreToolUse",
|
|
173
|
+
"permissionDecision": "deny",
|
|
174
|
+
"permissionDecisionReason": "blocked",
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
captured_stdout = io.StringIO()
|
|
178
|
+
error_output = io.StringIO()
|
|
179
|
+
with (
|
|
180
|
+
patch("sys.stdin", io.StringIO('{"tool_name": "Bash"}')),
|
|
181
|
+
patch("sys.stdout", captured_stdout),
|
|
182
|
+
patch("sys.stderr", error_output),
|
|
183
|
+
):
|
|
184
|
+
exit_code = pre_tool_use_stdin.print_decision_from_stdin(lambda payload: deny_decision)
|
|
185
|
+
assert exit_code == 0
|
|
186
|
+
assert captured_stdout.getvalue().splitlines() == [json.dumps(deny_decision)]
|
|
187
|
+
assert error_output.getvalue() == ""
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def test_print_decision_from_stdin_stays_silent_on_both_streams_for_none() -> None:
|
|
191
|
+
captured_stdout = io.StringIO()
|
|
192
|
+
error_output = io.StringIO()
|
|
193
|
+
with (
|
|
194
|
+
patch("sys.stdin", io.StringIO('{"tool_name": "Bash"}')),
|
|
195
|
+
patch("sys.stdout", captured_stdout),
|
|
196
|
+
patch("sys.stderr", error_output),
|
|
197
|
+
):
|
|
198
|
+
assert pre_tool_use_stdin.print_decision_from_stdin(lambda payload: None) == 0
|
|
199
|
+
assert captured_stdout.getvalue() == ""
|
|
200
|
+
assert error_output.getvalue() == ""
|
|
@@ -6,8 +6,13 @@ compound shells. No pytest-specific classification runs here.
|
|
|
6
6
|
|
|
7
7
|
from __future__ import annotations
|
|
8
8
|
|
|
9
|
+
import itertools
|
|
9
10
|
import pathlib
|
|
11
|
+
import shlex
|
|
10
12
|
import sys
|
|
13
|
+
import time
|
|
14
|
+
|
|
15
|
+
import pytest
|
|
11
16
|
|
|
12
17
|
_HOOKS_ROOT = pathlib.Path(__file__).resolve().parent.parent
|
|
13
18
|
if str(_HOOKS_ROOT) not in sys.path:
|
|
@@ -17,6 +22,7 @@ from hooks_constants.shell_command_pipeline import ( # noqa: E402
|
|
|
17
22
|
all_operator_aware_tokenizations,
|
|
18
23
|
join_line_continuations,
|
|
19
24
|
live_command_lines,
|
|
25
|
+
operator_aware_tokens,
|
|
20
26
|
pipeline_segments_for_command,
|
|
21
27
|
scannable_command_lines,
|
|
22
28
|
segments_with_following_operator,
|
|
@@ -133,3 +139,52 @@ def test_compound_shell_if_fi_tokens_survive_tokenization() -> None:
|
|
|
133
139
|
assert "if" in flat_tokens
|
|
134
140
|
assert "then" in flat_tokens
|
|
135
141
|
assert "fi" in flat_tokens
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def test_operator_aware_tokens_should_read_one_mode_at_a_time() -> None:
|
|
145
|
+
command = 'cd "a b" && git push'
|
|
146
|
+
assert operator_aware_tokens(command, True) == ["cd", "a b", "&&", "git", "push"]
|
|
147
|
+
assert operator_aware_tokens(command, False) == ["cd", '"a b"', "&&", "git", "push"]
|
|
148
|
+
assert operator_aware_tokens('echo "open', True) is None
|
|
149
|
+
assert operator_aware_tokens('echo "open', False) is None
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def _fastest_tokenizing_seconds(command: str, is_posix: bool) -> float:
|
|
153
|
+
all_seconds = []
|
|
154
|
+
for _each_attempt in range(3):
|
|
155
|
+
started = time.perf_counter()
|
|
156
|
+
operator_aware_tokens(command, is_posix)
|
|
157
|
+
all_seconds.append(time.perf_counter() - started)
|
|
158
|
+
return min(all_seconds)
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
@pytest.mark.parametrize("is_posix", [True, False])
|
|
162
|
+
def test_operator_aware_tokens_should_take_linear_time_on_a_long_quoted_word(is_posix: bool) -> None:
|
|
163
|
+
short_command = "tool --body '" + "ab cd; " * 8_000 + "'"
|
|
164
|
+
long_command = "tool --body '" + "ab cd; " * 32_000 + "'"
|
|
165
|
+
_fastest_tokenizing_seconds(short_command, is_posix)
|
|
166
|
+
growth = _fastest_tokenizing_seconds(long_command, is_posix) / _fastest_tokenizing_seconds(short_command, is_posix)
|
|
167
|
+
assert growth < 8
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
@pytest.mark.parametrize(
|
|
171
|
+
"command",
|
|
172
|
+
[
|
|
173
|
+
"tool --body '" + "ab cd; " * 2_000 + "' && next \"x\\\"y\" ; z",
|
|
174
|
+
'a "b c"d \'e f\' g\\ h|i&&j||k;l(m)n>o<p',
|
|
175
|
+
"a ''b \"\" c$'d' \\",
|
|
176
|
+
"cut 'open",
|
|
177
|
+
],
|
|
178
|
+
)
|
|
179
|
+
def test_operator_aware_tokens_should_give_the_words_shlex_gives(command: str) -> None:
|
|
180
|
+
for each_command, each_is_posix in itertools.product([command, "w" * 5_000 + " " + command], (True, False)):
|
|
181
|
+
lexer = shlex.shlex(each_command, posix=each_is_posix, punctuation_chars=True)
|
|
182
|
+
lexer.whitespace_split = True
|
|
183
|
+
lexer.commenters = ""
|
|
184
|
+
try:
|
|
185
|
+
expected = list(lexer)
|
|
186
|
+
except ValueError:
|
|
187
|
+
expected = None
|
|
188
|
+
all_tokens = operator_aware_tokens(each_command, each_is_posix)
|
|
189
|
+
assert all_tokens == expected
|
|
190
|
+
assert all(type(each_token) is str for each_token in all_tokens or [])
|
|
@@ -27,3 +27,18 @@ def test_should_return_the_subcommand_tokens_past_global_options(
|
|
|
27
27
|
all_arguments: list[str], all_expected_tokens: list[str]
|
|
28
28
|
) -> None:
|
|
29
29
|
assert shell_command_segments.git_subcommand_tokens(all_arguments) == all_expected_tokens
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@pytest.mark.parametrize(
|
|
33
|
+
("all_segment_tokens", "expected_program"),
|
|
34
|
+
[
|
|
35
|
+
(["GIT_TRACE=1", "git", "push"], "git"),
|
|
36
|
+
(["GIT_TRACE+=1", "git", "push"], "git"),
|
|
37
|
+
(["GIT_TRACE+=1"], None),
|
|
38
|
+
(["a+b=1", "git", "push"], "a+b=1"),
|
|
39
|
+
],
|
|
40
|
+
)
|
|
41
|
+
def test_should_step_over_set_and_append_assignments_to_the_program(
|
|
42
|
+
all_segment_tokens: list[str], expected_program: str | None
|
|
43
|
+
) -> None:
|
|
44
|
+
assert shell_command_segments.effective_leading_program(all_segment_tokens) == expected_program
|
|
@@ -89,6 +89,7 @@ def test_should_return_the_segments_of_every_wrapped_command_text(command: str)
|
|
|
89
89
|
(["command", "git", "push"], ("git", ["push"])),
|
|
90
90
|
(["command", "-p", "git", "push"], ("git", ["push"])),
|
|
91
91
|
(["exec", "-a", "name", "git", "push"], ("git", ["push"])),
|
|
92
|
+
(["GIT_TRACE+=1", "git", "push"], ("git", ["push"])),
|
|
92
93
|
],
|
|
93
94
|
)
|
|
94
95
|
def test_should_return_the_program_past_its_wrappers(
|
|
@@ -191,3 +192,8 @@ def test_should_parse_a_repeated_inner_command_once() -> None:
|
|
|
191
192
|
'bash -c "git push"; bash -c "git push"'
|
|
192
193
|
)
|
|
193
194
|
assert all_command_texts.count("git push") == 1
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def test_quoted_line_breaks_joined_should_join_only_quoted_line_breaks() -> None:
|
|
198
|
+
command = 'echo "a\nb"\ngit push'
|
|
199
|
+
assert shell_command_wrappers.quoted_line_breaks_joined(command) == 'echo "a b"\ngit push'
|
|
@@ -10,3 +10,9 @@ META_ENTRY_FIELD = "isMeta"
|
|
|
10
10
|
TOOL_RESULT_BLOCK_TYPE = "tool_result"
|
|
11
11
|
IS_ERROR_FIELD = "is_error"
|
|
12
12
|
TOOL_USE_ID_FIELD = "tool_use_id"
|
|
13
|
+
NEWLINE_BYTE = b"\n"
|
|
14
|
+
CARRIAGE_RETURN_BYTE = b"\r"
|
|
15
|
+
ALL_LINE_BREAK_BYTES = (NEWLINE_BYTE, CARRIAGE_RETURN_BYTE)
|
|
16
|
+
TRANSCRIPT_BLOCK_BYTES = 1 << 20
|
|
17
|
+
TRANSCRIPT_LINE_BYTE_CAP = 16 * 1024 * 1024
|
|
18
|
+
FORWARD_COPY_BYTE_CAP = 64 * 1024 * 1024
|
package/hooks/pyproject.toml
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
|
|
8
8
|
[tool.mypy]
|
|
9
9
|
mypy_path = "."
|
|
10
|
-
python_version = "3.
|
|
10
|
+
python_version = "3.11"
|
|
11
11
|
ignore_missing_imports = true
|
|
12
12
|
warn_unused_ignores = false
|
|
13
13
|
warn_redundant_casts = true
|
|
@@ -32,7 +32,7 @@ disallow_untyped_defs = false
|
|
|
32
32
|
|
|
33
33
|
[tool.ruff]
|
|
34
34
|
line-length = 100
|
|
35
|
-
target-version = "
|
|
35
|
+
target-version = "py311"
|
|
36
36
|
extend-exclude = [
|
|
37
37
|
".audit-trail",
|
|
38
38
|
".claude",
|
|
@@ -94,7 +94,6 @@ ignore = [
|
|
|
94
94
|
# Residual production carve-outs re-homed on #57 (gate friction on multi-line touch).
|
|
95
95
|
"validators/run_all_validators.py" = ["PLW1510"]
|
|
96
96
|
"validators/exempt_paths.py" = ["F401"]
|
|
97
|
-
"blocking/gate_run_reads.py" = ["UP047"]
|
|
98
97
|
"test_*.py" = ["B011", "PLR2004", "F401", "F841", "PLW1510", "B905", "B033", "SIM115", "B007", "B018", "B904"]
|
|
99
98
|
"*_test.py" = ["B011", "PLR2004", "F401", "F841", "PLW1510", "B905", "B033", "SIM115", "B007", "B018", "B904"]
|
|
100
99
|
"conftest.py" = ["B011", "F401", "F841", "PLW1510"]
|
|
@@ -6,6 +6,10 @@ adds the team-advisor starting points, such as a consult on a design question,
|
|
|
6
6
|
and leaves each call to the session's judgment. It emits them only when the user settings carry an
|
|
7
7
|
``advisorModel`` value and ``CLAUDE_CODE_DISABLE_ADVISOR_TOOL`` is not set, so a
|
|
8
8
|
session without the advisor is never told to call it.
|
|
9
|
+
It also stays silent when the SessionStart payload's ``model`` is the
|
|
10
|
+
``advisorModel`` value or belongs to its model family, so a session is never
|
|
11
|
+
told to consult itself. When the payload has no ``model``, the guidance names the advisor model
|
|
12
|
+
so the session can tell for itself.
|
|
9
13
|
The hook writes nothing and runs no tools itself.
|
|
10
14
|
"""
|
|
11
15
|
|
|
@@ -23,14 +27,17 @@ if _hooks_directory not in sys.path:
|
|
|
23
27
|
from hooks_constants.advisor_rules_prompt_constants import (
|
|
24
28
|
ADVISOR_DISABLE_ENV_VAR,
|
|
25
29
|
ADVISOR_MODEL_SETTINGS_KEY,
|
|
26
|
-
|
|
30
|
+
ADVISOR_RULES_PROMPT_TEMPLATE,
|
|
27
31
|
ALL_ADVISOR_DISABLE_ENV_TRUE_VALUES,
|
|
32
|
+
ALL_MODEL_FAMILY_NAMES,
|
|
28
33
|
CLAUDE_CONFIG_DIR_ENV_VAR,
|
|
29
34
|
DEFAULT_CLAUDE_CONFIG_DIRECTORY_NAME,
|
|
35
|
+
SESSION_MODEL_PAYLOAD_KEY,
|
|
30
36
|
USER_SETTINGS_FILE_NAME,
|
|
31
37
|
)
|
|
32
38
|
from hooks_constants.mod_handoff import is_mod_plugin_enabled
|
|
33
39
|
from hooks_constants.mod_handoff_constants import SESSION_PROMPTS_PLUGIN_NAME
|
|
40
|
+
from hooks_constants.pre_tool_use_stdin import read_hook_input_dictionary_from_stdin
|
|
34
41
|
|
|
35
42
|
|
|
36
43
|
def user_settings_path() -> Path:
|
|
@@ -47,30 +54,67 @@ def is_advisor_disabled_by_environment() -> bool:
|
|
|
47
54
|
return raw_value in ALL_ADVISOR_DISABLE_ENV_TRUE_VALUES
|
|
48
55
|
|
|
49
56
|
|
|
50
|
-
def
|
|
51
|
-
"""Return
|
|
57
|
+
def configured_advisor_model(settings_path: Path) -> str | None:
|
|
58
|
+
"""Return the settings file's non-empty advisor model, or None."""
|
|
52
59
|
try:
|
|
53
60
|
settings = json.loads(settings_path.read_text(encoding="utf-8"))
|
|
54
61
|
except (OSError, ValueError):
|
|
55
|
-
return
|
|
62
|
+
return None
|
|
56
63
|
if not isinstance(settings, dict):
|
|
57
|
-
return
|
|
64
|
+
return None
|
|
58
65
|
advisor_model = settings.get(ADVISOR_MODEL_SETTINGS_KEY)
|
|
59
|
-
|
|
66
|
+
if not isinstance(advisor_model, str) or not advisor_model.strip():
|
|
67
|
+
return None
|
|
68
|
+
return advisor_model.strip()
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def model_family(model_name: str) -> str | None:
|
|
72
|
+
"""Return the family an alias or full model id names, or None.
|
|
73
|
+
|
|
74
|
+
::
|
|
75
|
+
|
|
76
|
+
"fable" -> "fable" "claude-fable-5-2" -> "fable"
|
|
77
|
+
"claude-mythos-1" -> None
|
|
78
|
+
"""
|
|
79
|
+
lowered_model_name = model_name.lower()
|
|
80
|
+
for each_family_name in ALL_MODEL_FAMILY_NAMES:
|
|
81
|
+
if each_family_name in lowered_model_name:
|
|
82
|
+
return each_family_name
|
|
83
|
+
return None
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def runs_on_advisor_model(session_model: object, advisor_model: str) -> bool:
|
|
87
|
+
"""Return True when the session model is the advisor model or shares its known family.
|
|
88
|
+
|
|
89
|
+
::
|
|
90
|
+
|
|
91
|
+
"claude-fable-5-2", "fable" -> True "claude-mythos-1", "claude-mythos-1" -> True
|
|
92
|
+
"claude-opus-5-5", "fable" -> False "claude-mythos-1", "custom-advisor" -> False
|
|
93
|
+
"""
|
|
94
|
+
if not isinstance(session_model, str):
|
|
95
|
+
return False
|
|
96
|
+
if session_model.strip().lower() == advisor_model.lower():
|
|
97
|
+
return True
|
|
98
|
+
session_family = model_family(session_model)
|
|
99
|
+
return session_family is not None and session_family == model_family(advisor_model)
|
|
60
100
|
|
|
61
101
|
|
|
62
102
|
def main() -> None:
|
|
63
|
-
"""Emit the advisor guidance as SessionStart additionalContext when the advisor is on and the session-prompts mod is off."""
|
|
103
|
+
"""Emit the advisor guidance as SessionStart additionalContext when the advisor is on, the session runs on another model, and the session-prompts mod is off."""
|
|
64
104
|
if is_mod_plugin_enabled(SESSION_PROMPTS_PLUGIN_NAME):
|
|
65
105
|
return
|
|
66
106
|
if is_advisor_disabled_by_environment():
|
|
67
107
|
return
|
|
68
|
-
|
|
108
|
+
advisor_model = configured_advisor_model(user_settings_path())
|
|
109
|
+
if advisor_model is None:
|
|
110
|
+
return
|
|
111
|
+
session_start_payload = read_hook_input_dictionary_from_stdin() or {}
|
|
112
|
+
if runs_on_advisor_model(session_start_payload.get(SESSION_MODEL_PAYLOAD_KEY), advisor_model):
|
|
69
113
|
return
|
|
70
114
|
session_start_output = {
|
|
71
115
|
"hookSpecificOutput": {
|
|
72
116
|
"hookEventName": "SessionStart",
|
|
73
|
-
"additionalContext":
|
|
117
|
+
"additionalContext": ADVISOR_RULES_PROMPT_TEMPLATE.format(advisor_model=advisor_model),
|
|
74
118
|
}
|
|
75
119
|
}
|
|
76
120
|
sys.stdout.write(json.dumps(session_start_output) + "\n")
|