claude-dev-env 8.117.0 → 8.117.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/bin/ever-registered-hooks.test.mjs +4 -0
  2. package/docs/references/working-style.md +3 -0
  3. package/docs/rule-guides/question-presentation.md +8 -0
  4. package/hooks/blocking/final_reply_gate.py +20 -7
  5. package/hooks/blocking/open_tasks_stop_gate.py +133 -7
  6. package/hooks/blocking/open_tasks_transcript.py +77 -9
  7. package/hooks/blocking/test_final_reply_gate.py +14 -0
  8. package/hooks/blocking/test_open_tasks_stop_gate.py +204 -1
  9. package/hooks/blocking/test_open_tasks_transcript.py +123 -0
  10. package/hooks/blocking/test_turn_review_child.py +166 -0
  11. package/hooks/blocking/test_turn_review_claim.py +194 -0
  12. package/hooks/blocking/test_turn_review_repositories.py +65 -0
  13. package/hooks/blocking/test_turn_review_state.py +132 -0
  14. package/hooks/blocking/test_turn_review_transcript.py +125 -0
  15. package/hooks/blocking/test_user_step_wording.py +481 -0
  16. package/hooks/blocking/turn_review_child.py +145 -0
  17. package/hooks/blocking/turn_review_claim.py +306 -0
  18. package/hooks/blocking/turn_review_gate.py +32 -808
  19. package/hooks/blocking/turn_review_repositories.py +58 -0
  20. package/hooks/blocking/turn_review_state.py +260 -0
  21. package/hooks/blocking/turn_review_transcript.py +158 -0
  22. package/hooks/blocking/user_step_wording.py +384 -0
  23. package/hooks/features/conduct-gates.md +2 -2
  24. package/hooks/hooks_constants/final_reply_gate_constants.py +1 -1
  25. package/hooks/hooks_constants/open_tasks_stop_gate_constants.py +58 -5
  26. package/hooks/hooks_constants/session_title_constants.py +2 -2
  27. package/hooks/hooks_constants/user_step_wording_constants.py +79 -0
  28. package/hooks/routing/test_thread_spawn_pace_hook.py +32 -0
  29. package/hooks/session/test_background_silence_prompt.py +8 -0
  30. package/hooks/session/test_tracking_nudge.py +11 -0
  31. package/hooks/session_title_transcript.py +38 -17
  32. package/hooks/test_session_title_transcript.py +31 -0
  33. package/package.json +1 -1
  34. package/rules/question-presentation.md +1 -1
  35. package/scripts/account_broker_support.py +24 -5
  36. package/scripts/dev_env_scripts_constants/account_broker_constants.py +1 -0
  37. package/scripts/policy_lint/config/approved_test_pairs.py +27 -0
  38. package/scripts/test_account_broker_support.py +43 -1
  39. package/scripts/tests/test_policy_lint_rules_pairing.py +24 -0
@@ -52,13 +52,17 @@ def run_gate(
52
52
  capsys: pytest.CaptureFixture[str],
53
53
  transcript_path: Path | None,
54
54
  is_stop_hook_active: bool = False,
55
+ reply_text: str = "Done.",
56
+ working_directory: Path | None = None,
55
57
  ) -> dict[str, str]:
56
58
  hook_input: dict[str, object] = {
57
59
  "hook_event_name": "Stop",
58
60
  "session_id": SESSION_ID,
59
61
  "stop_hook_active": is_stop_hook_active,
60
- "last_assistant_message": "Done.",
62
+ "last_assistant_message": reply_text,
61
63
  }
64
+ if working_directory is not None:
65
+ hook_input["cwd"] = str(working_directory)
62
66
  if transcript_path is not None:
63
67
  hook_input["transcript_path"] = str(transcript_path)
64
68
  monkeypatch.setattr("sys.stdin", io.TextIOWrapper(io.BytesIO(json.dumps(hook_input).encode("utf-8"))))
@@ -349,6 +353,205 @@ def test_should_tell_a_held_stop_from_a_first_stop(hook_input: dict[str, object]
349
353
  assert open_tasks_stop_gate.is_held_stop(hook_input) is is_expected_held
350
354
 
351
355
 
356
+ STEP_REPLY = "Three items need you. The list is below."
357
+ READ_CALL = tool_call_record("mcp__github__pull_request_read", {"pullNumber": 12})
358
+ QUESTION_CALL = tool_call_record("AskUserQuestion", {"questions": [{"question": "Merge pull request 12 now?"}]})
359
+ TRACKER_CALL = tool_call_record("TaskUpdate", {"taskId": "2", "status": "in_progress"})
360
+ OPEN_TASK = {"id": "2", "subject": "Merge the docs pull request", "status": "pending"}
361
+ COMPLETED_TASK = {"id": "1", "subject": "Rotate the deploy key", "status": "completed"}
362
+
363
+
364
+ def test_should_block_a_turn_that_leaves_completed_items_beside_open_ones(
365
+ monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], tmp_path: Path
366
+ ) -> None:
367
+ write_task_store(tmp_path, [COMPLETED_TASK, OPEN_TASK])
368
+ transcript_path = write_records(tmp_path / "s.jsonl", [user_prompt_record("did the export fail?")])
369
+ block_output = run_gate(monkeypatch, capsys, transcript_path)
370
+ assert block_output["decision"] == "block"
371
+ assert "1 of 2 items are completed" in block_output["reason"]
372
+ assert block_output["reason"].endswith("Leave the reply as it stands.")
373
+
374
+
375
+ @pytest.mark.parametrize("all_tasks", [[COMPLETED_TASK], [OPEN_TASK]])
376
+ def test_should_allow_a_task_list_that_is_all_completed_or_all_open(
377
+ monkeypatch: pytest.MonkeyPatch,
378
+ capsys: pytest.CaptureFixture[str],
379
+ tmp_path: Path,
380
+ all_tasks: list[dict[str, str]],
381
+ ) -> None:
382
+ write_task_store(tmp_path, all_tasks)
383
+ transcript_path = write_records(tmp_path / "s.jsonl", [user_prompt_record("did the export fail?")])
384
+ assert run_gate(monkeypatch, capsys, transcript_path) == {}
385
+
386
+
387
+ def test_should_leave_a_task_list_shared_with_other_sessions_alone(
388
+ monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], tmp_path: Path
389
+ ) -> None:
390
+ write_task_store(tmp_path, [COMPLETED_TASK, OPEN_TASK])
391
+ monkeypatch.setenv("CLAUDE_CODE_TASK_LIST_ID", SESSION_ID)
392
+ transcript_path = write_records(tmp_path / "s.jsonl", [user_prompt_record("did the export fail?")])
393
+ assert run_gate(monkeypatch, capsys, transcript_path) == {}
394
+
395
+
396
+ def test_should_read_completed_items_from_the_transcript_when_the_session_has_no_task_store(
397
+ monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], tmp_path: Path
398
+ ) -> None:
399
+ all_todos = [{"content": "Export", "status": "completed"}, {"content": "Submit", "status": "pending"}]
400
+ transcript_path = write_records(
401
+ tmp_path / "s.jsonl", [user_prompt_record(WORK_PROMPT), tool_call_record("TodoWrite", {"todos": all_todos})]
402
+ )
403
+ assert "1 of 2 items are completed" in run_gate(monkeypatch, capsys, transcript_path)["reason"]
404
+
405
+
406
+ def test_should_let_the_task_store_decide_what_the_user_sees(tmp_path: Path) -> None:
407
+ all_todos = [{"content": "Export", "status": "completed"}, {"content": "Submit", "status": "pending"}]
408
+ transcript_path = write_records(tmp_path / "s.jsonl", [tool_call_record("TodoWrite", {"todos": all_todos})])
409
+ replay = replayed_transcript(str(transcript_path))
410
+ assert [each_item.subject for each_item in open_tasks_stop_gate.shown_task_items(SESSION_ID, replay)] == [
411
+ "Export",
412
+ "Submit",
413
+ ]
414
+ write_task_store(tmp_path, [OPEN_TASK])
415
+ assert open_tasks_stop_gate.shown_task_items(SESSION_ID, replay) == [
416
+ TaskItem("2", "Merge the docs pull request", "pending")
417
+ ]
418
+
419
+
420
+ def test_should_count_completed_items_only_beside_open_ones() -> None:
421
+ completed_item = TaskItem("1", "Export", "completed")
422
+ open_item = TaskItem("2", "Submit", "in_progress")
423
+ deleted_item = TaskItem("3", "Sign", "deleted")
424
+ mixed_reason = open_tasks_stop_gate.stale_list_reason([completed_item, completed_item, open_item, deleted_item])
425
+ assert "2 of 3 items are completed" in (mixed_reason or "")
426
+ assert open_tasks_stop_gate.stale_list_reason([completed_item, deleted_item]) is None
427
+ assert open_tasks_stop_gate.stale_list_reason([open_item]) is None
428
+
429
+
430
+ @pytest.mark.parametrize(
431
+ ("all_turn_calls", "expected_text", "absent_text"),
432
+ [
433
+ ([TRACKER_CALL], "ran no read call", "Leave the reply as it stands."),
434
+ ([TRACKER_CALL, READ_CALL], "sent no question through the native question tool", "ran no read call"),
435
+ ([TRACKER_CALL, QUESTION_CALL], "ran no read call", "sent no question"),
436
+ ],
437
+ )
438
+ def test_should_block_a_reply_that_hands_the_user_a_step_without_a_read_or_a_question_call(
439
+ monkeypatch: pytest.MonkeyPatch,
440
+ capsys: pytest.CaptureFixture[str],
441
+ tmp_path: Path,
442
+ all_turn_calls: list[dict[str, object]],
443
+ expected_text: str,
444
+ absent_text: str,
445
+ ) -> None:
446
+ transcript_path = write_records(tmp_path / "s.jsonl", [user_prompt_record("what needs me?"), *all_turn_calls])
447
+ block_output = run_gate(monkeypatch, capsys, transcript_path, reply_text=STEP_REPLY)
448
+ assert block_output["decision"] == "block"
449
+ assert '"need you"' in block_output["reason"]
450
+ assert expected_text in block_output["reason"]
451
+ assert absent_text not in block_output["reason"]
452
+ assert "read the live state of each item you show as open" in block_output["reason"]
453
+ assert block_output["reason"].endswith("end the turn and leave the reply as it stands.")
454
+
455
+
456
+ def test_should_allow_a_step_reply_after_a_read_call_and_a_question_call(
457
+ monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], tmp_path: Path
458
+ ) -> None:
459
+ transcript_path = write_records(
460
+ tmp_path / "s.jsonl", [user_prompt_record("what needs me?"), TRACKER_CALL, READ_CALL, QUESTION_CALL]
461
+ )
462
+ assert run_gate(monkeypatch, capsys, transcript_path, reply_text=STEP_REPLY) == {}
463
+
464
+
465
+ def test_should_not_count_a_read_or_a_question_call_from_an_earlier_turn(
466
+ monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], tmp_path: Path
467
+ ) -> None:
468
+ transcript_path = write_records(
469
+ tmp_path / "s.jsonl", [user_prompt_record("status?"), READ_CALL, QUESTION_CALL, user_prompt_record("what needs me?")]
470
+ )
471
+ block_reason = run_gate(monkeypatch, capsys, transcript_path, reply_text=STEP_REPLY)["reason"]
472
+ assert "ran no read call" in block_reason
473
+ assert "sent no question" in block_reason
474
+
475
+
476
+ def test_should_block_a_sent_status_file_that_says_something_waits_on_the_user(
477
+ monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], tmp_path: Path
478
+ ) -> None:
479
+ status_path = tmp_path / "status.md"
480
+ status_path.write_text("## What needs you\n\nSay when the demo sessions may be archived.", encoding="utf-8")
481
+ send_call = tool_call_record("SendUserFile", {"files": [str(status_path)]})
482
+ transcript_path = write_records(tmp_path / "s.jsonl", [user_prompt_record("what needs me?"), TRACKER_CALL, send_call])
483
+ block_reason = run_gate(monkeypatch, capsys, transcript_path, reply_text="The status list is attached.")["reason"]
484
+ assert '"needs you"' in block_reason
485
+ assert open_tasks_stop_gate.turn_waiting_phrase(
486
+ {"last_assistant_message": "The status list is attached."}, replayed_transcript(str(transcript_path))
487
+ ) == "needs you"
488
+
489
+
490
+ def test_should_read_a_relative_sent_path_from_the_working_directory_of_the_stop(
491
+ monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], tmp_path: Path
492
+ ) -> None:
493
+ sent_directory = tmp_path / "reports"
494
+ sent_directory.mkdir()
495
+ (sent_directory / "status.md").write_text("Two items need you.", encoding="utf-8")
496
+ send_call = tool_call_record("SendUserFile", {"files": ["status.md"]})
497
+ transcript_path = write_records(tmp_path / "s.jsonl", [user_prompt_record("what needs me?"), TRACKER_CALL, send_call])
498
+ block_output = run_gate(
499
+ monkeypatch, capsys, transcript_path, reply_text="The status list is attached.", working_directory=sent_directory
500
+ )
501
+ assert '"need you"' in block_output["reason"]
502
+ assert run_gate(monkeypatch, capsys, transcript_path, reply_text="The status list is attached.") == {}
503
+
504
+
505
+ def test_should_read_a_path_the_turn_sent_twice_once(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
506
+ status_path = tmp_path / "status.md"
507
+ status_path.write_text("Both builds passed.", encoding="utf-8")
508
+ send_call = tool_call_record("SendUserFile", {"files": [str(status_path), str(status_path)]})
509
+ transcript_path = write_records(tmp_path / "s.jsonl", [user_prompt_record("status?"), send_call, send_call])
510
+ all_read_paths: list[str] = []
511
+
512
+ def record_read(file_path_text: str, working_directory: object) -> None:
513
+ all_read_paths.append(file_path_text)
514
+
515
+ monkeypatch.setattr(open_tasks_stop_gate, "file_waiting_phrase", record_read)
516
+ assert open_tasks_stop_gate.turn_waiting_phrase(
517
+ {"last_assistant_message": "The status list is attached."}, replayed_transcript(str(transcript_path))
518
+ ) is None
519
+ assert all_read_paths == [str(status_path)]
520
+
521
+
522
+ def test_should_read_a_task_file_that_holds_a_byte_outside_utf8(
523
+ monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], tmp_path: Path
524
+ ) -> None:
525
+ write_task_store(tmp_path, [OPEN_TASK])
526
+ task_directory = tmp_path / ".claude" / "tasks" / SESSION_ID
527
+ (task_directory / "1.json").write_bytes(b'{"id": "1", "subject": "caf\xe9", "status": "completed"}')
528
+ transcript_path = write_records(tmp_path / "s.jsonl", [user_prompt_record("status?")])
529
+ assert "1 of 2 items are completed" in run_gate(monkeypatch, capsys, transcript_path)["reason"]
530
+
531
+
532
+ def test_should_give_no_step_reason_when_the_transcript_cannot_be_read(tmp_path: Path) -> None:
533
+ all_hook_input_fields = {"last_assistant_message": STEP_REPLY, "transcript_path": str(tmp_path / "missing.jsonl")}
534
+ assert open_tasks_stop_gate.user_step_reasons(all_hook_input_fields, replayed_transcript(None)) == []
535
+ assert open_tasks_stop_gate.turn_block_reason(all_hook_input_fields, replayed_transcript(None)) is None
536
+
537
+
538
+ def test_should_carry_every_finding_in_one_reason(tmp_path: Path) -> None:
539
+ write_task_store(tmp_path, [COMPLETED_TASK, OPEN_TASK])
540
+ transcript_path = write_records(tmp_path / "s.jsonl", [user_prompt_record(WORK_PROMPT), tool_call_record("Write")])
541
+ all_hook_input_fields = {
542
+ "session_id": SESSION_ID,
543
+ "last_assistant_message": STEP_REPLY,
544
+ "transcript_path": str(transcript_path),
545
+ }
546
+ replay = replayed_transcript(str(transcript_path))
547
+ assert len(open_tasks_stop_gate.tracker_reasons(all_hook_input_fields, replay)) == 2
548
+ assert len(open_tasks_stop_gate.user_step_reasons(all_hook_input_fields, replay)) == 3
549
+ block_reason = open_tasks_stop_gate.turn_block_reason(all_hook_input_fields, replay) or ""
550
+ assert block_reason.index("left the task list unchanged") < block_reason.index("1 of 2 items are completed")
551
+ assert block_reason.index("1 of 2 items are completed") < block_reason.index("ran no read call")
552
+ assert block_reason.index("ran no read call") < block_reason.index("sent no question")
553
+
554
+
352
555
  def test_should_block_a_work_turn_whose_transcript_holds_an_undecodable_byte(
353
556
  monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], tmp_path: Path
354
557
  ) -> None:
@@ -8,10 +8,13 @@ from open_tasks_transcript import (
8
8
  claude_prompt_text,
9
9
  codex_prompt_text,
10
10
  is_assistant_record,
11
+ is_codex_read_call,
11
12
  is_codex_work_call,
13
+ is_read_tool_name,
12
14
  is_work_tool_name,
13
15
  parsed_object,
14
16
  replayed_transcript,
17
+ send_call_file_paths,
15
18
  unwrapped_tool_call,
16
19
  )
17
20
 
@@ -61,6 +64,30 @@ def test_should_replay_cursor_dynamic_todo_writes_as_tracker_calls(tmp_path: Pat
61
64
  assert replay.has_turn_work_tool is False
62
65
 
63
66
 
67
+ def test_should_keep_a_record_whose_text_holds_an_unescaped_line_separator(tmp_path: Path) -> None:
68
+ bash_call = {"type": "tool_use", "id": "b1", "name": "Bash", "input": {"command": "ls"}}
69
+ all_records = [
70
+ {"type": "user", "message": {"role": "user", "content": "Check the open pull requests"}},
71
+ {"type": "assistant", "message": {"content": [bash_call]}},
72
+ {"type": "user", "message": {"role": "user", "content": "Now list what is left\u2028and\x85thanks"}},
73
+ ]
74
+ transcript_path = tmp_path / "claude.jsonl"
75
+ transcript_path.write_text(
76
+ "\n".join(json.dumps(each_record, ensure_ascii=False) for each_record in all_records), encoding="utf-8"
77
+ )
78
+ replay = replayed_transcript(str(transcript_path))
79
+ assert replay.turn_prompt_text == "Now list what is left\u2028and\x85thanks"
80
+ assert replay.has_turn_read_tool is False
81
+
82
+
83
+ def test_should_read_a_transcript_that_ends_in_half_a_character(tmp_path: Path) -> None:
84
+ prompt_record = {"type": "user", "message": {"role": "user", "content": "Export the APKs"}}
85
+ transcript_path = tmp_path / "claude.jsonl"
86
+ transcript_path.write_bytes(json.dumps(prompt_record).encode("utf-8") + b"\n{\"type\": \"assistant\", \"text\": \"\xc3")
87
+ replay = replayed_transcript(str(transcript_path))
88
+ assert replay.turn_prompt_text == "Export the APKs"
89
+
90
+
64
91
  def test_should_start_a_new_turn_at_each_prompt_and_reset_its_flags(tmp_path: Path) -> None:
65
92
  bash_call = {"type": "tool_use", "id": "b1", "name": "Bash", "input": {"command": "ls"}}
66
93
  transcript_path = write_transcript(
@@ -162,6 +189,11 @@ def test_should_parse_only_json_objects() -> None:
162
189
  assert parsed_object("not json") is None
163
190
 
164
191
 
192
+ def test_should_parse_text_nested_past_the_recursion_limit_as_no_object() -> None:
193
+ assert parsed_object("[" * 100_000) is None
194
+ assert parsed_object('{"a": ' * 100_000) is None
195
+
196
+
165
197
  def ccd_plan_record(all_plan_input: dict[str, object], record_type: str = "assistant") -> dict[str, object]:
166
198
  tool_use = {"type": "tool_use", "id": "p1", "name": "mcp__ccd_turn__update_plan", "input": all_plan_input}
167
199
  return {"type": record_type, "timestamp": "2026-01-01T00:00:00.000Z", "message": {"content": [tool_use]}}
@@ -249,3 +281,94 @@ def test_should_let_a_later_list_close_a_carried_item_by_subject(tmp_path: Path)
249
281
  ],
250
282
  )
251
283
  assert plan_statuses(transcript_path) == [("Beta", "completed"), ("alpha", "completed")]
284
+
285
+
286
+ @pytest.mark.parametrize(
287
+ "tool_name",
288
+ [
289
+ "Bash",
290
+ "Read",
291
+ "WebFetch",
292
+ "Agent",
293
+ "shell",
294
+ "mcp__github__pull_request_read",
295
+ "mcp__claude-code-remote__get_session",
296
+ "ReadMcpResourceTool",
297
+ "ListMcpResourcesTool",
298
+ "mcp__Context7__get-library-docs",
299
+ "mcp__tracker__getIssue",
300
+ ],
301
+ )
302
+ def test_should_call_a_tool_that_can_read_state_a_read_tool(tool_name: str) -> None:
303
+ assert is_read_tool_name(tool_name) is True
304
+
305
+
306
+ @pytest.mark.parametrize(
307
+ "tool_name",
308
+ [
309
+ "Write",
310
+ "Edit",
311
+ "SendUserFile",
312
+ "TaskList",
313
+ "TaskGet",
314
+ "TaskUpdate",
315
+ "AskUserQuestion",
316
+ "mcp__notes__getaway",
317
+ "mcp__tracker__update_status",
318
+ "mcp__store__update_auth_logs_export",
319
+ "AppendLog",
320
+ "mcp__logs__write_entry",
321
+ "mcp__status-page__publish",
322
+ None,
323
+ ],
324
+ )
325
+ def test_should_not_call_a_write_a_tracker_or_a_question_tool_a_read_tool(tool_name: object) -> None:
326
+ assert is_read_tool_name(tool_name) is False
327
+
328
+
329
+ def test_should_list_the_files_a_send_user_file_call_sends() -> None:
330
+ assert send_call_file_paths("SendUserFile", {"files": ["a.md", 3, "b.html"]}) == ["a.md", "b.html"]
331
+ assert send_call_file_paths("Write", {"files": ["a.md"]}) == []
332
+ assert send_call_file_paths("SendUserFile", {"files": "a.md"}) == []
333
+
334
+
335
+ def test_should_tell_a_codex_read_call_from_a_codex_write_call() -> None:
336
+ shell_call = {"type": "response_item", "payload": {"type": "function_call", "name": "shell", "arguments": "{}"}}
337
+ patch_call = {"type": "response_item", "payload": {"type": "custom_tool_call", "name": "apply_patch"}}
338
+ local_shell_call = {"type": "response_item", "payload": {"type": "local_shell_call", "action": {"command": ["git", "status"]}}}
339
+ assert is_codex_read_call(shell_call) is True
340
+ assert is_codex_read_call(local_shell_call) is True
341
+ assert is_codex_read_call(patch_call) is False
342
+
343
+
344
+ def test_should_note_a_codex_local_shell_call_as_a_read_of_the_turn(tmp_path: Path) -> None:
345
+ codex_prompt = {
346
+ "type": "response_item",
347
+ "payload": {"type": "message", "role": "user", "content": [{"type": "input_text", "text": "what needs me?"}]},
348
+ }
349
+ local_shell_call = {"type": "response_item", "payload": {"type": "local_shell_call", "action": {"command": ["git", "status"]}}}
350
+ patch_call = {"type": "response_item", "payload": {"type": "custom_tool_call", "name": "apply_patch"}}
351
+ read_replay = replayed_transcript(str(write_transcript(tmp_path / "read.jsonl", [codex_prompt, local_shell_call])))
352
+ write_replay = replayed_transcript(str(write_transcript(tmp_path / "write.jsonl", [codex_prompt, patch_call])))
353
+ assert (read_replay.has_turn_work_tool, read_replay.has_turn_read_tool) == (True, True)
354
+ assert (write_replay.has_turn_work_tool, write_replay.has_turn_read_tool) == (True, False)
355
+
356
+
357
+ def assistant_call_record(tool_name: str, all_input_fields: dict[str, object]) -> dict[str, object]:
358
+ tool_use = {"type": "tool_use", "id": tool_name, "name": tool_name, "input": all_input_fields}
359
+ return {"type": "assistant", "message": {"role": "assistant", "content": [tool_use]}}
360
+
361
+
362
+ def test_should_note_the_read_calls_and_sent_files_of_the_current_turn_only(tmp_path: Path) -> None:
363
+ first_prompt = {"type": "user", "message": {"role": "user", "content": "status?"}}
364
+ second_prompt = {"type": "user", "message": {"role": "user", "content": "what needs me?"}}
365
+ all_earlier_records = [
366
+ first_prompt,
367
+ assistant_call_record("Read", {}),
368
+ assistant_call_record("SendUserFile", {"files": ["old.md"]}),
369
+ ]
370
+ earlier_replay = replayed_transcript(str(write_transcript(tmp_path / "a.jsonl", all_earlier_records)))
371
+ all_later_records = [*all_earlier_records, second_prompt, assistant_call_record("SendUserFile", {"files": ["status.md"]})]
372
+ later_replay = replayed_transcript(str(write_transcript(tmp_path / "b.jsonl", all_later_records)))
373
+ assert (earlier_replay.has_turn_read_tool, earlier_replay.turn_sent_file_paths) == (True, ["old.md"])
374
+ assert (later_replay.has_turn_read_tool, later_replay.turn_sent_file_paths) == (False, ["status.md"])
@@ -0,0 +1,166 @@
1
+ import json
2
+ import sys
3
+ import tempfile
4
+ from pathlib import Path
5
+
6
+ import pytest
7
+
8
+ from hooks_constants.turn_review_gate_constants import REVIEW_FAILURE_DIAGNOSTIC_TEMPLATE
9
+ from turn_review_child import (
10
+ _child_stdout,
11
+ _ChildRun,
12
+ _judge_command,
13
+ _review_command,
14
+ _review_environment,
15
+ )
16
+
17
+ PARENT_SESSION_VARIABLES = (
18
+ "CLAUDE_CODE_SESSION_ID",
19
+ "CLAUDE_CODE_REMOTE_SESSION_ID",
20
+ "CLAUDE_CODE_MESSAGING_SOCKET",
21
+ "CLAUDE_CODE_MESSAGING_TOKEN",
22
+ "CLAUDE_SESSION_INGRESS_TOKEN_FILE",
23
+ "CLAUDE_CODE_POST_FOR_SESSION_INGRESS_V2",
24
+ "CLAUDE_CODE_TEE_SDK_STDOUT",
25
+ )
26
+ CHILD_REPORT_SOURCE = """import json
27
+ import os
28
+ import sys
29
+
30
+ print(json.dumps({
31
+ "cwd": os.getcwd(),
32
+ "stdin": sys.stdin.read(),
33
+ "marker": os.environ.get("CLAUDE_TURN_REVIEW_CHILD"),
34
+ "parent_session": os.environ.get("CLAUDE_CODE_SESSION_ID"),
35
+ }))
36
+ """
37
+ FAILING_CHILD_SOURCE = """import sys
38
+
39
+ print("partial review")
40
+ sys.exit(3)
41
+ """
42
+ SLOW_CHILD_SOURCE = """import time
43
+
44
+ time.sleep(5)
45
+ print("late review")
46
+ """
47
+
48
+
49
+ @pytest.fixture(autouse=True)
50
+ def isolated_home(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
51
+ home_directory = tmp_path / "home"
52
+ home_directory.mkdir()
53
+ state_directory = tmp_path / "state"
54
+ state_directory.mkdir()
55
+ monkeypatch.setenv("HOME", str(home_directory))
56
+ monkeypatch.setenv("USERPROFILE", str(home_directory))
57
+ monkeypatch.setattr(tempfile, "tempdir", str(state_directory))
58
+ return home_directory
59
+
60
+
61
+ @pytest.fixture
62
+ def checkout(tmp_path: Path) -> Path:
63
+ repository_root = tmp_path / "app"
64
+ repository_root.mkdir()
65
+ return repository_root
66
+
67
+
68
+ def child_run(
69
+ tmp_path: Path, repository_root: Path, child_source: str, prompt_text: str | None
70
+ ) -> _ChildRun:
71
+ child_script = tmp_path / "child.py"
72
+ child_script.write_text(child_source)
73
+ return _ChildRun(
74
+ repository_root,
75
+ [sys.executable, str(child_script)],
76
+ prompt_text,
77
+ REVIEW_FAILURE_DIAGNOSTIC_TEMPLATE,
78
+ )
79
+
80
+
81
+ def log_lines(home_directory: Path) -> list[str]:
82
+ log_path = home_directory / ".claude" / "logs" / "turn-review.log"
83
+ return log_path.read_text().splitlines() if log_path.exists() else []
84
+
85
+
86
+ def test_should_build_the_review_command_for_the_range_with_read_only_options(
87
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
88
+ ) -> None:
89
+ stub_directory = tmp_path / "bin"
90
+ stub_directory.mkdir()
91
+ stub_claude = stub_directory / "claude"
92
+ stub_claude.write_text("")
93
+ stub_claude.chmod(0o755)
94
+ monkeypatch.setenv("PATH", str(stub_directory))
95
+ review_command = _review_command("aaa111", "bbb222")
96
+ assert review_command[:7] == [
97
+ str(stub_claude),
98
+ "-p",
99
+ "/code-review low aaa111..bbb222",
100
+ "--model",
101
+ "sonnet",
102
+ "--effort",
103
+ "high",
104
+ ]
105
+ assert review_command[review_command.index("--tools") + 1] == "Read,Grep,Glob,Bash"
106
+ assert review_command[review_command.index("--permission-mode") + 1] == "dontAsk"
107
+ assert json.loads(review_command[review_command.index("--settings") + 1]) == {
108
+ "disableAllHooks": True
109
+ }
110
+
111
+
112
+ def test_should_build_the_judge_command_with_no_prompt_argument(
113
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
114
+ ) -> None:
115
+ monkeypatch.setenv("PATH", str(tmp_path))
116
+ judge_command = _judge_command()
117
+ assert judge_command[:6] == ["claude", "-p", "--model", "sonnet", "--effort", "high"]
118
+ assert "--no-session-persistence" in judge_command
119
+
120
+
121
+ def test_should_drop_every_parent_session_variable_from_the_child_environment(
122
+ monkeypatch: pytest.MonkeyPatch,
123
+ ) -> None:
124
+ for each_name in PARENT_SESSION_VARIABLES:
125
+ monkeypatch.setenv(each_name, "parent-value")
126
+ monkeypatch.setenv("TURN_REVIEW_KEPT_VARIABLE", "kept")
127
+ child_environment = _review_environment()
128
+ assert [
129
+ each_name for each_name in PARENT_SESSION_VARIABLES if each_name in child_environment
130
+ ] == []
131
+ assert child_environment["CLAUDE_TURN_REVIEW_CHILD"] == "1"
132
+ assert child_environment["TURN_REVIEW_KEPT_VARIABLE"] == "kept"
133
+
134
+
135
+ def test_should_run_the_child_in_the_checkout_with_the_prompt_on_stdin(
136
+ tmp_path: Path, checkout: Path, monkeypatch: pytest.MonkeyPatch
137
+ ) -> None:
138
+ monkeypatch.setenv("CLAUDE_CODE_SESSION_ID", "parent-session")
139
+ child_output = _child_stdout(
140
+ child_run(tmp_path, checkout, CHILD_REPORT_SOURCE, "judge data"), 30
141
+ )
142
+ assert child_output is not None
143
+ assert json.loads(child_output) == {
144
+ "cwd": str(checkout.resolve()),
145
+ "stdin": "judge data",
146
+ "marker": "1",
147
+ "parent_session": None,
148
+ }
149
+
150
+
151
+ def test_should_give_no_output_and_log_a_child_that_exits_with_an_error(
152
+ tmp_path: Path, checkout: Path, isolated_home: Path
153
+ ) -> None:
154
+ assert _child_stdout(child_run(tmp_path, checkout, FAILING_CHILD_SOURCE, None), 30) is None
155
+ assert [each_line.split(" ", 1)[1] for each_line in log_lines(isolated_home)] == [
156
+ "[turn_review_gate] review of app did not finish: exit 3"
157
+ ]
158
+
159
+
160
+ def test_should_give_no_output_and_log_a_child_that_runs_out_of_time(
161
+ tmp_path: Path, checkout: Path, isolated_home: Path
162
+ ) -> None:
163
+ assert _child_stdout(child_run(tmp_path, checkout, SLOW_CHILD_SOURCE, None), 0.5) is None
164
+ assert [each_line.split(" ", 1)[1] for each_line in log_lines(isolated_home)] == [
165
+ "[turn_review_gate] review of app did not finish: timed out"
166
+ ]