claude-dev-env 8.122.0 → 8.123.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/hooks/blocking/closing_question_round_gate.py +387 -0
- package/hooks/blocking/closing_question_round_lines.py +109 -0
- package/hooks/blocking/closing_question_round_open_items.py +348 -0
- package/hooks/blocking/closing_question_round_transcript.py +344 -0
- package/hooks/blocking/test_closing_question_round_gate.py +983 -0
- package/hooks/blocking/test_closing_question_round_gate_declaration.py +307 -0
- package/hooks/blocking/test_closing_question_round_gate_work.py +349 -0
- package/hooks/blocking/test_closing_question_round_lines.py +70 -0
- package/hooks/blocking/test_closing_question_round_open_items.py +238 -0
- package/hooks/blocking/test_closing_question_round_transcript.py +236 -0
- package/hooks/hooks_constants/closing_question_round_gate_constants.py +167 -0
- package/hooks/hooks_constants/test_closing_question_round_gate_constants.py +92 -0
- package/package.json +1 -1
|
@@ -0,0 +1,348 @@
|
|
|
1
|
+
"""Find the open-item lines and the declaration line in the texts the closing question round gate reads.
|
|
2
|
+
|
|
3
|
+
An open-item line comes from a text block of an assistant record in the
|
|
4
|
+
stretch, or from the closing reply. Fences, HTML blocks, quoted paragraphs,
|
|
5
|
+
and code spans are left out first, as
|
|
6
|
+
``final_reply_gate.prose_paragraphs_with_code_as`` does, and indented code
|
|
7
|
+
blocks before that. Each paragraph is matched with its single line breaks
|
|
8
|
+
folded to spaces, so "out of" at a line end and "scope" on the next line is
|
|
9
|
+
one marker. The line, or the lines joined by a space, that a marker spans is
|
|
10
|
+
quoted. A line that ends with a question mark, after trailing markup, is an
|
|
11
|
+
open-item line too. The markers, read with case folding and as whole words::
|
|
12
|
+
|
|
13
|
+
deferred, defer, defers, deferring, deferral, deferrals
|
|
14
|
+
follow-up, followup, and their plurals
|
|
15
|
+
a, the, another, or one, then "follow up" or "follow ups"
|
|
16
|
+
"follow up", then pr, pull request, issue, task, ticket, change, or commit
|
|
17
|
+
parked, out of scope or out-of-scope, not covered, for later
|
|
18
|
+
later pull request, later pr, separate pr, separate pull request
|
|
19
|
+
known gap, known limitation, and their plurals
|
|
20
|
+
open question, open questions
|
|
21
|
+
unresolved, uncertain, uncertainty, not sure, unsure, unclear
|
|
22
|
+
I assumed, we assumed, I assume, we assume, assuming, assumption,
|
|
23
|
+
assumptions
|
|
24
|
+
unverified, could not verify, couldn't verify, did not verify
|
|
25
|
+
untested, not tested, didn't test, did not test
|
|
26
|
+
could not confirm, couldn't confirm, unable to confirm
|
|
27
|
+
not yet implemented
|
|
28
|
+
judgment call, judgement call, and their plurals
|
|
29
|
+
your call, up to you, you may want to, your judgment, your judgement
|
|
30
|
+
needs your decision, judgment, judgement, or approval
|
|
31
|
+
need your input, needs your input, I need you to
|
|
32
|
+
pending, TODO, TBD, skipped, skipping, not done, blocked
|
|
33
|
+
not run, didn't run, could not reproduce, couldn't reproduce
|
|
34
|
+
left it, this, that, them, or these, then "for you"
|
|
35
|
+
for you to decide, waiting on you, waits on you
|
|
36
|
+
|
|
37
|
+
A straight or a curly apostrophe reads the same. The verb in "I will follow
|
|
38
|
+
up with the build" is no marker. A negation does not cancel a marker, so
|
|
39
|
+
"Nothing is deferred." is held; a wrong hold costs one card.
|
|
40
|
+
|
|
41
|
+
An indented code block is a run of lines indented by four spaces or a tab
|
|
42
|
+
that starts after a blank line, or at the start of the text, outside a list
|
|
43
|
+
item. A list item runs from its marker line until a line at the left margin
|
|
44
|
+
starts a paragraph after a blank line, so an indented paragraph inside it is
|
|
45
|
+
read as prose. Its lines read as blank. A text over 2 MiB is skipped.
|
|
46
|
+
Before matching, each run of two or more spaces, line breaks, or hyphens
|
|
47
|
+
reads as one character: a hyphen for a run of hyphens alone, a space for any
|
|
48
|
+
other run. No marker match is then longer than 128 characters. A paragraph
|
|
49
|
+
is matched in windows of 1 Mi characters that overlap by 128, so the clock
|
|
50
|
+
is read between windows. Each window also reads the 4 characters after it,
|
|
51
|
+
so the whole-word check sees past the window's end. A match that ends at the
|
|
52
|
+
end of a window before the paragraph's end is dropped, and the next window
|
|
53
|
+
reads it whole. A marker reads as a whole word, and one to three underscores
|
|
54
|
+
around it count as emphasis, so ``_untested_`` and ``__untested__`` are
|
|
55
|
+
markers, and ``retry_untested_flag`` and ``retry__untested__flag`` are none.
|
|
56
|
+
A marker inside a file name with a lower-case extension of 1 to 5 letters
|
|
57
|
+
or digits, such as ``todo.md``, or inside a path of two or more names that
|
|
58
|
+
ends in a slash or such a file name, such as ``docs/pending/``, is none
|
|
59
|
+
either. A marker joined to another word, such as ``skipped/untested``, still
|
|
60
|
+
counts, and so do a marker of two or more words and a path that reaches
|
|
61
|
+
more than 96 characters past the marker on either side, each hyphen of a
|
|
62
|
+
run counted as written. Outer quotes, brackets, and emphasis marks around
|
|
63
|
+
the word are stripped first.
|
|
64
|
+
"""
|
|
65
|
+
|
|
66
|
+
from __future__ import annotations
|
|
67
|
+
|
|
68
|
+
import bisect
|
|
69
|
+
import itertools
|
|
70
|
+
import sys
|
|
71
|
+
from collections.abc import Iterator
|
|
72
|
+
from pathlib import Path
|
|
73
|
+
|
|
74
|
+
hooks_root_directory = str(Path(__file__).resolve().parent.parent)
|
|
75
|
+
if hooks_root_directory not in sys.path:
|
|
76
|
+
sys.path.insert(0, hooks_root_directory)
|
|
77
|
+
blocking_directory = str(Path(__file__).resolve().parent)
|
|
78
|
+
if blocking_directory not in sys.path:
|
|
79
|
+
sys.path.insert(0, blocking_directory)
|
|
80
|
+
|
|
81
|
+
from closing_question_round_lines import before_deadline, is_within_scan_cap
|
|
82
|
+
from final_reply_gate import prose_paragraphs_with_code_as
|
|
83
|
+
from hooks_constants.closing_question_round_gate_constants import (
|
|
84
|
+
DECLARATION_LINE_PATTERN,
|
|
85
|
+
FILE_NAME_PATTERN,
|
|
86
|
+
INDENTED_CODE_LINE_PATTERN,
|
|
87
|
+
LIST_ITEM_LINE_PATTERN,
|
|
88
|
+
MINIMUM_PATH_SEGMENT_COUNT,
|
|
89
|
+
HYPHEN_CHARACTER,
|
|
90
|
+
MARKER_SCAN_LOOKAHEAD_CHARACTERS,
|
|
91
|
+
MARKER_SCAN_OVERLAP_CHARACTERS,
|
|
92
|
+
MARKER_SCAN_WINDOW_CHARACTERS,
|
|
93
|
+
OPEN_ITEM_MARKER_PATTERN,
|
|
94
|
+
PATH_JOINING_CHARACTERS,
|
|
95
|
+
PATH_SEPARATOR_PATTERN,
|
|
96
|
+
PATH_EDGE_CHARACTERS,
|
|
97
|
+
PATH_REACH_CHARACTERS,
|
|
98
|
+
PATH_BREAK_PATTERN,
|
|
99
|
+
SEPARATOR_RUN_PATTERN,
|
|
100
|
+
)
|
|
101
|
+
from hooks_constants.final_reply_gate_constants import QUESTION_MARK, TRAILING_MARKUP_CHARACTERS
|
|
102
|
+
from hooks_constants.open_tasks_stop_gate_constants import WORD_SEPARATOR
|
|
103
|
+
from hooks_constants.user_step_wording_constants import CODE_SPAN_STAND_IN, LINE_BREAK
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _is_list_context(each_line: str, was_list_context: bool, previous_line: str) -> bool:
|
|
107
|
+
if LIST_ITEM_LINE_PATTERN.match(each_line):
|
|
108
|
+
return True
|
|
109
|
+
starts_a_paragraph = bool(each_line.strip()) and not previous_line.strip()
|
|
110
|
+
return was_list_context and not (starts_a_paragraph and each_line == each_line.lstrip())
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def indented_code_masked(reply_text: str, deadline_at: float) -> str:
|
|
114
|
+
"""Return the text with each line of an indented code block read as blank.
|
|
115
|
+
|
|
116
|
+
::
|
|
117
|
+
|
|
118
|
+
"Run this:\\n\\n retry --deferred\\n\\nDone." -> "Run this:\\n\\n\\n\\nDone."
|
|
119
|
+
"- Item\\n\\n The retry is untested." -> unchanged, a list continuation
|
|
120
|
+
"One line\\n more deferred text" -> unchanged, no blank line before it
|
|
121
|
+
|
|
122
|
+
A block starts at a line indented by four spaces or a tab after a blank
|
|
123
|
+
line or the text start, outside a list, and runs over indented and blank
|
|
124
|
+
lines. The clock is read before each line, and TimeoutError is raised
|
|
125
|
+
once it reaches ``deadline_at``.
|
|
126
|
+
"""
|
|
127
|
+
all_kept_lines: list[str] = []
|
|
128
|
+
is_list_context = False
|
|
129
|
+
is_inside_code = False
|
|
130
|
+
previous_line = ""
|
|
131
|
+
for each_line in before_deadline(reply_text.split(LINE_BREAK), deadline_at):
|
|
132
|
+
is_indented = bool(INDENTED_CODE_LINE_PATTERN.match(each_line))
|
|
133
|
+
is_blank = not each_line.strip()
|
|
134
|
+
if is_inside_code:
|
|
135
|
+
is_inside_code = is_indented or is_blank
|
|
136
|
+
else:
|
|
137
|
+
is_inside_code = is_indented and not previous_line.strip() and not is_list_context
|
|
138
|
+
is_list_context = _is_list_context(each_line, is_list_context, previous_line)
|
|
139
|
+
all_kept_lines.append("" if is_inside_code else each_line)
|
|
140
|
+
previous_line = each_line
|
|
141
|
+
return LINE_BREAK.join(all_kept_lines)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _collapsed_separators(
|
|
145
|
+
folded_text: str, deadline_at: float
|
|
146
|
+
) -> tuple[str, list[int], list[int]]:
|
|
147
|
+
all_parts: list[str] = []
|
|
148
|
+
all_collapsed_offsets: list[int] = []
|
|
149
|
+
all_original_offsets: list[int] = []
|
|
150
|
+
collapsed_length = 0
|
|
151
|
+
copied_until = 0
|
|
152
|
+
all_runs = SEPARATOR_RUN_PATTERN.finditer(folded_text)
|
|
153
|
+
for each_run in before_deadline(all_runs, deadline_at):
|
|
154
|
+
is_hyphen_run = not each_run.group().strip(HYPHEN_CHARACTER)
|
|
155
|
+
all_parts.append(folded_text[copied_until : each_run.start()])
|
|
156
|
+
collapsed_length += each_run.start() - copied_until
|
|
157
|
+
all_parts.append(HYPHEN_CHARACTER if is_hyphen_run else WORD_SEPARATOR)
|
|
158
|
+
all_collapsed_offsets.extend((collapsed_length, collapsed_length + 1))
|
|
159
|
+
all_original_offsets.extend((each_run.start(), each_run.end()))
|
|
160
|
+
collapsed_length += 1
|
|
161
|
+
copied_until = each_run.end()
|
|
162
|
+
all_parts.append(folded_text[copied_until:])
|
|
163
|
+
return "".join(all_parts), all_collapsed_offsets, all_original_offsets
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _original_position(
|
|
167
|
+
collapsed_position: int, all_collapsed_offsets: list[int], all_original_offsets: list[int]
|
|
168
|
+
) -> int:
|
|
169
|
+
offset_index = bisect.bisect_right(all_collapsed_offsets, collapsed_position) - 1
|
|
170
|
+
if offset_index < 0:
|
|
171
|
+
return collapsed_position
|
|
172
|
+
return all_original_offsets[offset_index] + collapsed_position - all_collapsed_offsets[offset_index]
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _word_parts_around(text: str, marker_start: int, marker_end: int) -> tuple[str, str] | None:
|
|
176
|
+
leading_part = PATH_BREAK_PATTERN.split(
|
|
177
|
+
text[max(marker_start - PATH_REACH_CHARACTERS - 1, 0) : marker_start]
|
|
178
|
+
)[-1]
|
|
179
|
+
trailing_part = PATH_BREAK_PATTERN.split(
|
|
180
|
+
text[marker_end : marker_end + PATH_REACH_CHARACTERS + 1]
|
|
181
|
+
)[0]
|
|
182
|
+
if max(len(leading_part), len(trailing_part)) > PATH_REACH_CHARACTERS:
|
|
183
|
+
return None
|
|
184
|
+
return leading_part, trailing_part
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def _has_path_shape(path_text: str, marker_offset_end: int) -> bool:
|
|
188
|
+
all_segments = PATH_SEPARATOR_PATTERN.split(path_text)
|
|
189
|
+
file_name_match = FILE_NAME_PATTERN.fullmatch(all_segments[-1])
|
|
190
|
+
if file_name_match is not None:
|
|
191
|
+
return marker_offset_end <= len(path_text) - len(file_name_match["extension"]) - 1
|
|
192
|
+
has_directory_shape = len(all_segments) > 1 and not all_segments[-1]
|
|
193
|
+
named_segment_count = sum(1 for each_segment in all_segments if each_segment)
|
|
194
|
+
return has_directory_shape and named_segment_count >= MINIMUM_PATH_SEGMENT_COUNT
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def _is_inside_a_path(text: str, marker_start: int, marker_end: int) -> bool:
|
|
198
|
+
neighbor_text = text[max(marker_start - 1, 0) : marker_start] + text[marker_end : marker_end + 1]
|
|
199
|
+
if not any(each_character in PATH_JOINING_CHARACTERS for each_character in neighbor_text):
|
|
200
|
+
return False
|
|
201
|
+
if PATH_BREAK_PATTERN.search(text, marker_start, marker_end):
|
|
202
|
+
return False
|
|
203
|
+
word_parts = _word_parts_around(text, marker_start, marker_end)
|
|
204
|
+
if word_parts is None:
|
|
205
|
+
return False
|
|
206
|
+
leading_part, trailing_part = word_parts
|
|
207
|
+
left_stripped_word = (leading_part + text[marker_start:marker_end] + trailing_part).lstrip(
|
|
208
|
+
PATH_EDGE_CHARACTERS
|
|
209
|
+
)
|
|
210
|
+
path_text = left_stripped_word.rstrip(PATH_EDGE_CHARACTERS)
|
|
211
|
+
marker_offset_end = len(left_stripped_word) - len(trailing_part)
|
|
212
|
+
return marker_offset_end <= len(path_text) and _has_path_shape(path_text, marker_offset_end)
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def _collapsed_marker_spans(collapsed_text: str, deadline_at: float) -> Iterator[tuple[int, int]]:
|
|
216
|
+
all_window_starts = range(0, max(len(collapsed_text), 1), MARKER_SCAN_WINDOW_CHARACTERS)
|
|
217
|
+
for each_window_start in before_deadline(all_window_starts, deadline_at):
|
|
218
|
+
window_end = each_window_start + MARKER_SCAN_WINDOW_CHARACTERS + MARKER_SCAN_OVERLAP_CHARACTERS
|
|
219
|
+
scan_end = window_end + MARKER_SCAN_LOOKAHEAD_CHARACTERS
|
|
220
|
+
all_window_matches = OPEN_ITEM_MARKER_PATTERN.finditer(
|
|
221
|
+
collapsed_text, each_window_start, scan_end
|
|
222
|
+
)
|
|
223
|
+
yield from (
|
|
224
|
+
each_match.span()
|
|
225
|
+
for each_match in all_window_matches
|
|
226
|
+
if each_match.end() < window_end or scan_end >= len(collapsed_text)
|
|
227
|
+
)
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def _marker_spans(folded_text: str, deadline_at: float) -> Iterator[tuple[int, int]]:
|
|
231
|
+
collapsed_text, all_collapsed_offsets, all_original_offsets = _collapsed_separators(
|
|
232
|
+
folded_text, deadline_at
|
|
233
|
+
)
|
|
234
|
+
for each_marker_start, each_marker_end in _collapsed_marker_spans(collapsed_text, deadline_at):
|
|
235
|
+
original_start = _original_position(
|
|
236
|
+
each_marker_start, all_collapsed_offsets, all_original_offsets
|
|
237
|
+
)
|
|
238
|
+
original_end = (
|
|
239
|
+
_original_position(each_marker_end - 1, all_collapsed_offsets, all_original_offsets) + 1
|
|
240
|
+
)
|
|
241
|
+
if not _is_inside_a_path(folded_text, original_start, original_end):
|
|
242
|
+
yield original_start, original_end
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def _paragraph_quotes(paragraph_text: str, deadline_at: float) -> list[str]:
|
|
246
|
+
all_lines = paragraph_text.split(LINE_BREAK)
|
|
247
|
+
all_line_starts = list(
|
|
248
|
+
itertools.accumulate((len(each_line) + 1 for each_line in all_lines[:-1]), initial=0)
|
|
249
|
+
)
|
|
250
|
+
folded_text = paragraph_text.replace(LINE_BREAK, WORD_SEPARATOR)
|
|
251
|
+
all_line_ranges = {
|
|
252
|
+
(
|
|
253
|
+
bisect.bisect_right(all_line_starts, marker_start) - 1,
|
|
254
|
+
bisect.bisect_right(all_line_starts, marker_end - 1) - 1,
|
|
255
|
+
)
|
|
256
|
+
for marker_start, marker_end in _marker_spans(folded_text, deadline_at)
|
|
257
|
+
}
|
|
258
|
+
all_line_ranges.update(
|
|
259
|
+
(each_position, each_position)
|
|
260
|
+
for each_position, each_line in enumerate(before_deadline(all_lines, deadline_at))
|
|
261
|
+
if each_line.rstrip(TRAILING_MARKUP_CHARACTERS).endswith(QUESTION_MARK)
|
|
262
|
+
)
|
|
263
|
+
return [
|
|
264
|
+
WORD_SEPARATOR.join(each_line.strip() for each_line in all_lines[first : last + 1])
|
|
265
|
+
for first, last in sorted(all_line_ranges)
|
|
266
|
+
]
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
def _prose_paragraphs(reply_text: str, deadline_at: float) -> list[str]:
|
|
270
|
+
return prose_paragraphs_with_code_as(
|
|
271
|
+
indented_code_masked(reply_text, deadline_at), CODE_SPAN_STAND_IN
|
|
272
|
+
)
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def _marked_lines(reply_text: str, deadline_at: float) -> list[str]:
|
|
276
|
+
return [
|
|
277
|
+
each_quote
|
|
278
|
+
for each_paragraph in before_deadline(
|
|
279
|
+
_prose_paragraphs(reply_text, deadline_at), deadline_at
|
|
280
|
+
)
|
|
281
|
+
for each_quote in _paragraph_quotes(each_paragraph, deadline_at)
|
|
282
|
+
]
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def marked_open_lines(all_assistant_texts: list[str], deadline_at: float) -> list[str]:
|
|
286
|
+
"""Return each open-item line of the assistant texts, once, in order.
|
|
287
|
+
|
|
288
|
+
::
|
|
289
|
+
|
|
290
|
+
"The flag is in place.\\nThe retry path is untested." -> ["The retry path is untested."]
|
|
291
|
+
"The cleanup is out of\\nscope." -> ["The cleanup is out of scope."]
|
|
292
|
+
"Should the cache hold 64 entries?" -> ["Should the cache hold 64 entries?"]
|
|
293
|
+
"Nothing is deferred." -> ["Nothing is deferred."]
|
|
294
|
+
"The status is `deferred`." -> []
|
|
295
|
+
|
|
296
|
+
A marker that spans a line break is quoted as its lines joined by a
|
|
297
|
+
space. Each code span in a returned line reads as U+FFFC. A text over 2
|
|
298
|
+
MiB is skipped.
|
|
299
|
+
|
|
300
|
+
Args:
|
|
301
|
+
all_assistant_texts: The assistant text blocks of the stretch, then the closing reply.
|
|
302
|
+
deadline_at: The monotonic clock reading at which the scan gives up.
|
|
303
|
+
|
|
304
|
+
Returns:
|
|
305
|
+
The open-item lines, without repeats.
|
|
306
|
+
|
|
307
|
+
Raises:
|
|
308
|
+
TimeoutError: The deadline passed before the scan ended, read before
|
|
309
|
+
each text, paragraph, line, and marker scan window.
|
|
310
|
+
"""
|
|
311
|
+
all_marked_lines = (
|
|
312
|
+
each_line
|
|
313
|
+
for each_text in before_deadline(all_assistant_texts, deadline_at)
|
|
314
|
+
if is_within_scan_cap(each_text)
|
|
315
|
+
for each_line in _marked_lines(each_text, deadline_at)
|
|
316
|
+
)
|
|
317
|
+
return list(dict.fromkeys(all_marked_lines))
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
def declares_no_open_items(closing_reply: str, deadline_at: float) -> bool:
|
|
321
|
+
"""Return True when the reply's last prose line is the declaration ``Open items: none.``.
|
|
322
|
+
|
|
323
|
+
::
|
|
324
|
+
|
|
325
|
+
"Both tests pass.\\n\\nOpen items: none." -> True
|
|
326
|
+
"Both tests pass.\\n\\n**Open items: none.**" -> True
|
|
327
|
+
"Open items: none.\\n\\nBoth tests pass." -> False
|
|
328
|
+
"`Open items: none.`" -> False, a code span
|
|
329
|
+
"- Open items: none." -> False, a list item
|
|
330
|
+
"Open items: none" -> True, no period
|
|
331
|
+
|
|
332
|
+
The reply is masked as ``marked_open_lines`` masks it. Its last non-empty
|
|
333
|
+
line, with outer spaces stripped, must be the declaration alone or the
|
|
334
|
+
declaration wrapped in one bold or italic mark. The final period may be
|
|
335
|
+
left out. A ``* `` list item does not
|
|
336
|
+
count. A reply over 2 MiB never declares. The masking
|
|
337
|
+
raises TimeoutError once the clock reaches ``deadline_at``.
|
|
338
|
+
"""
|
|
339
|
+
if not is_within_scan_cap(closing_reply):
|
|
340
|
+
return False
|
|
341
|
+
all_paragraphs = _prose_paragraphs(closing_reply, deadline_at)
|
|
342
|
+
if not all_paragraphs:
|
|
343
|
+
return False
|
|
344
|
+
all_lines = [
|
|
345
|
+
each_line for each_line in all_paragraphs[-1].split(LINE_BREAK) if each_line.strip()
|
|
346
|
+
]
|
|
347
|
+
last_line = all_lines[-1].strip() if all_lines else ""
|
|
348
|
+
return DECLARATION_LINE_PATTERN.fullmatch(last_line) is not None
|
|
@@ -0,0 +1,344 @@
|
|
|
1
|
+
"""Read the transcript stretch the closing question round gate checks.
|
|
2
|
+
|
|
3
|
+
The stretch is every top-level record after the last question card that
|
|
4
|
+
reached the user::
|
|
5
|
+
|
|
6
|
+
reply, AskUserQuestion, its answer, reply -> its answer, reply
|
|
7
|
+
reply, AskUserQuestion, its refusal -> all three
|
|
8
|
+
reply, reply -> reply, reply
|
|
9
|
+
|
|
10
|
+
The transcript is read as bytes, a line over 16 MiB reads as an empty line,
|
|
11
|
+
and a line is JSON-parsed only when a substring scan says it can matter:
|
|
12
|
+
``"turnOrigin"`` or ``"user"`` for prompts, a quoted question tool name for
|
|
13
|
+
question calls, ``"tool_result"`` with a pending call id for their results,
|
|
14
|
+
``"assistant"`` or a reason's first sentence for stretch records and for
|
|
15
|
+
the last assistant text.
|
|
16
|
+
|
|
17
|
+
A question tool is a name in ``ALL_QUESTION_TOOL_NAMES``. A call reached the
|
|
18
|
+
user when a later ``tool_result`` carries its ``tool_use_id`` and has no truthy
|
|
19
|
+
``is_error``. A refused call, an errored call, a call with no result yet, and
|
|
20
|
+
a call whose name is no string do not count. The stretch is the whole
|
|
21
|
+
transcript when no call reached the user, and it spans turns. A record flagged
|
|
22
|
+
``isSidechain`` is never read. Any other tool call in the stretch is work.
|
|
23
|
+
|
|
24
|
+
Claude Code runs Stop hooks before it writes the closing reply. The payload's
|
|
25
|
+
``last_assistant_message``, when it is a non-empty string, is read as the
|
|
26
|
+
newest text of the stretch, once when the transcript already ends with it.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
from __future__ import annotations
|
|
30
|
+
|
|
31
|
+
import os
|
|
32
|
+
import sys
|
|
33
|
+
from pathlib import Path
|
|
34
|
+
|
|
35
|
+
hooks_root_directory = str(Path(__file__).resolve().parent.parent)
|
|
36
|
+
if hooks_root_directory not in sys.path:
|
|
37
|
+
sys.path.insert(0, hooks_root_directory)
|
|
38
|
+
blocking_directory = str(Path(__file__).resolve().parent)
|
|
39
|
+
if blocking_directory not in sys.path:
|
|
40
|
+
sys.path.insert(0, blocking_directory)
|
|
41
|
+
|
|
42
|
+
from hooks_constants.closing_question_round_gate_constants import (
|
|
43
|
+
ALL_QUESTION_TOOL_NAME_SCAN_TEXTS,
|
|
44
|
+
ALL_REASON_LEADS,
|
|
45
|
+
ASSISTANT_SCAN_TEXT,
|
|
46
|
+
ATTENDED_SESSION_TEXT,
|
|
47
|
+
HUMAN_TURN_ORIGIN,
|
|
48
|
+
IS_ERROR_KEY,
|
|
49
|
+
IS_SIDECHAIN_KEY,
|
|
50
|
+
LAST_ASSISTANT_MESSAGE_KEY,
|
|
51
|
+
SESSION_ATTENDED_ENVIRONMENT_VARIABLE,
|
|
52
|
+
TOOL_RESULT_SCAN_TEXT,
|
|
53
|
+
TOOL_USE_BLOCK_ID_KEY,
|
|
54
|
+
TURN_ORIGIN_KEY,
|
|
55
|
+
TURN_ORIGIN_SCAN_TEXT,
|
|
56
|
+
USER_ROLE_SCAN_TEXT,
|
|
57
|
+
)
|
|
58
|
+
from hooks_constants.open_tasks_stop_gate_constants import (
|
|
59
|
+
ALL_QUESTION_TOOL_NAMES,
|
|
60
|
+
RECORD_TYPE_KEY,
|
|
61
|
+
TEXT_KEY,
|
|
62
|
+
TOOL_NAME_KEY,
|
|
63
|
+
TOOL_RESULT_BLOCK_TYPE,
|
|
64
|
+
TOOL_USE_BLOCK_TYPE,
|
|
65
|
+
TOOL_USE_ID_KEY,
|
|
66
|
+
)
|
|
67
|
+
from closing_question_round_lines import before_deadline
|
|
68
|
+
from open_tasks_transcript_records import (
|
|
69
|
+
_content_blocks,
|
|
70
|
+
claude_prompt_text,
|
|
71
|
+
is_assistant_record,
|
|
72
|
+
parsed_object,
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
def _top_level_record(transcript_line: str) -> dict[str, object] | None:
|
|
76
|
+
each_record = parsed_object(transcript_line)
|
|
77
|
+
if each_record is None or each_record.get(IS_SIDECHAIN_KEY):
|
|
78
|
+
return None
|
|
79
|
+
return each_record
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _is_prompt_line(transcript_line: str) -> bool:
|
|
83
|
+
if USER_ROLE_SCAN_TEXT not in transcript_line:
|
|
84
|
+
return False
|
|
85
|
+
each_record = parsed_object(transcript_line)
|
|
86
|
+
return each_record is not None and claude_prompt_text(each_record) is not None
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _last_prompt_line_position(all_lines: list[str], deadline_at: float) -> int | None:
|
|
90
|
+
all_positions = before_deadline(range(len(all_lines) - 1, -1, -1), deadline_at)
|
|
91
|
+
return next(
|
|
92
|
+
(each_position for each_position in all_positions if _is_prompt_line(all_lines[each_position])),
|
|
93
|
+
None,
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def last_typed_prompt_position(all_lines: list[str], deadline_at: float) -> int | None:
|
|
98
|
+
"""Return the line position of the last prompt a person typed, or None when no person started the session.
|
|
99
|
+
|
|
100
|
+
::
|
|
101
|
+
|
|
102
|
+
{"turnOrigin": "human", "message": {"content": "Add the flag."}} -> its position
|
|
103
|
+
{"turnOrigin": "sdk", "message": {"content": "Add the flag."}} -> None
|
|
104
|
+
{"message": {"content": "Add the flag."}}, attended session -> its position
|
|
105
|
+
|
|
106
|
+
A line is parsed only when it holds ``"turnOrigin"``. When no record
|
|
107
|
+
carries that key, the last record that starts a turn counts instead, and
|
|
108
|
+
only when ``CLAUDE_CODE_SESSION_ATTENDED`` is ``1``; that second scan
|
|
109
|
+
reads from the end and parses only the lines that hold ``"user"``. Both
|
|
110
|
+
scans raise TimeoutError once the clock reaches ``deadline_at``.
|
|
111
|
+
"""
|
|
112
|
+
has_turn_origin_key = False
|
|
113
|
+
last_position: int | None = None
|
|
114
|
+
for each_position, each_line in enumerate(before_deadline(all_lines, deadline_at)):
|
|
115
|
+
if TURN_ORIGIN_SCAN_TEXT not in each_line:
|
|
116
|
+
continue
|
|
117
|
+
each_record = parsed_object(each_line)
|
|
118
|
+
if each_record is None or TURN_ORIGIN_KEY not in each_record:
|
|
119
|
+
continue
|
|
120
|
+
has_turn_origin_key = True
|
|
121
|
+
if (
|
|
122
|
+
each_record.get(TURN_ORIGIN_KEY) == HUMAN_TURN_ORIGIN
|
|
123
|
+
and claude_prompt_text(each_record) is not None
|
|
124
|
+
):
|
|
125
|
+
last_position = each_position
|
|
126
|
+
if has_turn_origin_key:
|
|
127
|
+
return last_position
|
|
128
|
+
if os.environ.get(SESSION_ATTENDED_ENVIRONMENT_VARIABLE) != ATTENDED_SESSION_TEXT:
|
|
129
|
+
return None
|
|
130
|
+
return _last_prompt_line_position(all_lines, deadline_at)
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _is_question_tool_name(tool_name: object) -> bool:
|
|
134
|
+
return isinstance(tool_name, str) and tool_name in ALL_QUESTION_TOOL_NAMES
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _is_question_block(all_block_fields: dict[str, object]) -> bool:
|
|
138
|
+
return (
|
|
139
|
+
all_block_fields.get(RECORD_TYPE_KEY) == TOOL_USE_BLOCK_TYPE
|
|
140
|
+
and _is_question_tool_name(all_block_fields.get(TOOL_NAME_KEY))
|
|
141
|
+
and isinstance(all_block_fields.get(TOOL_USE_BLOCK_ID_KEY), str)
|
|
142
|
+
)
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def _question_call_ids(all_record_fields: dict[str, object] | None) -> list[str]:
|
|
146
|
+
if all_record_fields is None or not is_assistant_record(all_record_fields):
|
|
147
|
+
return []
|
|
148
|
+
return [
|
|
149
|
+
str(each_block[TOOL_USE_BLOCK_ID_KEY])
|
|
150
|
+
for each_block in _content_blocks(all_record_fields)
|
|
151
|
+
if _is_question_block(each_block)
|
|
152
|
+
]
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def _tool_results(all_record_fields: dict[str, object] | None) -> list[tuple[str, bool]]:
|
|
156
|
+
if all_record_fields is None:
|
|
157
|
+
return []
|
|
158
|
+
return [
|
|
159
|
+
(str(each_block[TOOL_USE_ID_KEY]), bool(each_block.get(IS_ERROR_KEY)))
|
|
160
|
+
for each_block in _content_blocks(all_record_fields)
|
|
161
|
+
if each_block.get(RECORD_TYPE_KEY) == TOOL_RESULT_BLOCK_TYPE
|
|
162
|
+
and isinstance(each_block.get(TOOL_USE_ID_KEY), str)
|
|
163
|
+
]
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _answered_call_positions(
|
|
167
|
+
transcript_line: str, all_pending_call_positions: dict[str, int]
|
|
168
|
+
) -> list[int]:
|
|
169
|
+
if not all_pending_call_positions or TOOL_RESULT_SCAN_TEXT not in transcript_line:
|
|
170
|
+
return []
|
|
171
|
+
if not any(each_id in transcript_line for each_id in all_pending_call_positions):
|
|
172
|
+
return []
|
|
173
|
+
all_answered_positions: list[int] = []
|
|
174
|
+
for each_id, each_is_error in _tool_results(_top_level_record(transcript_line)):
|
|
175
|
+
call_position = all_pending_call_positions.pop(each_id, None)
|
|
176
|
+
if call_position is not None and not each_is_error:
|
|
177
|
+
all_answered_positions.append(call_position)
|
|
178
|
+
return all_answered_positions
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def _asked_call_ids(transcript_line: str) -> list[str]:
|
|
182
|
+
if not any(
|
|
183
|
+
each_scan_text in transcript_line for each_scan_text in ALL_QUESTION_TOOL_NAME_SCAN_TEXTS
|
|
184
|
+
):
|
|
185
|
+
return []
|
|
186
|
+
return _question_call_ids(_top_level_record(transcript_line))
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def stretch_start(all_lines: list[str], deadline_at: float) -> int:
|
|
190
|
+
"""Return the line position right after the last question call that reached the user, or 0.
|
|
191
|
+
|
|
192
|
+
::
|
|
193
|
+
|
|
194
|
+
reply, AskUserQuestion, its answer, reply -> 2, the answer's position
|
|
195
|
+
reply, AskUserQuestion, its refusal -> 0
|
|
196
|
+
reply, reply -> 0
|
|
197
|
+
|
|
198
|
+
A record flagged ``isSidechain`` is never a question call or its result.
|
|
199
|
+
|
|
200
|
+
Args:
|
|
201
|
+
all_lines: The transcript, one JSON record per line.
|
|
202
|
+
deadline_at: The monotonic clock reading at which the scan gives up.
|
|
203
|
+
|
|
204
|
+
Returns:
|
|
205
|
+
The position of the first line of the stretch.
|
|
206
|
+
|
|
207
|
+
Raises:
|
|
208
|
+
TimeoutError: The deadline passed before the scan ended.
|
|
209
|
+
"""
|
|
210
|
+
all_pending_call_positions: dict[str, int] = {}
|
|
211
|
+
start_position = 0
|
|
212
|
+
for each_position, each_line in enumerate(before_deadline(all_lines, deadline_at)):
|
|
213
|
+
all_answered_positions = _answered_call_positions(each_line, all_pending_call_positions)
|
|
214
|
+
start_position = max(
|
|
215
|
+
[
|
|
216
|
+
start_position,
|
|
217
|
+
*(each_answered_position + 1 for each_answered_position in all_answered_positions),
|
|
218
|
+
]
|
|
219
|
+
)
|
|
220
|
+
all_pending_call_positions.update(dict.fromkeys(_asked_call_ids(each_line), each_position))
|
|
221
|
+
return start_position
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def _may_matter(transcript_line: str) -> bool:
|
|
225
|
+
return ASSISTANT_SCAN_TEXT in transcript_line or any(
|
|
226
|
+
each_lead in transcript_line for each_lead in ALL_REASON_LEADS
|
|
227
|
+
)
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def top_level_records(all_lines: list[str], deadline_at: float) -> list[dict[str, object]]:
|
|
231
|
+
"""Return the assistant records and this gate's hold records among the lines, in order.
|
|
232
|
+
|
|
233
|
+
::
|
|
234
|
+
|
|
235
|
+
reply, tool result, Bash call, hold feedback -> reply, Bash call, hold feedback
|
|
236
|
+
a record flagged isSidechain -> left out
|
|
237
|
+
|
|
238
|
+
A line is parsed only when it holds ``"assistant"`` or the first sentence
|
|
239
|
+
of one of this gate's reasons. The records are not checked further here.
|
|
240
|
+
|
|
241
|
+
Args:
|
|
242
|
+
all_lines: The lines to read, one JSON record per line.
|
|
243
|
+
deadline_at: The monotonic clock reading at which the scan gives up.
|
|
244
|
+
|
|
245
|
+
Returns:
|
|
246
|
+
The parsed top-level records.
|
|
247
|
+
|
|
248
|
+
Raises:
|
|
249
|
+
TimeoutError: The deadline passed before the scan ended.
|
|
250
|
+
"""
|
|
251
|
+
all_records = (
|
|
252
|
+
_top_level_record(each_line)
|
|
253
|
+
for each_line in before_deadline(all_lines, deadline_at)
|
|
254
|
+
if _may_matter(each_line)
|
|
255
|
+
)
|
|
256
|
+
return [each_record for each_record in all_records if each_record is not None]
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def block_texts(all_record_fields: dict[str, object]) -> list[str]:
|
|
260
|
+
"""Return the string ``text`` of each text block the record's content holds, in order."""
|
|
261
|
+
all_block_texts = (
|
|
262
|
+
each_block.get(TEXT_KEY)
|
|
263
|
+
for each_block in _content_blocks(all_record_fields)
|
|
264
|
+
if each_block.get(RECORD_TYPE_KEY) == TEXT_KEY
|
|
265
|
+
)
|
|
266
|
+
return [each_text for each_text in all_block_texts if isinstance(each_text, str)]
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
def assistant_texts(all_stretch_records: list[dict[str, object]]) -> list[str]:
|
|
270
|
+
"""Return the text blocks of the assistant records in the stretch, in order."""
|
|
271
|
+
return [
|
|
272
|
+
each_text
|
|
273
|
+
for each_record in all_stretch_records
|
|
274
|
+
if is_assistant_record(each_record)
|
|
275
|
+
for each_text in block_texts(each_record)
|
|
276
|
+
]
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def has_work_call(all_stretch_records: list[dict[str, object]]) -> bool:
|
|
280
|
+
"""Return True when an assistant record in the stretch holds a tool call that is no question call.
|
|
281
|
+
|
|
282
|
+
A call whose name is no string counts as work.
|
|
283
|
+
"""
|
|
284
|
+
return any(
|
|
285
|
+
each_block.get(RECORD_TYPE_KEY) == TOOL_USE_BLOCK_TYPE
|
|
286
|
+
and not _is_question_tool_name(each_block.get(TOOL_NAME_KEY))
|
|
287
|
+
for each_record in all_stretch_records
|
|
288
|
+
if is_assistant_record(each_record)
|
|
289
|
+
for each_block in _content_blocks(each_record)
|
|
290
|
+
)
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def _last_assistant_text(all_lines: list[str], deadline_at: float) -> str | None:
|
|
294
|
+
for each_line in before_deadline(reversed(all_lines), deadline_at):
|
|
295
|
+
if ASSISTANT_SCAN_TEXT not in each_line:
|
|
296
|
+
continue
|
|
297
|
+
each_record = _top_level_record(each_line)
|
|
298
|
+
if each_record is None or not is_assistant_record(each_record):
|
|
299
|
+
continue
|
|
300
|
+
all_blocks = _content_blocks(each_record)
|
|
301
|
+
all_answer_blocks = list(all_blocks)
|
|
302
|
+
while all_answer_blocks and _is_question_block(all_answer_blocks[-1]):
|
|
303
|
+
all_answer_blocks.pop()
|
|
304
|
+
if all_blocks and not all_answer_blocks:
|
|
305
|
+
continue
|
|
306
|
+
last_block = all_answer_blocks[-1] if all_answer_blocks else {}
|
|
307
|
+
last_text = last_block.get(TEXT_KEY) if last_block.get(RECORD_TYPE_KEY) == TEXT_KEY else None
|
|
308
|
+
return last_text if isinstance(last_text, str) else None
|
|
309
|
+
return None
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
def closing_reply_texts(
|
|
313
|
+
all_hook_input_fields: dict[str, object], all_lines: list[str], deadline_at: float
|
|
314
|
+
) -> list[str]:
|
|
315
|
+
"""Return the payload's closing reply as a one-item list, or an empty list.
|
|
316
|
+
|
|
317
|
+
::
|
|
318
|
+
|
|
319
|
+
"Both tests pass." and the transcript ends with other text -> ["Both tests pass."]
|
|
320
|
+
"Both tests pass." and the transcript ends with it -> []
|
|
321
|
+
"" or no string -> []
|
|
322
|
+
|
|
323
|
+
The transcript ends with the reply when its last top-level assistant
|
|
324
|
+
record, question calls left aside, ends in a text block equal to it, with
|
|
325
|
+
outer whitespace stripped. A text before a later work call is not it.
|
|
326
|
+
|
|
327
|
+
Args:
|
|
328
|
+
all_hook_input_fields: The Stop payload.
|
|
329
|
+
all_lines: The transcript, one JSON record per line.
|
|
330
|
+
deadline_at: The monotonic clock reading at which the scan gives up.
|
|
331
|
+
|
|
332
|
+
Returns:
|
|
333
|
+
The closing reply to read, when the transcript does not hold it yet.
|
|
334
|
+
|
|
335
|
+
Raises:
|
|
336
|
+
TimeoutError: The deadline passed before the scan ended.
|
|
337
|
+
"""
|
|
338
|
+
closing_reply = all_hook_input_fields.get(LAST_ASSISTANT_MESSAGE_KEY)
|
|
339
|
+
if not isinstance(closing_reply, str) or not closing_reply.strip():
|
|
340
|
+
return []
|
|
341
|
+
last_written_text = _last_assistant_text(all_lines, deadline_at)
|
|
342
|
+
if last_written_text is not None and last_written_text.strip() == closing_reply.strip():
|
|
343
|
+
return []
|
|
344
|
+
return [closing_reply]
|