claude-dev-env 8.116.0 → 8.116.2

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 (39) hide show
  1. package/bin/install.prompt-context.test.mjs +5 -6
  2. package/docs/rule-guides/proof-before-pull-request.md +4 -2
  3. package/hooks/blocking/final_reply_gate.py +7 -29
  4. package/hooks/blocking/followup_pr_dedupe.py +118 -33
  5. package/hooks/blocking/gate_run_reads.py +284 -0
  6. package/hooks/blocking/pr_lifecycle_skill_gate.py +33 -33
  7. package/hooks/blocking/pull_request_proof.py +60 -63
  8. package/hooks/blocking/test_final_reply_gate.py +4 -196
  9. package/hooks/blocking/test_followup_pr_dedupe.py +59 -0
  10. package/hooks/blocking/test_gate_run_reads.py +241 -0
  11. package/hooks/blocking/test_pr_lifecycle_skill_gate.py +89 -1
  12. package/hooks/blocking/test_pull_request_proof.py +63 -2
  13. package/hooks/features/conduct-gates.md +6 -13
  14. package/hooks/hooks.json +1 -42
  15. package/hooks/hooks_constants/background_silence_prompt_constants.py +2 -0
  16. package/hooks/hooks_constants/gate_run_reads_constants.py +10 -0
  17. package/hooks/hooks_constants/resolve_thread_reply_gate_constants.py +0 -8
  18. package/hooks/hooks_constants/test_followup_pr_dedupe_constants.py +0 -4
  19. package/hooks/session/background_silence_prompt.py +1 -1
  20. package/hooks/test_context_budget_hooks.py +0 -1
  21. package/package.json +1 -1
  22. package/scripts/durable_post_lint.py +0 -12
  23. package/scripts/durable_post_lint_config/config/constants.py +1 -2
  24. package/scripts/policy_lint/adapter_configuration.py +0 -2
  25. package/scripts/policy_lint/config/constants.py +0 -2
  26. package/scripts/test_durable_post_lint.py +0 -53
  27. package/scripts/tests/test_adapter_configuration.py +0 -16
  28. package/hooks/blocking/chat_reply_gate.py +0 -260
  29. package/hooks/blocking/reply_length_gate.py +0 -804
  30. package/hooks/blocking/test_chat_reply_gate.py +0 -302
  31. package/hooks/blocking/test_reply_length_gate.py +0 -1324
  32. package/hooks/hooks_constants/chat_reply_gate_constants.py +0 -60
  33. package/hooks/hooks_constants/reply_length_gate_constants.py +0 -203
  34. package/hooks/hooks_constants/test_reply_length_gate_constants.py +0 -81
  35. package/hooks/hooks_constants/test_visual_reply_rules_constants.py +0 -50
  36. package/hooks/hooks_constants/visual_reply_rules_constants.py +0 -106
  37. package/hooks/test_visual_reply_rules.py +0 -362
  38. package/hooks/visual_reply_rules.py +0 -478
  39. package/rules/visual-reply-rules.json +0 -56
@@ -0,0 +1,10 @@
1
+ """Constants for the read deadlines of one pull request lifecycle gate run."""
2
+
3
+ PROOF_AND_LOOK_READS_SECONDS = 12
4
+ FOLLOWUP_READS_SECONDS = 8
5
+ KILL_GRACE_SECONDS = 1
6
+ MOST_CUT_READS_PER_RUN = 2
7
+ STARTUP_AND_SCAN_MARGIN_SECONDS = 5
8
+ READS_RAN_OUT_SENTENCE = (
9
+ " The gate's git and GitHub reads ran out of time on this run, so a second run may pass."
10
+ )
@@ -2,11 +2,6 @@
2
2
 
3
3
  import re
4
4
 
5
- from hooks_constants.reply_length_gate_constants import (
6
- MAXIMUM_SENTENCE_COUNT,
7
- MAXIMUM_WORDS_PER_SENTENCE,
8
- )
9
-
10
5
  RESOLVE_TOOL_NAME_PATTERN = re.compile(r"^mcp__.+__resolve_review_thread$")
11
6
  REVIEW_WRITE_TOOL_NAME_PATTERN = re.compile(r"^mcp__.+__pull_request_review_write$")
12
7
  REVIEW_WRITE_METHOD_KEY = "method"
@@ -31,7 +26,4 @@ MISSING_REPLY_REASON = (
31
26
  " or with gh api graphql addPullRequestReviewThreadReply and the thread's PRRT_ id, confirm its"
32
27
  " result came back without an error, then resolve the thread by its PRRT_ id or by the comment id the reply answered. A comment id"
33
28
  " ties to a thread only through a pull_request_read get_review_comments result in this session."
34
- " A reply that a hook refused did not post; shorten it to"
35
- f" at most {MAXIMUM_SENTENCE_COUNT} sentences of at most {MAXIMUM_WORDS_PER_SENTENCE} words each,"
36
- " footer included, and send it again."
37
29
  )
@@ -6,7 +6,3 @@ from hooks_constants import followup_pr_dedupe_constants as constants
6
6
  def test_parent_pattern_reads_both_spellings_and_stops_at_the_number() -> None:
7
7
  assert re.search(constants.FOLLOWUP_PARENT_PATTERN, "followup to #12", re.IGNORECASE)
8
8
  assert re.search(constants.FOLLOWUP_PARENT_PATTERN, "Follow-up to #1731", re.IGNORECASE).group(1) == "1731"
9
-
10
-
11
- def test_read_timeout_fits_inside_the_hook_timeout() -> None:
12
- assert constants.READ_TIMEOUT_SECONDS * 2 < 10
@@ -35,6 +35,7 @@ if blocking_directory not in sys.path:
35
35
  sys.path.insert(0, blocking_directory)
36
36
 
37
37
  from hooks_constants.background_silence_prompt_constants import (
38
+ ADDITIONAL_CONTEXT_KEY,
38
39
  ALL_LIFT_PATTERNS,
39
40
  ALL_SET_PATTERNS,
40
41
  BACKGROUND_EVENT_PATTERN,
@@ -63,7 +64,6 @@ from hooks_constants.open_tasks_stop_gate_constants import (
63
64
  TRANSCRIPT_PATH_KEY,
64
65
  )
65
66
  from hooks_constants.pre_tool_use_stdin import read_hook_input_dictionary_from_stdin
66
- from hooks_constants.reply_length_gate_constants import ADDITIONAL_CONTEXT_KEY
67
67
  from hooks_constants.spawn_readiness_hook_constants import (
68
68
  ALL_HARNESS_ENVELOPE_MARKERS,
69
69
  HUMAN_SENDER_MARKER,
@@ -24,7 +24,6 @@ CONTEXT_OUTPUT_PATTERN = re.compile(r"additionalContext|ADDITIONAL_CONTEXT|addit
24
24
  UNMEASURED_REASON_BY_SCRIPT = {
25
25
  "blocking/pre_tool_use_dispatcher.py": "relays its hosted hooks' output",
26
26
  "blocking/bash_pre_tool_use_dispatcher.py": "relays its hosted hooks' output",
27
- "blocking/reply_length_gate.py": "advises only on a widget while visual reply mode is on",
28
27
  "lifecycle/nested_project_hooks.py": "relays a nested project's own hooks",
29
28
  "routing/thread_spawn_pace_hook.py": "quotes a usage reading capped by its own constant",
30
29
  "session/issue_tracker_session_starter.py": "emits only for a repository the user's "
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-dev-env",
3
- "version": "8.116.0",
3
+ "version": "8.116.2",
4
4
  "description": "Claude Code development standards — rules, hooks, agents, commands, and skills",
5
5
  "type": "module",
6
6
  "bin": {
@@ -18,7 +18,6 @@ from dev_env_scripts_constants.private_term_constants import (
18
18
  PRIVATE_TERM_MESSAGE_TEMPLATE,
19
19
  )
20
20
  from durable_post_lint_config.config.constants import (
21
- ACTION_GITHUB_MCP_COMMENT,
22
21
  ACTION_PR_CREATE,
23
22
  ACTION_PR_EDIT,
24
23
  ALL_BARE_VOLATILE_PATH_MARKERS,
@@ -33,7 +32,6 @@ from durable_post_lint_config.config.constants import (
33
32
  BODY_MUST_NOT_BE_EMPTY_MESSAGE,
34
33
  BODY_REQUIRED_MESSAGE,
35
34
  CLEAN_EXIT_CODE,
36
- COMMENT_LENGTH_FINDING_CODE,
37
35
  CONTENT_FINDING_EXIT_CODE,
38
36
  CONVENTIONAL_TITLE_PATTERN,
39
37
  EDIT_INPUT_REQUIRED_MESSAGE,
@@ -73,7 +71,6 @@ from blocking.pull_request_proof import (
73
71
  missing_proof_reason,
74
72
  what_this_does_section,
75
73
  )
76
- from blocking.reply_length_gate import comment_length_violation
77
74
 
78
75
 
79
76
  class DurablePostUsageError(ValueError):
@@ -211,13 +208,6 @@ def _pull_request_proof_findings(
211
208
  ]
212
209
 
213
210
 
214
- def _comment_length_findings(body_text: str) -> list[DurablePostFinding]:
215
- violation = comment_length_violation(body_text)
216
- if violation is None:
217
- return []
218
- return [DurablePostFinding(code=COMMENT_LENGTH_FINDING_CODE, message=violation)]
219
-
220
-
221
211
  def _contrast_framing_findings(text: str) -> list[DurablePostFinding]:
222
212
  all_lines = text.splitlines()
223
213
  return [
@@ -307,8 +297,6 @@ def _body_findings(
307
297
  if action in (ACTION_PR_CREATE, ACTION_PR_EDIT):
308
298
  all_findings.extend(_description_flowchart_findings(body_text)
309
299
  )
310
- if action == ACTION_GITHUB_MCP_COMMENT:
311
- all_findings.extend(_comment_length_findings(body_text))
312
300
  all_findings.extend(_contrast_framing_findings(body_text))
313
301
  if find_volatile_path_marker(body_text) is not None:
314
302
  all_findings.append(
@@ -109,5 +109,4 @@ REWRITTEN_RELEASE_BODY_MESSAGE = (
109
109
  )
110
110
  REPOSITORY_OWNER_SEPARATOR = "/"
111
111
  PROOF_GATE_CREATE_TOOL_NAME = "mcp__github__create_pull_request"
112
- PULL_REQUEST_PROOF_FINDING_CODE = "pull-request-proof-section"
113
- COMMENT_LENGTH_FINDING_CODE = "github-comment-length"
112
+ PULL_REQUEST_PROOF_FINDING_CODE = "pull-request-proof-section"
@@ -130,8 +130,6 @@ def _names_exempt_registration_path(registered_string: str) -> bool:
130
130
  hooks/blocking/pr_lifecycle_skill_gate.py -> exempt
131
131
  hooks/blocking/verify_before_commit_gate.py -> exempt
132
132
  hooks/blocking/step_note_gate.py -> exempt
133
- hooks/blocking/reply_length_gate.py -> exempt
134
- hooks/blocking/chat_reply_gate.py -> exempt
135
133
  hooks/blocking/edit_marker_gate.py -> exempt
136
134
  hooks/blocking/issue_close_handoff_gate.py -> exempt
137
135
  hooks/blocking/verify_before_acting.py -> exempt
@@ -67,8 +67,6 @@ ALL_ACTION_BOUNDARY_EXEMPT_REGISTRATION_PATHS = (
67
67
  "blocking/verify_before_commit_gate.py",
68
68
  "blocking/merge_review_gate.py",
69
69
  "blocking/step_note_gate.py",
70
- "blocking/reply_length_gate.py",
71
- "blocking/chat_reply_gate.py",
72
70
  "blocking/edit_marker_gate.py",
73
71
  "blocking/issue_close_handoff_gate.py",
74
72
  "blocking/verify_before_acting.py",
@@ -10,10 +10,6 @@ from pathlib import Path
10
10
  import pytest
11
11
 
12
12
  import durable_post_lint
13
- from hooks_constants.reply_length_gate_constants import (
14
- MAXIMUM_SENTENCE_COUNT,
15
- MAXIMUM_WORDS_PER_SENTENCE,
16
- )
17
13
  from dev_env_scripts_constants.private_term_constants import PrivateTermDigest
18
14
  from hooks_constants.pull_request_proof_constants import (
19
15
  MISSING_EVAL_SECTION_REASON,
@@ -64,11 +60,6 @@ Ran `python scripts/durable_post_lint.py --action pr-create --body-file body.md`
64
60
 
65
61
  `python scripts/durable_post_lint.py --action pr-create --body-file eval_body.md`
66
62
  """
67
- OVER_LONG_REPLY_BODY = (
68
- "Fixed in `abc1234`.\n\n"
69
- + " ".join(f"Status line {each_number} is ready." for each_number in range(MAXIMUM_SENTENCE_COUNT + 1))
70
- + "\n\n---\nPosted by the review agent."
71
- )
72
63
  MINIMAL_PR_BODY = """## Why
73
64
 
74
65
  Why text.
@@ -447,30 +438,6 @@ def should_exit_with_findings_for_a_create_body_with_no_existing_work_section(
447
438
  assert completed_process.stderr == f"{MISSING_EXISTING_WORK_REASON}\n"
448
439
 
449
440
 
450
- def should_report_a_review_reply_over_the_sentence_limit() -> None:
451
- all_findings = durable_post_lint.lint_durable_post(
452
- action="github-mcp-comment",
453
- title=None,
454
- body_text=OVER_LONG_REPLY_BODY,
455
- )
456
- assert [each_finding.code for each_finding in all_findings] == [
457
- "github-comment-length"
458
- ]
459
-
460
-
461
- def should_report_a_review_reply_sentence_over_the_word_limit() -> None:
462
- all_findings = durable_post_lint.lint_durable_post(
463
- action="github-mcp-comment",
464
- title=None,
465
- body_text=(
466
- " ".join(f"word{each_number}" for each_number in range(MAXIMUM_WORDS_PER_SENTENCE + 1)) + "."
467
- ),
468
- )
469
- assert [each_finding.code for each_finding in all_findings] == [
470
- "github-comment-length"
471
- ]
472
-
473
-
474
441
  def should_accept_a_short_review_reply() -> None:
475
442
  all_findings = durable_post_lint.lint_durable_post(
476
443
  action="github-mcp-comment",
@@ -480,26 +447,6 @@ def should_accept_a_short_review_reply() -> None:
480
447
  assert all_findings == ()
481
448
 
482
449
 
483
- def should_exit_with_findings_for_an_over_long_review_reply(tmp_path: Path) -> None:
484
- body_file = tmp_path / "reply.md"
485
- body_file.write_text(OVER_LONG_REPLY_BODY, encoding="utf-8")
486
- completed_process = subprocess.run(
487
- [
488
- sys.executable,
489
- str(SCRIPT_PATH),
490
- "--action",
491
- "github-mcp-comment",
492
- "--body-file",
493
- str(body_file),
494
- ],
495
- check=False,
496
- capture_output=True,
497
- text=True,
498
- )
499
- assert completed_process.returncode == 1
500
- assert f"at most {MAXIMUM_SENTENCE_COUNT} short sentences" in completed_process.stderr
501
-
502
-
503
450
  def should_exit_clean_for_a_short_review_reply(tmp_path: Path) -> None:
504
451
  body_file = tmp_path / "reply.md"
505
452
  body_file.write_text("Fixed in `abc1234`.\n", encoding="utf-8")
@@ -98,22 +98,6 @@ def test_new_step_note_gate_registration_is_clean(tmp_path: Path) -> None:
98
98
  assert adapters.hook_configuration_diagnostics(current_document, tmp_path) == ()
99
99
 
100
100
 
101
- def test_new_reply_length_gate_registration_is_clean(tmp_path: Path) -> None:
102
- current_document = _hook_document(
103
- ["hooks/blocking/reply_length_gate.py"],
104
- '{"hooks": {}}',
105
- )
106
- assert adapters.hook_configuration_diagnostics(current_document, tmp_path) == ()
107
-
108
-
109
- def test_new_chat_reply_gate_registration_is_clean(tmp_path: Path) -> None:
110
- current_document = _hook_document(
111
- ["hooks/blocking/chat_reply_gate.py"],
112
- '{"hooks": {}}',
113
- )
114
- assert adapters.hook_configuration_diagnostics(current_document, tmp_path) == ()
115
-
116
-
117
101
  def test_new_edit_marker_gate_registration_is_clean(tmp_path: Path) -> None:
118
102
  current_document = _hook_document(
119
103
  ["hooks/blocking/edit_marker_gate.py"],
@@ -1,260 +0,0 @@
1
- #!/usr/bin/env python3
2
- """Hook that shows the user one short chat reply per message.
3
-
4
- ``reply_length_gate.py`` checks only the chat tools that post to Slack.
5
- A reply typed straight into the chat is no tool call, so this hook runs
6
- the same checks on it::
7
-
8
- UserPromptSubmit, first of the session -> additionalContext states the rules
9
- UserPromptSubmit, later -> only the draft the user saw, if any
10
- MessageDisplay, batch before the last -> hold the text, show nothing yet
11
- MessageDisplay, last batch, passes -> show the whole message
12
- MessageDisplay, last batch, fails -> show a draft from a small model that passes
13
-
14
- A Stop hook would see the reply only after it is on screen, so each block
15
- would add a second reply under the first. MessageDisplay changes the text
16
- before it renders. The transcript keeps the original, so the next
17
- UserPromptSubmit tells the agent the text the user saw.
18
-
19
- The draft comes from ``claude -p`` on DEFAULT_DRAFTER_MODEL with no setting
20
- sources and no tools. The draft must pass ``reply_violation``; after
21
- MAXIMUM_DRAFT_ATTEMPTS failed drafts, the original shows.
22
-
23
- The checks come from ``reply_length_gate.reply_violation``: at most
24
- MAXIMUM_SENTENCE_COUNT sentences of at most MAXIMUM_WORDS_PER_SENTENCE
25
- words, no mid-sentence colon, no em dash, linked pull requests, a source
26
- for each causal claim, and no banned word.
27
- """
28
-
29
- from __future__ import annotations
30
-
31
- import json
32
- import os
33
- import shutil
34
- import subprocess
35
- import sys
36
- import tempfile
37
- import uuid
38
- from pathlib import Path
39
-
40
- hooks_root_directory = str(Path(__file__).resolve().parent.parent)
41
- if hooks_root_directory not in sys.path:
42
- sys.path.insert(0, hooks_root_directory)
43
- blocking_directory = str(Path(__file__).resolve().parent)
44
- if blocking_directory not in sys.path:
45
- sys.path.insert(0, blocking_directory)
46
-
47
- from once_per_session import claim_first_showing, clear_showings
48
- from reply_length_gate import reply_violation
49
- from hooks_constants.chat_reply_gate_constants import (
50
- CLAUDE_SESSION_ID_ENV_VAR,
51
- DEFAULT_DRAFTER_MODEL,
52
- DELTA_KEY,
53
- DISPLAY_CONTENT_KEY,
54
- DRAFTER_GUARD_ENV_VAR,
55
- DRAFTER_MODEL_ENV_VAR,
56
- DRAFTER_REQUEST_TEMPLATE,
57
- DRAFTER_ERROR_KEY,
58
- DRAFTER_EXECUTABLE_NAME,
59
- DRAFTER_RESULT_KEY,
60
- DRAFTER_RULES,
61
- DRAFTER_TIMEOUT_SECONDS,
62
- FINAL_KEY,
63
- HELD_TEXT_FILE_PREFIX,
64
- HOOK_EVENT_NAME_INPUT_KEY,
65
- MAXIMUM_DRAFT_ATTEMPTS,
66
- MESSAGE_DISPLAY_EVENT_NAME,
67
- MESSAGE_ID_KEY,
68
- REPLY_LIMIT_ONCE_MARKER_NAME,
69
- REPLY_LIMIT_REMINDER,
70
- SESSION_END_EVENT_NAME,
71
- SESSION_ID_KEY,
72
- SHOWN_DRAFT_FILE_PREFIX,
73
- SHOWN_DRAFT_HEADING,
74
- SHOWN_DRAFT_PREFIX,
75
- STATE_FILE_ENCODING,
76
- STATE_FILE_SUFFIX,
77
- USER_PROMPT_SUBMIT_EVENT_NAME,
78
- )
79
- from hooks_constants.hook_block_logger import log_hook_block
80
- from hooks_constants.hook_specific_output_keys import (
81
- HOOK_EVENT_NAME_KEY,
82
- HOOK_SPECIFIC_OUTPUT_KEY,
83
- )
84
- from hooks_constants.pre_tool_use_stdin import read_hook_input_dictionary_from_stdin
85
- from hooks_constants.reply_length_gate_constants import (
86
- ADDITIONAL_CONTEXT_KEY,
87
- ALLOW_EXIT_CODE,
88
- )
89
- from hooks_constants.session_file_id import session_file_id
90
-
91
-
92
- def state_file_path(file_prefix: str, state_key: object) -> Path:
93
- """Return the temp file that holds one message's held text or one session's shown draft."""
94
- file_name = f"{file_prefix}{session_file_id(state_key)}{STATE_FILE_SUFFIX}"
95
- return Path(tempfile.gettempdir()) / file_name
96
-
97
-
98
- def read_state_text(state_path: Path) -> str:
99
- """Return the stored text, or an empty string when the file is absent or unreadable."""
100
- try:
101
- return state_path.read_text(encoding=STATE_FILE_ENCODING)
102
- except OSError:
103
- return ""
104
-
105
-
106
- def write_state_text(state_path: Path, state_text: str) -> None:
107
- """Store the text; a failed write leaves the shown text unchanged."""
108
- try:
109
- state_path.write_text(state_text, encoding=STATE_FILE_ENCODING)
110
- except OSError:
111
- return
112
-
113
-
114
- def drafter_command() -> list[str]:
115
- """Return the headless claude command that drafts with no settings and no tools."""
116
- return [
117
- shutil.which(DRAFTER_EXECUTABLE_NAME) or DRAFTER_EXECUTABLE_NAME,
118
- "-p",
119
- "--model",
120
- os.environ.get(DRAFTER_MODEL_ENV_VAR, DEFAULT_DRAFTER_MODEL),
121
- "--setting-sources",
122
- "",
123
- "--tools",
124
- "",
125
- "--no-session-persistence",
126
- "--session-id",
127
- str(uuid.uuid4()),
128
- "--output-format",
129
- "json",
130
- "--system-prompt",
131
- DRAFTER_RULES,
132
- ]
133
-
134
-
135
- def drafter_environment() -> dict[str, str]:
136
- """Return the drafter's environment, marked so this hook exits inside it."""
137
- environment = dict(os.environ)
138
- environment[DRAFTER_GUARD_ENV_VAR] = "1"
139
- environment.pop(CLAUDE_SESSION_ID_ENV_VAR, None)
140
- return environment
141
-
142
-
143
- def ask_drafter(reply_text: str, violation: str) -> str | None:
144
- """Return one draft from the small model, or None when the call fails."""
145
- try:
146
- completed = subprocess.run(
147
- drafter_command(),
148
- input=DRAFTER_REQUEST_TEMPLATE.format(violation=violation, reply_text=reply_text),
149
- capture_output=True,
150
- text=True,
151
- timeout=DRAFTER_TIMEOUT_SECONDS,
152
- env=drafter_environment(),
153
- check=False,
154
- )
155
- drafter_output = json.loads(completed.stdout)
156
- draft_text = drafter_output.get(DRAFTER_RESULT_KEY)
157
- except (OSError, subprocess.TimeoutExpired, json.JSONDecodeError, AttributeError):
158
- return None
159
- if drafter_output.get(DRAFTER_ERROR_KEY) is True:
160
- return None
161
- if not isinstance(draft_text, str) or not draft_text.strip():
162
- return None
163
- return draft_text.strip()
164
-
165
-
166
- def compliant_draft(reply_text: str, violation: str) -> str | None:
167
- """Return a draft that passes ``reply_violation``, or None after MAXIMUM_DRAFT_ATTEMPTS."""
168
- current_violation = violation
169
- for _ in range(MAXIMUM_DRAFT_ATTEMPTS):
170
- draft_text = ask_drafter(reply_text, current_violation)
171
- if draft_text is None:
172
- continue
173
- draft_violation = reply_violation(draft_text, None, None)
174
- if draft_violation is None:
175
- return draft_text
176
- current_violation = draft_violation
177
- return None
178
-
179
-
180
- def shown_text(all_hook_input: dict[str, object]) -> str | None:
181
- """Return the text to show for this batch, or None to show the batch as it is."""
182
- message_id = all_hook_input.get(MESSAGE_ID_KEY)
183
- if not isinstance(message_id, str) or not message_id:
184
- return None
185
- held_path = state_file_path(HELD_TEXT_FILE_PREFIX, message_id)
186
- held_text = read_state_text(held_path)
187
- message_text = held_text + str(all_hook_input.get(DELTA_KEY) or "")
188
- if not all_hook_input.get(FINAL_KEY):
189
- write_state_text(held_path, message_text)
190
- return ""
191
- held_path.unlink(missing_ok=True)
192
- shown_draft_path = state_file_path(SHOWN_DRAFT_FILE_PREFIX, all_hook_input.get(SESSION_ID_KEY))
193
- violation = reply_violation(message_text, None, None)
194
- draft_text = None if violation is None else compliant_draft(message_text, violation)
195
- if violation is None or draft_text is None:
196
- shown_draft_path.unlink(missing_ok=True)
197
- return message_text if held_text else None
198
- write_state_text(shown_draft_path, draft_text)
199
- log_hook_block(
200
- Path(__file__).name,
201
- MESSAGE_DISPLAY_EVENT_NAME,
202
- violation,
203
- offending_input_preview=message_text,
204
- )
205
- return draft_text
206
-
207
-
208
- def write_hook_output(event_name: str, output_key: str, output_text: str) -> None:
209
- """Print one hookSpecificOutput field for the event."""
210
- hook_event_output = {HOOK_EVENT_NAME_KEY: event_name, output_key: output_text}
211
- sys.stdout.write(json.dumps({HOOK_SPECIFIC_OUTPUT_KEY: hook_event_output}))
212
-
213
-
214
- def reply_limit_reminder(all_hook_fields: dict[str, object]) -> str:
215
- """Return the reply rules on a session's first prompt, plus the draft the user saw in place of the last reply.
216
-
217
- The rules show on the first prompt of a session and on the first prompt
218
- after each compaction; other prompts carry only a shown draft, or nothing.
219
- """
220
- reminder = (
221
- REPLY_LIMIT_REMINDER
222
- if claim_first_showing(REPLY_LIMIT_ONCE_MARKER_NAME, all_hook_fields)
223
- else ""
224
- )
225
- shown_draft_path = state_file_path(SHOWN_DRAFT_FILE_PREFIX, all_hook_fields.get(SESSION_ID_KEY))
226
- shown_draft = read_state_text(shown_draft_path)
227
- if not shown_draft:
228
- return reminder
229
- shown_draft_path.unlink(missing_ok=True)
230
- if not reminder:
231
- return SHOWN_DRAFT_HEADING + shown_draft
232
- return reminder + SHOWN_DRAFT_PREFIX + shown_draft
233
-
234
-
235
- def main() -> int:
236
- if os.environ.get(DRAFTER_GUARD_ENV_VAR):
237
- return ALLOW_EXIT_CODE
238
- hook_input = read_hook_input_dictionary_from_stdin()
239
- if hook_input is None:
240
- return ALLOW_EXIT_CODE
241
- event_name = hook_input.get(HOOK_EVENT_NAME_INPUT_KEY)
242
- if event_name == USER_PROMPT_SUBMIT_EVENT_NAME:
243
- prompt_context = reply_limit_reminder(hook_input)
244
- if prompt_context:
245
- write_hook_output(USER_PROMPT_SUBMIT_EVENT_NAME, ADDITIONAL_CONTEXT_KEY, prompt_context)
246
- return ALLOW_EXIT_CODE
247
- if event_name == SESSION_END_EVENT_NAME:
248
- state_file_path(SHOWN_DRAFT_FILE_PREFIX, hook_input.get(SESSION_ID_KEY)).unlink(missing_ok=True)
249
- clear_showings(hook_input.get(SESSION_ID_KEY))
250
- return ALLOW_EXIT_CODE
251
- if event_name != MESSAGE_DISPLAY_EVENT_NAME:
252
- return ALLOW_EXIT_CODE
253
- display_text = shown_text(hook_input)
254
- if display_text is not None:
255
- write_hook_output(MESSAGE_DISPLAY_EVENT_NAME, DISPLAY_CONTENT_KEY, display_text)
256
- return ALLOW_EXIT_CODE
257
-
258
-
259
- if __name__ == "__main__":
260
- sys.exit(main())