claude-dev-env 8.119.2 → 8.121.0
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/bin/ever-registered-hooks.mjs +1 -0
- package/hooks/advisory/auto_mode_denial_quick_fix.py +275 -27
- package/hooks/advisory/auto_mode_rule_flow_eval/auto_mode_rule_flow_cases.json +3475 -0
- package/hooks/advisory/auto_mode_rule_flow_eval/auto_mode_rule_flow_runner.py +849 -0
- package/hooks/advisory/auto_mode_rule_flow_eval/stub_allow_hook.py +20 -0
- package/hooks/advisory/auto_mode_rule_flow_eval/stub_hold_hook.py +54 -0
- package/hooks/advisory/auto_mode_rule_flow_eval/test_auto_mode_rule_flow_runner.py +143 -0
- package/hooks/advisory/test_auto_mode_denial_quick_fix.py +533 -9
- package/hooks/auto_mode_question_transcript.py +215 -0
- package/hooks/auto_mode_refusal_ledger.py +481 -0
- package/hooks/auto_mode_refusal_ledger_files.py +336 -0
- package/hooks/auto_mode_rule_steps.py +177 -0
- package/hooks/blocking/auto_mode_refusal_stop_gate.py +384 -0
- package/hooks/blocking/gh_api_budget_gate.py +286 -0
- package/hooks/blocking/test_auto_mode_refusal_stop_gate.py +484 -0
- package/hooks/blocking/test_bash_dispatcher_interpreter_starts.py +8 -3
- package/hooks/blocking/test_bash_pre_tool_use_dispatcher.py +1 -0
- package/hooks/blocking/test_gh_api_budget_gate.py +602 -0
- package/hooks/features/README.md +1 -1
- package/hooks/features/bash-dispatchers.md +3 -0
- package/hooks/features/session-context.md +5 -2
- package/hooks/hooks.json +5 -0
- package/hooks/hooks_constants/auto_mode_denial_quick_fix_constants.py +51 -3
- package/hooks/hooks_constants/auto_mode_refusal_ledger_constants.py +85 -0
- package/hooks/hooks_constants/auto_mode_refusal_stop_gate_constants.py +80 -0
- package/hooks/hooks_constants/auto_mode_rule_flow_runner_constants.py +225 -0
- package/hooks/hooks_constants/auto_mode_rule_steps_constants.py +82 -0
- package/hooks/hooks_constants/bash_pre_tool_use_dispatcher_constants.py +4 -0
- package/hooks/hooks_constants/gh_api_budget.py +186 -0
- package/hooks/hooks_constants/gh_api_budget_gate_constants.py +215 -0
- package/hooks/hooks_constants/gh_argument_lists.py +169 -0
- package/hooks/hooks_constants/gh_shell_loop_scan.py +386 -0
- package/hooks/hooks_constants/test_bash_pre_tool_use_dispatcher_constants.py +5 -1
- package/hooks/hooks_constants/test_gh_api_budget.py +125 -0
- package/hooks/hooks_constants/test_gh_argument_lists.py +49 -0
- package/hooks/hooks_constants/test_gh_shell_loop_scan.py +50 -0
- package/hooks/test_auto_mode_question_transcript.py +113 -0
- package/hooks/test_auto_mode_refusal_ledger.py +398 -0
- package/hooks/test_auto_mode_refusal_ledger_files.py +155 -0
- package/hooks/test_auto_mode_rule_steps.py +210 -0
- package/package.json +1 -1
- package/scripts/policy_lint/adapter_configuration.py +5 -0
- package/scripts/policy_lint/config/constants.py +1 -0
- package/scripts/tests/test_adapter_configuration.py +8 -0
|
@@ -0,0 +1,336 @@
|
|
|
1
|
+
"""Where the refusal ledger's files live, and how they are read and written.
|
|
2
|
+
|
|
3
|
+
A session's ledger folder sits under the config folder, and a step's id names
|
|
4
|
+
its file. Each JSON file in a session's ledger folder is parsed when it is read::
|
|
5
|
+
|
|
6
|
+
{"id": "3f9a...", "tool_name": "Bash", "rule_label": "Git Destructive",
|
|
7
|
+
"sequence": 1, "answer": null, ...} -> LedgerEntry
|
|
8
|
+
{"record": "question", "question": "...",
|
|
9
|
+
"entry_ids": ["3f9a..."], "transcript_offset": 900} -> QuestionRecord
|
|
10
|
+
{"answer": null} with no id, or "sequence": "first" -> None, skipped
|
|
11
|
+
|
|
12
|
+
A file that does not parse never raises, so one bad file cannot stop the
|
|
13
|
+
refusal hook or the Stop gate.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import hashlib
|
|
19
|
+
import json
|
|
20
|
+
import re
|
|
21
|
+
from dataclasses import dataclass
|
|
22
|
+
from pathlib import Path
|
|
23
|
+
from typing import TypeGuard
|
|
24
|
+
|
|
25
|
+
from atomic_file_writer import write_text_atomically
|
|
26
|
+
from hooks_constants.auto_mode_refusal_ledger_constants import (
|
|
27
|
+
ALL_ANSWERS,
|
|
28
|
+
ALL_LEDGER_RELATIVE_PARTS,
|
|
29
|
+
ALL_NARRATION_INPUT_KEYS,
|
|
30
|
+
ENTRY_FILE_SUFFIX,
|
|
31
|
+
ID_HEX_CHARACTERS,
|
|
32
|
+
JSON_INDENT_SPACES,
|
|
33
|
+
QUESTION_ASKED_FIELD,
|
|
34
|
+
QUESTION_CARD_OFFSET_FIELD,
|
|
35
|
+
QUESTION_FILE_PREFIX,
|
|
36
|
+
QUESTION_HOLDS_FIELD,
|
|
37
|
+
QUESTION_RECORD_KIND,
|
|
38
|
+
RULE_HOLDS_FIELD,
|
|
39
|
+
TEMPORARY_FILE_PREFIX,
|
|
40
|
+
TEMPORARY_FILE_SUFFIX,
|
|
41
|
+
TEXT_ENCODING,
|
|
42
|
+
)
|
|
43
|
+
from open_task_asks import claude_home
|
|
44
|
+
|
|
45
|
+
JsonObject = dict[str, object]
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@dataclass(frozen=True)
|
|
49
|
+
class LedgerEntry:
|
|
50
|
+
"""One refused step read from its ledger file.
|
|
51
|
+
|
|
52
|
+
Attributes:
|
|
53
|
+
entry_id: The step's id, which also names its file.
|
|
54
|
+
tool_name: The refused call's tool name.
|
|
55
|
+
rule_label: The rule label the step was refused under.
|
|
56
|
+
action_summary: One short line that names the step.
|
|
57
|
+
sequence: The step's place in refusal order.
|
|
58
|
+
answer: ``allowed``, ``kept``, or None while the step is pending.
|
|
59
|
+
question_holds: How many turns the Stop gate held to ask about it.
|
|
60
|
+
rule_holds: How many turns the Stop gate held for its rule.
|
|
61
|
+
is_question_asked: Whether the Stop gate saw its question asked.
|
|
62
|
+
question_card_offset: The transcript offset of the decision card
|
|
63
|
+
that asked it, or None when no card asked it.
|
|
64
|
+
"""
|
|
65
|
+
|
|
66
|
+
entry_id: str
|
|
67
|
+
tool_name: str
|
|
68
|
+
rule_label: str
|
|
69
|
+
action_summary: str
|
|
70
|
+
sequence: int
|
|
71
|
+
answer: str | None
|
|
72
|
+
question_holds: int = 0
|
|
73
|
+
rule_holds: int = 0
|
|
74
|
+
is_question_asked: bool = False
|
|
75
|
+
question_card_offset: int | None = None
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
@dataclass(frozen=True)
|
|
79
|
+
class QuestionRecord:
|
|
80
|
+
"""One question record read from its ledger file.
|
|
81
|
+
|
|
82
|
+
Attributes:
|
|
83
|
+
question: The exact question text.
|
|
84
|
+
all_entry_ids: The ids the question covers.
|
|
85
|
+
transcript_offset: The transcript size when the record was written.
|
|
86
|
+
tool_name: The tool the covered steps used, or empty when the file
|
|
87
|
+
names none.
|
|
88
|
+
"""
|
|
89
|
+
|
|
90
|
+
question: str
|
|
91
|
+
all_entry_ids: tuple[str, ...]
|
|
92
|
+
transcript_offset: int
|
|
93
|
+
tool_name: str = ""
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def ledger_directory_for(session_id: str) -> Path:
|
|
97
|
+
"""Return the folder that holds one session's ledger.
|
|
98
|
+
|
|
99
|
+
Args:
|
|
100
|
+
session_id: The session id from the hook input.
|
|
101
|
+
|
|
102
|
+
Returns:
|
|
103
|
+
``<config>/state/auto-mode-refusals/<session_id>``. A character
|
|
104
|
+
outside letters, digits, ``-`` and ``_`` becomes ``_`` in the name.
|
|
105
|
+
"""
|
|
106
|
+
safe_session_id = re.sub(r"[^A-Za-z0-9_-]", "_", session_id) or "_"
|
|
107
|
+
return claude_home().joinpath(*ALL_LEDGER_RELATIVE_PARTS, safe_session_id)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def entry_id_for(tool_name: str, tool_input: object) -> str:
|
|
111
|
+
"""Return the ledger id of one refused step.
|
|
112
|
+
|
|
113
|
+
::
|
|
114
|
+
|
|
115
|
+
Edit {"file_path": "a.py", "old_string": "x"} -> one id
|
|
116
|
+
Edit {"file_path": "a.py", "old_string": "y"} -> another id
|
|
117
|
+
Bash {"command": "c", "description": "Retry c"} -> the id of Bash {"command": "c"}
|
|
118
|
+
|
|
119
|
+
The model writes a new ``description`` for each try, so a retry of the
|
|
120
|
+
same command keeps the id, and its answer, of the first refusal.
|
|
121
|
+
|
|
122
|
+
Args:
|
|
123
|
+
tool_name: The refused call's tool name.
|
|
124
|
+
tool_input: The refused call's full ``tool_input``.
|
|
125
|
+
|
|
126
|
+
Returns:
|
|
127
|
+
The first hex characters of a SHA-256 over both, as sorted JSON,
|
|
128
|
+
with the ``description`` key left out of a ``tool_input`` object.
|
|
129
|
+
"""
|
|
130
|
+
identity_input = (
|
|
131
|
+
{
|
|
132
|
+
each_key: each_value
|
|
133
|
+
for each_key, each_value in tool_input.items()
|
|
134
|
+
if each_key not in ALL_NARRATION_INPUT_KEYS
|
|
135
|
+
}
|
|
136
|
+
if isinstance(tool_input, dict)
|
|
137
|
+
else tool_input
|
|
138
|
+
)
|
|
139
|
+
identity_text = json.dumps(
|
|
140
|
+
{"tool_name": tool_name, "tool_input": identity_input}, sort_keys=True, default=str
|
|
141
|
+
)
|
|
142
|
+
return hashlib.sha256(identity_text.encode(TEXT_ENCODING)).hexdigest()[:ID_HEX_CHARACTERS]
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def _is_integer(value: object) -> TypeGuard[int]:
|
|
147
|
+
return isinstance(value, int) and not isinstance(value, bool)
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _is_count(value: object) -> TypeGuard[int]:
|
|
151
|
+
return _is_integer(value) and value >= 0
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def read_json_object(file_path: Path) -> JsonObject | None:
|
|
155
|
+
"""Return the JSON object a file holds, or None.
|
|
156
|
+
|
|
157
|
+
Args:
|
|
158
|
+
file_path: One ledger file.
|
|
159
|
+
|
|
160
|
+
Returns:
|
|
161
|
+
The object, or None when the file cannot be read, is not JSON, or
|
|
162
|
+
holds something other than an object.
|
|
163
|
+
"""
|
|
164
|
+
try:
|
|
165
|
+
parsed_file = json.loads(file_path.read_text(encoding=TEXT_ENCODING))
|
|
166
|
+
except (OSError, ValueError):
|
|
167
|
+
return None
|
|
168
|
+
return parsed_file if isinstance(parsed_file, dict) else None
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def parse_entry(json_object: JsonObject | None) -> LedgerEntry | None:
|
|
172
|
+
"""Return the entry a ledger file's object describes, or None.
|
|
173
|
+
|
|
174
|
+
Args:
|
|
175
|
+
json_object: The object from ``read_json_object``.
|
|
176
|
+
|
|
177
|
+
Returns:
|
|
178
|
+
The entry when the object has an ``answer`` key, text ``id``,
|
|
179
|
+
``tool_name``, ``rule_label`` and ``action_summary``, an integer
|
|
180
|
+
``sequence``, and an answer that is null, ``allowed`` or ``kept``.
|
|
181
|
+
The Stop gate's ``question_holds`` and ``rule_holds`` default to 0
|
|
182
|
+
and must be integers of 0 or more, ``question_asked`` defaults to
|
|
183
|
+
false and must be a boolean, and ``question_card_offset`` defaults
|
|
184
|
+
to null and must be null or an integer of 0 or more.
|
|
185
|
+
"""
|
|
186
|
+
if json_object is None or "answer" not in json_object:
|
|
187
|
+
return None
|
|
188
|
+
all_text_fields = [json_object.get(each) for each in ("id", "tool_name", "rule_label")]
|
|
189
|
+
all_text_fields.append(json_object.get("action_summary", ""))
|
|
190
|
+
all_text_values = [each for each in all_text_fields if isinstance(each, str)]
|
|
191
|
+
sequence = json_object.get("sequence", 0)
|
|
192
|
+
all_hold_counts = [
|
|
193
|
+
json_object.get(each_name, 0) for each_name in (QUESTION_HOLDS_FIELD, RULE_HOLDS_FIELD)
|
|
194
|
+
]
|
|
195
|
+
all_count_values = [each for each in all_hold_counts if _is_count(each)]
|
|
196
|
+
answer = json_object["answer"]
|
|
197
|
+
is_question_asked = json_object.get(QUESTION_ASKED_FIELD, False)
|
|
198
|
+
question_card_offset = json_object.get(QUESTION_CARD_OFFSET_FIELD)
|
|
199
|
+
if not (
|
|
200
|
+
len(all_text_values) == len(all_text_fields)
|
|
201
|
+
and _is_integer(sequence)
|
|
202
|
+
and len(all_count_values) == len(all_hold_counts)
|
|
203
|
+
and (answer is None or answer in ALL_ANSWERS)
|
|
204
|
+
and isinstance(is_question_asked, bool)
|
|
205
|
+
and (question_card_offset is None or _is_count(question_card_offset))
|
|
206
|
+
):
|
|
207
|
+
return None
|
|
208
|
+
entry_id, tool_name, rule_label, action_summary = all_text_values
|
|
209
|
+
question_holds, rule_holds = all_count_values
|
|
210
|
+
return LedgerEntry(
|
|
211
|
+
entry_id, tool_name, rule_label, action_summary, sequence, answer,
|
|
212
|
+
question_holds, rule_holds, is_question_asked, question_card_offset,
|
|
213
|
+
)
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def parse_question_record(json_object: JsonObject | None) -> QuestionRecord | None:
|
|
217
|
+
"""Return the question record a ledger file's object describes, or None.
|
|
218
|
+
|
|
219
|
+
Args:
|
|
220
|
+
json_object: The object from ``read_json_object``.
|
|
221
|
+
|
|
222
|
+
Returns:
|
|
223
|
+
The record when the object is a question record with text
|
|
224
|
+
``question``, a list of text ``entry_ids`` and an integer
|
|
225
|
+
``transcript_offset``. A ``tool_name`` that is not text reads as
|
|
226
|
+
empty.
|
|
227
|
+
"""
|
|
228
|
+
if json_object is None or json_object.get("record") != QUESTION_RECORD_KIND:
|
|
229
|
+
return None
|
|
230
|
+
question = json_object.get("question")
|
|
231
|
+
all_entry_ids = json_object.get("entry_ids")
|
|
232
|
+
transcript_offset = json_object.get("transcript_offset", 0)
|
|
233
|
+
if not (
|
|
234
|
+
isinstance(question, str)
|
|
235
|
+
and isinstance(all_entry_ids, list)
|
|
236
|
+
and all(isinstance(each, str) for each in all_entry_ids)
|
|
237
|
+
and _is_integer(transcript_offset)
|
|
238
|
+
):
|
|
239
|
+
return None
|
|
240
|
+
tool_name = json_object.get("tool_name")
|
|
241
|
+
return QuestionRecord(
|
|
242
|
+
question,
|
|
243
|
+
tuple(all_entry_ids),
|
|
244
|
+
transcript_offset,
|
|
245
|
+
tool_name if isinstance(tool_name, str) else "",
|
|
246
|
+
)
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def write_json_object(file_path: Path, json_object: JsonObject) -> None:
|
|
250
|
+
"""Write one ledger file atomically, as sorted, indented JSON.
|
|
251
|
+
|
|
252
|
+
Args:
|
|
253
|
+
file_path: The ledger file to write.
|
|
254
|
+
json_object: The object to write.
|
|
255
|
+
"""
|
|
256
|
+
write_text_atomically(
|
|
257
|
+
file_path,
|
|
258
|
+
json.dumps(json_object, indent=JSON_INDENT_SPACES, sort_keys=True) + "\n",
|
|
259
|
+
TEXT_ENCODING,
|
|
260
|
+
TEMPORARY_FILE_PREFIX,
|
|
261
|
+
TEMPORARY_FILE_SUFFIX,
|
|
262
|
+
should_reap_orphans=False,
|
|
263
|
+
)
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def entry_file_path(ledger_directory: Path, entry_id: str) -> Path:
|
|
267
|
+
"""Return the file that holds one entry.
|
|
268
|
+
|
|
269
|
+
Args:
|
|
270
|
+
ledger_directory: One session's ledger folder.
|
|
271
|
+
entry_id: The entry's id.
|
|
272
|
+
|
|
273
|
+
Returns:
|
|
274
|
+
``<ledger_directory>/<entry_id>.json``.
|
|
275
|
+
"""
|
|
276
|
+
return ledger_directory / f"{entry_id}{ENTRY_FILE_SUFFIX}"
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def question_file_path(ledger_directory: Path, question: str) -> Path:
|
|
280
|
+
"""Return the file that holds the record of one question text.
|
|
281
|
+
|
|
282
|
+
Args:
|
|
283
|
+
ledger_directory: One session's ledger folder.
|
|
284
|
+
question: The exact question text.
|
|
285
|
+
|
|
286
|
+
Returns:
|
|
287
|
+
``<ledger_directory>/question-<digest>.json``.
|
|
288
|
+
"""
|
|
289
|
+
question_digest = hashlib.sha256(question.encode(TEXT_ENCODING)).hexdigest()
|
|
290
|
+
return (
|
|
291
|
+
ledger_directory
|
|
292
|
+
/ f"{QUESTION_FILE_PREFIX}{question_digest[:ID_HEX_CHARACTERS]}{ENTRY_FILE_SUFFIX}"
|
|
293
|
+
)
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
def load_entries(ledger_directory: Path) -> list[LedgerEntry]:
|
|
297
|
+
"""Return every refused-step entry in a ledger folder, oldest first.
|
|
298
|
+
|
|
299
|
+
Args:
|
|
300
|
+
ledger_directory: One session's ledger folder.
|
|
301
|
+
|
|
302
|
+
Returns:
|
|
303
|
+
The entries that parse, sorted by their ``sequence`` number. A file
|
|
304
|
+
that ``parse_entry`` rejects, or whose name is not ``<id>.json`` for
|
|
305
|
+
the id it holds, is skipped.
|
|
306
|
+
"""
|
|
307
|
+
if not ledger_directory.is_dir():
|
|
308
|
+
return []
|
|
309
|
+
all_entries = [
|
|
310
|
+
each_entry
|
|
311
|
+
for each_path in ledger_directory.glob(f"*{ENTRY_FILE_SUFFIX}")
|
|
312
|
+
if (each_entry := parse_entry(read_json_object(each_path))) is not None
|
|
313
|
+
and each_path == entry_file_path(ledger_directory, each_entry.entry_id)
|
|
314
|
+
]
|
|
315
|
+
return sorted(all_entries, key=lambda each_entry: each_entry.sequence)
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
def load_question_records(ledger_directory: Path) -> list[QuestionRecord]:
|
|
319
|
+
"""Return every question record in a ledger folder, in file name order.
|
|
320
|
+
|
|
321
|
+
Args:
|
|
322
|
+
ledger_directory: One session's ledger folder.
|
|
323
|
+
|
|
324
|
+
Returns:
|
|
325
|
+
The records that parse. A file that ``parse_question_record``
|
|
326
|
+
rejects is skipped.
|
|
327
|
+
"""
|
|
328
|
+
if not ledger_directory.is_dir():
|
|
329
|
+
return []
|
|
330
|
+
return [
|
|
331
|
+
each_record
|
|
332
|
+
for each_path in sorted(
|
|
333
|
+
ledger_directory.glob(f"{QUESTION_FILE_PREFIX}*{ENTRY_FILE_SUFFIX}")
|
|
334
|
+
)
|
|
335
|
+
if (each_record := parse_question_record(read_json_object(each_path))) is not None
|
|
336
|
+
]
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
"""Tell whether a refused step is one of the auto mode rule flow's own steps.
|
|
2
|
+
|
|
3
|
+
The rule playbook runs its own steps after the user answers ``Allow it``. A
|
|
4
|
+
refusal of one of them gets no new ledger entry, so the user is never asked a
|
|
5
|
+
second question about the flow itself. The skip is an exact match against a
|
|
6
|
+
short table, and every other command gets an entry::
|
|
7
|
+
|
|
8
|
+
python3 setup/add_auto_mode_rule.py add --label X --rule-file r.txt -> rule step
|
|
9
|
+
git push -u origin claude/auto-mode-rule-own-push (allowed entry) -> rule step
|
|
10
|
+
git commit -m "Add the rule" (allowed entry, HEAD on a rule branch) -> rule step
|
|
11
|
+
cd ../other && python3 setup/add_auto_mode_rule.py add ... -> not a rule step
|
|
12
|
+
git push --all origin -> not a rule step
|
|
13
|
+
git -C agent-channels push -u origin claude/auto-mode-rule-own-push -> not a rule step
|
|
14
|
+
|
|
15
|
+
A command is a rule step only when all of these hold:
|
|
16
|
+
|
|
17
|
+
- The tool is Bash and the ``cwd`` is an absolute path.
|
|
18
|
+
- Every character of the command is in ``ALL_SAFE_COMMAND_CHARACTERS``:
|
|
19
|
+
ASCII letters, digits, a plain space, ``.``, ``_``, ``/``, ``:``, ``=``,
|
|
20
|
+
``-`` and quotes. Braces, globs, tabs and every shell operator fail.
|
|
21
|
+
- Its shell words match one row of ``ALL_ACCEPTED_SHAPES`` exactly.
|
|
22
|
+
- The ``cwd``, after ``os.path.realpath``, is the rule repository root, or a
|
|
23
|
+
linked worktree of it: its ``.git`` is a plain file, not a symbolic link,
|
|
24
|
+
that leads through ``commondir`` to the root's ``.git``, and the
|
|
25
|
+
worktree's ``gitdir`` file points back to that same ``.git`` file.
|
|
26
|
+
- A git row also needs an allowed entry in the session's ledger, and the
|
|
27
|
+
commit row needs that folder's ``HEAD`` on a branch that matches
|
|
28
|
+
``RULE_BRANCH_PATTERN`` in full.
|
|
29
|
+
|
|
30
|
+
A command that does not split into words, or a git file that cannot be read,
|
|
31
|
+
counts as not a rule step.
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
from __future__ import annotations
|
|
35
|
+
|
|
36
|
+
import os
|
|
37
|
+
import re
|
|
38
|
+
import shlex
|
|
39
|
+
from dataclasses import dataclass
|
|
40
|
+
from pathlib import Path
|
|
41
|
+
|
|
42
|
+
from hooks_constants.auto_mode_rule_steps_constants import (
|
|
43
|
+
ALL_ACCEPTED_SHAPES,
|
|
44
|
+
ALL_SAFE_COMMAND_CHARACTERS,
|
|
45
|
+
ANY_WORDS_TAIL,
|
|
46
|
+
BASH_TOOL_NAME,
|
|
47
|
+
COMMON_DIRECTORY_FILE_NAME,
|
|
48
|
+
GIT_DIRECTORY_NAME,
|
|
49
|
+
GIT_FILE_PREFIX,
|
|
50
|
+
GITDIR_FILE_NAME,
|
|
51
|
+
HEAD_FILE_NAME,
|
|
52
|
+
HEAD_REF_PREFIX,
|
|
53
|
+
ONE_WORD_TAIL,
|
|
54
|
+
RULE_BRANCH_PATTERN,
|
|
55
|
+
TEXT_ENCODING,
|
|
56
|
+
AcceptedShape,
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
@dataclass(frozen=True)
|
|
61
|
+
class RuleFlowSetting:
|
|
62
|
+
"""What the skip rule needs to know about the session.
|
|
63
|
+
|
|
64
|
+
Attributes:
|
|
65
|
+
repository_root: The agent-channels checkout that holds the playbook.
|
|
66
|
+
has_allowed_entry: Whether the session's ledger holds an allowed entry.
|
|
67
|
+
"""
|
|
68
|
+
|
|
69
|
+
repository_root: Path
|
|
70
|
+
has_allowed_entry: bool
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _command_words(command: str) -> list[str] | None:
|
|
74
|
+
if not ALL_SAFE_COMMAND_CHARACTERS.issuperset(command):
|
|
75
|
+
return None
|
|
76
|
+
try:
|
|
77
|
+
return shlex.split(command)
|
|
78
|
+
except ValueError:
|
|
79
|
+
return None
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _is_rule_branch(branch_name: str | None) -> bool:
|
|
83
|
+
return branch_name is not None and re.fullmatch(RULE_BRANCH_PATTERN, branch_name) is not None
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _tail_matches(tail: str, all_tail_words: list[str]) -> bool:
|
|
87
|
+
if tail == ANY_WORDS_TAIL:
|
|
88
|
+
return True
|
|
89
|
+
if len(all_tail_words) != 1:
|
|
90
|
+
return False
|
|
91
|
+
return tail == ONE_WORD_TAIL or _is_rule_branch(all_tail_words[0])
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _accepted_shape_of(all_words: list[str]) -> AcceptedShape | None:
|
|
95
|
+
return next(
|
|
96
|
+
(
|
|
97
|
+
each_shape
|
|
98
|
+
for each_shape in ALL_ACCEPTED_SHAPES
|
|
99
|
+
if tuple(all_words[: len(each_shape.leading_words)]) == each_shape.leading_words
|
|
100
|
+
and _tail_matches(each_shape.tail, all_words[len(each_shape.leading_words) :])
|
|
101
|
+
),
|
|
102
|
+
None,
|
|
103
|
+
)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _resolved_path(path: Path) -> Path:
|
|
107
|
+
return Path(os.path.realpath(path))
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _rule_git_directory_of(folder: Path, repository_root: Path) -> Path | None:
|
|
111
|
+
repository_git_directory = _resolved_path(repository_root / GIT_DIRECTORY_NAME)
|
|
112
|
+
if _resolved_path(folder) == _resolved_path(repository_root):
|
|
113
|
+
return repository_git_directory
|
|
114
|
+
git_file = _resolved_path(folder) / GIT_DIRECTORY_NAME
|
|
115
|
+
if not git_file.is_file():
|
|
116
|
+
return None
|
|
117
|
+
git_file_text = git_file.read_text(encoding=TEXT_ENCODING).strip()
|
|
118
|
+
if not git_file_text.startswith(GIT_FILE_PREFIX):
|
|
119
|
+
return None
|
|
120
|
+
linked_git_directory = _resolved_path(folder / git_file_text[len(GIT_FILE_PREFIX) :].strip())
|
|
121
|
+
common_directory_file = linked_git_directory / COMMON_DIRECTORY_FILE_NAME
|
|
122
|
+
if not common_directory_file.is_file():
|
|
123
|
+
return None
|
|
124
|
+
common_text = common_directory_file.read_text(encoding=TEXT_ENCODING).strip()
|
|
125
|
+
if _resolved_path(linked_git_directory / common_text) != repository_git_directory:
|
|
126
|
+
return None
|
|
127
|
+
back_pointer_file = linked_git_directory / GITDIR_FILE_NAME
|
|
128
|
+
if not back_pointer_file.is_file():
|
|
129
|
+
return None
|
|
130
|
+
back_pointer_text = back_pointer_file.read_text(encoding=TEXT_ENCODING).strip()
|
|
131
|
+
if _resolved_path(linked_git_directory / back_pointer_text) != git_file:
|
|
132
|
+
return None
|
|
133
|
+
return linked_git_directory
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _head_branch_of(git_directory: Path) -> str | None:
|
|
137
|
+
head_file = git_directory / HEAD_FILE_NAME
|
|
138
|
+
if not head_file.is_file():
|
|
139
|
+
return None
|
|
140
|
+
head_text = head_file.read_text(encoding=TEXT_ENCODING).strip()
|
|
141
|
+
return head_text[len(HEAD_REF_PREFIX) :] if head_text.startswith(HEAD_REF_PREFIX) else None
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _folder_fits(shape: AcceptedShape, folder: Path, repository_root: Path) -> bool:
|
|
145
|
+
try:
|
|
146
|
+
git_directory = _rule_git_directory_of(folder, repository_root)
|
|
147
|
+
if git_directory is None:
|
|
148
|
+
return False
|
|
149
|
+
return not shape.needs_rule_branch_head or _is_rule_branch(_head_branch_of(git_directory))
|
|
150
|
+
except (OSError, ValueError):
|
|
151
|
+
return False
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def is_rule_flow_step(
|
|
155
|
+
tool_name: str, tool_input: object, working_folder: str | None, setting: RuleFlowSetting
|
|
156
|
+
) -> bool:
|
|
157
|
+
"""Return whether a refused call is one of the rule flow's own steps.
|
|
158
|
+
|
|
159
|
+
Args:
|
|
160
|
+
tool_name: The refused call's tool name.
|
|
161
|
+
tool_input: The refused call's ``tool_input``.
|
|
162
|
+
working_folder: The ``cwd`` from the hook input, or None.
|
|
163
|
+
setting: The playbook's repository and the session's allowed state.
|
|
164
|
+
|
|
165
|
+
Returns:
|
|
166
|
+
Whether the call meets every condition the module docstring lists.
|
|
167
|
+
"""
|
|
168
|
+
command = tool_input.get("command") if isinstance(tool_input, dict) else None
|
|
169
|
+
if tool_name != BASH_TOOL_NAME or not isinstance(command, str):
|
|
170
|
+
return False
|
|
171
|
+
if not working_folder or not os.path.isabs(working_folder):
|
|
172
|
+
return False
|
|
173
|
+
all_words = _command_words(command)
|
|
174
|
+
shape = _accepted_shape_of(all_words) if all_words else None
|
|
175
|
+
if shape is None or (shape.needs_allowed_entry and not setting.has_allowed_entry):
|
|
176
|
+
return False
|
|
177
|
+
return _folder_fits(shape, Path(working_folder), setting.repository_root)
|