claude-dev-env 8.116.4 → 8.117.0

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 (101) hide show
  1. package/bin/ever-registered-hooks.mjs +2 -0
  2. package/bin/install-constants.mjs +3 -1
  3. package/bin/install.cursor-rules.test.mjs +64 -2
  4. package/bin/install.mjs +15 -2
  5. package/bin/install.prune.test.mjs +92 -0
  6. package/bin/install.test.mjs +1 -0
  7. package/docs/model-choice/escalation.md +3 -3
  8. package/docs/model-choice/subagents-and-fan-out.md +2 -2
  9. package/docs/model-choice/which-model.md +1 -1
  10. package/docs/references/working-style.md +1 -0
  11. package/docs/rule-guides/question-presentation.md +6 -0
  12. package/docs/rule-guides/session-title.md +8 -9
  13. package/docs/rule-guides/subagent-model-effort.md +13 -13
  14. package/hooks/advisory/owned_pr_review_loop.py +2 -3
  15. package/hooks/blocking/bash_post_call_dispatcher.py +17 -9
  16. package/hooks/blocking/bash_pre_tool_use_dispatcher.py +12 -8
  17. package/hooks/blocking/final_reply_gate.py +5 -9
  18. package/hooks/blocking/open_tasks_stop_gate.py +9 -20
  19. package/hooks/blocking/open_tasks_transcript.py +8 -3
  20. package/hooks/blocking/pii_prevention_blocker_parts/repository_exemption.py +7 -2
  21. package/hooks/blocking/question_brief_gate.py +382 -0
  22. package/hooks/blocking/step_note_gate.py +5 -2
  23. package/hooks/blocking/task_subject_length_gate.py +111 -0
  24. package/hooks/blocking/test_bash_post_call_dispatcher.py +36 -1
  25. package/hooks/blocking/test_bash_pre_tool_use_dispatcher.py +57 -0
  26. package/hooks/blocking/test_final_reply_gate.py +26 -2
  27. package/hooks/blocking/test_open_tasks_stop_gate.py +21 -11
  28. package/hooks/blocking/test_question_brief_gate.py +916 -0
  29. package/hooks/blocking/test_step_note_gate.py +26 -0
  30. package/hooks/blocking/test_task_subject_length_gate.py +221 -0
  31. package/hooks/blocking/test_turn_review_findings.py +124 -1
  32. package/hooks/blocking/test_turn_review_gate.py +1312 -10
  33. package/hooks/blocking/test_turn_review_snapshot.py +8 -0
  34. package/hooks/blocking/tests/test_repository_exemption.py +11 -0
  35. package/hooks/blocking/turn_review_findings.py +173 -13
  36. package/hooks/blocking/turn_review_gate.py +878 -105
  37. package/hooks/blocking/turn_review_snapshot.py +5 -1
  38. package/hooks/features/bash-dispatchers.md +1 -3
  39. package/hooks/features/conduct-gates.md +19 -9
  40. package/hooks/features/lifecycle-cleanup.md +1 -1
  41. package/hooks/features/spawn-routing.md +1 -1
  42. package/hooks/hooks.json +24 -11
  43. package/hooks/hooks_constants/final_reply_gate_constants.py +0 -3
  44. package/hooks/hooks_constants/hook_time_budget.py +61 -0
  45. package/hooks/hooks_constants/hosted_hook_runner.py +51 -21
  46. package/hooks/hooks_constants/hosted_hook_runner_constants.py +3 -0
  47. package/hooks/hooks_constants/nested_project_hooks_constants.py +8 -0
  48. package/hooks/hooks_constants/once_per_session_constants.py +1 -0
  49. package/hooks/hooks_constants/open_tasks_stop_gate_constants.py +0 -4
  50. package/hooks/hooks_constants/owned_pr_review_loop_constants.py +0 -4
  51. package/hooks/hooks_constants/pre_tool_use_context_runner.py +23 -3
  52. package/hooks/hooks_constants/pre_tool_use_context_runner_constants.py +5 -0
  53. package/hooks/hooks_constants/pre_tool_use_stdin.py +1 -1
  54. package/hooks/hooks_constants/question_brief_gate_constants.py +66 -0
  55. package/hooks/hooks_constants/session_title_constants.py +6 -27
  56. package/hooks/hooks_constants/stop_hook_hold.py +54 -0
  57. package/hooks/hooks_constants/stop_hook_hold_constants.py +9 -0
  58. package/hooks/hooks_constants/subagent_effort_levels.json +6 -0
  59. package/hooks/hooks_constants/subagent_effort_route_constants.py +20 -19
  60. package/hooks/hooks_constants/task_subject_length_gate_constants.py +43 -0
  61. package/hooks/hooks_constants/test_hook_time_budget.py +104 -0
  62. package/hooks/hooks_constants/test_hosted_hook_runner.py +12 -0
  63. package/hooks/hooks_constants/test_pre_tool_use_context_runner.py +16 -0
  64. package/hooks/hooks_constants/test_pre_tool_use_stdin.py +6 -0
  65. package/hooks/hooks_constants/test_stop_hook_hold.py +40 -0
  66. package/hooks/hooks_constants/thread_spawn_pace_hook_constants.py +1 -2
  67. package/hooks/hooks_constants/turn_review_gate_constants.py +246 -12
  68. package/hooks/lifecycle/nested_project_hooks.py +34 -4
  69. package/hooks/lifecycle/test_nested_project_hooks.py +52 -0
  70. package/hooks/once_per_session.py +33 -4
  71. package/hooks/open_task_asks.py +1 -1
  72. package/hooks/owned_pr_session_record.py +1 -76
  73. package/hooks/routing/subagent_effort_route.py +107 -13
  74. package/hooks/routing/subagent_effort_route_hook.py +9 -8
  75. package/hooks/routing/test_subagent_effort_route.py +201 -14
  76. package/hooks/routing/test_subagent_effort_route_hook.py +56 -0
  77. package/hooks/routing/thread_spawn_pace_hook.py +3 -3
  78. package/hooks/session/background_silence_prompt.py +1 -1
  79. package/hooks/session/test_tracking_nudge.py +114 -2
  80. package/hooks/session/tracking_nudge.py +28 -18
  81. package/hooks/session_title_transcript.py +195 -0
  82. package/hooks/test_once_per_session.py +10 -0
  83. package/hooks/test_owned_pr_session_record.py +0 -26
  84. package/hooks/test_session_title_transcript.py +111 -0
  85. package/hooks/validation/post_tool_use_dispatcher.py +38 -21
  86. package/hooks/validation/test_post_tool_use_dispatcher.py +43 -0
  87. package/hooks/validators/ruff_integration.py +46 -4
  88. package/hooks/validators/test_ruff_integration.py +67 -5
  89. package/package.json +1 -1
  90. package/rules/question-presentation.md +4 -4
  91. package/rules/subagent-model-effort.md +1 -1
  92. package/scripts/claude_account_worker.py +4 -3
  93. package/scripts/policy_lint/adapter_configuration.py +12 -11
  94. package/scripts/policy_lint/config/constants.py +2 -2
  95. package/scripts/test_claude_account_worker.py +1 -0
  96. package/scripts/tests/test_adapter_configuration.py +10 -2
  97. package/hooks/blocking/owned_pr_merge_stop_gate.py +0 -185
  98. package/hooks/blocking/session_title_turn_gate.py +0 -417
  99. package/hooks/blocking/test_owned_pr_merge_stop_gate.py +0 -254
  100. package/hooks/blocking/test_session_title_turn_gate.py +0 -396
  101. package/hooks/hooks_constants/owned_pr_merge_stop_gate_constants.py +0 -40
@@ -139,8 +139,8 @@ def test_should_stay_silent_for_a_prompt_that_asks_for_no_work(
139
139
 
140
140
 
141
141
  def test_should_skip_the_title_note_in_a_session_without_the_title_tool() -> None:
142
- assert tracking_nudge.title_nudge([]) is None
143
- assert tracking_nudge.title_nudge(titled_entries("✅ Gate")) is not None
142
+ assert tracking_nudge.title_nudge([], {}) is None
143
+ assert tracking_nudge.title_nudge(titled_entries("✅ Gate"), {}) is not None
144
144
 
145
145
 
146
146
  def test_should_build_the_note_only_for_a_work_prompt() -> None:
@@ -164,6 +164,118 @@ def test_should_print_the_documented_output_through_a_subprocess(tmp_path: Path)
164
164
  assert "the session's task list tool" in hook_output["additionalContext"]
165
165
 
166
166
 
167
+ PACKAGE_ROOT = _SESSION_DIR.parent.parent
168
+ HOURGLASS_FORM = "'⏳ <name>'"
169
+ UNTITLED_ENTRIES: list[dict[str, object]] = [TOOL_LISTING]
170
+
171
+
172
+ def run_nudge_script(
173
+ tmp_path: Path, prompt_text: str, all_entries: list[dict[str, object]]
174
+ ) -> subprocess.CompletedProcess[str]:
175
+ transcript_path = tmp_path / "script_session.jsonl"
176
+ transcript_path.write_text(
177
+ "".join(json.dumps(each) + "\n" for each in all_entries), encoding="utf-8"
178
+ )
179
+ hook_input = {
180
+ "hook_event_name": "UserPromptSubmit",
181
+ "session_id": "script_session",
182
+ "prompt": prompt_text,
183
+ "transcript_path": str(transcript_path),
184
+ }
185
+ environment = {**os.environ, "TMP": str(tmp_path), "TEMP": str(tmp_path), "TMPDIR": str(tmp_path)}
186
+ return subprocess.run(
187
+ [sys.executable, str(NUDGE_PATH)],
188
+ input=json.dumps(hook_input),
189
+ capture_output=True,
190
+ text=True,
191
+ env=environment,
192
+ check=False,
193
+ )
194
+
195
+
196
+ def script_context(completed_process: subprocess.CompletedProcess[str]) -> str:
197
+ if not completed_process.stdout:
198
+ return ""
199
+ return json.loads(completed_process.stdout)["hookSpecificOutput"]["additionalContext"]
200
+
201
+
202
+ def test_should_ask_for_a_first_title_in_a_titled_tool_session_with_no_title(tmp_path: Path) -> None:
203
+ context_text = script_context(run_nudge_script(tmp_path, "Export the APKs", UNTITLED_ENTRIES))
204
+ assert "no title yet" in context_text
205
+ assert TITLE_TOOL in context_text
206
+ assert HOURGLASS_FORM in context_text
207
+
208
+
209
+ def test_should_ask_for_a_first_title_at_most_once_in_a_session(tmp_path: Path) -> None:
210
+ first_text = script_context(run_nudge_script(tmp_path, "Export the APKs", UNTITLED_ENTRIES))
211
+ second_text = script_context(run_nudge_script(tmp_path, "Now sign the APKs", UNTITLED_ENTRIES))
212
+ after_compaction_text = script_context(
213
+ run_nudge_script(tmp_path, "Upload the APKs", [*UNTITLED_ENTRIES, COMPACTION_ENTRY])
214
+ )
215
+ assert "no title yet" in first_text
216
+ assert "no title yet" not in second_text
217
+ assert "no title yet" not in after_compaction_text
218
+
219
+
220
+ def test_should_not_spend_the_first_title_note_on_a_prompt_that_asks_for_no_work(
221
+ tmp_path: Path,
222
+ ) -> None:
223
+ assert script_context(run_nudge_script(tmp_path, "did the export fail?", UNTITLED_ENTRIES)) == ""
224
+ assert "no title yet" in script_context(
225
+ run_nudge_script(tmp_path, "Export the APKs", UNTITLED_ENTRIES)
226
+ )
227
+
228
+
229
+ def test_should_add_nothing_about_titles_in_a_session_without_a_title_tool(tmp_path: Path) -> None:
230
+ context_text = script_context(run_nudge_script(tmp_path, "Export the APKs", [{"type": "user"}]))
231
+ assert TASK_LIST_NUDGE in context_text
232
+ assert "title" not in context_text
233
+
234
+
235
+ @pytest.mark.parametrize("earlier_title", ["\U0001f6a9 Merge approval", "✅ Gate"])
236
+ def test_should_keep_the_stale_title_note_through_the_script(
237
+ tmp_path: Path, earlier_title: str
238
+ ) -> None:
239
+ context_text = script_context(
240
+ run_nudge_script(tmp_path, "Export the APKs", titled_entries(earlier_title))
241
+ )
242
+ assert earlier_title in context_text
243
+ assert TITLE_TOOL in context_text
244
+ assert HOURGLASS_FORM in context_text
245
+
246
+
247
+ def test_should_add_no_title_note_when_the_title_already_shows_the_hourglass(tmp_path: Path) -> None:
248
+ context_text = script_context(
249
+ run_nudge_script(tmp_path, "Export the APKs", titled_entries("⏳ Export"))
250
+ )
251
+ assert TASK_LIST_NUDGE in context_text
252
+ assert "title" not in context_text
253
+
254
+
255
+ @pytest.mark.parametrize(
256
+ "all_entries",
257
+ [UNTITLED_ENTRIES, [{"type": "user"}], [TOOL_LISTING, {"type": "assistant", "message": "broken"}]],
258
+ )
259
+ def test_should_never_block_the_prompt(
260
+ tmp_path: Path, all_entries: list[dict[str, object]]
261
+ ) -> None:
262
+ completed_process = run_nudge_script(tmp_path, "Export the APKs", all_entries)
263
+ assert (completed_process.returncode, completed_process.stderr) == (0, "")
264
+ assert "decision" not in completed_process.stdout
265
+
266
+
267
+ def test_should_describe_the_prompt_note_and_no_title_send_back_in_the_docs() -> None:
268
+ all_doc_texts = [
269
+ (PACKAGE_ROOT / "docs" / "rule-guides" / "session-title.md").read_text(encoding="utf-8"),
270
+ (PACKAGE_ROOT / "hooks" / "features" / "conduct-gates.md").read_text(encoding="utf-8"),
271
+ ]
272
+ for each_doc_text in all_doc_texts:
273
+ assert "session_title_turn_gate" not in each_doc_text
274
+ assert "No hook holds the end of a turn for the title." in each_doc_text
275
+ assert "no title yet" in each_doc_text
276
+ assert "tracking_nudge.py" in each_doc_text
277
+
278
+
167
279
  def test_replay_of_two_asks_and_a_compaction_through_the_script(tmp_path: Path) -> None:
168
280
  transcript_path = tmp_path / "session.jsonl"
169
281
  transcript_path.write_text(json.dumps({"type": "user"}) + "\n", encoding="utf-8")
@@ -10,14 +10,17 @@ on the first ask after each compaction::
10
10
  "Export the APKs", first ask -> task list note
11
11
  "Export the APKs", title shows a red flag or a check mark
12
12
  -> task list note + title note
13
+ "Export the APKs", title tool and no title yet, first time in the session
14
+ -> task list note + no title note
13
15
  "Sign the APKs", a later ask -> nothing, or the title note
14
16
  "did the export fail?" -> nothing
15
17
  "<task-notification>...</task-notification>"
16
18
  -> nothing
17
19
 
18
- The note never blocks. The Stop gates ``open_tasks_stop_gate.py`` and
19
- ``session_title_turn_gate.py`` hold the turn once only when the agent skipped it.
20
- The title note needs the title tool in the transcript, as the title gate does.
20
+ The note never blocks. The Stop gate ``open_tasks_stop_gate.py`` holds the turn
21
+ once only when the agent skipped the task list. No hook holds a turn for the
22
+ title. Both title notes need the title tool in the transcript, and the no title
23
+ note shows at most once in a session, compactions included.
21
24
  """
22
25
 
23
26
  from __future__ import annotations
@@ -46,12 +49,14 @@ from hooks_constants.open_tasks_stop_gate_constants import (
46
49
  from hooks_constants.pre_tool_use_stdin import read_hook_input_dictionary_from_stdin
47
50
  from hooks_constants.session_title_constants import (
48
51
  ALL_STALE_AT_START_STATUSES,
52
+ NO_TITLE_NUDGE_ONCE_MARKER_NAME,
53
+ NO_TITLE_NUDGE_TEMPLATE,
49
54
  TITLE_NUDGE_TEMPLATE,
50
55
  TITLE_TOOL_DISPLAY_SEPARATOR,
51
56
  )
52
- from once_per_session import claim_first_showing
57
+ from once_per_session import claim_first_showing, claim_only_showing
53
58
  from open_task_asks import is_ask
54
- from session_title_turn_gate import (
59
+ from session_title_transcript import (
55
60
  available_title_tools,
56
61
  read_transcript_entries,
57
62
  shown_title,
@@ -59,32 +64,36 @@ from session_title_turn_gate import (
59
64
  )
60
65
 
61
66
 
62
- def title_nudge(all_entries: list[dict[str, object]]) -> str | None:
63
- """Return the title note when the shown title says the session waits or is done, else None.
67
+ def title_nudge(
68
+ all_entries: list[dict[str, object]], all_hook_fields: Mapping[str, object]
69
+ ) -> str | None:
70
+ """Return the title note when the session has no title or a stale one, else None.
64
71
 
65
72
  ::
66
73
 
67
74
  title tool listed, shows "\U0001f6a9 Merge approval" -> note naming that title
68
- title tool listed, shows "⏳ Export" -> None
75
+ title tool listed, no title -> no title note, once a session
76
+ title tool listed, shows "⏳ Export" -> None
69
77
  no title tool in the transcript -> None
70
78
 
71
79
  Args:
72
80
  all_entries: The transcript entries, oldest first.
81
+ all_hook_fields: The hook payload, read for the once-per-session marker.
73
82
 
74
83
  Returns:
75
84
  The note text, or None.
76
85
  """
77
86
  all_title_tools = available_title_tools(all_entries)
87
+ if not all_title_tools:
88
+ return None
89
+ tool_name = TITLE_TOOL_DISPLAY_SEPARATOR.join(all_title_tools)
78
90
  title = shown_title(all_entries)
79
- if (
80
- not all_title_tools
81
- or title is None
82
- or title_status(title) not in ALL_STALE_AT_START_STATUSES
83
- ):
91
+ if title is None:
92
+ is_first_showing = claim_only_showing(NO_TITLE_NUDGE_ONCE_MARKER_NAME, all_hook_fields)
93
+ return NO_TITLE_NUDGE_TEMPLATE.format(tool_name=tool_name) if is_first_showing else None
94
+ if title_status(title) not in ALL_STALE_AT_START_STATUSES:
84
95
  return None
85
- return TITLE_NUDGE_TEMPLATE.format(
86
- title=title, tool_name=TITLE_TOOL_DISPLAY_SEPARATOR.join(all_title_tools)
87
- )
96
+ return TITLE_NUDGE_TEMPLATE.format(title=title, tool_name=tool_name)
88
97
 
89
98
 
90
99
  def ask_tracking_context(
@@ -95,7 +104,8 @@ def ask_tracking_context(
95
104
  """Return the note for a prompt that asks for work, or None for any other prompt.
96
105
 
97
106
  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.
107
+ after each compaction. The title note shows on every ask while the title is stale,
108
+ and the no title note on the first ask in the session that finds no title.
99
109
  """
100
110
  if not is_ask(prompt_text):
101
111
  return None
@@ -104,7 +114,7 @@ def ask_tracking_context(
104
114
  if claim_first_showing(TASK_LIST_NUDGE_ONCE_MARKER_NAME, all_hook_fields)
105
115
  else None
106
116
  )
107
- all_notes = [tracker_note, title_nudge(all_entries)]
117
+ all_notes = [tracker_note, title_nudge(all_entries, all_hook_fields)]
108
118
  return WORD_SEPARATOR.join(each_note for each_note in all_notes if each_note) or None
109
119
 
110
120
 
@@ -0,0 +1,195 @@
1
+ """Read the session title tool and the shown title from a Claude Code transcript.
2
+
3
+ The prompt hooks use this module to learn two facts about a session::
4
+
5
+ attachment.tools[].name / attachment.entries[].name (tool listing)
6
+ attachment.addedNames / attachment.readdedNames (deferred tools)
7
+ assistant tool_use name (an earlier call)
8
+ -> the session has a ``mcp__*__set_session_title`` tool
9
+
10
+ main-chain title call whose result came back without an error
11
+ -> the title the session shows
12
+
13
+ A later ``removedNames`` entry takes a title tool away again. A title call on a
14
+ sidechain entry belongs to a subagent and does not count, and neither does a
15
+ title the format gate denied.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import json
21
+ from pathlib import Path
22
+
23
+ from hooks_constants.session_title_constants import (
24
+ ALL_TOOL_LISTING_NAME_KEYS,
25
+ ALL_TOOL_LISTING_RECORD_KEYS,
26
+ ASSISTANT_ENTRY_TYPE,
27
+ ATTACHMENT_KEY,
28
+ BLOCK_ID_KEY,
29
+ BLOCK_INPUT_KEY,
30
+ BLOCK_NAME_KEY,
31
+ CONTENT_KEY,
32
+ DECODE_ERRORS_POLICY,
33
+ ENTRY_TYPE_KEY,
34
+ IS_ERROR_KEY,
35
+ MESSAGE_KEY,
36
+ REMOVED_NAMES_KEY,
37
+ SIDECHAIN_FLAG_KEY,
38
+ STATUS_PREFIX_PATTERN,
39
+ TITLE_INPUT_KEY,
40
+ TITLE_TOOL_NAME_PATTERN,
41
+ TOOL_RESULT_BLOCK_TYPE,
42
+ TOOL_USE_BLOCK_TYPE,
43
+ TOOL_USE_ID_KEY,
44
+ USER_ENTRY_TYPE,
45
+ UTF8_ENCODING,
46
+ )
47
+
48
+
49
+ def _content_blocks(all_entry_fields: dict[str, object]) -> list[dict[str, object]]:
50
+ message = all_entry_fields.get(MESSAGE_KEY)
51
+ content = message.get(CONTENT_KEY) if isinstance(message, dict) else None
52
+ if not isinstance(content, list):
53
+ return []
54
+ return [each_block for each_block in content if isinstance(each_block, dict)]
55
+
56
+
57
+ def _tool_use_blocks(all_entry_fields: dict[str, object]) -> list[dict[str, object]]:
58
+ if all_entry_fields.get(ENTRY_TYPE_KEY) != ASSISTANT_ENTRY_TYPE:
59
+ return []
60
+ return [
61
+ each_block
62
+ for each_block in _content_blocks(all_entry_fields)
63
+ if each_block.get(ENTRY_TYPE_KEY) == TOOL_USE_BLOCK_TYPE
64
+ ]
65
+
66
+
67
+ def _title_names(all_values: object) -> list[str]:
68
+ if not isinstance(all_values, list):
69
+ return []
70
+ all_names = [
71
+ each_value.get(BLOCK_NAME_KEY) if isinstance(each_value, dict) else each_value
72
+ for each_value in all_values
73
+ ]
74
+ return [
75
+ each_name
76
+ for each_name in all_names
77
+ if isinstance(each_name, str) and TITLE_TOOL_NAME_PATTERN.match(each_name)
78
+ ]
79
+
80
+
81
+ def _apply_tool_listing(
82
+ all_available_names: dict[str, None], all_attachment_fields: dict[str, object]
83
+ ) -> None:
84
+ for each_key in (*ALL_TOOL_LISTING_NAME_KEYS, *ALL_TOOL_LISTING_RECORD_KEYS):
85
+ all_available_names.update(dict.fromkeys(_title_names(all_attachment_fields.get(each_key))))
86
+ for each_removed_name in _title_names(all_attachment_fields.get(REMOVED_NAMES_KEY)):
87
+ all_available_names.pop(each_removed_name, None)
88
+
89
+
90
+ def available_title_tools(all_entries: list[dict[str, object]]) -> list[str]:
91
+ """Return the title tool names the session holds at the end of the transcript.
92
+
93
+ ::
94
+
95
+ attachment {"tools": [{"name": "mcp__x__set_session_title"}]} -> ["mcp__x__set_session_title"]
96
+ then attachment {"removedNames": ["mcp__x__set_session_title"]} -> []
97
+ no listing and no call -> []
98
+
99
+ Args:
100
+ all_entries: The transcript entries, oldest first.
101
+
102
+ Returns:
103
+ The title tool names, in the order the transcript first named them.
104
+ """
105
+ available_names: dict[str, None] = {}
106
+ for each_entry in all_entries:
107
+ attachment = each_entry.get(ATTACHMENT_KEY)
108
+ if isinstance(attachment, dict):
109
+ _apply_tool_listing(available_names, attachment)
110
+ available_names.update(dict.fromkeys(_title_names(_tool_use_blocks(each_entry))))
111
+ return list(available_names)
112
+
113
+
114
+ def _main_chain(all_entries: list[dict[str, object]]) -> list[dict[str, object]]:
115
+ return [each_entry for each_entry in all_entries if not each_entry.get(SIDECHAIN_FLAG_KEY)]
116
+
117
+
118
+ def _successful_title_call_ids(all_scoped_entries: list[dict[str, object]]) -> set[object]:
119
+ all_title_call_ids = {
120
+ each_block.get(BLOCK_ID_KEY)
121
+ for each_entry in all_scoped_entries
122
+ for each_block in _tool_use_blocks(each_entry)
123
+ if TITLE_TOOL_NAME_PATTERN.match(str(each_block.get(BLOCK_NAME_KEY)))
124
+ }
125
+ return {
126
+ each_block.get(TOOL_USE_ID_KEY)
127
+ for each_entry in all_scoped_entries
128
+ if each_entry.get(ENTRY_TYPE_KEY) == USER_ENTRY_TYPE
129
+ for each_block in _content_blocks(each_entry)
130
+ if each_block.get(ENTRY_TYPE_KEY) == TOOL_RESULT_BLOCK_TYPE
131
+ and each_block.get(TOOL_USE_ID_KEY) in all_title_call_ids
132
+ and not each_block.get(IS_ERROR_KEY)
133
+ }
134
+
135
+
136
+ def _title_input(all_block_fields: dict[str, object]) -> str | None:
137
+ all_input_fields = all_block_fields.get(BLOCK_INPUT_KEY)
138
+ title = all_input_fields.get(TITLE_INPUT_KEY) if isinstance(all_input_fields, dict) else None
139
+ return title if isinstance(title, str) else None
140
+
141
+
142
+ def shown_title(all_entries: list[dict[str, object]]) -> str | None:
143
+ """Return the title of the last main-chain title call that came back without an error.
144
+
145
+ ::
146
+
147
+ "⏳ Export" ok, then "✅ Export" denied -> "⏳ Export"
148
+ no title call -> None
149
+
150
+ Args:
151
+ all_entries: The transcript entries, oldest first.
152
+
153
+ Returns:
154
+ The title the session shows, or None when no title call succeeded.
155
+ """
156
+ all_main_entries = _main_chain(all_entries)
157
+ all_successful_ids = _successful_title_call_ids(all_main_entries)
158
+ all_titles = [
159
+ _title_input(each_block)
160
+ for each_entry in all_main_entries
161
+ for each_block in _tool_use_blocks(each_entry)
162
+ if each_block.get(BLOCK_ID_KEY) in all_successful_ids
163
+ ]
164
+ all_text_titles = [each_title for each_title in all_titles if each_title is not None]
165
+ return all_text_titles[-1] if all_text_titles else None
166
+
167
+
168
+ def title_status(title: str) -> str | None:
169
+ """Return the status emoji the title starts with, without a variation selector, or None."""
170
+ status_match = STATUS_PREFIX_PATTERN.match(title)
171
+ return status_match.group(1) if status_match else None
172
+
173
+
174
+ def _parsed_entry(line: str) -> dict[str, object] | None:
175
+ try:
176
+ parsed_entry = json.loads(line)
177
+ except json.JSONDecodeError:
178
+ return None
179
+ return parsed_entry if isinstance(parsed_entry, dict) else None
180
+
181
+
182
+ def read_transcript_entries(transcript_path: object) -> list[dict[str, object]]:
183
+ """Return the transcript's JSON object entries, or an empty list when it cannot be read."""
184
+ if not isinstance(transcript_path, str) or not transcript_path:
185
+ return []
186
+ try:
187
+ all_lines = (
188
+ Path(transcript_path)
189
+ .read_text(encoding=UTF8_ENCODING, errors=DECODE_ERRORS_POLICY)
190
+ .splitlines()
191
+ )
192
+ except OSError:
193
+ return []
194
+ all_parsed_entries = (_parsed_entry(each_line) for each_line in all_lines)
195
+ return [each_entry for each_entry in all_parsed_entries if each_entry is not None]
@@ -6,6 +6,7 @@ import pytest
6
6
 
7
7
  from once_per_session import (
8
8
  claim_first_showing,
9
+ claim_only_showing,
9
10
  clear_showings,
10
11
  compaction_count,
11
12
  )
@@ -107,3 +108,12 @@ def test_should_show_every_time_when_the_marker_cannot_be_written(
107
108
  monkeypatch.setattr(tempfile, "gettempdir", lambda: str(tmp_path / "absent_directory"))
108
109
  assert claim_first_showing("hook", {"session_id": "s1"}) is True
109
110
  assert claim_first_showing("hook", {"session_id": "s1"}) is True
111
+
112
+
113
+ def test_should_show_only_once_in_a_session_across_compactions(transcript_path: Path) -> None:
114
+ assert claim_only_showing("hook", _fields(transcript_path)) is True
115
+ _append(transcript_path, CLAUDE_COMPACTION_LINE)
116
+ assert claim_only_showing("hook", _fields(transcript_path)) is False
117
+ assert claim_only_showing("hook", _fields(transcript_path, session_id="s2")) is True
118
+ clear_showings("s1")
119
+ assert claim_only_showing("hook", _fields(transcript_path)) is True
@@ -22,32 +22,6 @@ def isolated_temp_folder(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> Non
22
22
  monkeypatch.setattr(owned_pr_session_record.tempfile, "gettempdir", lambda: str(tmp_path))
23
23
 
24
24
 
25
- def test_record_blocked_heads_should_keep_the_other_pull_requests() -> None:
26
- owned_pr_session_record.record_blocked_heads(SESSION_ID, {PULL_REQUEST["url"]: "abc123"})
27
- owned_pr_session_record.record_blocked_heads(SESSION_ID, {"https://github.com/o/r/pull/2": "def456"})
28
- owned_pr_session_record.record_blocked_heads(SESSION_ID, {PULL_REQUEST["url"]: "fed789"})
29
- assert owned_pr_session_record.all_blocked_heads(SESSION_ID) == {
30
- PULL_REQUEST["url"]: "fed789",
31
- "https://github.com/o/r/pull/2": "def456",
32
- }
33
-
34
-
35
- def test_all_blocked_heads_should_read_a_malformed_record_as_empty() -> None:
36
- owned_pr_session_record.stop_block_record_path(SESSION_ID).write_text("[1, 2]", encoding="utf-8")
37
- assert owned_pr_session_record.all_blocked_heads(SESSION_ID) == {}
38
-
39
-
40
- def test_record_blocked_heads_should_skip_a_payload_with_no_session_id(tmp_path: Path) -> None:
41
- owned_pr_session_record.record_blocked_heads(None, {PULL_REQUEST["url"]: "abc123"})
42
- assert list(tmp_path.iterdir()) == []
43
-
44
-
45
- def test_stop_block_record_path_should_stay_apart_from_the_pull_request_record() -> None:
46
- assert owned_pr_session_record.stop_block_record_path(SESSION_ID) != (
47
- owned_pr_session_record.session_record_path(SESSION_ID)
48
- )
49
-
50
-
51
25
  def test_session_record_path_should_name_the_session_in_the_temp_folder(tmp_path: Path) -> None:
52
26
  assert (
53
27
  owned_pr_session_record.session_record_path("a/b c") == tmp_path / "owned-pr-loop-abc.json"
@@ -0,0 +1,111 @@
1
+ import json
2
+ from pathlib import Path
3
+
4
+ import pytest
5
+
6
+ from session_title_transcript import (
7
+ available_title_tools,
8
+ read_transcript_entries,
9
+ shown_title,
10
+ title_status,
11
+ )
12
+
13
+ REMOTE_TITLE_TOOL = "mcp__claude-code-remote__set_session_title"
14
+ DESKTOP_TITLE_TOOL = "mcp__ccd_session_mgmt__set_session_title"
15
+ SNAPSHOT_LISTING = {
16
+ "type": "attachment",
17
+ "attachment": {
18
+ "type": "prompt_snapshot",
19
+ "tools": [{"name": "Bash"}, {"name": REMOTE_TITLE_TOOL}],
20
+ },
21
+ }
22
+ DEFERRED_LISTING = {
23
+ "type": "attachment",
24
+ "attachment": {"type": "deferred_tools_delta", "addedNames": [DESKTOP_TITLE_TOOL]},
25
+ }
26
+ REMOVAL_LISTING = {
27
+ "type": "attachment",
28
+ "attachment": {"type": "deferred_tools_delta", "removedNames": [DESKTOP_TITLE_TOOL]},
29
+ }
30
+ RED_FLAG_TITLE = "\U0001f6a9 Merge approval"
31
+ HOURGLASS_TITLE = "⏳ Export"
32
+
33
+
34
+ def title_call(tool_use_id: str, title: str, is_sidechain: bool = False) -> dict[str, object]:
35
+ return {
36
+ "type": "assistant",
37
+ "isSidechain": is_sidechain,
38
+ "message": {
39
+ "content": [
40
+ {
41
+ "type": "tool_use",
42
+ "id": tool_use_id,
43
+ "name": REMOTE_TITLE_TOOL,
44
+ "input": {"title": title},
45
+ }
46
+ ]
47
+ },
48
+ }
49
+
50
+
51
+ def title_result(
52
+ tool_use_id: str, is_error: bool = False, is_sidechain: bool = False
53
+ ) -> dict[str, object]:
54
+ return {
55
+ "type": "user",
56
+ "isSidechain": is_sidechain,
57
+ "message": {
58
+ "content": [
59
+ {
60
+ "type": "tool_result",
61
+ "tool_use_id": tool_use_id,
62
+ "content": "ok",
63
+ "is_error": is_error,
64
+ }
65
+ ]
66
+ },
67
+ }
68
+
69
+
70
+ def test_should_find_the_title_tool_in_a_listing_a_deferred_delta_or_a_call() -> None:
71
+ assert available_title_tools([SNAPSHOT_LISTING]) == [REMOTE_TITLE_TOOL]
72
+ assert available_title_tools([DEFERRED_LISTING]) == [DESKTOP_TITLE_TOOL]
73
+ assert available_title_tools([title_call("t1", HOURGLASS_TITLE)]) == [REMOTE_TITLE_TOOL]
74
+ assert available_title_tools([{"type": "user"}]) == []
75
+
76
+
77
+ def test_should_drop_a_title_tool_a_later_delta_removes() -> None:
78
+ assert available_title_tools([DEFERRED_LISTING, REMOVAL_LISTING]) == []
79
+
80
+
81
+ def test_should_return_the_last_main_chain_title_that_came_back_without_an_error() -> None:
82
+ all_entries = [
83
+ title_call("t1", HOURGLASS_TITLE),
84
+ title_result("t1"),
85
+ title_call("t2", RED_FLAG_TITLE),
86
+ title_result("t2", is_error=True),
87
+ title_call("t3", "✅ Subagent", is_sidechain=True),
88
+ title_result("t3", is_sidechain=True),
89
+ ]
90
+ assert shown_title(all_entries) == HOURGLASS_TITLE
91
+ assert shown_title([SNAPSHOT_LISTING]) is None
92
+
93
+
94
+ @pytest.mark.parametrize(
95
+ ("title", "expected_status"),
96
+ [(RED_FLAG_TITLE, "\U0001f6a9"), ("⏳️ Export", "⏳"), ("Export", None)],
97
+ )
98
+ def test_should_read_the_status_emoji_without_its_variation_selector(
99
+ title: str, expected_status: str | None
100
+ ) -> None:
101
+ assert title_status(title) == expected_status
102
+
103
+
104
+ def test_should_read_object_lines_and_skip_the_rest(tmp_path: Path) -> None:
105
+ transcript_path = tmp_path / "session.jsonl"
106
+ transcript_path.write_text(
107
+ json.dumps(SNAPSHOT_LISTING) + "\nnot json\n[1, 2]\n", encoding="utf-8"
108
+ )
109
+ assert read_transcript_entries(str(transcript_path)) == [SNAPSHOT_LISTING]
110
+ assert read_transcript_entries(str(tmp_path / "missing.jsonl")) == []
111
+ assert read_transcript_entries(None) == []