claude-dev-env 8.114.4 → 8.114.6

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.
@@ -5,7 +5,8 @@
5
5
  A reply typed straight into the chat is no tool call, so this hook runs
6
6
  the same checks on it::
7
7
 
8
- UserPromptSubmit -> additionalContext states the rules
8
+ UserPromptSubmit, first of the session -> additionalContext states the rules
9
+ UserPromptSubmit, later -> only the draft the user saw, if any
9
10
  MessageDisplay, batch before the last -> hold the text, show nothing yet
10
11
  MessageDisplay, last batch, passes -> show the whole message
11
12
  MessageDisplay, last batch, fails -> show a draft from a small model that passes
@@ -43,6 +44,7 @@ blocking_directory = str(Path(__file__).resolve().parent)
43
44
  if blocking_directory not in sys.path:
44
45
  sys.path.insert(0, blocking_directory)
45
46
 
47
+ from once_per_session import claim_first_showing, clear_showings
46
48
  from reply_length_gate import reply_violation
47
49
  from hooks_constants.chat_reply_gate_constants import (
48
50
  CLAUDE_SESSION_ID_ENV_VAR,
@@ -63,10 +65,12 @@ from hooks_constants.chat_reply_gate_constants import (
63
65
  MAXIMUM_DRAFT_ATTEMPTS,
64
66
  MESSAGE_DISPLAY_EVENT_NAME,
65
67
  MESSAGE_ID_KEY,
68
+ REPLY_LIMIT_ONCE_MARKER_NAME,
66
69
  REPLY_LIMIT_REMINDER,
67
70
  SESSION_END_EVENT_NAME,
68
71
  SESSION_ID_KEY,
69
72
  SHOWN_DRAFT_FILE_PREFIX,
73
+ SHOWN_DRAFT_HEADING,
70
74
  SHOWN_DRAFT_PREFIX,
71
75
  STATE_FILE_ENCODING,
72
76
  STATE_FILE_SUFFIX,
@@ -207,14 +211,25 @@ def write_hook_output(event_name: str, output_key: str, output_text: str) -> Non
207
211
  sys.stdout.write(json.dumps({HOOK_SPECIFIC_OUTPUT_KEY: hook_event_output}))
208
212
 
209
213
 
210
- def reply_limit_reminder(session_id: object) -> str:
211
- """Return the reply rules, plus the draft the user saw in place of the last reply."""
212
- shown_draft_path = state_file_path(SHOWN_DRAFT_FILE_PREFIX, session_id)
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))
213
226
  shown_draft = read_state_text(shown_draft_path)
214
227
  if not shown_draft:
215
- return REPLY_LIMIT_REMINDER
228
+ return reminder
216
229
  shown_draft_path.unlink(missing_ok=True)
217
- return REPLY_LIMIT_REMINDER + SHOWN_DRAFT_PREFIX + shown_draft
230
+ if not reminder:
231
+ return SHOWN_DRAFT_HEADING + shown_draft
232
+ return reminder + SHOWN_DRAFT_PREFIX + shown_draft
218
233
 
219
234
 
220
235
  def main() -> int:
@@ -225,14 +240,13 @@ def main() -> int:
225
240
  return ALLOW_EXIT_CODE
226
241
  event_name = hook_input.get(HOOK_EVENT_NAME_INPUT_KEY)
227
242
  if event_name == USER_PROMPT_SUBMIT_EVENT_NAME:
228
- write_hook_output(
229
- USER_PROMPT_SUBMIT_EVENT_NAME,
230
- ADDITIONAL_CONTEXT_KEY,
231
- reply_limit_reminder(hook_input.get(SESSION_ID_KEY)),
232
- )
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)
233
246
  return ALLOW_EXIT_CODE
234
247
  if event_name == SESSION_END_EVENT_NAME:
235
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))
236
250
  return ALLOW_EXIT_CODE
237
251
  if event_name != MESSAGE_DISPLAY_EVENT_NAME:
238
252
  return ALLOW_EXIT_CODE
@@ -1,12 +1,18 @@
1
1
  import io
2
2
  import json
3
+ import os
4
+ import subprocess
5
+ import sys
3
6
  from pathlib import Path
4
7
 
5
8
  import pytest
6
9
 
7
10
  import chat_reply_gate
11
+ from hooks_constants.chat_reply_gate_constants import REPLY_LIMIT_REMINDER, SHOWN_DRAFT_HEADING
8
12
  from hooks_constants.reply_length_gate_constants import MAXIMUM_SENTENCE_COUNT
9
13
 
14
+ CHAT_REPLY_GATE_SCRIPT = Path(__file__).resolve().parent / "chat_reply_gate.py"
15
+
10
16
  OVER_LIMIT_SENTENCES = [
11
17
  f"Status line {each_number} is ready." for each_number in range(MAXIMUM_SENTENCE_COUNT + 1)
12
18
  ]
@@ -115,31 +121,99 @@ def test_should_tell_the_agent_which_draft_the_user_saw(
115
121
  monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
116
122
  ) -> None:
117
123
  monkeypatch.setattr(chat_reply_gate, "ask_drafter", lambda *_args: PASSING_DRAFT)
118
- run_hook(monkeypatch, capsys, display_input(OVER_LIMIT_REPLY))
119
124
  prompt_input = {"hook_event_name": "UserPromptSubmit", "session_id": "abc"}
120
125
  _, first_output = run_hook(monkeypatch, capsys, prompt_input)
126
+ run_hook(monkeypatch, capsys, display_input(OVER_LIMIT_REPLY))
121
127
  _, second_output = run_hook(monkeypatch, capsys, prompt_input)
128
+ _, third_output = run_hook(monkeypatch, capsys, prompt_input)
122
129
  assert first_output is not None and second_output is not None
123
- assert str(first_output["additionalContext"]).endswith(PASSING_DRAFT)
124
- assert PASSING_DRAFT not in str(second_output["additionalContext"])
130
+ assert str(first_output["additionalContext"]) == REPLY_LIMIT_REMINDER
131
+ assert second_output["additionalContext"] == SHOWN_DRAFT_HEADING + PASSING_DRAFT
132
+ assert third_output is None
133
+
134
+
135
+ def _prompt_input(transcript_path: Path) -> dict[str, object]:
136
+ return {
137
+ "hook_event_name": "UserPromptSubmit",
138
+ "session_id": "abc",
139
+ "prompt": "status?",
140
+ "transcript_path": str(transcript_path),
141
+ }
142
+
143
+
144
+ def test_should_add_the_reply_limit_once_per_session_and_again_after_a_compaction(
145
+ monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], tmp_path: Path
146
+ ) -> None:
147
+ transcript_path = tmp_path / "session.jsonl"
148
+ transcript_path.write_text(json.dumps({"type": "user"}) + "\n", encoding="utf-8")
149
+ _, first_output = run_hook(monkeypatch, capsys, _prompt_input(transcript_path))
150
+ _, second_output = run_hook(monkeypatch, capsys, _prompt_input(transcript_path))
151
+ with transcript_path.open("a", encoding="utf-8") as transcript:
152
+ transcript.write(json.dumps({"type": "system", "subtype": "compact_boundary"}) + "\n")
153
+ _, after_compaction_output = run_hook(monkeypatch, capsys, _prompt_input(transcript_path))
154
+ _, later_output = run_hook(monkeypatch, capsys, _prompt_input(transcript_path))
155
+ assert first_output is not None
156
+ assert first_output["additionalContext"] == REPLY_LIMIT_REMINDER
157
+ assert second_output is None
158
+ assert after_compaction_output is not None
159
+ assert after_compaction_output["additionalContext"] == REPLY_LIMIT_REMINDER
160
+ assert later_output is None
161
+
162
+
163
+ def test_replay_of_two_prompts_and_a_compaction_through_the_script(tmp_path: Path) -> None:
164
+ transcript_path = tmp_path / "session.jsonl"
165
+ transcript_path.write_text(json.dumps({"type": "user"}) + "\n", encoding="utf-8")
166
+ environment = {
167
+ **os.environ,
168
+ "TMP": str(tmp_path),
169
+ "TEMP": str(tmp_path),
170
+ "TMPDIR": str(tmp_path),
171
+ "CLAUDE_REPLY_BANNED_WORDS_PATH": str(tmp_path / "absent.json"),
172
+ }
173
+ environment.pop("CHAT_REPLY_DRAFTER_ACTIVE", None)
174
+
175
+ def replay_prompt() -> str:
176
+ return subprocess.run(
177
+ [sys.executable, str(CHAT_REPLY_GATE_SCRIPT)],
178
+ input=json.dumps(_prompt_input(transcript_path)),
179
+ capture_output=True,
180
+ text=True,
181
+ env=environment,
182
+ check=True,
183
+ ).stdout
184
+
185
+ first_stdout = replay_prompt()
186
+ second_stdout = replay_prompt()
187
+ with transcript_path.open("a", encoding="utf-8") as transcript:
188
+ transcript.write(json.dumps({"type": "system", "subtype": "compact_boundary"}) + "\n")
189
+ after_compaction_stdout = replay_prompt()
190
+ assert REPLY_LIMIT_REMINDER in json.loads(first_stdout)["hookSpecificOutput"]["additionalContext"]
191
+ assert second_stdout == ""
192
+ assert (
193
+ REPLY_LIMIT_REMINDER
194
+ in json.loads(after_compaction_stdout)["hookSpecificOutput"]["additionalContext"]
195
+ )
125
196
 
126
197
 
127
198
  def test_should_delete_the_shown_draft_at_session_end(
128
199
  monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
129
200
  ) -> None:
130
201
  monkeypatch.setattr(chat_reply_gate, "ask_drafter", lambda *_args: PASSING_DRAFT)
202
+ run_hook(monkeypatch, capsys, {"hook_event_name": "UserPromptSubmit", "session_id": "abc"})
131
203
  run_hook(monkeypatch, capsys, display_input(OVER_LIMIT_REPLY))
132
204
  shown_draft_path = chat_reply_gate.state_file_path("claude-chat-reply-shown-", "abc")
133
205
  assert shown_draft_path.exists()
206
+ assert list(Path(chat_reply_gate.tempfile.gettempdir()).glob("claude-once-*"))
134
207
  exit_code, hook_output = run_hook(
135
208
  monkeypatch, capsys, {"hook_event_name": "SessionEnd", "session_id": "abc"}
136
209
  )
137
210
  assert exit_code == 0
138
211
  assert hook_output is None
139
212
  assert not shown_draft_path.exists()
213
+ assert not list(Path(chat_reply_gate.tempfile.gettempdir()).glob("claude-once-*"))
140
214
 
141
215
 
142
- def test_should_add_the_reply_limit_on_each_user_prompt(
216
+ def test_should_add_the_reply_limit_to_a_prompt_with_no_session_id(
143
217
  monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
144
218
  ) -> None:
145
219
  exit_code, hook_output = run_hook(
@@ -7,10 +7,10 @@ This family stops a chat reply, edited message, or tool call when its payload br
7
7
  - `blocking/reply_length_gate.py` caps chat reply length, denies a configured banned word, requires a readable link when the text names a pull request number, and denies a causal claim in a reply that cites no code span, output block, or link. It denies a sentence that guesses, estimates, hedges a duration, or admits a skipped check, such as "I didn't confirm this one." It denies a cited Actions run, pull request, or run, job, or check id that no successful tool result in the transcript shows; a subagent's report is the result of its Agent call. A question card from `AskUserQuestion` gets the banned word check and `unvalidated_claim_violation`, like a decision card. One refusal names every broken rule and every offending sentence, numbered, and ends with "Fix every item above in your next write." With visual reply mode on, it also runs the checks in `visual_reply_rules.py` from the rule list in `rules/visual-reply-rules.json`: no abbreviation or tracker number outside a link, a widget or page before a reply of more than one sentence, and no anchor link inside widget code. The mode is off by default; `~/.claude/visual-reply-mode.json` with `{"enabled": true}` turns the mode checks on. The results-picture check runs with the mode off too. A reply with a markdown table, or more than two figures, needs a picture: an attached `.svg`, `.png`, `.jpg`, `.jpeg`, `.gif`, or `.webp` file, an attached `frame` output such as a published page, or a markdown picture outside code. The check reads the attached name only, so it does not confirm that the file exists. It skips an edit of a posted message, because the edit tool attaches nothing, and the closing reply of a turn, which `blocking/final_reply_gate.py` does not run it on.
8
8
  - `blocking/final_reply_gate.py` applies the banned words, `unvalidated_claim_violation`, and `unseen_citation_violation` from the reply gate to the reply a session ends its turn with. Its `windows_path_violation` blocks a path the terminal would render without one of its backslashes. Its `unbriefed_question_violation` blocks a reply whose last paragraph, with fences, quotes, and code spans left out, ends with a question mark or says a question still stands, when the turn sent no `AskUserQuestion`, hearthbot decision card, or Codex `request_user_input` call; it is skipped when the transcript cannot be read.
9
9
  - `blocking/open_tasks_stop_gate.py` holds the end of a turn once when the prompt that started it asks for work, the turn ran a work tool, and the turn made no tracker call: TaskCreate, TaskUpdate, TodoWrite, the Codex `update_plan`, or the desktop `mcp__ccd_turn__update_plan`. A work tool is any tool but a tracker call, the session title tool, `AskUserQuestion`, a hearthbot decision card, Codex `request_user_input`, `ToolSearch`, `TaskList`, or `TaskGet`. It never reads the reply text. `open_task_asks.is_ask` decides whether a prompt asks for work: a question-only prompt, an acknowledgement such as `thanks!`, an empty prompt, a prompt of only `<system-reminder>` blocks, and an envelope such as `<agent-message>` or `<task-notification>` do not. `blocking/open_tasks_transcript.py` replays the transcript for it: the turn's prompt, its tool calls, and the task list. `session_task_items` merges the task store with the transcript items whose subject the store does not hold, for the session title gate.
10
- - `session/tracking_nudge.py` adds one `additionalContext` note to a prompt that asks for work. The note asks for a task list item. When the title shows the red flag or the check mark, it also asks for the hourglass before other work. It never blocks.
10
+ - `session/tracking_nudge.py` adds one `additionalContext` note to a prompt that asks for work. The note asks for an item in the session's task list tool. It shows on the session's first ask and on the first ask after each compaction, through `once_per_session.py`. When the title shows the red flag or the check mark, it also asks for the hourglass before other work. It never blocks.
11
11
  - `session/background_silence_prompt.py` adds one `additionalContext` note to a background event prompt, one that starts with `<task-notification>` or opens itself or a `<system-reminder>` block with `[SYSTEM NOTIFICATION - NOT USER INPUT]`, while the user asked for silence. The newest user-typed message that sets silence ("silent unless", "stay silent", "silent on updates", "no updates unless") or lifts it ("you can talk again", "updates are fine", "stop being silent") decides. The note quotes the user's "unless" or "except" clause word for word, or the whole message when it has no such clause, and says to end the turn with no text unless that exception applies now. Envelope prompts, compaction summaries, and quoted `>` lines are not the user's words. It never blocks.
12
12
  - The claim judge is a `prompt` hook in `hooks.json`, with no `model` set, so Claude Code's small default hook model reads each chat message and denies every claim, numbered in one refusal, about how code, a file, a tool, a service, a run, or a process behaves, or why something happened, when nothing in the message shows it: inline code that quotes output or a code line, a file and line, or a link. A pull request link covers what that change does, what it blocks or lets through, and its checks. The author's own actions, a restatement of the user's words, questions, instructions, and a decision card's option consequences pass. It catches the plain claims the causal word list in `blocking/reply_length_gate.py` misses, such as "The code lets any of them rewrite it mid-check." `continueOnBlock` returns the reason to the agent as the tool error, so it can add the source and send again. The installer owns it through the `claude-dev-env: ` prefix on its `statusMessage`. It skips `post_widget`, whose input is SVG or HTML markup.
13
- - `blocking/chat_reply_gate.py` runs the `reply_length_gate.py` reply checks on a plain chat reply, which is no tool call. On `UserPromptSubmit` it adds the reply rules as `additionalContext`. On `MessageDisplay` it holds each streamed batch until the message ends. A message that passes shows whole. A message that fails shows as a draft from `claude -p` on Haiku that passes the same checks, and the original shows when two drafts fail. The draft changes only the text on screen, so the next `UserPromptSubmit` tells the agent the text the user saw, and `SessionEnd` deletes the stored draft. The [reply arena harness](https://github.com/jl-cmd-projects/claude-dev-env/tree/160349b90f627ea542fc6bc7b2b7f86dcbf98b73/tests/reply_arena) ran the comparison that chose this display path.
13
+ - `blocking/chat_reply_gate.py` runs the `reply_length_gate.py` reply checks on a plain chat reply, which is no tool call. On the first `UserPromptSubmit` of a session, and on the first one after each compaction, it adds the reply rules as `additionalContext`. On `MessageDisplay` it holds each streamed batch until the message ends. A message that passes shows whole. A message that fails shows as a draft from `claude -p` on Haiku that passes the same checks, and the original shows when two drafts fail. The draft changes only the text on screen, so the next `UserPromptSubmit` tells the agent the text the user saw, and `SessionEnd` deletes the stored draft and the session's once-per-session markers for all three hooks. The [reply arena harness](https://github.com/jl-cmd-projects/claude-dev-env/tree/160349b90f627ea542fc6bc7b2b7f86dcbf98b73/tests/reply_arena) ran the comparison that chose this display path.
14
14
  - `blocking/edit_marker_gate.py` rejects strikethrough and edit-note markers in replacement chat text or cards.
15
15
  - `blocking/issue_close_handoff_gate.py` denies an issue comment or issue write that closes the issue and routes a found defect to another issue or epic.
16
16
  - `blocking/session_title_format_gate.py` denies a session title that breaks the `<emoji> <name>` shape or has a name longer than 25 characters.
@@ -62,10 +62,10 @@ Preconditions:
62
62
  - **Resolve reply.** Input is a transcript where a thread reply came back refused, or with no reply, or with one reply already spent on a resolve, or with a reply on another thread, then a resolve call, a `pull_request_review_write` `resolve_thread` call, a graphql `resolveReviewThread` command, or a `ccr/comments/<id>/resolve` call. Run `python -m pytest packages/claude-dev-env/hooks/blocking/test_resolve_thread_reply_gate.py -q`. The adjacent test observes a deny whose reason says to post the reply, confirm it posted, then resolve. A reply that posted before the resolve passes, and an unreadable transcript passes.
63
63
  - **Final reply.** Input is a closing reply that says "My guess is one to two hours." or cites a run no tool result shows. Run `python -m pytest packages/claude-dev-env/hooks/blocking/test_final_reply_gate.py -q`. The adjacent test observes a `block` decision that quotes the sentence or the citation; a reply that cites a run a tool result shows passes. A reply with a plain-text `D:\Reports\.claude\report.html` is blocked; the same path in backticks or a fenced block passes.
64
64
  - **Open tasks.** Input is a transcript whose last prompt asks for work and whose turn ran a Bash call and no tracker call. Run `python -m pytest packages/claude-dev-env/hooks/blocking/test_open_tasks_stop_gate.py -q`. The adjacent test observes one `block` decision; the same turn with a TaskCreate, TaskUpdate, TodoWrite, or desktop plan call passes. A question, an acknowledgement, a `<task-notification>` envelope, a tool-free turn, and a held stop pass. The same file covers Codex and Cursor payloads.
65
- - **Ask nudge.** Input is a `UserPromptSubmit` payload with a work prompt, a question, and a `<task-notification>` envelope, after a transcript whose title shows the red flag. Run `python -m pytest packages/claude-dev-env/hooks/session/test_tracking_nudge.py -q`. The adjacent test observes a task list note and a title note for the work prompt, and empty stdout for the other two.
65
+ - **Ask nudge.** Input is a `UserPromptSubmit` payload with a work prompt, a question, and a `<task-notification>` envelope, after a transcript whose title shows the red flag. Run `python -m pytest packages/claude-dev-env/hooks/session/test_tracking_nudge.py -q`. The adjacent test observes a task list note and a title note for the work prompt, and empty stdout for the other two. A second ask in the same session gets no task list note until the transcript records a compaction.
66
66
  - **Background silence.** Input is a `UserPromptSubmit` payload whose prompt is a `<task-notification>` envelope, after a transcript whose user message reads "Silent on updates unless something merges or youre blocked". Run `python -m pytest packages/claude-dev-env/hooks/session/test_background_silence_prompt.py -q`. The adjacent test observes a note that quotes "unless something merges or youre blocked", and empty stdout for a user-typed prompt, after a lift, and with no silence message.
67
67
  - **Claim judge.** Input is a headless `claude -p` session with a stub MCP server named `hearthbot` that exposes `reply` and `ask_decision`, told to send "The code lets any of them rewrite it mid-check." The session settings add the `hooks.json` prompt hook. The stub logs zero bytes sent, and the tool error reads `PreToolUse:mcp__hearthbot__reply hook error: [<the prompt>]: Facts with no source: 1. ...`, numbering every failing claim. The same sentence with a `file:line` in backticks posts. A hook whose `model` Claude Code does not recognize lets every message through, so leave `model` unset. Run `node --test packages/claude-dev-env/bin/install.prompt-hook.test.mjs` for the installer side; it observes one managed prompt hook after two installs and none after uninstall.
68
- - **Chat reply.** Input is a `MessageDisplay` event whose message holds four sentences, the same message split over two batches, and a `UserPromptSubmit` event. Run `python -m pytest packages/claude-dev-env/hooks/blocking/test_chat_reply_gate.py -q`. The adjacent test observes the drafter's text in `displayContent`, an empty first batch, no output for three sentences, the original after two failed drafts, the shown draft in the next `additionalContext`, and the stored draft deleted at session end.
68
+ - **Chat reply.** Input is a `MessageDisplay` event whose message holds four sentences, the same message split over two batches, and a `UserPromptSubmit` event. Run `python -m pytest packages/claude-dev-env/hooks/blocking/test_chat_reply_gate.py -q`. The adjacent test observes the drafter's text in `displayContent`, an empty first batch, no output for three sentences, the original after two failed drafts, the shown draft in the next `additionalContext`, and the stored draft deleted at session end. A replay of two prompts and a compaction observes the reply rules on the first prompt, no output on the second, and the rules again after the compaction.
69
69
  - **Edit marker.** Input is an update message with strikethrough or an edit note. Run `python -m pytest packages/claude-dev-env/hooks/blocking/test_edit_marker_gate.py -q`. The adjacent test observes a denial; clean replacement text passes.
70
70
  - **Handoff close.** Input is an issue comment that says the issue is closed and that the found defect belongs to another issue. Run `python -m pytest packages/claude-dev-env/hooks/blocking/test_issue_close_handoff_gate.py -q`. The adjacent test observes a denial; a close with a plain cross-reference and a routing comment on an open issue both pass.
71
71
  - **Session title.** Input is a set session title call with no leading emoji or a name over 25 characters. Run `python -m pytest packages/claude-dev-env/hooks/blocking/test_session_title_format_gate.py -q`. The adjacent test observes a denial that names the broken rule; a well-formed title passes.
@@ -5,7 +5,7 @@ This family reminds the agent to gather context before a spawn, refuses a brief
5
5
  ## Checks
6
6
 
7
7
  - `routing/spawn_readiness_hook.py` adds context to a spawn that comes before a read step, or before an answered question or a settled-scope line. The spawn still runs.
8
- - `routing/spawn_oversight_hook.py` denies a spawn whose brief has no `Outcome:` line or no `On a blocker:` clause, each with text after it. A spawn that passes gets the orchestrator oversight directive: run each piece through the verified-work flow, with a fresh verifier agent that checks the research, the plan, and the fix, reproduces the issue before it confirms the fix, and leaves the worker's conclusion out of its brief; ask the user before new scope; report as done only what a verifier passed; and watch the agent while it runs. `routing/spawn_brief_text.py` reads the brief from each spawn tool for this hook and the readiness hook.
8
+ - `routing/spawn_oversight_hook.py` denies a spawn whose brief has no `Outcome:` line or no `On a blocker:` clause, each with text after it. The first passing spawn of a session, the first of each subagent, and the first after each compaction get the orchestrator oversight directive; the brief check runs on every spawn. The directive says: run each piece through the verified-work flow, with a fresh verifier agent that checks the research, the plan, and the fix, reproduces the issue before it confirms the fix, and leaves the worker's conclusion out of its brief; ask the user before new scope; report as done only what a verifier passed; and watch the agent while it runs. `routing/spawn_brief_text.py` reads the brief from each spawn tool for this hook and the readiness hook.
9
9
  - `routing/thread_spawn_pace_hook.py` reshapes a thread request to Opus at medium when usage is over pace or unreadable. Under pace, a thread request that names a model gets the effort its model allows.
10
10
  - `routing/subagent_effort_route_hook.py` sets an allowed effort on an Agent or Task spawn: Opus medium, Sonnet high, Fable low, medium or high, and Haiku any effort. A spawn with no effort or one outside its model's list gets Opus medium, Sonnet high, Fable high, or Haiku medium. `routing/subagent_effort_route.py` holds the rule for this hook and the pace hook.
11
11
  - `routing/subagent_model_routing.mjs` allows a selected Luna model, remaps eligible requests, and denies unsupported model routing.
@@ -27,7 +27,7 @@ Preconditions:
27
27
  - Run each command from the repository root. Python and pytest cover the two Python scripts; Node covers the model router.
28
28
 
29
29
  - **Spawn readiness.** Input is a spawn after a read, a question, and its answer. Run `python -m pytest packages/claude-dev-env/hooks/routing/test_spawn_readiness_hook.py -q`. The adjacent test observes no output for a ready spawn and reminder context for each missing step.
30
- - **Spawn oversight.** Input is a route-only brief, a brief with both clauses, and briefs with one clause, on each registered tool, plus a non-spawn call. Run `python -m pytest packages/claude-dev-env/hooks/routing/test_spawn_oversight_hook.py packages/claude-dev-env/hooks/routing/test_spawn_brief_text.py -q`. The adjacent test observes a deny for each brief missing a clause, the directive for the passing brief, and no output for the other calls.
30
+ - **Spawn oversight.** Input is a route-only brief, a brief with both clauses, and briefs with one clause, on each registered tool, plus a non-spawn call. Run `python -m pytest packages/claude-dev-env/hooks/routing/test_spawn_oversight_hook.py packages/claude-dev-env/hooks/routing/test_spawn_brief_text.py -q`. The adjacent test observes a deny for each brief missing a clause, the directive for the passing brief, and no output for the other calls. A replay of two spawns and a compaction in one session observes the directive, then no output, then the directive again, and a brief missing a clause is denied on every spawn.
31
31
  - **Thread pace.** Input is a thread spawn with usage over pace, and thread spawns under pace that name a model. Run `python -m pytest packages/claude-dev-env/hooks/routing/test_thread_spawn_pace_hook.py -q`. The adjacent test observes Opus at medium over pace, the allowed effort under pace, and no output for an allowed pair.
32
32
  - **Subagent effort route.** Input is an Agent spawn on each model family at allowed and outside efforts, a spawn with no model and a transcript, a fork, and stdin that is not an object. Run `python -m pytest packages/claude-dev-env/hooks/routing/test_subagent_effort_route.py packages/claude-dev-env/hooks/routing/test_subagent_effort_route_hook.py -q`. The adjacent test observes updated tool input with the allowed effort and a context line, and no output for an allowed pair, a fork, or an unknown model.
33
33
  - **Haiku slim gate.** Input is a spawn with a Haiku alias or model ID, with `subagent_type` set to `lean-worker` or to another type, and spawns on other models or with no model. Run `python -m pytest packages/claude-dev-env/hooks/blocking/test_haiku_spawn_slim_gate.py -q`. The adjacent test observes no output for a Haiku spawn of `lean-worker`, a deny with both routes for each other Haiku spawn, and no output for the rest.
@@ -30,6 +30,8 @@ REPLY_LIMIT_REMINDER = (
30
30
  " Count your sentences before you send."
31
31
  )
32
32
  SHOWN_DRAFT_PREFIX = "\n\nThe user saw your last reply condensed to this text, so build on it:\n\n"
33
+ SHOWN_DRAFT_HEADING = SHOWN_DRAFT_PREFIX.lstrip()
34
+ REPLY_LIMIT_ONCE_MARKER_NAME = "chat_reply_limit"
33
35
  DRAFTER_GUARD_ENV_VAR = "CHAT_REPLY_DRAFTER_ACTIVE"
34
36
  DRAFTER_MODEL_ENV_VAR = "CHAT_REPLY_DRAFTER_MODEL"
35
37
  DEFAULT_DRAFTER_MODEL = "haiku"
@@ -0,0 +1,29 @@
1
+ """Names for the marker files that let a hook show its fixed text once per session.
2
+
3
+ Groups: the payload keys the helper reads, the marker file name parts, and the
4
+ transcript entries that mark a compaction in Claude Code and in Codex.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ SESSION_ID_KEY = "session_id"
10
+ AGENT_ID_KEY = "agent_id"
11
+ TRANSCRIPT_PATH_KEY = "transcript_path"
12
+
13
+ ONCE_MARKER_FILE_PREFIX = "claude-once-"
14
+ ONCE_MARKER_FILE_SUFFIX = ".marker"
15
+ ONCE_MARKER_NAME_SEPARATOR = "."
16
+ EXCLUSIVE_CREATE_MODE = "x"
17
+
18
+ TRANSCRIPT_READ_MODE = "rb"
19
+ CLAUDE_COMPACTION_FIELD = "subtype"
20
+ CLAUDE_COMPACTION_VALUE = "compact_boundary"
21
+ CODEX_COMPACTION_FIELD = "type"
22
+ CODEX_COMPACTION_VALUE = "compacted"
23
+ ALL_COMPACTION_ENTRY_FIELDS = (
24
+ (CLAUDE_COMPACTION_FIELD, CLAUDE_COMPACTION_VALUE),
25
+ (CODEX_COMPACTION_FIELD, CODEX_COMPACTION_VALUE),
26
+ )
27
+ ALL_COMPACTION_LINE_MARKERS = tuple(
28
+ each_value.encode() for _, each_value in ALL_COMPACTION_ENTRY_FIELDS
29
+ )
@@ -119,6 +119,7 @@ BLOCK_REASON = (
119
119
  )
120
120
  PROMPT_SUBMIT_EVENT_NAME = "UserPromptSubmit"
121
121
  TASK_LIST_NUDGE = (
122
- "The user follows your work in the task list. Give this ask a task list item (TaskCreate) and"
123
- " keep each item's status current as the work moves."
122
+ "The user follows your work in the task list. Give each ask an item in the session's task list"
123
+ " tool and keep each item's status current as the work moves."
124
124
  )
125
+ TASK_LIST_NUDGE_ONCE_MARKER_NAME = "tracking_nudge"
@@ -14,6 +14,7 @@ ADDITIONAL_CONTEXT_KEY = "additionalContext"
14
14
  PERMISSION_DECISION_REASON_KEY = "permissionDecisionReason"
15
15
  DENY_DECISION = "deny"
16
16
  WORKFLOW_TOOL_NAME = "Workflow"
17
+ SPAWN_OVERSIGHT_ONCE_MARKER_NAME = "spawn_oversight"
17
18
 
18
19
  ALL_OUTCOME_MARKERS = ("outcome:",)
19
20
  ALL_BLOCKER_CLAUSE_MARKERS = ("on a blocker:", "at a blocker:")
@@ -0,0 +1,107 @@
1
+ """Let a hook show its fixed text once per session and once more after each compaction.
2
+
3
+ A compaction drops the earlier text from the agent's context, so the count of
4
+ compactions in the transcript is part of the marker name. A new compaction
5
+ gives a new name, and the next event shows the text again::
6
+
7
+ session s1, first event -> True, writes the s1, 0 compactions marker
8
+ session s1, later event -> False
9
+ session s1, event after a compaction -> True, writes the s1, 1 compaction marker
10
+ subagent a1 in session s1, first event -> True, its own marker
11
+ payload with no session id -> True on every event
12
+ marker cannot be written -> True on every event
13
+
14
+ Claude Code marks a compaction with a ``compact_boundary`` system entry, and a
15
+ Codex rollout with a ``compacted`` entry.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import json
21
+ import tempfile
22
+ from collections.abc import Mapping
23
+ from pathlib import Path
24
+
25
+ from hooks_constants.once_per_session_constants import (
26
+ AGENT_ID_KEY,
27
+ ALL_COMPACTION_ENTRY_FIELDS,
28
+ ALL_COMPACTION_LINE_MARKERS,
29
+ EXCLUSIVE_CREATE_MODE,
30
+ ONCE_MARKER_FILE_PREFIX,
31
+ ONCE_MARKER_FILE_SUFFIX,
32
+ ONCE_MARKER_NAME_SEPARATOR,
33
+ SESSION_ID_KEY,
34
+ TRANSCRIPT_PATH_KEY,
35
+ TRANSCRIPT_READ_MODE,
36
+ )
37
+ from hooks_constants.session_file_id import session_file_id
38
+
39
+ __all__ = ["claim_first_showing", "clear_showings", "compaction_count"]
40
+
41
+
42
+ def _is_compaction_entry(transcript_line: bytes) -> bool:
43
+ if not any(each_marker in transcript_line for each_marker in ALL_COMPACTION_LINE_MARKERS):
44
+ return False
45
+ try:
46
+ all_entry_fields = json.loads(transcript_line)
47
+ except ValueError:
48
+ return False
49
+ return isinstance(all_entry_fields, dict) and any(
50
+ all_entry_fields.get(each_field) == each_value
51
+ for each_field, each_value in ALL_COMPACTION_ENTRY_FIELDS
52
+ )
53
+
54
+
55
+ def compaction_count(transcript_path: object) -> int:
56
+ """Return the number of compactions the transcript records, or 0 when it cannot be read."""
57
+ if not isinstance(transcript_path, str) or not transcript_path:
58
+ return 0
59
+ try:
60
+ with Path(transcript_path).open(TRANSCRIPT_READ_MODE) as transcript:
61
+ return sum(1 for each_line in transcript if _is_compaction_entry(each_line))
62
+ except OSError:
63
+ return 0
64
+
65
+
66
+ def _marker_path(hook_name: str, session_id: str, all_hook_fields: Mapping[str, object]) -> Path:
67
+ all_name_parts = [hook_name, session_file_id(session_id)]
68
+ agent_id = all_hook_fields.get(AGENT_ID_KEY)
69
+ if isinstance(agent_id, str) and agent_id:
70
+ all_name_parts.append(session_file_id(agent_id))
71
+ all_name_parts.append(str(compaction_count(all_hook_fields.get(TRANSCRIPT_PATH_KEY))))
72
+ marker_name = ONCE_MARKER_NAME_SEPARATOR.join(all_name_parts)
73
+ return (
74
+ Path(tempfile.gettempdir())
75
+ / f"{ONCE_MARKER_FILE_PREFIX}{marker_name}{ONCE_MARKER_FILE_SUFFIX}"
76
+ )
77
+
78
+
79
+ def claim_first_showing(hook_name: str, all_hook_fields: Mapping[str, object]) -> bool:
80
+ """Return True when the hook should show its fixed text now, and record that it did.
81
+
82
+ Args:
83
+ hook_name: A short name that keeps each hook's marker apart.
84
+ all_hook_fields: The hook payload, read for its session id, agent id,
85
+ and transcript path.
86
+ """
87
+ session_id = all_hook_fields.get(SESSION_ID_KEY)
88
+ if not isinstance(session_id, str) or not session_id:
89
+ return True
90
+ try:
91
+ with _marker_path(hook_name, session_id, all_hook_fields).open(EXCLUSIVE_CREATE_MODE):
92
+ return True
93
+ except FileExistsError:
94
+ return False
95
+ except OSError:
96
+ return True
97
+
98
+
99
+ def clear_showings(session_id: object) -> None:
100
+ """Delete every hook's markers for the session, its subagents included, at session end."""
101
+ if not isinstance(session_id, str) or not session_id:
102
+ return
103
+ session_pattern = ONCE_MARKER_NAME_SEPARATOR.join(["*", session_file_id(session_id), "*"])
104
+ for each_marker in Path(tempfile.gettempdir()).glob(
105
+ f"{ONCE_MARKER_FILE_PREFIX}{session_pattern}{ONCE_MARKER_FILE_SUFFIX}"
106
+ ):
107
+ each_marker.unlink(missing_ok=True)
@@ -14,14 +14,18 @@ the outcome and any route named is a default.
14
14
  Agent {"prompt": "Run X via RC."} -> deny: no outcome, no blocker clause
15
15
  Agent {"prompt": "Outcome: ... On a blocker: ..."}
16
16
  -> additionalContext: the directive
17
+ the same spawn again in that session -> no output
17
18
  Workflow {"name": "saved-review"} -> additionalContext: the directive
18
19
  actions trigger {"method": "cancel_workflow_run"}
19
20
  -> no output
20
21
  Bash {"command": "ls"} -> no output
21
22
  Agent "not an object" -> no output
22
23
 
23
- A passing spawn gets the oversight directive, so the spawner owns the work it
24
- delegates. Subagent and read-only helper spawns are checked the same way. A
24
+ The first passing spawn of a session gets the oversight directive, so the
25
+ spawner owns the work it delegates. Each subagent gets it on its own first
26
+ spawn, and the session gets it again on the first spawn after a compaction.
27
+ Every spawn gets the brief check. Subagent and read-only helper spawns are
28
+ checked the same way. A
25
29
  ``Workflow`` call with no script text, such as a saved or resumed run, passes
26
30
  with the directive.
27
31
  """
@@ -58,10 +62,12 @@ from hooks_constants.spawn_oversight_hook_constants import (
58
62
  REFUSAL_PREFIX,
59
63
  REFUSAL_SUFFIX,
60
64
  SPAWN_OVERSIGHT_DIRECTIVE,
65
+ SPAWN_OVERSIGHT_ONCE_MARKER_NAME,
61
66
  TOOL_INPUT_KEY,
62
67
  TOOL_NAME_KEY,
63
68
  WORKFLOW_TOOL_NAME,
64
69
  )
70
+ from once_per_session import claim_first_showing
65
71
  from spawn_brief_text import spawn_brief_text
66
72
 
67
73
 
@@ -112,7 +118,9 @@ def brief_gaps(brief: str) -> list[str]:
112
118
  return all_gaps
113
119
 
114
120
 
115
- def _directive_output() -> dict[str, object]:
121
+ def _directive_output(all_hook_fields: dict[str, object]) -> dict[str, object] | None:
122
+ if not claim_first_showing(SPAWN_OVERSIGHT_ONCE_MARKER_NAME, all_hook_fields):
123
+ return None
116
124
  return {
117
125
  HOOK_SPECIFIC_OUTPUT_KEY: {
118
126
  HOOK_EVENT_NAME_KEY: PRE_TOOL_USE_EVENT_NAME,
@@ -134,13 +142,15 @@ def _deny_output(all_gaps: list[str]) -> dict[str, object]:
134
142
 
135
143
 
136
144
  def decide_hook_output(all_hook_fields: dict[str, object]) -> dict[str, object] | None:
137
- """Return a deny for a brief that lacks a clause, the directive for one that passes.
145
+ """Return a deny for a brief that lacks a clause, the directive for the session's first one that passes.
138
146
 
139
147
  Args:
140
148
  all_hook_fields: The parsed PreToolUse payload.
141
149
 
142
150
  Returns:
143
- None for a call that spawns no agent, else the deny or the directive.
151
+ None for a call that spawns no agent or for a passing spawn after the
152
+ directive already showed in this session since its last compaction,
153
+ else the deny or the directive.
144
154
  """
145
155
  all_tool_input_fields = all_hook_fields.get(TOOL_INPUT_KEY)
146
156
  if not isinstance(all_tool_input_fields, dict):
@@ -150,11 +160,11 @@ def decide_hook_output(all_hook_fields: dict[str, object]) -> dict[str, object]
150
160
  if brief is None:
151
161
  return None
152
162
  if tool_name == WORKFLOW_TOOL_NAME and not brief:
153
- return _directive_output()
163
+ return _directive_output(all_hook_fields)
154
164
  all_gaps = brief_gaps(brief)
155
165
  if all_gaps:
156
166
  return _deny_output(all_gaps)
157
- return _directive_output()
167
+ return _directive_output(all_hook_fields)
158
168
 
159
169
 
160
170
  def main() -> int:
@@ -1,6 +1,8 @@
1
1
  import json
2
+ import os
2
3
  import subprocess
3
4
  import sys
5
+ import tempfile
4
6
  from pathlib import Path
5
7
 
6
8
  import pytest
@@ -189,6 +191,93 @@ def test_other_calls_get_no_output(payload: dict[str, object]) -> None:
189
191
  assert spawn_oversight_hook.decide_hook_output(payload) is None
190
192
 
191
193
 
194
+ def _session_spawn(
195
+ brief: str, transcript_path: Path, agent_id: str | None = None
196
+ ) -> dict[str, object]:
197
+ payload: dict[str, object] = {
198
+ **_spawn_payload("Agent", brief),
199
+ "session_id": "session_one",
200
+ "transcript_path": str(transcript_path),
201
+ }
202
+ if agent_id is not None:
203
+ payload["agent_id"] = agent_id
204
+ return payload
205
+
206
+
207
+ @pytest.fixture
208
+ def session_transcript(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> Path:
209
+ monkeypatch.setattr(tempfile, "gettempdir", lambda: str(tmp_path))
210
+ transcript_path = tmp_path / "session.jsonl"
211
+ transcript_path.write_text(json.dumps({"type": "user"}) + "\n", encoding="utf-8")
212
+ return transcript_path
213
+
214
+
215
+ def _append_compaction(transcript_path: Path) -> None:
216
+ with transcript_path.open("a", encoding="utf-8") as transcript:
217
+ transcript.write(json.dumps({"type": "system", "subtype": "compact_boundary"}) + "\n")
218
+
219
+
220
+ def test_the_directive_shows_once_per_session_and_again_after_a_compaction(
221
+ session_transcript: Path,
222
+ ) -> None:
223
+ decide = spawn_oversight_hook.decide_hook_output
224
+ assert decide(_session_spawn(GOOD_BRIEF, session_transcript)) == _directive_output()
225
+ assert decide(_session_spawn(GOOD_BRIEF, session_transcript)) is None
226
+ _append_compaction(session_transcript)
227
+ assert decide(_session_spawn(GOOD_BRIEF, session_transcript)) == _directive_output()
228
+ assert decide(_session_spawn(GOOD_BRIEF, session_transcript)) is None
229
+
230
+
231
+ def test_a_brief_missing_a_clause_is_refused_on_every_spawn_of_a_session(
232
+ session_transcript: Path,
233
+ ) -> None:
234
+ decide = spawn_oversight_hook.decide_hook_output
235
+ assert MISSING_OUTCOME_REASON in _deny_reason(
236
+ decide(_session_spawn(ROUTE_ONLY_BRIEF, session_transcript))
237
+ )
238
+ assert decide(_session_spawn(GOOD_BRIEF, session_transcript)) == _directive_output()
239
+ assert MISSING_OUTCOME_REASON in _deny_reason(
240
+ decide(_session_spawn(ROUTE_ONLY_BRIEF, session_transcript))
241
+ )
242
+ assert MISSING_BLOCKER_CLAUSE_REASON in _deny_reason(
243
+ decide(_session_spawn(OUTCOME_ONLY_BRIEF, session_transcript))
244
+ )
245
+
246
+
247
+ def test_a_subagent_gets_the_directive_on_its_own_first_spawn(
248
+ session_transcript: Path,
249
+ ) -> None:
250
+ decide = spawn_oversight_hook.decide_hook_output
251
+ assert decide(_session_spawn(GOOD_BRIEF, session_transcript)) == _directive_output()
252
+ child_spawn = _session_spawn(GOOD_BRIEF, session_transcript, agent_id="agent_child")
253
+ assert decide(child_spawn) == _directive_output()
254
+ assert decide(child_spawn) is None
255
+
256
+
257
+ def test_replay_of_two_spawns_and_a_compaction_through_the_script(tmp_path: Path) -> None:
258
+ transcript_path = tmp_path / "session.jsonl"
259
+ transcript_path.write_text(json.dumps({"type": "user"}) + "\n", encoding="utf-8")
260
+ environment = {**os.environ, "TMP": str(tmp_path), "TEMP": str(tmp_path), "TMPDIR": str(tmp_path)}
261
+
262
+ def replay_spawn() -> str:
263
+ return subprocess.run(
264
+ [sys.executable, str(HOOK_SCRIPT)],
265
+ input=json.dumps(_session_spawn(GOOD_BRIEF, transcript_path)),
266
+ capture_output=True,
267
+ text=True,
268
+ env=environment,
269
+ check=True,
270
+ ).stdout
271
+
272
+ first_stdout = replay_spawn()
273
+ second_stdout = replay_spawn()
274
+ _append_compaction(transcript_path)
275
+ after_compaction_stdout = replay_spawn()
276
+ assert json.loads(first_stdout) == _directive_output()
277
+ assert second_stdout == ""
278
+ assert json.loads(after_compaction_stdout) == _directive_output()
279
+
280
+
192
281
  def _run_script(stdin_text: str) -> str:
193
282
  completed = subprocess.run(
194
283
  [sys.executable, str(HOOK_SCRIPT)],