claude-dev-env 8.120.0 → 8.122.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.
Files changed (42) hide show
  1. package/bin/ever-registered-hooks.mjs +2 -0
  2. package/docs/rule-guides/question-presentation.md +4 -0
  3. package/hooks/advisory/auto_mode_denial_quick_fix.py +275 -27
  4. package/hooks/advisory/auto_mode_rule_flow_eval/auto_mode_rule_flow_cases.json +3475 -0
  5. package/hooks/advisory/auto_mode_rule_flow_eval/auto_mode_rule_flow_runner.py +849 -0
  6. package/hooks/advisory/auto_mode_rule_flow_eval/stub_allow_hook.py +20 -0
  7. package/hooks/advisory/auto_mode_rule_flow_eval/stub_hold_hook.py +54 -0
  8. package/hooks/advisory/auto_mode_rule_flow_eval/test_auto_mode_rule_flow_runner.py +143 -0
  9. package/hooks/advisory/test_auto_mode_denial_quick_fix.py +533 -9
  10. package/hooks/auto_mode_question_transcript.py +215 -0
  11. package/hooks/auto_mode_refusal_ledger.py +481 -0
  12. package/hooks/auto_mode_refusal_ledger_files.py +336 -0
  13. package/hooks/auto_mode_rule_steps.py +177 -0
  14. package/hooks/blocking/auto_mode_refusal_stop_gate.py +384 -0
  15. package/hooks/blocking/sent_file_question_detector.py +340 -0
  16. package/hooks/blocking/sent_file_question_gate.py +307 -0
  17. package/hooks/blocking/sent_file_scan.py +209 -0
  18. package/hooks/blocking/test_auto_mode_refusal_stop_gate.py +484 -0
  19. package/hooks/blocking/test_sent_file_question_detector.py +68 -0
  20. package/hooks/blocking/test_sent_file_question_gate.py +688 -0
  21. package/hooks/blocking/test_sent_file_scan.py +71 -0
  22. package/hooks/blocking/test_user_step_wording.py +46 -0
  23. package/hooks/blocking/user_step_wording.py +113 -15
  24. package/hooks/features/README.md +1 -1
  25. package/hooks/features/conduct-gates.md +3 -0
  26. package/hooks/features/session-context.md +5 -2
  27. package/hooks/hooks.json +15 -0
  28. package/hooks/hooks_constants/auto_mode_denial_quick_fix_constants.py +51 -3
  29. package/hooks/hooks_constants/auto_mode_refusal_ledger_constants.py +85 -0
  30. package/hooks/hooks_constants/auto_mode_refusal_stop_gate_constants.py +80 -0
  31. package/hooks/hooks_constants/auto_mode_rule_flow_runner_constants.py +225 -0
  32. package/hooks/hooks_constants/auto_mode_rule_steps_constants.py +82 -0
  33. package/hooks/hooks_constants/sent_file_question_gate_constants.py +261 -0
  34. package/hooks/hooks_constants/user_step_wording_constants.py +4 -0
  35. package/hooks/test_auto_mode_question_transcript.py +113 -0
  36. package/hooks/test_auto_mode_refusal_ledger.py +398 -0
  37. package/hooks/test_auto_mode_refusal_ledger_files.py +155 -0
  38. package/hooks/test_auto_mode_rule_steps.py +210 -0
  39. package/package.json +1 -1
  40. package/scripts/policy_lint/adapter_configuration.py +10 -0
  41. package/scripts/policy_lint/config/constants.py +2 -0
  42. package/scripts/tests/test_adapter_configuration.py +16 -0
@@ -0,0 +1,384 @@
1
+ #!/usr/bin/env python3
2
+ """Stop gate that holds a turn while a refused step waits on the user or on its rule.
3
+
4
+ At each turn end the gate reads the refusal ledger the PermissionDenied hook
5
+ keeps, and the session transcript::
6
+
7
+ flow switch off, playbook missing, or print mode -> turn ends, no output
8
+ answers read from transcript_path -> answered entries leave the queue
9
+ pending entry, not asked, held under 2 times -> question hold, 4 groups at most
10
+ allowed entry, no add call names it, held under 2 times -> rule hold
11
+ none left -> turn ends, no output
12
+ a transcript it cannot read -> no calls seen, holds as above
13
+ any other error -> turn ends, no output
14
+ reader closed stdout before the hold -> exit 0, the hold text is dropped
15
+
16
+ An entry counts as asked once an answered ``AskUserQuestion`` call at or after
17
+ a question record's ``transcript_offset`` asks that record's exact text, with
18
+ any answer, or once a decision card call claims it. A card call that did not
19
+ fail and carries the card question ``Should auto mode have refused this <tool>
20
+ step?`` claims the oldest pending, unasked group of that tool that has an
21
+ entry with a question record at or before the card, and within it those
22
+ entries. Each card claims one
23
+ group, and the entry keeps the card's offset so a later Stop does not claim
24
+ again with it. The asked mark stays on the entry. An add call
25
+ is a Bash call that did not fail whose command holds ``add_auto_mode_rule.py
26
+ add`` and the entry's id, which its ledger file name carries. The gate keeps
27
+ its own counts in each entry file, so it acts the same whether or not
28
+ ``stop_hook_active`` is set, and an entry holds four turns at most. A hold
29
+ exits 2 with a block object, through ``hold_stop``.
30
+ """
31
+
32
+ from __future__ import annotations
33
+
34
+ import json
35
+ import os
36
+ import sys
37
+ from pathlib import Path
38
+
39
+ _hooks_root_directory = str(Path(__file__).resolve().parent.parent)
40
+ if _hooks_root_directory not in sys.path:
41
+ sys.path.insert(0, _hooks_root_directory)
42
+
43
+ import auto_mode_refusal_ledger
44
+ from auto_mode_question_transcript import (
45
+ AskedQuestions,
46
+ TranscriptCall,
47
+ read_transcript,
48
+ )
49
+ from auto_mode_refusal_ledger_files import (
50
+ JsonObject,
51
+ LedgerEntry,
52
+ QuestionRecord,
53
+ entry_file_path,
54
+ )
55
+ from hooks_constants.auto_mode_refusal_ledger_constants import (
56
+ ALLOWED_ANSWER,
57
+ QUESTION_ASKED_FIELD,
58
+ QUESTION_CARD_OFFSET_FIELD,
59
+ QUESTION_HOLDS_FIELD,
60
+ RULE_HOLDS_FIELD,
61
+ )
62
+ from hooks_constants.auto_mode_refusal_stop_gate_constants import (
63
+ ALL_CARD_TOOL_NAMES,
64
+ ALLOW_EXIT_CODE,
65
+ BASH_TOOL_NAME,
66
+ CARD_QUESTION_TEMPLATE,
67
+ COMMAND_INPUT_KEY,
68
+ ENTRYPOINT_ENVIRONMENT_VARIABLE,
69
+ LIST_LINE_TEMPLATE,
70
+ MAXIMUM_HOLDS_PER_KIND,
71
+ MAXIMUM_QUESTIONS_PER_HOLD,
72
+ PRINT_MODE_ENTRYPOINT,
73
+ QUESTION_BLOCK_TEMPLATE,
74
+ QUESTION_SECTION_FOOTER_TEMPLATE,
75
+ QUESTION_SECTION_HEADER,
76
+ RULE_ADD_COMMAND_MARKER,
77
+ RULE_SECTION_HEADER_TEMPLATE,
78
+ SECTION_SEPARATOR,
79
+ STOP_EVENT_NAME,
80
+ )
81
+ from hooks_constants.hook_block_logger import log_hook_block
82
+ from hooks_constants.stop_hook_hold import hold_stop
83
+
84
+
85
+ def _all_text_values(tool_input: object) -> list[str]:
86
+ if isinstance(tool_input, str):
87
+ return [tool_input]
88
+ if isinstance(tool_input, dict):
89
+ return [each for each_value in tool_input.values() for each in _all_text_values(each_value)]
90
+ if isinstance(tool_input, list):
91
+ return [each for each_value in tool_input for each in _all_text_values(each_value)]
92
+ return []
93
+
94
+
95
+ def _is_card_for(call: TranscriptCall, tool_name: str) -> bool:
96
+ return (
97
+ call.tool_name in ALL_CARD_TOOL_NAMES
98
+ and not call.is_error
99
+ and CARD_QUESTION_TEMPLATE.format(tool_name=tool_name) in _all_text_values(call.tool_input)
100
+ )
101
+
102
+
103
+ def _is_text_asked(record: QuestionRecord, all_asked: list[AskedQuestions]) -> bool:
104
+ return any(
105
+ each_asked.call_offset >= record.transcript_offset
106
+ and record.question in each_asked.answer_by_question
107
+ for each_asked in all_asked
108
+ )
109
+
110
+
111
+ def _earliest_record_offset_by_id(all_records: list[QuestionRecord]) -> dict[str, int]:
112
+ offset_by_id: dict[str, int] = {}
113
+ for each_record in all_records:
114
+ for each_id in each_record.all_entry_ids:
115
+ offset_by_id[each_id] = min(
116
+ offset_by_id.get(each_id, each_record.transcript_offset),
117
+ each_record.transcript_offset,
118
+ )
119
+ return offset_by_id
120
+
121
+
122
+ def _card_offset_by_id(
123
+ all_unasked_entries: list[LedgerEntry],
124
+ all_records: list[QuestionRecord],
125
+ all_calls: list[TranscriptCall],
126
+ all_used_card_offsets: set[int | None],
127
+ ) -> dict[str, int]:
128
+ record_offset_by_id = _earliest_record_offset_by_id(all_records)
129
+ card_offset_by_id: dict[str, int] = {}
130
+ for each_call in all_calls:
131
+ if each_call.call_offset in all_used_card_offsets:
132
+ continue
133
+ for each_group in auto_mode_refusal_ledger.question_groups(
134
+ [each for each in all_unasked_entries if each.entry_id not in card_offset_by_id]
135
+ ):
136
+ all_card_ids = [
137
+ each_id
138
+ for each_id in each_group.all_entry_ids
139
+ if each_id in record_offset_by_id
140
+ and record_offset_by_id[each_id] <= each_call.call_offset
141
+ ]
142
+ if all_card_ids and _is_card_for(each_call, each_group.tool_name):
143
+ card_offset_by_id.update(dict.fromkeys(all_card_ids, each_call.call_offset))
144
+ break
145
+ return card_offset_by_id
146
+
147
+
148
+ def _asked_entry_ids(
149
+ ledger_directory: Path,
150
+ all_entries: list[LedgerEntry],
151
+ all_asked: list[AskedQuestions],
152
+ all_calls: list[TranscriptCall],
153
+ ) -> dict[str, int | None]:
154
+ all_known_ids = {each.entry_id for each in all_entries}
155
+ all_records = auto_mode_refusal_ledger.load_question_records(ledger_directory)
156
+ card_offset_by_id: dict[str, int | None] = {
157
+ each_id: None
158
+ for each_record in all_records
159
+ if _is_text_asked(each_record, all_asked)
160
+ for each_id in each_record.all_entry_ids
161
+ if each_id in all_known_ids
162
+ }
163
+ all_unasked_entries = [
164
+ each
165
+ for each in all_entries
166
+ if each.answer is None
167
+ and not each.is_question_asked
168
+ and each.entry_id not in card_offset_by_id
169
+ ]
170
+ card_offset_by_id.update(
171
+ _card_offset_by_id(
172
+ all_unasked_entries,
173
+ all_records,
174
+ all_calls,
175
+ {each.question_card_offset for each in all_entries},
176
+ )
177
+ )
178
+ return card_offset_by_id
179
+
180
+
181
+ def _has_add_call(entry: LedgerEntry, all_calls: list[TranscriptCall]) -> bool:
182
+ for each_call in all_calls:
183
+ if each_call.tool_name != BASH_TOOL_NAME or each_call.is_error:
184
+ continue
185
+ command = (
186
+ each_call.tool_input.get(COMMAND_INPUT_KEY)
187
+ if isinstance(each_call.tool_input, dict)
188
+ else None
189
+ )
190
+ if (
191
+ isinstance(command, str)
192
+ and RULE_ADD_COMMAND_MARKER in command
193
+ and entry.entry_id in command
194
+ ):
195
+ return True
196
+ return False
197
+
198
+
199
+ def _could_hold(entry: LedgerEntry) -> bool:
200
+ if entry.answer is None:
201
+ return entry.question_holds < MAXIMUM_HOLDS_PER_KIND and not entry.is_question_asked
202
+ return entry.answer == ALLOWED_ANSWER and entry.rule_holds < MAXIMUM_HOLDS_PER_KIND
203
+
204
+
205
+ def _ledger_lines(ledger_directory: Path, all_entry_ids: list[str]) -> str:
206
+ return "".join(
207
+ LIST_LINE_TEMPLATE.format(text=entry_file_path(ledger_directory, each_id))
208
+ for each_id in all_entry_ids
209
+ )
210
+
211
+
212
+ def hold_reason_for(
213
+ all_groups: list[auto_mode_refusal_ledger.QuestionGroup],
214
+ all_rule_entry_ids: list[str],
215
+ ledger_directory: Path,
216
+ playbook_path: Path,
217
+ ) -> str:
218
+ """Return the hold text for the questions to ask and the rules to add.
219
+
220
+ ::
221
+
222
+ one group, no rule entry -> header with the card question form,
223
+ "Question: ...", steps, the order after
224
+ Allow it, ledger files
225
+ no group, one rule entry -> the playbook path and the ledger file
226
+
227
+ Args:
228
+ all_groups: The question groups to ask, four at most.
229
+ all_rule_entry_ids: The allowed entries that still need a rule.
230
+ ledger_directory: One session's ledger folder.
231
+ playbook_path: The rule playbook the flow switch names.
232
+
233
+ Returns:
234
+ The question section, the rule section, or both.
235
+ """
236
+ all_sections: list[str] = []
237
+ if all_groups:
238
+ question_text = QUESTION_SECTION_HEADER
239
+ for each_group in all_groups:
240
+ question_text += QUESTION_BLOCK_TEMPLATE.format(question=each_group.question)
241
+ question_text += "".join(
242
+ LIST_LINE_TEMPLATE.format(text=each_summary)
243
+ for each_summary in each_group.all_action_summaries
244
+ )
245
+ question_text += QUESTION_SECTION_FOOTER_TEMPLATE.format(playbook_path=playbook_path)
246
+ question_text += _ledger_lines(
247
+ ledger_directory,
248
+ [each_id for each_group in all_groups for each_id in each_group.all_entry_ids],
249
+ )
250
+ all_sections.append(question_text)
251
+ if all_rule_entry_ids:
252
+ all_sections.append(
253
+ RULE_SECTION_HEADER_TEMPLATE.format(playbook_path=playbook_path)
254
+ + _ledger_lines(ledger_directory, all_rule_entry_ids)
255
+ )
256
+ return SECTION_SEPARATOR.join(all_sections)
257
+
258
+
259
+ def _flow_folders(all_stop_fields: dict[str, object]) -> tuple[Path, Path] | None:
260
+ if os.environ.get(ENTRYPOINT_ENVIRONMENT_VARIABLE) == PRINT_MODE_ENTRYPOINT:
261
+ return None
262
+ playbook_path = auto_mode_refusal_ledger.playbook_path_from_environment()
263
+ session_id = all_stop_fields.get("session_id")
264
+ if playbook_path is None or not isinstance(session_id, str) or not session_id:
265
+ return None
266
+ ledger_directory = auto_mode_refusal_ledger.ledger_directory_for(session_id)
267
+ if not ledger_directory.is_dir():
268
+ return None
269
+ return playbook_path, ledger_directory
270
+
271
+
272
+ def _counted_fields(
273
+ all_entries: list[LedgerEntry],
274
+ all_card_offset_by_asked_id: dict[str, int | None],
275
+ all_groups: list[auto_mode_refusal_ledger.QuestionGroup],
276
+ all_rule_entries: list[LedgerEntry],
277
+ ) -> dict[str, JsonObject]:
278
+ entry_by_id = {each.entry_id: each for each in all_entries}
279
+ fields_by_entry_id: dict[str, JsonObject] = {
280
+ each.entry_id: {QUESTION_ASKED_FIELD: True}
281
+ for each in all_entries
282
+ if each.entry_id in all_card_offset_by_asked_id and not each.is_question_asked
283
+ }
284
+ for each_id, each_card_offset in all_card_offset_by_asked_id.items():
285
+ if each_card_offset is not None:
286
+ fields_by_entry_id[each_id][QUESTION_CARD_OFFSET_FIELD] = each_card_offset
287
+ for each_id in (each for each_group in all_groups for each in each_group.all_entry_ids):
288
+ fields_by_entry_id.setdefault(each_id, {})[QUESTION_HOLDS_FIELD] = (
289
+ entry_by_id[each_id].question_holds + 1
290
+ )
291
+ for each_entry in all_rule_entries:
292
+ fields_by_entry_id.setdefault(each_entry.entry_id, {})[RULE_HOLDS_FIELD] = (
293
+ each_entry.rule_holds + 1
294
+ )
295
+ return fields_by_entry_id
296
+
297
+
298
+ def _entries_to_hold(
299
+ all_entries: list[LedgerEntry],
300
+ all_asked_ids: dict[str, int | None],
301
+ all_calls: list[TranscriptCall],
302
+ ) -> tuple[list[auto_mode_refusal_ledger.QuestionGroup], list[LedgerEntry]]:
303
+ all_groups = auto_mode_refusal_ledger.question_groups(
304
+ [
305
+ each
306
+ for each in all_entries
307
+ if each.answer is None and _could_hold(each) and each.entry_id not in all_asked_ids
308
+ ]
309
+ )[:MAXIMUM_QUESTIONS_PER_HOLD]
310
+ all_rule_entries = [
311
+ each
312
+ for each in all_entries
313
+ if each.answer == ALLOWED_ANSWER and _could_hold(each) and not _has_add_call(each, all_calls)
314
+ ]
315
+ return all_groups, all_rule_entries
316
+
317
+
318
+ def hold_reason_for_stop(all_stop_fields: dict[str, object]) -> str | None:
319
+ """Return the hold text for one Stop payload, and record the hold in the ledger.
320
+
321
+ Args:
322
+ all_stop_fields: The Stop hook input JSON.
323
+
324
+ Returns:
325
+ The hold text, or None to let the turn end.
326
+ """
327
+ flow_folders = _flow_folders(all_stop_fields)
328
+ if flow_folders is None:
329
+ return None
330
+ playbook_path, ledger_directory = flow_folders
331
+ raw_transcript_path = all_stop_fields.get("transcript_path")
332
+ transcript_path = Path(raw_transcript_path) if isinstance(raw_transcript_path, str) else None
333
+ all_entries = auto_mode_refusal_ledger.load_entries(ledger_directory)
334
+ if not any(each.answer is None or _could_hold(each) for each in all_entries):
335
+ return None
336
+ transcript_reading = read_transcript(transcript_path)
337
+ auto_mode_refusal_ledger.apply_asked_answers(ledger_directory, transcript_reading.all_asked)
338
+ all_entries = auto_mode_refusal_ledger.load_entries(ledger_directory)
339
+ if not any(_could_hold(each) for each in all_entries):
340
+ return None
341
+ all_calls = transcript_reading.all_calls
342
+ all_asked_ids = _asked_entry_ids(
343
+ ledger_directory, all_entries, transcript_reading.all_asked, all_calls
344
+ )
345
+ all_groups, all_rule_entries = _entries_to_hold(all_entries, all_asked_ids, all_calls)
346
+ if all_groups:
347
+ auto_mode_refusal_ledger.write_question_records(
348
+ ledger_directory, all_groups, transcript_path
349
+ )
350
+ auto_mode_refusal_ledger.merge_entry_fields(
351
+ ledger_directory, _counted_fields(all_entries, all_asked_ids, all_groups, all_rule_entries)
352
+ )
353
+ if not all_groups and not all_rule_entries:
354
+ return None
355
+ return hold_reason_for(
356
+ all_groups, [each.entry_id for each in all_rule_entries], ledger_directory, playbook_path
357
+ )
358
+
359
+
360
+ def main() -> int:
361
+ try:
362
+ payload = json.load(sys.stdin)
363
+ except (json.JSONDecodeError, ValueError):
364
+ return ALLOW_EXIT_CODE
365
+ if not isinstance(payload, dict):
366
+ return ALLOW_EXIT_CODE
367
+ try:
368
+ hold_reason = hold_reason_for_stop(payload)
369
+ except Exception:
370
+ return ALLOW_EXIT_CODE
371
+ if hold_reason is None:
372
+ return ALLOW_EXIT_CODE
373
+ log_hook_block(Path(__file__).name, STOP_EVENT_NAME, hold_reason)
374
+ try:
375
+ exit_code = hold_stop(payload, hold_reason)
376
+ sys.stdout.flush()
377
+ except OSError:
378
+ os.dup2(os.open(os.devnull, os.O_WRONLY), sys.stdout.fileno())
379
+ return ALLOW_EXIT_CODE
380
+ return exit_code
381
+
382
+
383
+ if __name__ == "__main__":
384
+ raise SystemExit(main())