claude-dev-env 8.114.7 → 8.114.9

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 (35) hide show
  1. package/.agents/skills/build-eval/reference/context-budget.md +2 -0
  2. package/hooks/blocking/final_reply_gate.py +4 -3
  3. package/hooks/blocking/merge_review_gate.py +98 -1
  4. package/hooks/blocking/owned_pr_merge_stop_gate.py +50 -20
  5. package/hooks/blocking/reply_length_gate.py +52 -10
  6. package/hooks/blocking/test_final_reply_gate.py +136 -0
  7. package/hooks/blocking/test_merge_review_gate.py +48 -0
  8. package/hooks/blocking/test_owned_pr_merge_stop_gate.py +97 -6
  9. package/hooks/blocking/test_reply_length_gate.py +39 -0
  10. package/hooks/context_budget/model.py +3 -0
  11. package/hooks/context_budget/policy_changes.py +54 -5
  12. package/hooks/context_budget/policy_file.py +1 -0
  13. package/hooks/context_budget/tests/test_model.py +1 -0
  14. package/hooks/context_budget/tests/test_policy_changes.py +121 -1
  15. package/hooks/context_budget/tests/test_policy_file.py +11 -0
  16. package/hooks/features/bash-dispatchers.md +2 -2
  17. package/hooks/features/conduct-gates.md +3 -3
  18. package/hooks/hooks_constants/context_budget_constants.py +1 -0
  19. package/hooks/hooks_constants/merge_review_gate_constants.py +28 -1
  20. package/hooks/hooks_constants/owned_pr_merge_stop_gate_constants.py +4 -1
  21. package/hooks/hooks_constants/owned_pr_review_loop_constants.py +4 -0
  22. package/hooks/hooks_constants/reply_length_gate_constants.py +17 -1
  23. package/hooks/hooks_constants/test_reply_length_gate_constants.py +20 -0
  24. package/hooks/hooks_constants/test_usage_pace_constants.py +8 -1
  25. package/hooks/hooks_constants/test_visual_reply_rules_constants.py +5 -0
  26. package/hooks/hooks_constants/usage_pace_constants.py +1 -0
  27. package/hooks/hooks_constants/visual_reply_rules_constants.py +11 -0
  28. package/hooks/owned_pr_session_record.py +76 -1
  29. package/hooks/routing/test_usage_pace.py +60 -2
  30. package/hooks/routing/usage_pace.py +26 -11
  31. package/hooks/test_owned_pr_session_record.py +26 -0
  32. package/hooks/test_visual_reply_rules.py +27 -0
  33. package/hooks/visual_reply_rules.py +64 -0
  34. package/package.json +1 -1
  35. package/scripts/tests/test_policy_lint_rules_context_budget.py +15 -0
@@ -154,13 +154,29 @@ UNVALIDATED_CLAIM_MESSAGE = (
154
154
  " this turn, report it as `Open: <check> - <next step>`."
155
155
  )
156
156
  CITED_NUMBER_PATTERN = re.compile(
157
- r"/actions/runs/(\d+)|/pull/(\d+)|\b(?:run|job|check)\s+#?(\d{5,})\b", re.IGNORECASE
157
+ r"/actions/runs/(\d+)|/pull/(?P<pull_number>\d+)|\b(?:run|job|check)\s+#?(\d{5,})\b",
158
+ re.IGNORECASE,
158
159
  )
160
+ CITED_PULL_NUMBER_GROUP = "pull_number"
159
161
  CITED_NUMBER_IN_RESULT_TEMPLATE = r"(?<!\d){number}(?!\d)"
162
+ PULL_LINK_IN_HOOK_TEXT_TEMPLATE = r"/pull/{number}(?!\d)"
160
163
  UNSEEN_CITATION_MESSAGE = (
161
164
  'The text cites "{citation}", and no tool result in this session shows it.'
162
165
  " Read it yourself or through a subagent first."
163
166
  )
167
+ ALL_REPLY_QUOTING_MESSAGES = (
168
+ UNSEEN_CITATION_MESSAGE,
169
+ UNVALIDATED_CLAIM_MESSAGE,
170
+ UNSOURCED_CAUSE_MESSAGE,
171
+ LONG_SENTENCE_MESSAGE,
172
+ )
173
+ MESSAGE_PLACEHOLDER_PATTERN = re.compile(r"\\\{\w+\\\}")
174
+ REPLY_ECHO_PATTERN = re.compile(
175
+ "|".join(
176
+ MESSAGE_PLACEHOLDER_PATTERN.sub(".*?", re.escape(each_message))
177
+ for each_message in ALL_REPLY_QUOTING_MESSAGES
178
+ )
179
+ )
164
180
 
165
181
  ADDITIONAL_CONTEXT_KEY = "additionalContext"
166
182
  ALL_CHECKED_MCP_TOOL_NAMES = frozenset(
@@ -11,6 +11,26 @@ def test_gate_checks_the_three_chat_tools_that_post_to_the_user() -> None:
11
11
  )
12
12
 
13
13
 
14
+ def test_reply_echo_pattern_matches_each_message_that_quotes_the_reply() -> None:
15
+ quoted = 'See "the /pull/8127 link" there'
16
+ all_messages = [
17
+ constants.UNSEEN_CITATION_MESSAGE.format(citation="/pull/8127"),
18
+ constants.UNVALIDATED_CLAIM_MESSAGE.format(claim=quoted),
19
+ constants.UNSOURCED_CAUSE_MESSAGE.format(sentence=quoted),
20
+ constants.LONG_SENTENCE_MESSAGE.format(word_count=40, word_limit=35, sentence_preview=quoted),
21
+ ]
22
+ for each_message in all_messages:
23
+ assert constants.REPLY_ECHO_PATTERN.sub("", f"before {each_message} after") == "before after"
24
+
25
+
26
+ def test_cited_number_pattern_names_the_pull_request_group() -> None:
27
+ all_pull_numbers = [
28
+ each_match[constants.CITED_PULL_NUMBER_GROUP]
29
+ for each_match in constants.CITED_NUMBER_PATTERN.finditer("see https://github.com/o/r/pull/42, run 123456")
30
+ ]
31
+ assert all_pull_numbers == ["42", None]
32
+
33
+
14
34
  def test_gate_exit_codes_match_the_hook_contract() -> None:
15
35
  assert (constants.ALLOW_EXIT_CODE, constants.BLOCK_EXIT_CODE) == (0, 2)
16
36
 
@@ -1,6 +1,9 @@
1
1
  from datetime import timedelta
2
2
 
3
- from hooks_constants.usage_pace_constants import ALL_RATE_WINDOW_LENGTHS
3
+ from hooks_constants.usage_pace_constants import (
4
+ ALL_OPTIONAL_WINDOW_NAMES,
5
+ ALL_RATE_WINDOW_LENGTHS,
6
+ )
4
7
 
5
8
 
6
9
  def test_usage_pace_windows_have_expected_lengths() -> None:
@@ -8,3 +11,7 @@ def test_usage_pace_windows_have_expected_lengths() -> None:
8
11
  "five_hour": timedelta(hours=5),
9
12
  "seven_day": timedelta(days=7),
10
13
  }
14
+
15
+
16
+ def test_usage_pace_treats_only_the_five_hour_window_as_optional() -> None:
17
+ assert ALL_OPTIONAL_WINDOW_NAMES == {"five_hour"}
@@ -4,6 +4,11 @@ import re
4
4
  from hooks_constants import visual_reply_rules_constants as constants
5
5
 
6
6
 
7
+ def test_hook_text_attachment_types_leave_out_blocking_errors() -> None:
8
+ assert "hook_blocking_error" not in constants.ALL_HOOK_TEXT_ATTACHMENT_TYPES
9
+ assert "hook_additional_context" in constants.ALL_HOOK_TEXT_ATTACHMENT_TYPES
10
+
11
+
7
12
  def test_rules_file_path_points_at_the_shipped_rule_list() -> None:
8
13
  assert constants.RULES_FILE_PATH.is_file()
9
14
 
@@ -30,6 +30,7 @@ ALL_RATE_WINDOW_LENGTHS = (
30
30
  ("five_hour", timedelta(hours=5)),
31
31
  ("seven_day", timedelta(days=7)),
32
32
  )
33
+ ALL_OPTIONAL_WINDOW_NAMES = frozenset({"five_hour"})
33
34
  PERCENT_SCALE = 100.0
34
35
  PERCENT_DECIMAL_PLACES = 1
35
36
  MINIMUM_ELAPSED_PERCENT_FOR_PACE = 10.0
@@ -81,6 +81,17 @@ IS_ERROR_KEY = "is_error"
81
81
  IS_META_KEY = "isMeta"
82
82
  BLOCK_TEXT_KEY = "text"
83
83
  RESULT_TEXT_SEPARATOR = "\n"
84
+ ATTACHMENT_ENTRY_TYPE = "attachment"
85
+ ATTACHMENT_KEY = "attachment"
86
+ QUEUED_COMMAND_ATTACHMENT_TYPE = "queued_command"
87
+ ALL_HOOK_TEXT_ATTACHMENT_TYPES = frozenset(
88
+ {"hook_additional_context", "hook_system_message", QUEUED_COMMAND_ATTACHMENT_TYPE}
89
+ )
90
+ ALL_ATTACHMENT_TEXT_KEYS = ("content", "prompt")
91
+ ALL_HOOK_MESSAGE_PREFIXES = ("Stop hook feedback:", "<system-reminder>")
92
+ ORIGIN_KEY = "origin"
93
+ ORIGIN_KIND_KEY = "kind"
94
+ TASK_NOTIFICATION_ORIGIN_KIND = "task-notification"
84
95
 
85
96
  ABBREVIATION_MESSAGE = 'Abbreviation "{abbreviation}" in the text. {reminder}'
86
97
  TRACKER_NUMBER_MESSAGE = 'Tracker number "{reference}" in the text. {reminder}'
@@ -10,6 +10,12 @@ request Stop gate reads the same file back::
10
10
 
11
11
  Both Claude Code and Codex send ``session_id`` to PostToolUse and Stop hooks,
12
12
  so the file links the two hooks on either host.
13
+
14
+ The Stop gate keeps its own file of the head it last blocked on for each
15
+ pull request, so it blocks once per head::
16
+
17
+ owned-pr-stop-blocks-<session id>.json
18
+ {"https://github.com/acme/widgets/pull/42": "<head sha>"}
13
19
  """
14
20
 
15
21
  from __future__ import annotations
@@ -25,10 +31,19 @@ from hooks_constants.owned_pr_review_loop_constants import (
25
31
  NAME_DIGEST_TEXT_ENCODING,
26
32
  SESSION_RECORD_FILE_TEMPLATE,
27
33
  SESSION_RECORD_TEMPORARY_PREFIX,
34
+ STOP_BLOCK_RECORD_FILE_TEMPLATE,
35
+ STOP_BLOCK_RECORD_TEMPORARY_PREFIX,
28
36
  )
29
37
  from hooks_constants.session_file_id import session_file_id
30
38
 
31
- __all__ = ["session_record_path", "all_recorded_pull_requests", "record_pull_request"]
39
+ __all__ = [
40
+ "session_record_path",
41
+ "all_recorded_pull_requests",
42
+ "record_pull_request",
43
+ "stop_block_record_path",
44
+ "all_blocked_heads",
45
+ "record_blocked_heads",
46
+ ]
32
47
 
33
48
 
34
49
  def session_record_path(session_id: object) -> Path:
@@ -102,3 +117,63 @@ def record_pull_request(session_id: object, all_pull_request_fields: dict[str, s
102
117
  )
103
118
  except (OSError, UnicodeError):
104
119
  return
120
+
121
+
122
+ def stop_block_record_path(session_id: object) -> Path:
123
+ """Return the file that maps each pull request url to the head the Stop gate last blocked on.
124
+
125
+ Args:
126
+ session_id: The ``session_id`` field of the hook payload.
127
+ """
128
+ file_name = STOP_BLOCK_RECORD_FILE_TEMPLATE.format(session_file_id=session_file_id(session_id))
129
+ return Path(tempfile.gettempdir()) / file_name
130
+
131
+
132
+ def all_blocked_heads(session_id: object) -> dict[str, str]:
133
+ """Return the head sha the Stop gate last blocked on, keyed by pull request url.
134
+
135
+ A payload with no session id, or a missing, unreadable, or malformed
136
+ file, reads as no blocks.
137
+
138
+ Args:
139
+ session_id: The ``session_id`` field of the hook payload.
140
+ """
141
+ if not _is_session_id(session_id):
142
+ return {}
143
+ try:
144
+ record_text = stop_block_record_path(session_id).read_text(encoding=NAME_DIGEST_TEXT_ENCODING)
145
+ all_heads_by_url = json.loads(record_text)
146
+ except (OSError, ValueError):
147
+ return {}
148
+ if not isinstance(all_heads_by_url, dict):
149
+ return {}
150
+ return {
151
+ each_url: each_head
152
+ for each_url, each_head in all_heads_by_url.items()
153
+ if isinstance(each_url, str) and isinstance(each_head, str)
154
+ }
155
+
156
+
157
+ def record_blocked_heads(session_id: object, all_heads_by_url: dict[str, str]) -> None:
158
+ """Record the head sha each pull request was blocked on, keeping the other entries.
159
+
160
+ A payload with no session id records nothing. A write that fails leaves
161
+ the record as it was, so the gate blocks again on the next stop.
162
+
163
+ Args:
164
+ session_id: The ``session_id`` field of the hook payload.
165
+ all_heads_by_url: The head sha to record for each pull request url.
166
+ """
167
+ if not _is_session_id(session_id):
168
+ return
169
+ try:
170
+ write_text_atomically(
171
+ stop_block_record_path(session_id),
172
+ json.dumps({**all_blocked_heads(session_id), **all_heads_by_url}),
173
+ NAME_DIGEST_TEXT_ENCODING,
174
+ STOP_BLOCK_RECORD_TEMPORARY_PREFIX,
175
+ ATOMIC_WRITE_TEMPORARY_SUFFIX,
176
+ False,
177
+ )
178
+ except (OSError, UnicodeError):
179
+ return
@@ -105,7 +105,9 @@ def test_should_report_under_pace_when_every_window_trails() -> None:
105
105
  @pytest.mark.parametrize(
106
106
  "broken_payload",
107
107
  [
108
- {"seven_day": {"utilization": 20.0, "resets_at": WEEKLY_RESET}},
108
+ {"five_hour": {"utilization": 1.0, "resets_at": FIVE_HOUR_RESET}},
109
+ {"five_hour": None, "seven_day": None},
110
+ {},
109
111
  {
110
112
  "five_hour": {"utilization": None, "resets_at": FIVE_HOUR_RESET},
111
113
  "seven_day": {"utilization": 1.0, "resets_at": WEEKLY_RESET},
@@ -123,6 +125,42 @@ def test_should_treat_a_missing_or_unreadable_window_as_unreadable(
123
125
  measure_account_pace(broken_payload, NOW)
124
126
 
125
127
 
128
+ @pytest.mark.parametrize(
129
+ "weekly_only_payload",
130
+ [
131
+ {"five_hour": None, "seven_day": {"utilization": 93.0, "resets_at": WEEKLY_RESET}},
132
+ {"seven_day": {"utilization": 93.0, "resets_at": WEEKLY_RESET}},
133
+ ],
134
+ )
135
+ def test_should_measure_only_the_weekly_window_when_the_account_has_no_five_hour_window(
136
+ weekly_only_payload: dict[str, object],
137
+ ) -> None:
138
+ all_window_paces = measure_account_pace(weekly_only_payload, NOW)
139
+ assert [each.name for each in all_window_paces] == ["seven_day"]
140
+ verdict = build_verdict(all_window_paces, NOW)
141
+ assert verdict["over_pace"] is True
142
+ assert [each["window"] for each in verdict["windows"]] == ["seven_day"]
143
+
144
+
145
+ def test_should_report_under_pace_when_a_weekly_only_account_trails_the_clock() -> None:
146
+ weekly_only_payload = {
147
+ "five_hour": None,
148
+ "seven_day": {"utilization": 20.0, "resets_at": WEEKLY_RESET},
149
+ }
150
+ verdict = build_verdict(measure_account_pace(weekly_only_payload, NOW), NOW)
151
+ assert verdict["over_pace"] is False
152
+ assert [each["window"] for each in verdict["windows"]] == ["seven_day"]
153
+
154
+
155
+ def test_should_still_reject_a_five_hour_window_that_is_present_but_unreadable() -> None:
156
+ broken_five_hour_payload = {
157
+ "five_hour": {"utilization": 1.0},
158
+ "seven_day": {"utilization": 1.0, "resets_at": WEEKLY_RESET},
159
+ }
160
+ with pytest.raises(UsageUnreadable):
161
+ measure_account_pace(broken_five_hour_payload, NOW)
162
+
163
+
126
164
  def test_should_exit_zero_with_the_verdict_when_over_pace(tmp_path: Path) -> None:
127
165
  exit_code, verdict = _run_script(tmp_path, _payload(3.0, 93.0))
128
166
  assert exit_code == 0
@@ -135,8 +173,28 @@ def test_should_exit_one_when_under_pace(tmp_path: Path) -> None:
135
173
  assert verdict["over_pace"] is False
136
174
 
137
175
 
176
+ def test_should_exit_zero_for_a_weekly_only_account_running_ahead(tmp_path: Path) -> None:
177
+ exit_code, verdict = _run_script(
178
+ tmp_path,
179
+ {"five_hour": None, "seven_day": {"utilization": 93.0, "resets_at": WEEKLY_RESET}},
180
+ )
181
+ assert exit_code == 0
182
+ assert verdict["over_pace"] is True
183
+ assert [each["window"] for each in verdict["windows"]] == ["seven_day"]
184
+
185
+
186
+ def test_should_exit_one_for_a_weekly_only_account_under_pace(tmp_path: Path) -> None:
187
+ exit_code, verdict = _run_script(
188
+ tmp_path,
189
+ {"five_hour": None, "seven_day": {"utilization": 20.0, "resets_at": WEEKLY_RESET}},
190
+ )
191
+ assert exit_code == 1
192
+ assert verdict["over_pace"] is False
193
+ assert [each["window"] for each in verdict["windows"]] == ["seven_day"]
194
+
195
+
138
196
  def test_should_exit_two_with_a_null_verdict_when_unreadable(tmp_path: Path) -> None:
139
197
  exit_code, verdict = _run_script(tmp_path, {"five_hour": None})
140
198
  assert exit_code == 2
141
199
  assert verdict["over_pace"] is None
142
- assert verdict["error"] == "usage response has no five_hour window"
200
+ assert verdict["error"] == "usage response has no seven_day window"
@@ -12,10 +12,12 @@
12
12
 
13
13
  A window is over pace when at least 10% of it has elapsed and its used percent
14
14
  exceeds the percent already elapsed. The floor keeps a window's first minutes,
15
- where any spend outruns the clock, from reading as over pace. The account is over pace when any window is. The script reads
16
- the OAuth usage endpoint with the session ingress bearer token, the same probe
17
- the usage-pause skill's ``resolve_usage_window.py`` uses. It never prints or
18
- stores the token.
15
+ where any spend outruns the clock, from reading as over pace. The account is
16
+ over pace when any window is. An account with only a weekly window reports
17
+ ``five_hour`` as null or leaves it out, and the verdict then covers the weekly
18
+ window alone. The script reads the OAuth usage endpoint with the session
19
+ ingress bearer token, the same probe the usage-pause skill's
20
+ ``resolve_usage_window.py`` uses. It never prints or stores the token.
19
21
 
20
22
  Exit codes: 0 over pace, 1 under pace, 2 unreadable. ``--payload-file`` and
21
23
  ``--now`` replace the live probe and the clock for a deterministic run.
@@ -39,6 +41,7 @@ if hooks_root_directory not in sys.path:
39
41
  sys.path.insert(0, hooks_root_directory)
40
42
 
41
43
  from hooks_constants.usage_pace_constants import (
44
+ ALL_OPTIONAL_WINDOW_NAMES,
42
45
  ALL_RATE_WINDOW_LENGTHS,
43
46
  ANTHROPIC_BETA_HEADER,
44
47
  AUTHORIZATION_HEADER,
@@ -169,22 +172,34 @@ def measure_window_pace(
169
172
  def measure_account_pace(
170
173
  all_usage_buckets: dict[str, object], now: datetime
171
174
  ) -> list[WindowPace]:
172
- """Measure every rate window the verdict covers.
175
+ """Measure every rate window the account has.
176
+
177
+ ::
178
+
179
+ {"five_hour": None, "seven_day": {...}} -> [seven_day]
180
+ {"five_hour": {...}, "seven_day": {...}} -> [five_hour, seven_day]
181
+
182
+ The five-hour window is optional because accounts with only a weekly
183
+ window report it as null or leave it out. The weekly window is required.
173
184
 
174
185
  Args:
175
186
  all_usage_buckets: The decoded usage response body.
176
187
  now: The time the pace is measured at.
177
188
 
178
189
  Returns:
179
- One WindowPace per rate window, five-hour first.
190
+ One WindowPace per rate window the account has, five-hour first.
180
191
 
181
192
  Raises:
182
- UsageUnreadable: Any covered window is missing or unreadable.
193
+ UsageUnreadable: A required window is missing, or a window that is
194
+ present is unreadable.
183
195
  """
184
- return [
185
- measure_window_pace(each_name, each_length, all_usage_buckets.get(each_name), now)
186
- for each_name, each_length in ALL_RATE_WINDOW_LENGTHS
187
- ]
196
+ all_window_paces: list[WindowPace] = []
197
+ for each_name, each_length in ALL_RATE_WINDOW_LENGTHS:
198
+ each_bucket = all_usage_buckets.get(each_name)
199
+ if each_bucket is None and each_name in ALL_OPTIONAL_WINDOW_NAMES:
200
+ continue
201
+ all_window_paces.append(measure_window_pace(each_name, each_length, each_bucket, now))
202
+ return all_window_paces
188
203
 
189
204
 
190
205
  def build_verdict(
@@ -22,6 +22,32 @@ def isolated_temp_folder(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> Non
22
22
  monkeypatch.setattr(owned_pr_session_record.tempfile, "gettempdir", lambda: str(tmp_path))
23
23
 
24
24
 
25
+ def test_record_blocked_heads_should_keep_the_other_pull_requests() -> None:
26
+ owned_pr_session_record.record_blocked_heads(SESSION_ID, {PULL_REQUEST["url"]: "abc123"})
27
+ owned_pr_session_record.record_blocked_heads(SESSION_ID, {"https://github.com/o/r/pull/2": "def456"})
28
+ owned_pr_session_record.record_blocked_heads(SESSION_ID, {PULL_REQUEST["url"]: "fed789"})
29
+ assert owned_pr_session_record.all_blocked_heads(SESSION_ID) == {
30
+ PULL_REQUEST["url"]: "fed789",
31
+ "https://github.com/o/r/pull/2": "def456",
32
+ }
33
+
34
+
35
+ def test_all_blocked_heads_should_read_a_malformed_record_as_empty() -> None:
36
+ owned_pr_session_record.stop_block_record_path(SESSION_ID).write_text("[1, 2]", encoding="utf-8")
37
+ assert owned_pr_session_record.all_blocked_heads(SESSION_ID) == {}
38
+
39
+
40
+ def test_record_blocked_heads_should_skip_a_payload_with_no_session_id(tmp_path: Path) -> None:
41
+ owned_pr_session_record.record_blocked_heads(None, {PULL_REQUEST["url"]: "abc123"})
42
+ assert list(tmp_path.iterdir()) == []
43
+
44
+
45
+ def test_stop_block_record_path_should_stay_apart_from_the_pull_request_record() -> None:
46
+ assert owned_pr_session_record.stop_block_record_path(SESSION_ID) != (
47
+ owned_pr_session_record.session_record_path(SESSION_ID)
48
+ )
49
+
50
+
25
51
  def test_session_record_path_should_name_the_session_in_the_temp_folder(tmp_path: Path) -> None:
26
52
  assert (
27
53
  owned_pr_session_record.session_record_path("a/b c") == tmp_path / "owned-pr-loop-abc.json"
@@ -12,6 +12,7 @@ from hooks_constants.visual_reply_rules_constants import RULES_FILE_PATH
12
12
  from visual_reply_rules import (
13
13
  abbreviation_violation,
14
14
  attaches_picture,
15
+ hook_supplied_text,
15
16
  load_rules,
16
17
  mode_enabled,
17
18
  replies_sent_this_turn,
@@ -267,6 +268,32 @@ def test_successful_result_text_joins_only_results_without_an_error(tmp_path: Pa
267
268
  assert successful_result_text(str(tmp_path / "missing.jsonl")) is None
268
269
 
269
270
 
271
+ def test_hook_supplied_text_joins_hook_and_harness_text_only(tmp_path: Path) -> None:
272
+ all_entries = [
273
+ {"type": "user", "message": {"content": "pull/1 from the prompt"}},
274
+ {"type": "user", "isMeta": True, "message": {"content": "Stop hook feedback:\npull/2 open"}},
275
+ {"type": "user", "isMeta": True, "message": {"content": [{"type": "text", "text": "Base directory for this skill: pull/11"}]}},
276
+ {"type": "user", "isMeta": True, "message": {"content": "<system-reminder>\npull/12 watched\n</system-reminder>"}},
277
+ {"type": "user", "origin": {"kind": "task-notification"}, "message": {"content": "pull/3 done"}},
278
+ {"type": "attachment", "attachment": {"type": "hook_additional_context", "content": ["pull/4 ctx"]}},
279
+ {"type": "attachment", "attachment": {"type": "hook_system_message", "content": "pull/5 msg"}},
280
+ {
281
+ "type": "attachment",
282
+ "attachment": {"type": "queued_command", "origin": {"kind": "task-notification"}, "prompt": "pull/6 queued"},
283
+ },
284
+ {"type": "attachment", "attachment": {"type": "queued_command", "origin": {"kind": "human"}, "prompt": "pull/9 typed"}},
285
+ {"type": "attachment", "attachment": {"type": ["hook_additional_context"], "content": "pull/10 odd"}},
286
+ {"type": "attachment", "attachment": {"type": "hook_blocking_error", "blockingError": {"blockingError": "pull/7"}}},
287
+ {"type": "user", "message": {"content": [{"type": "tool_result", "content": "pull/8 result"}]}},
288
+ ]
289
+ transcript_path = tmp_path / "s.jsonl"
290
+ transcript_path.write_text("\n".join(json.dumps(each) for each in all_entries), encoding="utf-8")
291
+ assert hook_supplied_text(str(transcript_path)) == (
292
+ "Stop hook feedback:\npull/2 open\n<system-reminder>\npull/12 watched\n</system-reminder>\npull/3 done\npull/4 ctx\npull/5 msg\npull/6 queued"
293
+ )
294
+ assert hook_supplied_text(str(tmp_path / "missing.jsonl")) is None
295
+
296
+
270
297
  def test_reports_results_flags_a_markdown_table_and_three_figures() -> None:
271
298
  assert reports_results("| Check | Result |\n|---|---|\n| Unit tests | passed |")
272
299
  assert reports_results("The run shows 65 passed, 0 failed, and 3 skipped.")
@@ -21,10 +21,15 @@ from hooks_constants.visual_reply_rules_constants import (
21
21
  ABBREVIATION_MESSAGE,
22
22
  VIOLATION_LINE_SEPARATOR,
23
23
  ABBREVIATIONS_RULE_KEY,
24
+ ALL_ATTACHMENT_TEXT_KEYS,
25
+ ALL_HOOK_MESSAGE_PREFIXES,
26
+ ALL_HOOK_TEXT_ATTACHMENT_TYPES,
24
27
  ALL_REPLY_TOOL_NAME_SUFFIXES,
25
28
  ALL_VISUAL_TOOL_NAME_SUFFIXES,
26
29
  ALLOWED_CAPITALIZED_WORDS_KEY,
27
30
  ASSISTANT_ENTRY_TYPE,
31
+ ATTACHMENT_ENTRY_TYPE,
32
+ ATTACHMENT_KEY,
28
33
  BLOCK_ID_KEY,
29
34
  BLOCK_NAME_KEY,
30
35
  BLOCK_TEXT_KEY,
@@ -44,6 +49,9 @@ from hooks_constants.visual_reply_rules_constants import (
44
49
  NO_PICTURE_RULE_KEY,
45
50
  NO_VISUAL_MESSAGE,
46
51
  ONE_ITEM_RULE_KEY,
52
+ ORIGIN_KEY,
53
+ ORIGIN_KIND_KEY,
54
+ QUEUED_COMMAND_ATTACHMENT_TYPE,
47
55
  RULE_KEY_FIELD,
48
56
  RULE_LABEL_FIELD,
49
57
  RULE_REMINDER_FIELD,
@@ -52,6 +60,7 @@ from hooks_constants.visual_reply_rules_constants import (
52
60
  RULES_FILE_PATH,
53
61
  RULES_LIST_KEY,
54
62
  SECOND_REPLY_MESSAGE,
63
+ TASK_NOTIFICATION_ORIGIN_KIND,
55
64
  TEXT_BLOCK_TYPE,
56
65
  TOOL_RESULT_BLOCK_TYPE,
57
66
  TOOL_USE_BLOCK_TYPE,
@@ -326,6 +335,61 @@ def successful_result_text(transcript_path: object) -> str | None:
326
335
  )
327
336
 
328
337
 
338
+ def _attachment_texts(all_entry_fields: dict[str, object]) -> list[str]:
339
+ attachment = all_entry_fields.get(ATTACHMENT_KEY)
340
+ if not isinstance(attachment, dict):
341
+ return []
342
+ attachment_type = attachment.get(BLOCK_TYPE_KEY)
343
+ if not isinstance(attachment_type, str) or attachment_type not in ALL_HOOK_TEXT_ATTACHMENT_TYPES:
344
+ return []
345
+ if attachment_type == QUEUED_COMMAND_ATTACHMENT_TYPE and not _is_task_notification(attachment):
346
+ return []
347
+ all_texts = []
348
+ for each_key in ALL_ATTACHMENT_TEXT_KEYS:
349
+ field_value = attachment.get(each_key)
350
+ all_texts.extend(_result_texts(field_value))
351
+ if isinstance(field_value, list):
352
+ all_texts.extend(each_item for each_item in field_value if isinstance(each_item, str))
353
+ return all_texts
354
+
355
+
356
+ def _is_task_notification(all_entry_fields: dict[str, object]) -> bool:
357
+ origin = all_entry_fields.get(ORIGIN_KEY)
358
+ return isinstance(origin, dict) and origin.get(ORIGIN_KIND_KEY) == TASK_NOTIFICATION_ORIGIN_KIND
359
+
360
+
361
+ def _hook_texts(all_entry_fields: dict[str, object]) -> list[str]:
362
+ entry_type = all_entry_fields.get(ENTRY_TYPE_KEY)
363
+ if entry_type == ATTACHMENT_ENTRY_TYPE:
364
+ return _attachment_texts(all_entry_fields)
365
+ if entry_type != USER_ENTRY_TYPE:
366
+ return []
367
+ message = all_entry_fields.get(MESSAGE_KEY)
368
+ all_texts = _result_texts(message.get(CONTENT_KEY) if isinstance(message, dict) else None)
369
+ if _is_task_notification(all_entry_fields):
370
+ return all_texts
371
+ if not all_entry_fields.get(IS_META_KEY):
372
+ return []
373
+ return [each_text for each_text in all_texts if each_text.lstrip().startswith(ALL_HOOK_MESSAGE_PREFIXES)]
374
+
375
+
376
+ def hook_supplied_text(transcript_path: object) -> str | None:
377
+ """Join the text hooks and the harness put in the session outside tool results.
378
+
379
+ It covers stop-hook feedback, system reminders, a background agent's task
380
+ notification, and hook additional context, hook system message, and queued
381
+ task notification attachments. A skill body, or a prompt the user typed
382
+ while the session worked, does not count. Returns None when the transcript
383
+ cannot be read.
384
+ """
385
+ all_lines = _read_transcript_lines(transcript_path)
386
+ if all_lines is None:
387
+ return None
388
+ return RESULT_TEXT_SEPARATOR.join(
389
+ each_text for each_entry in _parsed_entries(all_lines) for each_text in _hook_texts(each_entry)
390
+ )
391
+
392
+
329
393
  def visual_shown_this_turn(all_transcript_lines: Iterable[str]) -> bool:
330
394
  """Return True when a widget or page call after the last prompt did not come back with an error."""
331
395
  all_entries = _entries_this_turn(all_transcript_lines)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-dev-env",
3
- "version": "8.114.7",
3
+ "version": "8.114.9",
4
4
  "description": "Claude Code development standards — rules, hooks, agents, commands, and skills",
5
5
  "type": "module",
6
6
  "bin": {
@@ -125,6 +125,21 @@ def test_raising_a_baseline_entry_is_a_shrink_only_finding(tmp_path: Path) -> No
125
125
  assert "the over-budget list may only shrink" in all_diagnostics[0].message
126
126
 
127
127
 
128
+ def test_a_first_baseline_on_a_policy_without_the_key_passes(tmp_path: Path) -> None:
129
+ raw_prior = _policy()
130
+ del raw_prior["baseline"]
131
+ current_text = json.dumps(_policy({_SKILL_PATH: {"lines": 300, "sections": []}}))
132
+ (tmp_path / _SKILL_PATH).parent.mkdir(parents=True)
133
+ (tmp_path / _SKILL_PATH).write_text("line\n" * 300, encoding="utf-8")
134
+
135
+ assert (
136
+ adapters.context_budget_policy_diagnostics(
137
+ _document(_POLICY_PATH, current_text, json.dumps(raw_prior)), tmp_path
138
+ )
139
+ == ()
140
+ )
141
+
142
+
128
143
  def test_a_new_or_shrunk_policy_file_passes_and_a_malformed_one_reports(
129
144
  tmp_path: Path,
130
145
  ) -> None: