claude-dev-env 8.114.5 → 8.114.7

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.
@@ -2,7 +2,7 @@
2
2
 
3
3
  Every agent that spawns a subagent, thread, or session owns that work until it reaches the user.
4
4
  Agents make mistakes. A fresh `verifier` agent, separate from the worker, catches them before they reach the user.
5
- The `spawn_oversight_hook` adds this duty to every spawn, at every level of the tree.
5
+ The `spawn_oversight_hook` adds this duty to the first spawn of each agent in the tree, and again after a compaction.
6
6
 
7
7
  - Run each piece through the verified-work flow in `~/.claude/docs/rule-guides/verified-work.md`: research, verify, plan, verify, implement, verify.
8
8
  - Brief each worker with the user's own words, the standards that apply, and the acceptance check.
@@ -27,9 +27,9 @@ On exit 0 the script prints one JSON object:
27
27
  | Field | Meaning |
28
28
  |---|---|
29
29
  | `source` | `probe` or `override` |
30
- | `reset_at` | When the 5-hour window resets (ISO-8601, local zone) |
31
- | `seconds_until_reset` | The wait the stage plan covers |
32
- | `stages_seconds` | The ScheduleWakeup stage durations, in firing order |
30
+ | `reset_at` | When the 5-hour window resets (ISO-8601, local zone). Null when the account has no 5-hour window |
31
+ | `seconds_until_reset` | The wait the stage plan covers (0 when `reset_at` is null) |
32
+ | `stages_seconds` | The ScheduleWakeup stage durations, in firing order (empty when `reset_at` is null) |
33
33
  | `session_utilization` | Percent of the 5-hour window spent (null on override) |
34
34
  | `weekly_utilization` | Percent of the weekly window spent (null on override) |
35
35
  | `weekly_resets_at` | When the weekly window resets (null on override) |
@@ -46,7 +46,7 @@ In short: the resolver picks a bearer token, probes the OAuth usage endpoint the
46
46
  - **Desktop host** (the `CLAUDE_CODE_ENTRYPOINT` variable is `claude-desktop`): the resolver does not read the CLI credential file, which belongs to a different authentication session than the one the desktop app counts usage against. It uses the session ingress token when one is set, and otherwise takes the manual-override path.
47
47
  - **Every other host**: the resolver reads the Claude Code CLI's stored OAuth access token first (honored only while unexpired), then the session ingress bearer token file named by `CLAUDE_SESSION_INGRESS_TOKEN_FILE` (cloud sessions) when the credential token is unavailable. The credential file lives under the directory `CLAUDE_CONFIG_DIR` names when that variable is set — a profile-isolated session's own account — else the home-directory default; the home file on a multi-profile machine can belong to a different account, whose meter is the wrong one to read.
48
48
 
49
- Fallbacks, in order: both token sources unavailable (expired/unreadable credential and no ingress file), a failed request, or a response with no readable session-window reset time all end in exit 2 — the manual-override ask above. The manual path works with no probe at all, so the skill functions even when both token sources are unavailable.
49
+ Fallbacks, in order: both token sources unavailable (expired/unreadable credential and no ingress file), a failed request, or a response with no readable window all end in exit 2 — the manual-override ask above. A reply with only a weekly window is not a failure: it exits 0 with a null `reset_at`. The manual path works with no probe at all, so the skill functions even when both token sources are unavailable.
50
50
 
51
51
  Why this probe and not the others:
52
52
 
@@ -59,6 +59,8 @@ Why this probe and not the others:
59
59
 
60
60
  When `weekly_near_cap` is true, WARN the user — report `weekly_utilization` and `weekly_resets_at` — and stop. No pause choreography runs around the weekly limit; waiting out a weekly window is its own later build.
61
61
 
62
+ A null `reset_at` with an empty `stages_seconds` says the account has no 5-hour window. Skip Step 2, since there is nothing to wait out, and still apply this guard to the weekly fields.
63
+
62
64
  ## Step 2 — the pause chain
63
65
 
64
66
  Before the first sleep:
@@ -64,6 +64,7 @@ from usage_pause_constants.resolve_usage_window_constants import (
64
64
  MINIMUM_STAGE_SECONDS,
65
65
  MINUTES_PER_HOUR,
66
66
  NOON_HOUR,
67
+ NO_FIVE_HOUR_WINDOW_LOG_MESSAGE,
67
68
  OAUTH_BETA_HEADER_NAME,
68
69
  OAUTH_BETA_HEADER_VALUE,
69
70
  OAUTH_USAGE_ENDPOINT_URL,
@@ -414,7 +415,7 @@ def extract_usage_windows(all_usage_buckets: dict[str, object]) -> UsageWindows:
414
415
 
415
416
  def build_pause_plan(
416
417
  source: str,
417
- reset_at: datetime,
418
+ reset_at: datetime | None,
418
419
  now: datetime,
419
420
  session_utilization: float | None,
420
421
  weekly_utilization: float | None,
@@ -422,9 +423,19 @@ def build_pause_plan(
422
423
  ) -> dict[str, object]:
423
424
  """Assemble the resolver's JSON-ready output for one resolved reset time.
424
425
 
426
+ ::
427
+
428
+ reset_at = <74 minutes out> -> seconds_until_reset 4440, three stages
429
+ reset_at = None -> seconds_until_reset 0, no stages
430
+
431
+ An account with no 5-hour window has nothing to wait out, so a None
432
+ reset time yields a null reset, a zero wait, and an empty stage plan
433
+ while the weekly meters and the near-cap flag still report.
434
+
425
435
  Args:
426
436
  source: Where the reset time came from, probe or override.
427
- reset_at: When the 5-hour window resets.
437
+ reset_at: When the 5-hour window resets, or None when the account
438
+ has no 5-hour window.
428
439
  now: The current local time the wait is measured from.
429
440
  session_utilization: Percent of the 5-hour window spent, when known.
430
441
  weekly_utilization: Percent of the weekly window spent, when known.
@@ -435,16 +446,21 @@ def build_pause_plan(
435
446
  stage plan, both utilization meters, the weekly reset time, and the
436
447
  weekly near-cap flag.
437
448
  """
438
- seconds_until_reset = max(int((reset_at - now).total_seconds()), 0)
449
+ seconds_until_reset = (
450
+ max(int((reset_at - now).total_seconds()), 0) if reset_at is not None else 0
451
+ )
452
+ stages_seconds = (
453
+ plan_wakeup_stages(seconds_until_reset) if reset_at is not None else []
454
+ )
439
455
  weekly_near_cap = (
440
456
  weekly_utilization is not None
441
457
  and weekly_utilization >= WEEKLY_UTILIZATION_WARN_THRESHOLD
442
458
  )
443
459
  return {
444
460
  RESULT_KEY_SOURCE: source,
445
- RESULT_KEY_RESET_AT: reset_at.isoformat(),
461
+ RESULT_KEY_RESET_AT: reset_at.isoformat() if reset_at is not None else None,
446
462
  RESULT_KEY_SECONDS_UNTIL_RESET: seconds_until_reset,
447
- RESULT_KEY_STAGES_SECONDS: plan_wakeup_stages(seconds_until_reset),
463
+ RESULT_KEY_STAGES_SECONDS: stages_seconds,
448
464
  RESULT_KEY_SESSION_UTILIZATION: session_utilization,
449
465
  RESULT_KEY_WEEKLY_UTILIZATION: weekly_utilization,
450
466
  RESULT_KEY_WEEKLY_RESETS_AT: weekly_resets_at.isoformat()
@@ -585,6 +601,18 @@ def main() -> int:
585
601
  )
586
602
  )
587
603
  return EXIT_CODE_RESOLVED
604
+ return _resolve_from_probe(arguments, now)
605
+
606
+
607
+ def _has_no_resolvable_window(windows: UsageWindows) -> bool:
608
+ has_session_meter = windows.session_utilization is not None
609
+ has_weekly_window = (
610
+ windows.weekly_utilization is not None or windows.weekly_resets_at is not None
611
+ )
612
+ return has_session_meter or not has_weekly_window
613
+
614
+
615
+ def _resolve_from_probe(arguments: argparse.Namespace, now: datetime) -> int:
588
616
  credentials_path = (
589
617
  Path(arguments.credentials_path)
590
618
  if arguments.credentials_path
@@ -605,7 +633,9 @@ def main() -> int:
605
633
  return _emit_error(f"usage probe failed: {probe_error}")
606
634
  windows = extract_usage_windows(usage_payload)
607
635
  if windows.session_resets_at is None:
608
- return _emit_error("usage response carried no five_hour reset time")
636
+ if _has_no_resolvable_window(windows):
637
+ return _emit_error("usage response carried no five_hour reset time")
638
+ logger.info(NO_FIVE_HOUR_WINDOW_LOG_MESSAGE)
609
639
  print(
610
640
  json.dumps(
611
641
  build_pause_plan(
@@ -487,6 +487,109 @@ class TestBuildPausePlan:
487
487
  assert resolved_payload["reset_at"] == reset_at.isoformat()
488
488
 
489
489
 
490
+ class TestBuildPausePlanWithoutSessionWindow:
491
+ def should_plan_no_wait_and_keep_weekly_meters(self) -> None:
492
+ resolver = load_resolver_module()
493
+ now = local_now()
494
+ weekly_resets_at = now + timedelta(days=3)
495
+ resolved_payload = resolver.build_pause_plan(
496
+ "probe", None, now, None, 92.0, weekly_resets_at
497
+ )
498
+ assert resolved_payload["reset_at"] is None
499
+ assert resolved_payload["seconds_until_reset"] == 0
500
+ assert resolved_payload["stages_seconds"] == []
501
+ assert resolved_payload["weekly_near_cap"] is True
502
+ assert resolved_payload["weekly_resets_at"] == weekly_resets_at.isoformat()
503
+
504
+
505
+ class TestWeeklyOnlyUsageReply:
506
+ @pytest.fixture
507
+ def run_probe_with_reply(
508
+ self, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
509
+ ):
510
+ def run(usage_reply: dict[str, object]) -> tuple[int, dict[str, object]]:
511
+ resolver = load_resolver_module()
512
+ monkeypatch.setattr(sys, "argv", ["resolve_usage_window.py"])
513
+ monkeypatch.setattr(
514
+ resolver, "resolve_access_token", lambda credentials_path, now: "stub"
515
+ )
516
+ monkeypatch.setattr(
517
+ resolver, "_fetch_usage_payload", lambda access_token: usage_reply
518
+ )
519
+ exit_code = resolver.main()
520
+ return exit_code, json.loads(capsys.readouterr().out)
521
+
522
+ return run
523
+
524
+ def should_resolve_with_no_wait_when_five_hour_is_null(
525
+ self, run_probe_with_reply
526
+ ) -> None:
527
+ exit_code, resolved_payload = run_probe_with_reply(
528
+ {
529
+ "five_hour": None,
530
+ "seven_day": {
531
+ "utilization": 63,
532
+ "resets_at": "2026-07-12T00:00:00+00:00",
533
+ },
534
+ }
535
+ )
536
+ assert exit_code == 0
537
+ assert resolved_payload["source"] == "probe"
538
+ assert resolved_payload["reset_at"] is None
539
+ assert resolved_payload["seconds_until_reset"] == 0
540
+ assert resolved_payload["stages_seconds"] == []
541
+ assert resolved_payload["session_utilization"] is None
542
+ assert resolved_payload["weekly_utilization"] == 63.0
543
+ assert resolved_payload["weekly_near_cap"] is False
544
+
545
+ def should_flag_weekly_near_cap_when_five_hour_is_null(
546
+ self, run_probe_with_reply
547
+ ) -> None:
548
+ exit_code, resolved_payload = run_probe_with_reply(
549
+ {
550
+ "five_hour": None,
551
+ "seven_day": {
552
+ "utilization": 95,
553
+ "resets_at": "2026-07-12T00:00:00+00:00",
554
+ },
555
+ }
556
+ )
557
+ assert exit_code == 0
558
+ assert resolved_payload["weekly_near_cap"] is True
559
+ assert resolved_payload["weekly_resets_at"] is not None
560
+
561
+ def should_resolve_when_five_hour_key_is_absent(self, run_probe_with_reply) -> None:
562
+ exit_code, resolved_payload = run_probe_with_reply(
563
+ {"seven_day": {"utilization": 20, "resets_at": "2026-07-12T00:00:00+00:00"}}
564
+ )
565
+ assert exit_code == 0
566
+ assert resolved_payload["stages_seconds"] == []
567
+
568
+ def should_still_exit_two_when_no_window_is_readable(
569
+ self, run_probe_with_reply
570
+ ) -> None:
571
+ exit_code, resolved_payload = run_probe_with_reply(
572
+ {"five_hour": None, "seven_day": None}
573
+ )
574
+ assert exit_code == 2
575
+ assert "error" in resolved_payload
576
+
577
+ def should_still_exit_two_when_five_hour_has_utilization_but_no_reset(
578
+ self, run_probe_with_reply
579
+ ) -> None:
580
+ exit_code, resolved_payload = run_probe_with_reply(
581
+ {
582
+ "five_hour": {"utilization": 30},
583
+ "seven_day": {
584
+ "utilization": 20,
585
+ "resets_at": "2026-07-12T00:00:00+00:00",
586
+ },
587
+ }
588
+ )
589
+ assert exit_code == 2
590
+ assert "error" in resolved_payload
591
+
592
+
490
593
  class TestCommandLine:
491
594
  def run_resolver(
492
595
  self,
@@ -70,3 +70,6 @@ EXIT_CODE_RESOLVED = 0
70
70
  EXIT_CODE_PROBE_UNAVAILABLE = 2
71
71
 
72
72
  LOGGING_FORMAT = "%(levelname)s %(name)s: %(message)s"
73
+ NO_FIVE_HOUR_WINDOW_LOG_MESSAGE = (
74
+ "usage response has no five_hour window; nothing to wait out, reporting the weekly window only"
75
+ )
@@ -45,7 +45,7 @@ The gate holds a turn once when all three hold:
45
45
 
46
46
  The gate never reads the reply text. A held turn passes, so the gate adds at most one step to a turn.
47
47
 
48
- In Claude Code, `tracking_nudge.py` runs on `UserPromptSubmit`. For a prompt that asks for work, it adds one note that asks for a task list item, so the agent tracks the ask before it starts. The note never blocks.
48
+ In Claude Code, `tracking_nudge.py` runs on `UserPromptSubmit`. For the session's first prompt that asks for work, and the first after each compaction, it adds one note that asks for an item in the session's task list tool, so the agent tracks the ask before it starts. The note never blocks.
49
49
 
50
50
  ## Cursor
51
51
 
@@ -50,4 +50,4 @@ Report only what a verifier passed. Name the verifier's verdict and the evidence
50
50
 
51
51
  ## Enforcement
52
52
 
53
- `hooks/routing/spawn_oversight_hook.py` adds the six steps, the separate verifier, the reproduce-first check, the scope ask, and the reporting rule to every spawn at every level of the agent tree whose brief has an `Outcome:` line and an `On a blocker:` line; the hook already denies a brief without them, and the verifier brief template carries both. The flow itself adds context only. No hook refuses a report, a commit, or a spawn for a missing verifier run, so the flow never blocks work the user asked for.
53
+ `hooks/routing/spawn_oversight_hook.py` adds the six steps, the separate verifier, the reproduce-first check, the scope ask, and the reporting rule to the first passing spawn of each agent in the tree, and again after a compaction. A passing brief has an `Outcome:` line and an `On a blocker:` line; the hook denies a brief without them on every spawn, and the verifier brief template carries both. The flow itself adds context only. No hook refuses a report, a commit, or a spawn for a missing verifier run, so the flow never blocks work the user asked for.
@@ -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)],
@@ -1,12 +1,16 @@
1
1
  import importlib
2
2
  import io
3
3
  import json
4
+ import os
4
5
  import subprocess
5
6
  import sys
7
+ import tempfile
6
8
  from pathlib import Path
7
9
 
8
10
  import pytest
9
11
 
12
+ from hooks_constants.open_tasks_stop_gate_constants import TASK_LIST_NUDGE
13
+
10
14
  _SESSION_DIR = Path(__file__).resolve().parent
11
15
  if str(_SESSION_DIR) not in sys.path:
12
16
  sys.path.insert(0, str(_SESSION_DIR))
@@ -34,16 +38,19 @@ def run_nudge(
34
38
  tmp_path: Path,
35
39
  prompt_text: str,
36
40
  all_entries: list[dict[str, object]],
41
+ session_id: str | None = None,
37
42
  ) -> str:
38
43
  transcript_path = tmp_path / "s.jsonl"
39
44
  transcript_path.write_text(
40
45
  "\n".join(json.dumps(each) for each in all_entries), encoding="utf-8"
41
46
  )
42
- hook_input = {
47
+ hook_input: dict[str, object] = {
43
48
  "hook_event_name": "UserPromptSubmit",
44
49
  "prompt": prompt_text,
45
50
  "transcript_path": str(transcript_path),
46
51
  }
52
+ if session_id is not None:
53
+ hook_input["session_id"] = session_id
47
54
  monkeypatch.setattr(
48
55
  "sys.stdin", io.TextIOWrapper(io.BytesIO(json.dumps(hook_input).encode("utf-8")))
49
56
  )
@@ -62,10 +69,43 @@ def test_should_remind_a_work_prompt_to_use_the_task_list(
62
69
  context_text = run_nudge(
63
70
  monkeypatch, capsys, tmp_path, "Export the APKs", titled_entries("⏳ Export")
64
71
  )
65
- assert "TaskCreate" in context_text
72
+ assert "the session's task list tool" in context_text
73
+ assert "TaskCreate" not in context_text
66
74
  assert "⏳ Export" not in context_text
67
75
 
68
76
 
77
+ COMPACTION_ENTRY = {"type": "system", "subtype": "compact_boundary"}
78
+
79
+
80
+ def test_should_add_the_task_list_note_once_per_session_and_again_after_a_compaction(
81
+ monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], tmp_path: Path
82
+ ) -> None:
83
+ monkeypatch.setattr(tempfile, "gettempdir", lambda: str(tmp_path))
84
+ entries = titled_entries("⏳ Export")
85
+
86
+ def nudge(prompt_text: str, all_entries: list[dict[str, object]]) -> str:
87
+ return run_nudge(monkeypatch, capsys, tmp_path, prompt_text, all_entries, "session_one")
88
+
89
+ assert nudge("thanks!", entries) == ""
90
+ assert TASK_LIST_NUDGE in nudge("Export the APKs", entries)
91
+ assert nudge("Now sign the APKs", entries) == ""
92
+ assert TASK_LIST_NUDGE in nudge("Upload the APKs", [*entries, COMPACTION_ENTRY])
93
+ assert nudge("Tag the release", [*entries, COMPACTION_ENTRY]) == ""
94
+
95
+
96
+ def test_should_keep_the_title_note_on_each_ask_after_the_task_list_note_shows(
97
+ monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], tmp_path: Path
98
+ ) -> None:
99
+ monkeypatch.setattr(tempfile, "gettempdir", lambda: str(tmp_path))
100
+ entries = titled_entries("\U0001f6a9 Merge approval")
101
+ run_nudge(monkeypatch, capsys, tmp_path, "Export the APKs", entries, "session_one")
102
+ second_text = run_nudge(
103
+ monkeypatch, capsys, tmp_path, "Now sign the APKs", entries, "session_one"
104
+ )
105
+ assert TASK_LIST_NUDGE not in second_text
106
+ assert "\U0001f6a9 Merge approval" in second_text
107
+
108
+
69
109
  @pytest.mark.parametrize("earlier_title", ["\U0001f6a9 Merge approval", "✅ Gate"])
70
110
  def test_should_ask_to_refresh_a_title_that_says_the_session_waits_or_is_done(
71
111
  monkeypatch: pytest.MonkeyPatch,
@@ -104,8 +144,8 @@ def test_should_skip_the_title_note_in_a_session_without_the_title_tool() -> Non
104
144
 
105
145
 
106
146
  def test_should_build_the_note_only_for_a_work_prompt() -> None:
107
- assert tracking_nudge.ask_tracking_context("did it fail?", []) is None
108
- assert "task list" in (tracking_nudge.ask_tracking_context("Export the APKs", []) or "")
147
+ assert tracking_nudge.ask_tracking_context("did it fail?", [], {}) is None
148
+ assert "task list" in (tracking_nudge.ask_tracking_context("Export the APKs", [], {}) or "")
109
149
 
110
150
 
111
151
  def test_should_print_the_documented_output_through_a_subprocess(tmp_path: Path) -> None:
@@ -121,4 +161,38 @@ def test_should_print_the_documented_output_through_a_subprocess(tmp_path: Path)
121
161
  assert completed_process.returncode == 0
122
162
  hook_output = json.loads(completed_process.stdout)["hookSpecificOutput"]
123
163
  assert hook_output["hookEventName"] == "UserPromptSubmit"
124
- assert "TaskCreate" in hook_output["additionalContext"]
164
+ assert "the session's task list tool" in hook_output["additionalContext"]
165
+
166
+
167
+ def test_replay_of_two_asks_and_a_compaction_through_the_script(tmp_path: Path) -> None:
168
+ transcript_path = tmp_path / "session.jsonl"
169
+ transcript_path.write_text(json.dumps({"type": "user"}) + "\n", encoding="utf-8")
170
+ environment = {**os.environ, "TMP": str(tmp_path), "TEMP": str(tmp_path), "TMPDIR": str(tmp_path)}
171
+
172
+ def replay_ask(prompt_text: str) -> str:
173
+ hook_input = {
174
+ "hook_event_name": "UserPromptSubmit",
175
+ "session_id": "session_one",
176
+ "prompt": prompt_text,
177
+ "transcript_path": str(transcript_path),
178
+ }
179
+ return subprocess.run(
180
+ [sys.executable, str(NUDGE_PATH)],
181
+ input=json.dumps(hook_input),
182
+ capture_output=True,
183
+ text=True,
184
+ env=environment,
185
+ check=True,
186
+ ).stdout
187
+
188
+ first_stdout = replay_ask("Export the APKs")
189
+ second_stdout = replay_ask("Now sign the APKs")
190
+ with transcript_path.open("a", encoding="utf-8") as transcript:
191
+ transcript.write(json.dumps(COMPACTION_ENTRY) + "\n")
192
+ after_compaction_stdout = replay_ask("Upload the APKs")
193
+ assert TASK_LIST_NUDGE in json.loads(first_stdout)["hookSpecificOutput"]["additionalContext"]
194
+ assert second_stdout == ""
195
+ assert (
196
+ TASK_LIST_NUDGE
197
+ in json.loads(after_compaction_stdout)["hookSpecificOutput"]["additionalContext"]
198
+ )
@@ -4,11 +4,13 @@
4
4
  The user follows a session in two places: the task list shows what the agent
5
5
  does, and the title's status emoji shows whether the session needs them. A new
6
6
  ask changes both, so the hook adds one short ``additionalContext`` note when the
7
- prompt asks for work::
7
+ prompt asks for work. The task list note shows on the session's first ask and
8
+ on the first ask after each compaction::
8
9
 
9
- "Export the APKs" -> task list note
10
+ "Export the APKs", first ask -> task list note
10
11
  "Export the APKs", title shows a red flag or a check mark
11
12
  -> task list note + title note
13
+ "Sign the APKs", a later ask -> nothing, or the title note
12
14
  "did the export fail?" -> nothing
13
15
  "<task-notification>...</task-notification>"
14
16
  -> nothing
@@ -22,6 +24,7 @@ from __future__ import annotations
22
24
 
23
25
  import json
24
26
  import sys
27
+ from collections.abc import Mapping
25
28
  from pathlib import Path
26
29
 
27
30
  hooks_root_directory = str(Path(__file__).resolve().parent.parent)
@@ -36,6 +39,7 @@ from hooks_constants.open_tasks_stop_gate_constants import (
36
39
  PROMPT_KEY,
37
40
  PROMPT_SUBMIT_EVENT_NAME,
38
41
  TASK_LIST_NUDGE,
42
+ TASK_LIST_NUDGE_ONCE_MARKER_NAME,
39
43
  TRANSCRIPT_PATH_KEY,
40
44
  WORD_SEPARATOR,
41
45
  )
@@ -45,6 +49,7 @@ from hooks_constants.session_title_constants import (
45
49
  TITLE_NUDGE_TEMPLATE,
46
50
  TITLE_TOOL_DISPLAY_SEPARATOR,
47
51
  )
52
+ from once_per_session import claim_first_showing
48
53
  from open_task_asks import is_ask
49
54
  from session_title_turn_gate import (
50
55
  available_title_tools,
@@ -82,12 +87,25 @@ def title_nudge(all_entries: list[dict[str, object]]) -> str | None:
82
87
  )
83
88
 
84
89
 
85
- def ask_tracking_context(prompt_text: str, all_entries: list[dict[str, object]]) -> str | None:
86
- """Return the note for a prompt that asks for work, or None for any other prompt."""
90
+ def ask_tracking_context(
91
+ prompt_text: str,
92
+ all_entries: list[dict[str, object]],
93
+ all_hook_fields: Mapping[str, object],
94
+ ) -> str | None:
95
+ """Return the note for a prompt that asks for work, or None for any other prompt.
96
+
97
+ The task list note shows on the session's first ask and on the first ask
98
+ after each compaction. The title note shows on every ask while the title is stale.
99
+ """
87
100
  if not is_ask(prompt_text):
88
101
  return None
89
- all_notes = [TASK_LIST_NUDGE, title_nudge(all_entries)]
90
- return WORD_SEPARATOR.join(each_note for each_note in all_notes if each_note)
102
+ tracker_note = (
103
+ TASK_LIST_NUDGE
104
+ if claim_first_showing(TASK_LIST_NUDGE_ONCE_MARKER_NAME, all_hook_fields)
105
+ else None
106
+ )
107
+ all_notes = [tracker_note, title_nudge(all_entries)]
108
+ return WORD_SEPARATOR.join(each_note for each_note in all_notes if each_note) or None
91
109
 
92
110
 
93
111
  def main() -> int:
@@ -96,7 +114,7 @@ def main() -> int:
96
114
  if hook_input is None or not isinstance(prompt_value, str):
97
115
  return ALLOW_EXIT_CODE
98
116
  context_text = ask_tracking_context(
99
- prompt_value, read_transcript_entries(hook_input.get(TRANSCRIPT_PATH_KEY))
117
+ prompt_value, read_transcript_entries(hook_input.get(TRANSCRIPT_PATH_KEY)), hook_input
100
118
  )
101
119
  if context_text:
102
120
  hook_output = {
@@ -0,0 +1,109 @@
1
+ import json
2
+ import tempfile
3
+ from pathlib import Path
4
+
5
+ import pytest
6
+
7
+ from once_per_session import (
8
+ claim_first_showing,
9
+ clear_showings,
10
+ compaction_count,
11
+ )
12
+
13
+ CLAUDE_COMPACTION_LINE = json.dumps({"type": "system", "subtype": "compact_boundary"})
14
+ CODEX_COMPACTION_LINE = json.dumps({"type": "compacted", "payload": {"message": ""}})
15
+ QUOTED_COMPACTION_LINE = json.dumps(
16
+ {"type": "user", "message": {"content": 'grep output: {"subtype": "compact_boundary"}'}}
17
+ )
18
+
19
+
20
+ @pytest.fixture
21
+ def transcript_path(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> Path:
22
+ monkeypatch.setattr(tempfile, "gettempdir", lambda: str(tmp_path))
23
+ session_transcript = tmp_path / "session.jsonl"
24
+ session_transcript.write_text(json.dumps({"type": "user"}) + "\n", encoding="utf-8")
25
+ return session_transcript
26
+
27
+
28
+ def _append(transcript_path: Path, transcript_line: str) -> None:
29
+ with transcript_path.open("a", encoding="utf-8") as transcript:
30
+ transcript.write(transcript_line + "\n")
31
+
32
+
33
+ def _fields(transcript_path: Path, **all_extra_fields: object) -> dict[str, object]:
34
+ return {"session_id": "s1", "transcript_path": str(transcript_path), **all_extra_fields}
35
+
36
+
37
+ def test_should_show_once_per_session(transcript_path: Path) -> None:
38
+ assert claim_first_showing("hook", _fields(transcript_path)) is True
39
+ assert claim_first_showing("hook", _fields(transcript_path)) is False
40
+
41
+
42
+ def test_should_keep_each_hook_and_session_apart(transcript_path: Path) -> None:
43
+ assert claim_first_showing("hook", _fields(transcript_path)) is True
44
+ assert claim_first_showing("other_hook", _fields(transcript_path)) is True
45
+ assert claim_first_showing("hook", _fields(transcript_path, session_id="s2")) is True
46
+
47
+
48
+ def test_should_give_a_subagent_its_own_showing(transcript_path: Path) -> None:
49
+ assert claim_first_showing("hook", _fields(transcript_path)) is True
50
+ assert claim_first_showing("hook", _fields(transcript_path, agent_id="a1")) is True
51
+ assert claim_first_showing("hook", _fields(transcript_path, agent_id="a1")) is False
52
+
53
+
54
+ @pytest.mark.parametrize("compaction_line", [CLAUDE_COMPACTION_LINE, CODEX_COMPACTION_LINE])
55
+ def test_should_show_again_after_a_compaction(transcript_path: Path, compaction_line: str) -> None:
56
+ assert claim_first_showing("hook", _fields(transcript_path)) is True
57
+ _append(transcript_path, compaction_line)
58
+ assert claim_first_showing("hook", _fields(transcript_path)) is True
59
+ assert claim_first_showing("hook", _fields(transcript_path)) is False
60
+
61
+
62
+ def test_should_not_count_a_quoted_compaction_marker(transcript_path: Path) -> None:
63
+ _append(transcript_path, QUOTED_COMPACTION_LINE)
64
+ _append(transcript_path, "not json compact_boundary")
65
+ assert compaction_count(str(transcript_path)) == 0
66
+ _append(transcript_path, CLAUDE_COMPACTION_LINE)
67
+ assert compaction_count(str(transcript_path)) == 1
68
+
69
+
70
+ def test_should_skip_a_line_that_is_not_utf8(transcript_path: Path) -> None:
71
+ with transcript_path.open("ab") as transcript:
72
+ transcript.write(b'{"subtype": "compact_boundary\xff"}\n')
73
+ _append(transcript_path, CLAUDE_COMPACTION_LINE)
74
+ assert compaction_count(str(transcript_path)) == 1
75
+
76
+
77
+ @pytest.mark.parametrize("transcript_value", [None, "", 7])
78
+ def test_should_count_no_compaction_without_a_readable_transcript(
79
+ tmp_path: Path, transcript_value: object
80
+ ) -> None:
81
+ assert compaction_count(transcript_value) == 0
82
+ assert compaction_count(str(tmp_path / "absent.jsonl")) == 0
83
+
84
+
85
+ @pytest.mark.parametrize("session_value", [None, "", 7])
86
+ def test_should_show_every_time_without_a_session_id(
87
+ transcript_path: Path, session_value: object
88
+ ) -> None:
89
+ all_fields = _fields(transcript_path, session_id=session_value)
90
+ assert claim_first_showing("hook", all_fields) is True
91
+ assert claim_first_showing("hook", all_fields) is True
92
+
93
+
94
+ def test_should_clear_only_the_ended_session_markers(transcript_path: Path) -> None:
95
+ claim_first_showing("hook", _fields(transcript_path))
96
+ claim_first_showing("other_hook", _fields(transcript_path, agent_id="a1"))
97
+ claim_first_showing("hook", _fields(transcript_path, session_id="s2"))
98
+ clear_showings("s1")
99
+ assert claim_first_showing("hook", _fields(transcript_path)) is True
100
+ assert claim_first_showing("other_hook", _fields(transcript_path, agent_id="a1")) is True
101
+ assert claim_first_showing("hook", _fields(transcript_path, session_id="s2")) is False
102
+
103
+
104
+ def test_should_show_every_time_when_the_marker_cannot_be_written(
105
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
106
+ ) -> None:
107
+ monkeypatch.setattr(tempfile, "gettempdir", lambda: str(tmp_path / "absent_directory"))
108
+ assert claim_first_showing("hook", {"session_id": "s1"}) is True
109
+ assert claim_first_showing("hook", {"session_id": "s1"}) is True
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-dev-env",
3
- "version": "8.114.5",
3
+ "version": "8.114.7",
4
4
  "description": "Claude Code development standards — rules, hooks, agents, commands, and skills",
5
5
  "type": "module",
6
6
  "bin": {