claude-dev-env 8.123.0 → 8.125.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 (46) hide show
  1. package/bin/ever-registered-hooks.mjs +2 -0
  2. package/bin/ever-registered-hooks.test.mjs +5 -0
  3. package/bin/profile-stop-gate.mjs +5 -7
  4. package/bin/profile-stop-gate.test.mjs +29 -1
  5. package/docs/agents-guidance/asks.md +1 -1
  6. package/docs/rule-guides/question-presentation.md +1 -1
  7. package/docs/templates/artifact-page/README.md +14 -1
  8. package/docs/templates/artifact-page/review-rounds.md +1 -1
  9. package/docs/templates/artifact-page/template.html +26 -18
  10. package/docs/templates/html-plan/README.md +4 -0
  11. package/hooks/blocking/artifact_current_page_fixtures/piled_review_page.html +399 -0
  12. package/hooks/blocking/artifact_current_page_fixtures/rebuilt_review_page.html +403 -0
  13. package/hooks/blocking/artifact_current_page_gate.py +418 -0
  14. package/hooks/blocking/artifact_repeated_item_render.cjs +112 -0
  15. package/hooks/blocking/closing_reply_judge.py +332 -0
  16. package/hooks/blocking/closing_reply_shapes.py +365 -0
  17. package/hooks/blocking/conftest.py +84 -0
  18. package/hooks/blocking/open_tasks_stop_gate.py +259 -11
  19. package/hooks/blocking/open_tasks_transcript.py +55 -2
  20. package/hooks/blocking/open_tasks_transcript_records.py +67 -1
  21. package/hooks/blocking/question_brief_gate.py +6 -4
  22. package/hooks/blocking/test_artifact_current_page_gate.py +415 -0
  23. package/hooks/blocking/test_closing_reply_judge.py +246 -0
  24. package/hooks/blocking/test_closing_reply_shapes.py +247 -0
  25. package/hooks/blocking/test_open_tasks_stop_gate.py +626 -0
  26. package/hooks/blocking/test_open_tasks_transcript.py +57 -0
  27. package/hooks/blocking/test_open_tasks_transcript_records.py +48 -0
  28. package/hooks/blocking/test_question_brief_gate.py +22 -0
  29. package/hooks/features/conduct-gates.md +10 -3
  30. package/hooks/hooks.json +16 -1
  31. package/hooks/hooks_constants/artifact_current_page_gate_constants.py +91 -0
  32. package/hooks/hooks_constants/artifact_dark_mode_gate_constants.py +3 -3
  33. package/hooks/hooks_constants/closing_reply_judge_constants.py +143 -0
  34. package/hooks/hooks_constants/open_tasks_stop_gate_constants.py +101 -0
  35. package/hooks/hooks_constants/test_artifact_current_page_gate_constants.py +53 -0
  36. package/hooks/hooks_constants/test_artifact_dark_mode_gate_constants.py +6 -0
  37. package/hooks/hooks_constants/test_hook_time_budget.py +7 -0
  38. package/hooks/once_per_session.py +65 -1
  39. package/hooks/session/artifact_link_record.py +109 -0
  40. package/hooks/session/test_artifact_link_record.py +101 -0
  41. package/hooks/test_context_budget_hooks.py +2 -0
  42. package/hooks/test_once_per_session.py +35 -0
  43. package/package.json +1 -1
  44. package/scripts/policy_lint/adapter_configuration.py +6 -0
  45. package/scripts/policy_lint/config/constants.py +1 -0
  46. package/scripts/tests/test_adapter_configuration.py +8 -0
@@ -0,0 +1,332 @@
1
+ """Ask one small model call whether a closing reply promises a later report or lists open decisions.
2
+
3
+ The open tasks Stop gate sends the turn's prompt and its closing reply to
4
+ ``claude -p --model haiku --effort medium`` with the prompt on stdin, and reads
5
+ back one JSON verdict::
6
+
7
+ in: {"prompt_kind": "typed", "user_prompt": "...", "reply": "...", "question_tool_used": false}
8
+ out: {"promised_report": true, "promise_span": "...", "decisions_as_list": false, "list_span": ""}
9
+
10
+ The prompt kind tells the model where the prompt came from::
11
+
12
+ "<task-notification>...<summary>Lint ended</summary>..." -> task_notification, "Lint ended"
13
+ "<command-name>/review</command-name><command-args>12</command-args>" -> slash_command, "/review 12"
14
+ any other prompt -> typed, its first 4,000 characters
15
+
16
+ A verdict counts only when it is the four-key object, bare or in one ``json``
17
+ code fence, and each raised flag names a nonempty span found in the reply.
18
+ Two code gates then drop the list flag: the turn used the question tool, or
19
+ the prompt asked for a list.
20
+
21
+ The child runs in a new empty folder with no tools, no hooks, no MCP servers,
22
+ no CLAUDE.md files, no auto memory, ``CLAUDE_TURN_REVIEW_CHILD=1``, and none of
23
+ the parent session's id, messaging, or ingress variables. Every failure gives
24
+ no verdict and one line in ``~/.claude/logs/closing-reply-judge.log``::
25
+
26
+ the child times out, cannot start, or exits with another code than 0
27
+ stdout is not one JSON object with a string result, or is_error is set
28
+ the result is not the verdict shape, or a span is not in the reply
29
+ """
30
+
31
+ from __future__ import annotations
32
+
33
+ import datetime
34
+ import json
35
+ import os
36
+ import shutil
37
+ import subprocess
38
+ import tempfile
39
+ from pathlib import Path
40
+ from typing import NamedTuple
41
+
42
+ from closing_reply_shapes import prompt_asks_for_list
43
+ from hooks_constants.closing_reply_judge_constants import (
44
+ ALL_JUDGE_COMMAND_FLAGS,
45
+ ALL_JUDGE_ENVIRONMENT_SETTINGS,
46
+ ALL_LOG_PATH_PARTS,
47
+ ALL_VERDICT_KEYS,
48
+ ANSWER_FENCE_PATTERN,
49
+ ANSWER_IS_ERROR_KEY,
50
+ ANSWER_RESULT_KEY,
51
+ CHILD_DECODE_ERRORS,
52
+ CHILD_TEXT_ENCODING,
53
+ CLAUDE_EXECUTABLE_NAME,
54
+ COMMAND_ARGS_PATTERN,
55
+ COMMAND_NAME_PATTERN,
56
+ COMMAND_PART_SEPARATOR,
57
+ COMMAND_START_PATTERN,
58
+ DECISIONS_AS_LIST_KEY,
59
+ ERROR_ANSWER_REASON,
60
+ EXIT_CODE_REASON_TEMPLATE,
61
+ JUDGE_DATA_INDENT,
62
+ JUDGE_DATA_PLACEHOLDER,
63
+ JUDGE_PROMPT_TEMPLATE,
64
+ JUDGE_TIMEOUT_SECONDS,
65
+ LIST_SPAN_KEY,
66
+ LOG_LINE_TEMPLATE,
67
+ NO_VERDICT_LOG_TEMPLATE,
68
+ NOT_JSON_REASON,
69
+ NOTIFICATION_SUMMARY_PATTERN,
70
+ PROMISE_SPAN_KEY,
71
+ PROMISED_REPORT_KEY,
72
+ PROMPT_KIND_KEY,
73
+ QUESTION_TOOL_USED_KEY,
74
+ REPLY_KEY,
75
+ SLASH_COMMAND_PROMPT_KIND,
76
+ START_FAILURE_REASON,
77
+ TASK_NOTIFICATION_PREFIX,
78
+ TASK_NOTIFICATION_PROMPT_KIND,
79
+ TIMEOUT_REASON,
80
+ TYPED_PROMPT_CHARACTER_LIMIT,
81
+ TYPED_PROMPT_KIND,
82
+ USER_PROMPT_KEY,
83
+ VERDICT_SHAPE_REASON,
84
+ )
85
+ from hooks_constants.subprocess_window import hidden_window_creation_flags
86
+ from hooks_constants.turn_review_gate_constants import (
87
+ ALL_PARENT_SESSION_VARIABLES,
88
+ REVIEW_CHILD_ENVIRONMENT_VARIABLE,
89
+ REVIEW_CHILD_MARKER,
90
+ )
91
+
92
+
93
+ class JudgeVerdict(NamedTuple):
94
+ """The spans the judge raised: the promised report and the open-decision list, each empty when not raised."""
95
+
96
+ promise_span: str
97
+ list_span: str
98
+
99
+
100
+ def _log(diagnostic_text: str) -> None:
101
+ timestamp = datetime.datetime.now(datetime.timezone.utc).isoformat()
102
+ try:
103
+ log_path = Path.home().joinpath(*ALL_LOG_PATH_PARTS)
104
+ log_path.parent.mkdir(parents=True, exist_ok=True)
105
+ with log_path.open(
106
+ "a", encoding=CHILD_TEXT_ENCODING, errors=CHILD_DECODE_ERRORS
107
+ ) as log_file:
108
+ log_file.write(LOG_LINE_TEMPLATE.format(timestamp=timestamp, text=diagnostic_text))
109
+ except (OSError, RuntimeError):
110
+ return
111
+
112
+
113
+ def log_no_verdict(reason: str) -> None:
114
+ """Write one line to the judge log that names why the judge gave no verdict."""
115
+ _log(NO_VERDICT_LOG_TEMPLATE.format(reason=reason))
116
+
117
+
118
+ def _prompt_kind_and_text(prompt_text: str) -> tuple[str, str]:
119
+ stripped_prompt = prompt_text.lstrip()
120
+ if stripped_prompt.startswith(TASK_NOTIFICATION_PREFIX):
121
+ summary_match = NOTIFICATION_SUMMARY_PATTERN.search(stripped_prompt)
122
+ return TASK_NOTIFICATION_PROMPT_KIND, summary_match.group(
123
+ 1
124
+ ).strip() if summary_match else ""
125
+ if COMMAND_START_PATTERN.match(stripped_prompt):
126
+ all_command_parts = (
127
+ each_match.group(1).strip()
128
+ for each_match in (
129
+ COMMAND_NAME_PATTERN.search(stripped_prompt),
130
+ COMMAND_ARGS_PATTERN.search(stripped_prompt),
131
+ )
132
+ if each_match is not None
133
+ )
134
+ return SLASH_COMMAND_PROMPT_KIND, COMMAND_PART_SEPARATOR.join(
135
+ each_part for each_part in all_command_parts if each_part
136
+ )
137
+ return TYPED_PROMPT_KIND, prompt_text[:TYPED_PROMPT_CHARACTER_LIMIT]
138
+
139
+
140
+ def judge_input(prompt_text: str, reply_text: str, has_question_tool_call: bool) -> dict[str, object]:
141
+ """Return the data the judge reads: the prompt kind, the prompt text, the reply, and the question-tool flag.
142
+
143
+ ::
144
+
145
+ "<task-notification>...<summary>Lint ended</summary>" -> task_notification, "Lint ended"
146
+ "<command-name>/review</command-name>" -> slash_command, "/review"
147
+ "Fix the build" -> typed, "Fix the build"
148
+
149
+ Args:
150
+ prompt_text: The prompt that started the turn.
151
+ reply_text: The closing reply the turn ends with.
152
+ has_question_tool_call: Whether the turn called the question tool.
153
+ """
154
+ prompt_kind, user_prompt = _prompt_kind_and_text(prompt_text)
155
+ return {
156
+ PROMPT_KIND_KEY: prompt_kind,
157
+ USER_PROMPT_KEY: user_prompt,
158
+ REPLY_KEY: reply_text,
159
+ QUESTION_TOOL_USED_KEY: bool(has_question_tool_call),
160
+ }
161
+
162
+
163
+ def judge_prompt(prompt_text: str, reply_text: str, has_question_tool_call: bool) -> str:
164
+ """Return the full judge prompt, with the ``judge_input`` data as indented JSON in place of ``$DATA``."""
165
+ judge_data = json.dumps(
166
+ judge_input(prompt_text, reply_text, has_question_tool_call),
167
+ ensure_ascii=False,
168
+ indent=JUDGE_DATA_INDENT,
169
+ )
170
+ return JUDGE_PROMPT_TEMPLATE.replace(JUDGE_DATA_PLACEHOLDER, judge_data)
171
+
172
+
173
+ def judge_command(claude_path: str) -> list[str]:
174
+ """Return the ``claude -p`` command for the judge: Haiku at medium effort, JSON out, no tools, hooks, or MCP."""
175
+ return [claude_path, *ALL_JUDGE_COMMAND_FLAGS]
176
+
177
+
178
+ def child_environment() -> dict[str, str]:
179
+ """Return this process's environment without the parent session's variables, marked as a review child."""
180
+ all_child_variables = {
181
+ each_name: each_value
182
+ for each_name, each_value in os.environ.items()
183
+ if each_name not in ALL_PARENT_SESSION_VARIABLES
184
+ }
185
+ all_child_variables[REVIEW_CHILD_ENVIRONMENT_VARIABLE] = REVIEW_CHILD_MARKER
186
+ all_child_variables.update(ALL_JUDGE_ENVIRONMENT_SETTINGS)
187
+ return all_child_variables
188
+
189
+
190
+ def is_judge_available() -> bool:
191
+ """Return True when a ``claude`` executable is on PATH."""
192
+ return shutil.which(CLAUDE_EXECUTABLE_NAME) is not None
193
+
194
+
195
+ def _answer_result(stdout_text: str) -> str | None:
196
+ try:
197
+ answer = json.loads(stdout_text)
198
+ except (ValueError, RecursionError):
199
+ log_no_verdict(NOT_JSON_REASON)
200
+ return None
201
+ if not isinstance(answer, dict) or not isinstance(answer.get(ANSWER_RESULT_KEY), str):
202
+ log_no_verdict(NOT_JSON_REASON)
203
+ return None
204
+ if answer.get(ANSWER_IS_ERROR_KEY) is True:
205
+ log_no_verdict(ERROR_ANSWER_REASON)
206
+ return None
207
+ return answer[ANSWER_RESULT_KEY]
208
+
209
+
210
+ def _claude_result(claude_path: str, prompt: str, timeout_seconds: float) -> str | None:
211
+ try:
212
+ with tempfile.TemporaryDirectory() as empty_folder:
213
+ completed_process = subprocess.run(
214
+ judge_command(claude_path),
215
+ check=False,
216
+ capture_output=True,
217
+ text=True,
218
+ encoding=CHILD_TEXT_ENCODING,
219
+ errors=CHILD_DECODE_ERRORS,
220
+ timeout=timeout_seconds,
221
+ cwd=empty_folder,
222
+ env=child_environment(),
223
+ creationflags=hidden_window_creation_flags(),
224
+ input=prompt,
225
+ )
226
+ except subprocess.TimeoutExpired:
227
+ log_no_verdict(TIMEOUT_REASON)
228
+ return None
229
+ except OSError:
230
+ log_no_verdict(START_FAILURE_REASON)
231
+ return None
232
+ if completed_process.returncode != 0:
233
+ log_no_verdict(EXIT_CODE_REASON_TEMPLATE.format(exit_code=completed_process.returncode))
234
+ return None
235
+ return _answer_result(completed_process.stdout)
236
+
237
+
238
+ def _raised_span(
239
+ all_verdict_fields: dict[str, object], flag_key: str, span_key: str, reply_text: str
240
+ ) -> str | None:
241
+ is_raised = all_verdict_fields[flag_key]
242
+ span = all_verdict_fields[span_key]
243
+ if not isinstance(is_raised, bool) or not isinstance(span, str):
244
+ return None
245
+ if not is_raised:
246
+ return ""
247
+ return span if span and span in reply_text else None
248
+
249
+
250
+ def parsed_verdict(result_text: str, reply_text: str) -> JudgeVerdict | None:
251
+ """Return the verdict in the judge's result text, or None when it is not the verdict shape.
252
+
253
+ ::
254
+
255
+ '{"promised_report": true, "promise_span": "I will report back", ...}' -> JudgeVerdict("I will report back", "")
256
+ the same object inside one json code fence -> the same verdict
257
+ a raised flag whose span is empty or not in the reply -> None
258
+ prose, an extra key, or a string in place of a bool -> None
259
+
260
+ Args:
261
+ result_text: The ``result`` string of the ``claude -p`` JSON answer.
262
+ reply_text: The closing reply the judge read.
263
+ """
264
+ fence_match = ANSWER_FENCE_PATTERN.match(result_text)
265
+ verdict_text = fence_match.group(1) if fence_match else result_text.strip()
266
+ try:
267
+ all_verdict_fields = json.loads(verdict_text)
268
+ except (ValueError, RecursionError):
269
+ return None
270
+ if not isinstance(all_verdict_fields, dict) or set(all_verdict_fields) != ALL_VERDICT_KEYS:
271
+ return None
272
+ promise_span = _raised_span(
273
+ all_verdict_fields, PROMISED_REPORT_KEY, PROMISE_SPAN_KEY, reply_text
274
+ )
275
+ list_span = _raised_span(all_verdict_fields, DECISIONS_AS_LIST_KEY, LIST_SPAN_KEY, reply_text)
276
+ if promise_span is None or list_span is None:
277
+ return None
278
+ return JudgeVerdict(promise_span, list_span)
279
+
280
+
281
+ def gated_verdict(
282
+ verdict: JudgeVerdict, prompt_text: str, has_question_tool_call: bool
283
+ ) -> JudgeVerdict:
284
+ """Return the verdict with its list span dropped when the turn used the question tool or the prompt asked for a list.
285
+
286
+ ::
287
+
288
+ list span "Open calls:", no question tool, prompt "fix the build" -> the list span stays
289
+ the same verdict after an AskUserQuestion call -> list span ""
290
+ the same verdict after the prompt "list the open calls as bullets" -> list span ""
291
+ """
292
+ if has_question_tool_call or prompt_asks_for_list(prompt_text):
293
+ return verdict._replace(list_span="")
294
+ return verdict
295
+
296
+
297
+ def judged_verdict(
298
+ prompt_text: str,
299
+ reply_text: str,
300
+ has_question_tool_call: bool,
301
+ timeout_seconds: float | None = None,
302
+ ) -> JudgeVerdict | None:
303
+ """Run the judge once on a closing reply and return its gated verdict, or None when it gave none.
304
+
305
+ ::
306
+
307
+ a reply that promises a report later -> JudgeVerdict("<the promise>", "")
308
+ a reply with no fault -> JudgeVerdict("", "")
309
+ no claude on PATH, a timeout, a bad answer, or a span not in the reply -> None
310
+
311
+ Args:
312
+ prompt_text: The prompt that started the turn.
313
+ reply_text: The closing reply the turn ends with.
314
+ has_question_tool_call: Whether the turn called the question tool.
315
+ timeout_seconds: How long the child may run; ``JUDGE_TIMEOUT_SECONDS`` when None.
316
+ """
317
+ claude_path = shutil.which(CLAUDE_EXECUTABLE_NAME)
318
+ if claude_path is None:
319
+ log_no_verdict(START_FAILURE_REASON)
320
+ return None
321
+ result_text = _claude_result(
322
+ claude_path,
323
+ judge_prompt(prompt_text, reply_text, has_question_tool_call),
324
+ JUDGE_TIMEOUT_SECONDS if timeout_seconds is None else timeout_seconds,
325
+ )
326
+ if result_text is None:
327
+ return None
328
+ verdict = parsed_verdict(result_text, reply_text)
329
+ if verdict is None:
330
+ log_no_verdict(VERDICT_SHAPE_REASON)
331
+ return None
332
+ return gated_verdict(verdict, prompt_text, has_question_tool_call)
@@ -0,0 +1,365 @@
1
+ """Find two closing-reply shapes the user corrected: a promised later report, and open items sent as a list.
2
+
3
+ The open tasks Stop gate reads the reply a turn ends with. Two shapes in it
4
+ leave work with the user that the agent could carry itself::
5
+
6
+ flag: The benchmark table will be posted when you get back.
7
+ flag: I'll report back once CI ends.
8
+ flag: What I deferred: followed by 3 or more list or table items
9
+ ok: No report will follow.
10
+ ok: I'll merge each lint fix once the bots report back.
11
+ ok: Changed files: followed by 5 bullets
12
+ ok: Deferred: followed by 2 bullets
13
+
14
+ The promise patterns are ``when you're / are / get / come back``; a report,
15
+ summary, write-up, recap, or result that "will be here / waiting / ready /
16
+ posted" or "will follow / land / arrive / come"; ``I'll`` or ``I will``
17
+ report, post, send, share, update you, let you know, follow up, circle back,
18
+ check back, or get back to you before when, once, after, later, tomorrow, or
19
+ in the morning; and ``I'll report back``. A match is skipped when no, not,
20
+ never, none, or nothing comes before it in its sentence.
21
+
22
+ An open-item list is a run of item lines: bullets, numbered lines, and table
23
+ body rows. A run goes on across blank lines, indented lines, and a table's
24
+ header and separator rows. Its lead is the nearest non-blank line above it.
25
+ The lead loses its code spans and its double-quoted text first. It must
26
+ name open work (deferred, sidestepped, remaining, outstanding, still open,
27
+ open items, next steps, follow-ups, to-dos, pending, parked, and the like)
28
+ and hold no no, none, nothing, nobody, or zero. A lead whose every open-work
29
+ word has a completion word in its clause names done work, and so does a lead
30
+ whose last word is a completion word that is not negated::
31
+
32
+ flag: Remaining work after the merged fixes: "after" ends the clause
33
+ flag: What I fixed and what I deferred: "and" ends the clause
34
+ flag: Follow-ups not yet merged: a negated completion word
35
+ flag: Remaining tasks, not done: a negated last word
36
+ ok: I fixed the three follow-ups you flagged:
37
+ ok: All pending checks passed:
38
+ ok: Remaining tasks, now done: the last word is "done"
39
+
40
+ The completion words are fixed, closed, resolved, removed, passed, passes,
41
+ completed, merged, landed, addressed, finished, cleared, shipped, handled,
42
+ done, and covers. Not, never, or a word ending in n't before one, with an
43
+ optional yet or been, negates it. A clause ends at punctuation, a dash, or
44
+ and, or, but, while, after, before, besides, except, beyond, or plus.
45
+
46
+ Fences, HTML blocks, quoted lines, and code spans are left out of both checks,
47
+ and the list lead also loses its double-quoted text.
48
+
49
+ The typed prompt can ask for either shape. Before the ask check, the prompt
50
+ loses its ``<system-reminder>`` blocks, its ``>`` quoted lines, its code
51
+ spans, and any double-quoted text that holds a space. An ask counts unless a
52
+ negator (no, not, never, none, nothing, without, don't, do not, no need,
53
+ never mind) comes before it in its clause; clauses end at ``. ! ? ; ,`` or a
54
+ line break, and a new clause starts at the word "then". A report ask is a verb
55
+ ask (report back, summarize, update me, let me know, tell me when, once, or
56
+ how), or a bare report, summary, or recap in a clause that also names a later
57
+ time (when, once, after, later, tomorrow, then, at the end). A prompt that
58
+ opens with a harness envelope, such as ``<task-notification>``, never asks::
59
+
60
+ exempts the promise: "report back when the run ends"
61
+ exempts the promise: "don't stop until it is merged, then give me a summary"
62
+ exempts the list: "list the deferred items as bullets"
63
+ no exemption: "no report needed, just finish"
64
+ no exemption: "Fix the report page."
65
+ no exemption: "no list please, ask me instead"
66
+ """
67
+
68
+ from __future__ import annotations
69
+
70
+ import re
71
+ import sys
72
+ from pathlib import Path
73
+ from typing import NamedTuple
74
+
75
+ hooks_root_directory = str(Path(__file__).resolve().parent.parent)
76
+ if hooks_root_directory not in sys.path:
77
+ sys.path.insert(0, hooks_root_directory)
78
+ blocking_directory = str(Path(__file__).resolve().parent)
79
+ if blocking_directory not in sys.path:
80
+ sys.path.insert(0, blocking_directory)
81
+
82
+ from final_reply_gate import blocks_masked, prose_paragraphs
83
+ from hooks_constants.final_reply_gate_constants import (
84
+ ALL_HTML_BLOCK_CLOSER_PATTERNS,
85
+ CARRIAGE_RETURN_LINE_BREAK,
86
+ HTML_BLOCK_OPENER_PATTERN,
87
+ LINE_BREAK,
88
+ )
89
+ from hooks_constants.open_tasks_stop_gate_constants import (
90
+ ALL_ASK_ONLY_ENVELOPE_MARKERS,
91
+ ALL_PROMISED_REPORT_PATTERNS,
92
+ ASK_NEGATOR_PATTERN,
93
+ BACKTICK_TEXT_PATTERN,
94
+ ALL_INDENTED_LINE_PREFIXES,
95
+ COMPLETION_NEGATOR_GROUP,
96
+ COMPLETION_WORD_PATTERN,
97
+ DONE_LEAD_TAIL_PATTERN,
98
+ GOVERNANCE_BREAK_PATTERN,
99
+ LATER_TIME_PATTERN,
100
+ LEAD_NEGATOR_PATTERN,
101
+ LEAD_QUOTED_TEXT_PATTERN,
102
+ LIST_ASK_PATTERN,
103
+ OPEN_ITEM_LEAD_PATTERN,
104
+ OPEN_ITEM_LIST_MINIMUM,
105
+ PROMISE_NEGATOR_PATTERN,
106
+ PROMPT_CLAUSE_SPLIT_PATTERN,
107
+ QUOTED_PROMPT_LINE_PATTERN,
108
+ QUOTED_REPLY_LINE_PATTERN,
109
+ REMOVED_PROMPT_TEXT,
110
+ REPLY_SENTENCE_END_PATTERN,
111
+ REPORT_NOUN_ASK_PATTERN,
112
+ REPORT_VERB_ASK_PATTERN,
113
+ SPACED_QUOTE_PATTERN,
114
+ )
115
+ from hooks_constants.question_brief_gate_constants import (
116
+ TABLE_ROW_LINE_PATTERN,
117
+ TABLE_SEPARATOR_LINE_PATTERN,
118
+ )
119
+ from hooks_constants.spawn_readiness_hook_constants import ALL_HARNESS_ENVELOPE_MARKERS
120
+ from open_task_asks import prompt_without_reminders
121
+ from question_brief_gate import is_item_line, lines_outside_code_fences
122
+
123
+
124
+ class OpenItemList(NamedTuple):
125
+ """A run of open items in a closing reply: the lead line above it, and how many items it holds."""
126
+
127
+ lead: str
128
+ item_count: int
129
+
130
+
131
+ def _prompt_asks_for(
132
+ prompt_text: str, ask_pattern: re.Pattern[str], clause_pattern: re.Pattern[str] | None
133
+ ) -> bool:
134
+ stripped_text = prompt_without_reminders(prompt_text)
135
+ if stripped_text.startswith((*ALL_HARNESS_ENVELOPE_MARKERS, *ALL_ASK_ONLY_ENVELOPE_MARKERS)):
136
+ return False
137
+ cleaned_text = QUOTED_PROMPT_LINE_PATTERN.sub(REMOVED_PROMPT_TEXT, stripped_text)
138
+ cleaned_text = BACKTICK_TEXT_PATTERN.sub(REMOVED_PROMPT_TEXT, cleaned_text)
139
+ cleaned_text = SPACED_QUOTE_PATTERN.sub(REMOVED_PROMPT_TEXT, cleaned_text)
140
+ return any(
141
+ ASK_NEGATOR_PATTERN.search(each_clause[: each_ask.start()]) is None
142
+ for each_clause in PROMPT_CLAUSE_SPLIT_PATTERN.split(cleaned_text)
143
+ if clause_pattern is None or clause_pattern.search(each_clause) is not None
144
+ for each_ask in ask_pattern.finditer(each_clause)
145
+ )
146
+
147
+
148
+ def _prompt_asks_for_report(prompt_text: str) -> bool:
149
+ return _prompt_asks_for(prompt_text, REPORT_VERB_ASK_PATTERN, None) or _prompt_asks_for(
150
+ prompt_text, REPORT_NOUN_ASK_PATTERN, LATER_TIME_PATTERN
151
+ )
152
+
153
+
154
+ def prompt_asks_for_list(prompt_text: str) -> bool:
155
+ """Return True when the typed prompt asks for a list, by the ask rules above.
156
+
157
+ ::
158
+
159
+ "list the deferred items as bullets" -> True
160
+ "don't list them, just fix them" -> False
161
+ "Fix the build" -> False
162
+ """
163
+ return _prompt_asks_for(prompt_text, LIST_ASK_PATTERN, None)
164
+
165
+
166
+ def _sentence_before(paragraph_text: str, match_start: int) -> str:
167
+ all_sentence_ends = list(REPLY_SENTENCE_END_PATTERN.finditer(paragraph_text, 0, match_start))
168
+ sentence_start = all_sentence_ends[-1].end() if all_sentence_ends else 0
169
+ return paragraph_text[sentence_start:match_start]
170
+
171
+
172
+ def promised_report_phrase(reply_text: str, prompt_text: str) -> str | None:
173
+ """Return the words in the closing reply that promise the user a later report, or None.
174
+
175
+ ::
176
+
177
+ "The benchmark table will be posted when you get back." -> "when you get back"
178
+ "I'll report back once CI ends." -> "I'll report back"
179
+ "No report will follow." -> None
180
+ the promise, after the prompt "report back when the run ends" -> None
181
+
182
+ Args:
183
+ reply_text: The closing reply the turn ends with.
184
+ prompt_text: The prompt that started the turn.
185
+
186
+ Returns:
187
+ The matched promise, or None when the reply holds none or the prompt asked for a report.
188
+ """
189
+ if _prompt_asks_for_report(prompt_text):
190
+ return None
191
+ all_promises = (
192
+ _unnegated_promise(each_paragraph) for each_paragraph in prose_paragraphs(reply_text)
193
+ )
194
+ return next((each_promise for each_promise in all_promises if each_promise is not None), None)
195
+
196
+
197
+ def _unnegated_promise(paragraph_text: str) -> str | None:
198
+ all_matches = (
199
+ each_match
200
+ for each_pattern in ALL_PROMISED_REPORT_PATTERNS
201
+ for each_match in each_pattern.finditer(paragraph_text)
202
+ )
203
+ return next(
204
+ (
205
+ each_match.group()
206
+ for each_match in all_matches
207
+ if PROMISE_NEGATOR_PATTERN.search(_sentence_before(paragraph_text, each_match.start()))
208
+ is None
209
+ ),
210
+ None,
211
+ )
212
+
213
+
214
+ def _html_block_closer_for(opener: re.Match[str]) -> re.Pattern[str]:
215
+ return ALL_HTML_BLOCK_CLOSER_PATTERNS[opener.lastgroup or ""]
216
+
217
+
218
+ def _is_run_line(line: str, next_line: str) -> bool:
219
+ if QUOTED_REPLY_LINE_PATTERN.match(line):
220
+ return False
221
+ return is_item_line(line, next_line) or bool(
222
+ TABLE_ROW_LINE_PATTERN.match(line) or TABLE_SEPARATOR_LINE_PATTERN.match(line)
223
+ )
224
+
225
+
226
+ def _is_run_continuation(line: str) -> bool:
227
+ return not line.strip() or line.startswith(ALL_INDENTED_LINE_PREFIXES)
228
+
229
+
230
+ def _line_after(all_lines: list[str], line_index: int) -> str:
231
+ return all_lines[line_index + 1] if line_index + 1 < len(all_lines) else ""
232
+
233
+
234
+ def _is_item_at(all_lines: list[str], line_index: int) -> bool:
235
+ line = all_lines[line_index]
236
+ next_line = _line_after(all_lines, line_index)
237
+ return _is_run_line(line, next_line) and is_item_line(line, next_line)
238
+
239
+
240
+ def _continues_run_at(all_lines: list[str], line_index: int) -> bool:
241
+ line = all_lines[line_index]
242
+ return _is_run_line(line, _line_after(all_lines, line_index)) or _is_run_continuation(line)
243
+
244
+
245
+ def _item_run_at(all_lines: list[str], run_start: int) -> tuple[int, int]:
246
+ item_count = 0
247
+ line_index = run_start
248
+ while line_index < len(all_lines) and _continues_run_at(all_lines, line_index):
249
+ item_count += _is_item_at(all_lines, line_index)
250
+ line_index += 1
251
+ return line_index, item_count
252
+
253
+
254
+ def _lead_above(all_lines: list[str], run_start: int) -> str:
255
+ return next(
256
+ (each_line.strip() for each_line in reversed(all_lines[:run_start]) if each_line.strip()),
257
+ "",
258
+ )
259
+
260
+
261
+ def _reply_lines(reply_text: str) -> list[str]:
262
+ line_feed_text = reply_text.replace(CARRIAGE_RETURN_LINE_BREAK, LINE_BREAK)
263
+ return lines_outside_code_fences(
264
+ blocks_masked(line_feed_text, HTML_BLOCK_OPENER_PATTERN, _html_block_closer_for)
265
+ )
266
+
267
+
268
+ def _governs(lead: str, open_match: re.Match[str], completion_match: re.Match[str]) -> bool:
269
+ if completion_match.group(COMPLETION_NEGATOR_GROUP) is not None:
270
+ return False
271
+ if completion_match.start() < open_match.end() and open_match.start() < completion_match.end():
272
+ return False
273
+ gap_start = min(open_match.end(), completion_match.end())
274
+ gap_end = max(open_match.start(), completion_match.start())
275
+ return GOVERNANCE_BREAK_PATTERN.search(lead, gap_start, gap_end) is None
276
+
277
+
278
+ def _ends_in_done_word(lead: str, all_completion_matches: list[re.Match[str]]) -> bool:
279
+ if not all_completion_matches:
280
+ return False
281
+ last_completion_match = all_completion_matches[-1]
282
+ if last_completion_match.group(COMPLETION_NEGATOR_GROUP) is not None:
283
+ return False
284
+ return DONE_LEAD_TAIL_PATTERN.fullmatch(lead, last_completion_match.end()) is not None
285
+
286
+
287
+ def _is_open_item_lead(lead: str) -> bool:
288
+ unquoted_lead = LEAD_QUOTED_TEXT_PATTERN.sub(REMOVED_PROMPT_TEXT, lead)
289
+ if LEAD_NEGATOR_PATTERN.search(unquoted_lead) is not None:
290
+ return False
291
+ all_completion_matches = list(COMPLETION_WORD_PATTERN.finditer(unquoted_lead))
292
+ if _ends_in_done_word(unquoted_lead, all_completion_matches):
293
+ return False
294
+ return any(
295
+ not any(
296
+ _governs(unquoted_lead, each_open_match, each_completion_match)
297
+ for each_completion_match in all_completion_matches
298
+ )
299
+ for each_open_match in OPEN_ITEM_LEAD_PATTERN.finditer(unquoted_lead)
300
+ )
301
+
302
+
303
+ def _next_filled_line_index(all_lines: list[str], line_index: int) -> int | None:
304
+ return next(
305
+ (each_next for each_next in range(line_index + 1, len(all_lines)) if all_lines[each_next].strip()),
306
+ None,
307
+ )
308
+
309
+
310
+ def item_count_under(reply_text: str, lead: str) -> int:
311
+ """Return how many items the run under the lead line holds, or every item line in the reply when no run follows it.
312
+
313
+ ::
314
+
315
+ "Open calls:" over 3 bullets, then 2 more bullets elsewhere -> 3
316
+ a lead the reply holds on no line above a run -> 5
317
+
318
+ The lead matches the first line that holds its first line of text.
319
+ Fences, HTML blocks, and quoted lines are left out, as in ``open_item_list``.
320
+ """
321
+ all_lines = _reply_lines(reply_text)
322
+ all_lead_lines = lead.strip().splitlines()
323
+ lead_line = all_lead_lines[0].strip() if all_lead_lines else ""
324
+ for each_index, each_line in enumerate(all_lines):
325
+ if not lead_line or lead_line not in each_line:
326
+ continue
327
+ run_start = _next_filled_line_index(all_lines, each_index)
328
+ if run_start is not None and _is_run_line(all_lines[run_start], _line_after(all_lines, run_start)):
329
+ return _item_run_at(all_lines, run_start)[1]
330
+ break
331
+ return sum(_is_item_at(all_lines, each_index) for each_index in range(len(all_lines)))
332
+
333
+
334
+ def open_item_list(reply_text: str, prompt_text: str) -> OpenItemList | None:
335
+ """Return the first run of 3 or more open items under an open-item lead in the closing reply, or None.
336
+
337
+ ::
338
+
339
+ "What I deferred:" over 5 numbered lines -> OpenItemList("What I deferred:", 5)
340
+ "Open items:" over a table with 3 body rows -> OpenItemList("Open items:", 3)
341
+ "Changed files:" over 5 bullets -> None
342
+ "Nothing deferred." over 3 bullets -> None
343
+ the list, after the prompt "list the deferred items as bullets" -> None
344
+
345
+ Args:
346
+ reply_text: The closing reply the turn ends with.
347
+ prompt_text: The prompt that started the turn.
348
+
349
+ Returns:
350
+ The lead and the item count, or None when no run qualifies or the prompt asked for a list.
351
+ """
352
+ if prompt_asks_for_list(prompt_text):
353
+ return None
354
+ all_lines = _reply_lines(reply_text)
355
+ line_index = 0
356
+ while line_index < len(all_lines):
357
+ if not _is_run_line(all_lines[line_index], _line_after(all_lines, line_index)):
358
+ line_index += 1
359
+ continue
360
+ run_end, item_count = _item_run_at(all_lines, line_index)
361
+ lead = _lead_above(all_lines, line_index)
362
+ if item_count >= OPEN_ITEM_LIST_MINIMUM and _is_open_item_lead(lead):
363
+ return OpenItemList(lead, item_count)
364
+ line_index = run_end
365
+ return None