claude-dev-env 8.112.0 → 8.113.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.
@@ -13,3 +13,5 @@ The `spawn_oversight_hook` adds this duty to every spawn, at every level of the
13
13
  - Tag each piece in-scope or new scope. Ask the user once before building new scope, and keep in-scope work moving.
14
14
  - Keep each brief, prompt, and context file you hand an agent a short map: when to use it, the steps, and pointers to reference files it opens on demand.
15
15
  - Report as done only what a verifier passed, and name the verdict and its evidence. Report the rest as waiting on verification.
16
+
17
+ When the user asks for silence, such as "silent unless something merges or you are blocked", the coordinator sets each watcher to emit only the events the user named. It briefs each delegate to send one final report and to start no watch loop that ends its turn. Every other event starts a turn the user did not ask to see, and `hooks/session/background_silence_prompt.py` tells that turn to end with no text.
@@ -35,7 +35,7 @@ test('reinstall drops the retired style reminder and keeps one skill reminder ho
35
35
  mergeHooksIntoSettings(settings, hooksConfig, 'C:/Users/example/.claude', 'python');
36
36
 
37
37
  const userPromptHooks = settings.hooks.UserPromptSubmit.flatMap(eachGroup => eachGroup.hooks);
38
- assert.equal(userPromptHooks.length, 7);
38
+ assert.equal(userPromptHooks.length, 8);
39
39
  assert.equal(userPromptHooks[0].command, userCommand);
40
40
  assert.match(userPromptHooks[1].command, /session\/skill_loaded_reminder\.py$/);
41
41
  assert.match(userPromptHooks[2].command, /lifecycle\/nested_project_hooks\.py$/);
@@ -43,6 +43,7 @@ test('reinstall drops the retired style reminder and keeps one skill reminder ho
43
43
  assert.match(userPromptHooks[4].command, /session\/tracking_nudge\.py$/);
44
44
  assert.match(userPromptHooks[5].command, /session\/plugin_change_warning\.py$/);
45
45
  assert.match(userPromptHooks[6].command, /blocking\/turn_review_gate\.py$/);
46
+ assert.match(userPromptHooks[7].command, /session\/background_silence_prompt\.py$/);
46
47
  assert.ok(userPromptHooks.every(eachHook => !eachHook.command.includes('style_reminder_prompt')));
47
48
 
48
49
  const firstMerge = JSON.stringify(settings);
@@ -8,6 +8,7 @@ This family stops a chat reply, edited message, or tool call when its payload br
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
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.
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.
11
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.
12
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
14
  - `blocking/edit_marker_gate.py` rejects strikethrough and edit-note markers in replacement chat text or cards.
@@ -32,6 +33,7 @@ This family stops a chat reply, edited message, or tool call when its payload br
32
33
  - `blocking/final_reply_gate.py` runs on `Stop`, timeout `10` seconds in `hooks.json`.
33
34
  - `blocking/open_tasks_stop_gate.py` runs on `Stop`, timeout `10` seconds in `hooks.json`. The installer also registers it on Codex `Stop` and as a native Cursor `stop` entry in `~/.cursor/hooks.json`, where a block also returns `followup_message`. A Cursor stop with status `aborted` or `error` passes. A Cursor stop whose `loop_count` is above 0 passes, because a copy Cursor imports from `~/.claude/settings.json` has no follow-up limit.
34
35
  - `session/tracking_nudge.py` runs on `UserPromptSubmit`, matcher empty, timeout `10` seconds in `hooks.json`.
36
+ - `session/background_silence_prompt.py` runs on `UserPromptSubmit`, matcher empty, timeout `10` seconds in `hooks.json`. It reads the transcript only for a background event prompt.
35
37
  - The claim judge runs on `PreToolUse`, matcher `mcp__hearthbot__reply|mcp__hearthbot__post_message|mcp__hearthbot__update_message|mcp__hearthbot__ask_decision`, timeout `30` seconds in `hooks.json`.
36
38
  - `blocking/chat_reply_gate.py` runs on `UserPromptSubmit`, matcher empty, timeout `10` seconds, on `MessageDisplay`, timeout `100` seconds, and on `SessionEnd`, timeout `3` seconds, in `hooks.json`.
37
39
  - `blocking/edit_marker_gate.py` runs on `PreToolUse`, matcher `mcp__.*__update_message`, timeout `10` seconds in `hooks.json`.
@@ -61,6 +63,7 @@ Preconditions:
61
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.
62
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.
63
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.
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.
64
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.
65
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.
66
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.
@@ -81,6 +84,7 @@ Preconditions:
81
84
  ## Gotchas
82
85
 
83
86
  - The ask nudge runs only from `hooks.json`, so Codex and Cursor sessions get no turn-start note. Their Stop gate still holds a work turn with no tracker call.
87
+ - The background silence note is the last point before the reply. A Stop hook sees the reply after it is on screen, and holding the text at `MessageDisplay` would need a judgment on whether the exception applies.
84
88
  - `blocking/turn_review_gate.py` starts `claude -p`, which inherits the parent session id unless the gate strips it. A review that kept `CLAUDE_CODE_SESSION_ID` would write into the parent's transcript.
85
89
  - Each review run calls a model and costs about $0.03. Leave `CLAUDE_TURN_REVIEW_REPOSITORIES` unset and the gate makes no snapshot and no call.
86
90
  - `blocking/step_note_gate.py` is off by default and polls for the transcript record. Subagent calls and unreadable records pass.
package/hooks/hooks.json CHANGED
@@ -358,6 +358,11 @@
358
358
  "type": "command",
359
359
  "command": "python3 ${CLAUDE_PLUGIN_ROOT}/hooks/blocking/turn_review_gate.py",
360
360
  "timeout": 30
361
+ },
362
+ {
363
+ "type": "command",
364
+ "command": "python3 ${CLAUDE_PLUGIN_ROOT}/hooks/session/background_silence_prompt.py",
365
+ "timeout": 10
361
366
  }
362
367
  ]
363
368
  }
@@ -0,0 +1,40 @@
1
+ """Constants for the UserPromptSubmit hook that keeps a background event turn silent."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+
7
+ ORIGIN_KEY = "origin"
8
+ ORIGIN_KIND_KEY = "kind"
9
+ HUMAN_ORIGIN_KIND = "human"
10
+ TASK_NOTIFICATION_MARKER = "<task-notification"
11
+ BACKGROUND_EVENT_PATTERN = re.compile(
12
+ r"(?:\A\s*|<system-reminder>\s*)" + re.escape("[SYSTEM NOTIFICATION - NOT USER INPUT]")
13
+ )
14
+ ALL_SET_PATTERNS = (
15
+ re.compile(r"\b(?:silent|quiet)\s+unless\b", re.IGNORECASE),
16
+ re.compile(r"\b(?:stay|go)\s+(?:silent|quiet)\b", re.IGNORECASE),
17
+ re.compile(r"\bsilent\s+on\s+updates\b", re.IGNORECASE),
18
+ re.compile(r"\bno\s+updates\s+unless\b", re.IGNORECASE),
19
+ )
20
+ ALL_LIFT_PATTERNS = (
21
+ re.compile(r"\byou\s+can\s+talk\s+again\b", re.IGNORECASE),
22
+ re.compile(r"\bupdates\s+are\s+(?:fine|ok(?:ay)?)\b", re.IGNORECASE),
23
+ re.compile(r"\bstop\s+being\s+(?:silent|quiet)\b", re.IGNORECASE),
24
+ re.compile(r"\b(?:don['’]?t|do\s+not)\s+(?:stay|be|go)\s+(?:silent|quiet)\b", re.IGNORECASE),
25
+ )
26
+ EXCEPTION_CLAUSE_PATTERN = re.compile(r"\b(?:unless|except)\b.*?(?=[.!?]*\s*\Z)", re.IGNORECASE)
27
+ QUOTED_LINE_PATTERN = re.compile(r"^[ \t]*>.*$", re.MULTILINE)
28
+ MAXIMUM_QUOTED_CHARACTERS = 300
29
+ SILENCE_NOTE_TEMPLATE = (
30
+ 'The user asked you to stay silent "{exception_clause}".'
31
+ " This prompt is a background event, not a message from the user."
32
+ " End this turn with no text at all unless that exception applies now."
33
+ ' Tool calls are fine, and a status line such as "No change." counts as text.'
34
+ )
35
+ SILENCE_NOTE_WITHOUT_EXCEPTION = (
36
+ 'The user asked you to stay silent in the message "{silence_message}".'
37
+ " This prompt is a background event, not a message from the user."
38
+ " End this turn with no text at all unless that message names an exception that applies now."
39
+ ' Tool calls are fine, and a status line such as "No change." counts as text.'
40
+ )
@@ -0,0 +1,223 @@
1
+ #!/usr/bin/env python3
2
+ """UserPromptSubmit hook that keeps a background event turn silent while the user asked for silence.
3
+
4
+ The user tells the session to stay quiet. A background event, such as a
5
+ finished delegate or a monitor line, still starts a turn, and each such turn
6
+ tends to end with a line like "No change." The hook adds one note to that turn::
7
+
8
+ user said "silent unless something merges", prompt is a <task-notification>
9
+ -> note quoting "unless something merges"
10
+ same transcript, the prompt is user-typed -> nothing
11
+ the user later said "you can talk again" -> nothing
12
+ the user never asked for silence -> nothing
13
+
14
+ The newest user-typed message that sets or lifts silence decides it. A prompt
15
+ that starts with an envelope such as ``<task-notification>`` or
16
+ ``<agent-message>``, a ``[SYSTEM NOTIFICATION - NOT USER INPUT]`` prompt, a
17
+ compaction summary, and a quoted ``>`` line are not the user's words.
18
+
19
+ A Stop hook cannot hold this, because the reply is already on screen when Stop
20
+ runs.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import json
26
+ import re
27
+ import sys
28
+ from pathlib import Path
29
+
30
+ hooks_root_directory = str(Path(__file__).resolve().parent.parent)
31
+ if hooks_root_directory not in sys.path:
32
+ sys.path.insert(0, hooks_root_directory)
33
+ blocking_directory = str(Path(__file__).resolve().parent.parent / "blocking")
34
+ if blocking_directory not in sys.path:
35
+ sys.path.insert(0, blocking_directory)
36
+
37
+ from hooks_constants.background_silence_prompt_constants import (
38
+ ALL_LIFT_PATTERNS,
39
+ ALL_SET_PATTERNS,
40
+ BACKGROUND_EVENT_PATTERN,
41
+ EXCEPTION_CLAUSE_PATTERN,
42
+ HUMAN_ORIGIN_KIND,
43
+ MAXIMUM_QUOTED_CHARACTERS,
44
+ ORIGIN_KEY,
45
+ ORIGIN_KIND_KEY,
46
+ QUOTED_LINE_PATTERN,
47
+ SILENCE_NOTE_TEMPLATE,
48
+ SILENCE_NOTE_WITHOUT_EXCEPTION,
49
+ TASK_NOTIFICATION_MARKER,
50
+ )
51
+ from hooks_constants.hook_specific_output_keys import (
52
+ HOOK_EVENT_NAME_KEY,
53
+ HOOK_SPECIFIC_OUTPUT_KEY,
54
+ )
55
+ from hooks_constants.open_tasks_stop_gate_constants import (
56
+ ALL_ASK_ONLY_ENVELOPE_MARKERS,
57
+ ALLOW_EXIT_CODE,
58
+ PROMPT_KEY,
59
+ PROMPT_SUBMIT_EVENT_NAME,
60
+ SENTENCE_SPLIT_PATTERN,
61
+ TRANSCRIPT_PATH_KEY,
62
+ )
63
+ from hooks_constants.pre_tool_use_stdin import read_hook_input_dictionary_from_stdin
64
+ from hooks_constants.reply_length_gate_constants import ADDITIONAL_CONTEXT_KEY
65
+ from hooks_constants.spawn_readiness_hook_constants import (
66
+ ALL_HARNESS_ENVELOPE_MARKERS,
67
+ HUMAN_SENDER_MARKER,
68
+ )
69
+ from open_task_asks import prompt_without_reminders
70
+ from open_tasks_transcript import claude_prompt_text
71
+ from session_title_turn_gate import read_transcript_entries
72
+
73
+
74
+ def _is_user_typed_text(prompt_text: str) -> bool:
75
+ if BACKGROUND_EVENT_PATTERN.search(prompt_text):
76
+ return False
77
+ stripped_text = prompt_without_reminders(prompt_text)
78
+ if stripped_text.startswith((*ALL_HARNESS_ENVELOPE_MARKERS, *ALL_ASK_ONLY_ENVELOPE_MARKERS)):
79
+ return HUMAN_SENDER_MARKER in stripped_text.split(">", 1)[0]
80
+ return bool(stripped_text)
81
+
82
+
83
+ def _user_words(all_record_fields: dict[str, object]) -> str | None:
84
+ origin = all_record_fields.get(ORIGIN_KEY)
85
+ if isinstance(origin, dict) and origin.get(ORIGIN_KIND_KEY) not in (None, HUMAN_ORIGIN_KIND):
86
+ return None
87
+ prompt_text = claude_prompt_text(all_record_fields)
88
+ if prompt_text is None or not _is_user_typed_text(prompt_text):
89
+ return None
90
+ return QUOTED_LINE_PATTERN.sub("", prompt_without_reminders(prompt_text)).strip()
91
+
92
+
93
+ def _sets_silence(text: str) -> bool:
94
+ return any(each_pattern.search(text) for each_pattern in ALL_SET_PATTERNS)
95
+
96
+
97
+ def is_background_event(prompt_text: str) -> bool:
98
+ """Return True when the submitted prompt is a background event and not the user's own words.
99
+
100
+ ::
101
+
102
+ "<task-notification>...</task-notification>" -> True
103
+ "<system-reminder>[SYSTEM NOTIFICATION - NOT USER INPUT]..." -> True
104
+ "did PR 12 merge?" -> False
105
+ '<agent-message from="a1">Report</agent-message>' -> False
106
+
107
+ Args:
108
+ prompt_text: The ``prompt`` field of the UserPromptSubmit payload.
109
+
110
+ Returns:
111
+ True for a prompt that starts with ``<task-notification>`` after its
112
+ ``<system-reminder>`` blocks, or that opens itself or a
113
+ ``<system-reminder>`` block with the system notification marker.
114
+ """
115
+ if _is_user_typed_text(prompt_text):
116
+ return False
117
+ return bool(BACKGROUND_EVENT_PATTERN.search(prompt_text)) or prompt_without_reminders(
118
+ prompt_text
119
+ ).startswith(TASK_NOTIFICATION_MARKER)
120
+
121
+
122
+ def newest_silence_message(all_entries: list[dict[str, object]]) -> str | None:
123
+ """Return the user's newest message that sets silence, or None once a newer one lifts it.
124
+
125
+ ::
126
+
127
+ "Silent on updates unless something merges" -> that message
128
+ ... then "ok you can talk again" -> None
129
+ ... then "stay silent unless blocked" -> "stay silent unless blocked"
130
+ no user message names silence -> None
131
+
132
+ Args:
133
+ all_entries: The transcript entries, oldest first.
134
+
135
+ Returns:
136
+ The message text with its quoted lines removed, or None.
137
+ """
138
+ for each_entry in reversed(all_entries):
139
+ user_words = _user_words(each_entry)
140
+ if not user_words:
141
+ continue
142
+ if any(each_pattern.search(user_words) for each_pattern in ALL_LIFT_PATTERNS):
143
+ return None
144
+ if _sets_silence(user_words):
145
+ return user_words
146
+ return None
147
+
148
+
149
+ def exception_clause(silence_message: str) -> str | None:
150
+ """Return the exception the user gave, word for word, or None when they gave none.
151
+
152
+ The clause runs from "unless" or "except" to the end of the sentence that
153
+ sets silence, or is the next sentence when that one opens with either word::
154
+
155
+ "Silent on updates unless something merges or youre blocked"
156
+ -> "unless something merges or youre blocked"
157
+ "Stay silent. Except for a failed check."
158
+ -> "Except for a failed check"
159
+ "Stay silent. Ship PR 12 unless it is red."
160
+ -> None
161
+ "Stay silent." -> None
162
+
163
+ Args:
164
+ silence_message: The message ``newest_silence_message`` returned.
165
+
166
+ Returns:
167
+ The clause, cut to MAXIMUM_QUOTED_CHARACTERS, or None.
168
+ """
169
+ all_sentences = re.split(SENTENCE_SPLIT_PATTERN, silence_message)
170
+ for each_index, each_sentence in enumerate(all_sentences):
171
+ if not _sets_silence(each_sentence):
172
+ continue
173
+ clause_match = EXCEPTION_CLAUSE_PATTERN.search(each_sentence)
174
+ if clause_match is None and each_index + 1 < len(all_sentences):
175
+ clause_match = EXCEPTION_CLAUSE_PATTERN.match(all_sentences[each_index + 1].strip())
176
+ if clause_match is None:
177
+ return None
178
+ return clause_match.group(0).strip()[:MAXIMUM_QUOTED_CHARACTERS]
179
+ return None
180
+
181
+
182
+ def silence_context(all_entries: list[dict[str, object]]) -> str | None:
183
+ """Return the note for a background event turn while the user asked for silence, else None.
184
+
185
+ Args:
186
+ all_entries: The transcript entries, oldest first.
187
+
188
+ Returns:
189
+ The note that quotes the user's exception clause, the note that quotes
190
+ the whole message when it has no "unless" or "except" clause, or None.
191
+ """
192
+ silence_message = newest_silence_message(all_entries)
193
+ if silence_message is None:
194
+ return None
195
+ clause = exception_clause(silence_message)
196
+ if clause is None:
197
+ return SILENCE_NOTE_WITHOUT_EXCEPTION.format(
198
+ silence_message=silence_message[:MAXIMUM_QUOTED_CHARACTERS]
199
+ )
200
+ return SILENCE_NOTE_TEMPLATE.format(exception_clause=clause)
201
+
202
+
203
+ def main() -> int:
204
+ hook_input = read_hook_input_dictionary_from_stdin()
205
+ prompt_value = hook_input.get(PROMPT_KEY) if hook_input is not None else None
206
+ if (
207
+ hook_input is None
208
+ or not isinstance(prompt_value, str)
209
+ or not is_background_event(prompt_value)
210
+ ):
211
+ return ALLOW_EXIT_CODE
212
+ context_text = silence_context(read_transcript_entries(hook_input.get(TRANSCRIPT_PATH_KEY)))
213
+ if context_text:
214
+ hook_event_output = {
215
+ HOOK_EVENT_NAME_KEY: PROMPT_SUBMIT_EVENT_NAME,
216
+ ADDITIONAL_CONTEXT_KEY: context_text,
217
+ }
218
+ sys.stdout.write(json.dumps({HOOK_SPECIFIC_OUTPUT_KEY: hook_event_output}))
219
+ return ALLOW_EXIT_CODE
220
+
221
+
222
+ if __name__ == "__main__":
223
+ sys.exit(main())
@@ -0,0 +1,280 @@
1
+ import importlib
2
+ import io
3
+ import json
4
+ import subprocess
5
+ import sys
6
+ from pathlib import Path
7
+
8
+ import pytest
9
+
10
+ _SESSION_DIR = Path(__file__).resolve().parent
11
+ if str(_SESSION_DIR) not in sys.path:
12
+ sys.path.insert(0, str(_SESSION_DIR))
13
+
14
+ background_silence_prompt = importlib.import_module("background_silence_prompt")
15
+
16
+ HOOK_PATH = _SESSION_DIR / "background_silence_prompt.py"
17
+ SILENCE_REQUEST = "Silent on updates unless something merges or youre blocked "
18
+ EXCEPTION_TEXT = "unless something merges or youre blocked"
19
+ NOTIFICATION_PROMPT = (
20
+ "<task-notification>\n<task-id>a1</task-id>\n<status>completed</status>\n"
21
+ '<summary>Agent "Ship it" finished</summary>\n</task-notification>'
22
+ )
23
+ MARKER_PROMPT = (
24
+ "<system-reminder>\n[SYSTEM NOTIFICATION - NOT USER INPUT]\n"
25
+ "This is an automated background-task event, NOT a message from the user.\n"
26
+ "</system-reminder>"
27
+ )
28
+
29
+
30
+ def typed_entry(text: str) -> dict[str, object]:
31
+ return {
32
+ "type": "user",
33
+ "origin": {"kind": "human"},
34
+ "message": {"role": "user", "content": text},
35
+ }
36
+
37
+
38
+ def notification_entry(text: str) -> dict[str, object]:
39
+ return {
40
+ "type": "user",
41
+ "origin": {"kind": "task-notification"},
42
+ "message": {"role": "user", "content": text},
43
+ }
44
+
45
+
46
+ def assistant_entry(text: str) -> dict[str, object]:
47
+ return {
48
+ "type": "assistant",
49
+ "message": {"role": "assistant", "content": [{"type": "text", "text": text}]},
50
+ }
51
+
52
+
53
+ def run_hook(
54
+ monkeypatch: pytest.MonkeyPatch,
55
+ capsys: pytest.CaptureFixture[str],
56
+ tmp_path: Path,
57
+ prompt_text: str,
58
+ all_entries: list[dict[str, object]],
59
+ ) -> str:
60
+ transcript_path = tmp_path / "session.jsonl"
61
+ transcript_path.write_text(
62
+ "\n".join(json.dumps(each) for each in all_entries), encoding="utf-8"
63
+ )
64
+ hook_input = {
65
+ "hook_event_name": "UserPromptSubmit",
66
+ "prompt": prompt_text,
67
+ "transcript_path": str(transcript_path),
68
+ }
69
+ monkeypatch.setattr(
70
+ "sys.stdin", io.TextIOWrapper(io.BytesIO(json.dumps(hook_input).encode("utf-8")))
71
+ )
72
+ assert background_silence_prompt.main() == 0
73
+ printed_output = capsys.readouterr().out
74
+ return (
75
+ json.loads(printed_output)["hookSpecificOutput"]["additionalContext"]
76
+ if printed_output
77
+ else ""
78
+ )
79
+
80
+
81
+ @pytest.mark.parametrize("prompt_text", [NOTIFICATION_PROMPT, MARKER_PROMPT])
82
+ def test_should_quote_the_exception_for_a_background_event_under_silence(
83
+ monkeypatch: pytest.MonkeyPatch,
84
+ capsys: pytest.CaptureFixture[str],
85
+ tmp_path: Path,
86
+ prompt_text: str,
87
+ ) -> None:
88
+ all_entries = [typed_entry(SILENCE_REQUEST), assistant_entry("Understood.")]
89
+ context_text = run_hook(monkeypatch, capsys, tmp_path, prompt_text, all_entries)
90
+ assert f'"{EXCEPTION_TEXT}"' in context_text
91
+ assert "no text at all" in context_text
92
+
93
+
94
+ def test_should_add_nothing_to_a_user_typed_prompt_under_silence(
95
+ monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], tmp_path: Path
96
+ ) -> None:
97
+ all_entries = [typed_entry(SILENCE_REQUEST)]
98
+ assert run_hook(monkeypatch, capsys, tmp_path, "did PR 12 merge?", all_entries) == ""
99
+
100
+
101
+ @pytest.mark.parametrize(
102
+ "lift_text", ["ok you can talk again", "updates are fine now", "stop being silent"]
103
+ )
104
+ def test_should_add_nothing_once_the_user_lifts_silence(
105
+ monkeypatch: pytest.MonkeyPatch,
106
+ capsys: pytest.CaptureFixture[str],
107
+ tmp_path: Path,
108
+ lift_text: str,
109
+ ) -> None:
110
+ all_entries = [typed_entry(SILENCE_REQUEST), typed_entry(lift_text)]
111
+ assert run_hook(monkeypatch, capsys, tmp_path, NOTIFICATION_PROMPT, all_entries) == ""
112
+
113
+
114
+ def test_should_add_nothing_without_a_silence_instruction(
115
+ monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], tmp_path: Path
116
+ ) -> None:
117
+ all_entries = [typed_entry("Ship PR 12 and watch its checks")]
118
+ assert run_hook(monkeypatch, capsys, tmp_path, NOTIFICATION_PROMPT, all_entries) == ""
119
+
120
+
121
+ def test_should_add_nothing_when_the_transcript_cannot_be_read(
122
+ monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], tmp_path: Path
123
+ ) -> None:
124
+ hook_input = {"prompt": NOTIFICATION_PROMPT, "transcript_path": str(tmp_path / "missing.jsonl")}
125
+ monkeypatch.setattr(
126
+ "sys.stdin", io.TextIOWrapper(io.BytesIO(json.dumps(hook_input).encode("utf-8")))
127
+ )
128
+ assert background_silence_prompt.main() == 0
129
+ assert capsys.readouterr().out == ""
130
+
131
+
132
+ def test_should_restore_silence_that_the_user_sets_again_after_a_lift(
133
+ monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], tmp_path: Path
134
+ ) -> None:
135
+ all_entries = [
136
+ typed_entry(SILENCE_REQUEST),
137
+ typed_entry("you can talk again"),
138
+ typed_entry("keep draining, silent unless youre blocked"),
139
+ ]
140
+ context_text = run_hook(monkeypatch, capsys, tmp_path, NOTIFICATION_PROMPT, all_entries)
141
+ assert '"unless youre blocked"' in context_text
142
+
143
+
144
+ @pytest.mark.parametrize(
145
+ "later_entry",
146
+ [
147
+ notification_entry("<task-notification>updates are fine</task-notification>"),
148
+ typed_entry('<agent-message from="a1">you can talk again</agent-message>'),
149
+ {
150
+ "type": "user",
151
+ "isCompactSummary": True,
152
+ "message": {"role": "user", "content": "updates are fine"},
153
+ },
154
+ typed_entry("> you can talk again\n\nthis is not staying silent"),
155
+ ],
156
+ )
157
+ def test_should_keep_silence_through_text_that_is_not_the_user_lifting_it(
158
+ monkeypatch: pytest.MonkeyPatch,
159
+ capsys: pytest.CaptureFixture[str],
160
+ tmp_path: Path,
161
+ later_entry: dict[str, object],
162
+ ) -> None:
163
+ all_entries = [typed_entry(SILENCE_REQUEST), later_entry]
164
+ context_text = run_hook(monkeypatch, capsys, tmp_path, NOTIFICATION_PROMPT, all_entries)
165
+ assert f'"{EXCEPTION_TEXT}"' in context_text
166
+
167
+
168
+ @pytest.mark.parametrize(
169
+ "earlier_entry",
170
+ [
171
+ notification_entry("<task-notification>stay silent unless blocked</task-notification>"),
172
+ typed_entry('<agent-message from="a1">stay silent unless blocked</agent-message>'),
173
+ typed_entry("> stay silent unless blocked\n\nwhy is this so loud?"),
174
+ ],
175
+ )
176
+ def test_should_not_set_silence_from_text_that_is_not_the_users_own(
177
+ monkeypatch: pytest.MonkeyPatch,
178
+ capsys: pytest.CaptureFixture[str],
179
+ tmp_path: Path,
180
+ earlier_entry: dict[str, object],
181
+ ) -> None:
182
+ assert run_hook(monkeypatch, capsys, tmp_path, NOTIFICATION_PROMPT, [earlier_entry]) == ""
183
+
184
+
185
+ @pytest.mark.parametrize(
186
+ "silence_message",
187
+ ["Stay silent.", "Silent on updates. Only ping me when a PR merges."],
188
+ )
189
+ def test_should_quote_the_whole_message_when_it_has_no_unless_clause(
190
+ monkeypatch: pytest.MonkeyPatch,
191
+ capsys: pytest.CaptureFixture[str],
192
+ tmp_path: Path,
193
+ silence_message: str,
194
+ ) -> None:
195
+ context_text = run_hook(
196
+ monkeypatch, capsys, tmp_path, NOTIFICATION_PROMPT, [typed_entry(silence_message)]
197
+ )
198
+ assert f'"{silence_message}"' in context_text
199
+ assert "no text at all" in context_text
200
+
201
+
202
+ @pytest.mark.parametrize(
203
+ ("prompt_text", "is_background"),
204
+ [
205
+ (NOTIFICATION_PROMPT, True),
206
+ (MARKER_PROMPT, True),
207
+ ("<system-reminder>Tool loaded.</system-reminder>\n" + NOTIFICATION_PROMPT, True),
208
+ ("did PR 12 merge?", False),
209
+ ('<agent-message from="a1">Report</agent-message>', False),
210
+ ("Here is the log:\n<task-notification>done</task-notification>", False),
211
+ ("[SYSTEM NOTIFICATION - NOT USER INPUT]\nBackground task finished.", True),
212
+ ("why does [SYSTEM NOTIFICATION - NOT USER INPUT] show up?", False),
213
+ ('<task-notification><summary>quoted from="human"</summary></task-notification>', True),
214
+ ],
215
+ )
216
+ def test_should_tell_a_background_event_from_a_user_prompt(
217
+ prompt_text: str, is_background: bool
218
+ ) -> None:
219
+ assert background_silence_prompt.is_background_event(prompt_text) is is_background
220
+
221
+
222
+ def test_should_return_the_newest_message_that_sets_silence() -> None:
223
+ all_entries = [typed_entry("stay silent"), typed_entry("Ship it"), typed_entry(SILENCE_REQUEST)]
224
+ assert background_silence_prompt.newest_silence_message(all_entries) == SILENCE_REQUEST.strip()
225
+ assert (
226
+ background_silence_prompt.newest_silence_message(
227
+ [*all_entries, typed_entry("you can talk again")]
228
+ )
229
+ is None
230
+ )
231
+
232
+
233
+ @pytest.mark.parametrize(
234
+ ("silence_message", "expected_clause"),
235
+ [
236
+ (SILENCE_REQUEST, EXCEPTION_TEXT),
237
+ (
238
+ "Merge the stack. Then stay quiet except for a failed check. Thanks",
239
+ "except for a failed check",
240
+ ),
241
+ ("no updates unless a PR lands", "unless a PR lands"),
242
+ ("Stay silent. Except for a failed check.", "Except for a failed check"),
243
+ ("Silent on updates unless the build on v1.2 is red!", "unless the build on v1.2 is red"),
244
+ ("Stay silent. Ship PR 12 unless it is red.", None),
245
+ ("Stay silent.", None),
246
+ ],
247
+ )
248
+ def test_should_quote_the_exception_clause_word_for_word(
249
+ silence_message: str, expected_clause: str | None
250
+ ) -> None:
251
+ assert background_silence_prompt.exception_clause(silence_message) == expected_clause
252
+
253
+
254
+ def test_should_build_the_note_only_under_silence() -> None:
255
+ assert background_silence_prompt.silence_context([typed_entry("Ship it")]) is None
256
+ assert EXCEPTION_TEXT in (
257
+ background_silence_prompt.silence_context([typed_entry(SILENCE_REQUEST)]) or ""
258
+ )
259
+
260
+
261
+ def test_should_print_the_documented_output_through_a_subprocess(tmp_path: Path) -> None:
262
+ transcript_path = tmp_path / "session.jsonl"
263
+ transcript_path.write_text(json.dumps(typed_entry(SILENCE_REQUEST)), encoding="utf-8")
264
+ hook_input = {
265
+ "hook_event_name": "UserPromptSubmit",
266
+ "prompt": NOTIFICATION_PROMPT,
267
+ "transcript_path": str(transcript_path),
268
+ }
269
+ completed_process = subprocess.run(
270
+ [sys.executable, str(HOOK_PATH)],
271
+ input=json.dumps(hook_input),
272
+ capture_output=True,
273
+ text=True,
274
+ env={"HOME": str(tmp_path), "USERPROFILE": str(tmp_path), "PATH": ""},
275
+ check=False,
276
+ )
277
+ assert completed_process.returncode == 0
278
+ hook_output = json.loads(completed_process.stdout)["hookSpecificOutput"]
279
+ assert hook_output["hookEventName"] == "UserPromptSubmit"
280
+ assert f'"{EXCEPTION_TEXT}"' in hook_output["additionalContext"]
@@ -0,0 +1 @@
1
+ {"type": "user", "origin": {"kind": "human"}, "message": {"role": "user", "content": "Silent on updates unless something merges or the run is blocked"}}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-dev-env",
3
- "version": "8.112.0",
3
+ "version": "8.113.0",
4
4
  "description": "Claude Code development standards — rules, hooks, agents, commands, and skills",
5
5
  "type": "module",
6
6
  "bin": {
@@ -17,11 +17,15 @@
17
17
  - When the fast-forward fails because the files were already copied in,
18
18
  moves HEAD with a mixed reset, which writes no files. It keeps that move
19
19
  only when every file the remote changed now matches the remote
20
+ - When a -Mirror tree diverged from the remote, keeps the old tip under
21
+ refs/mirror-backup/, moves HEAD with a mixed reset, and stashes every
22
+ tracked file that still differs from the remote
20
23
  - Logs and exits non-zero on skip, diverge, or failure so a Task Scheduler
21
24
  history row can surface a problem instead of a silent no-op
22
25
 
23
26
  Exit codes: 0 success, 1 git operation failed, 2 configuration or repo
24
- problem, 3 skipped by a safety rule, 4 diverged from the remote.
27
+ problem, 3 skipped by a safety rule, 4 diverged from the remote (a -Mirror
28
+ tree realigns instead).
25
29
 
26
30
  .PARAMETER RepoPath
27
31
  Absolute path to the git working tree. Required.
@@ -58,6 +62,15 @@
58
62
  back to the old checkout and the run exits 1. Without the switch, any
59
63
  other checkout is skipped.
60
64
 
65
+ A mirror whose history diverged from the remote, as after a rewrite of the
66
+ remote history, realigns instead of exiting 4. The old tip stays reachable
67
+ as refs/mirror-backup/<yyyy-MM-dd>-<tip>, HEAD and the index move to the
68
+ remote tip with a mixed reset, and every tracked file that still differs is
69
+ stashed as "mirror realign <yyyy-MM-dd>: tree before moving <tip> to
70
+ <remote>/<branch>". Untracked files are never touched. A staged index skips
71
+ the realign. When a step fails, HEAD goes back to the old tip and the run
72
+ exits 1.
73
+
61
74
  .PARAMETER LogPath
62
75
  Absolute path to the run log (default: $HOME\.claude\logs\sync-repo-main.log).
63
76
  #>
@@ -284,6 +297,67 @@ function Invoke-AdoptCopiedTree {
284
297
  return $false
285
298
  }
286
299
 
300
+ function Invoke-MirrorRealign {
301
+ <#
302
+ Moves a mirror whose history diverged from the remote onto the remote
303
+ tip. A rewritten remote history leaves a mirror with commits the remote
304
+ no longer holds, and a fast-forward can never reach it again.
305
+
306
+ The old tip is kept under refs/mirror-backup/ first. A mixed reset then
307
+ moves HEAD and the index to the remote tip and writes no files. Every
308
+ tracked file that still differs from the remote is stashed, which puts the
309
+ remote content in its place and keeps the old content in the stash list.
310
+ Untracked files stay. A failure after the reset puts HEAD back on the old
311
+ tip, so the next run meets the same state and tries again.
312
+ #>
313
+ param(
314
+ [Parameter(Mandatory)]
315
+ [string]$LocalTip,
316
+ [Parameter(Mandatory)]
317
+ [string]$RemoteRef
318
+ )
319
+ $stagedResult = Invoke-Git -Arguments @('diff', '--cached', '--quiet')
320
+ if ($stagedResult.ExitCode -ne 0) {
321
+ Write-SyncLog -Level 'ERROR' -Message 'realign skipped: the index holds staged changes'
322
+ return $false
323
+ }
324
+ $backupRef = 'refs/mirror-backup/{0}-{1}' -f (Get-Date -Format 'yyyy-MM-dd'), $LocalTip.Substring(0, 12)
325
+ $backupResult = Invoke-Git -Arguments @('update-ref', $backupRef, $LocalTip)
326
+ if ($backupResult.ExitCode -ne 0) {
327
+ Write-SyncLog -Level 'ERROR' -Message "realign skipped: cannot keep the old tip under ${backupRef}: $($backupResult.Output)"
328
+ return $false
329
+ }
330
+ $resetResult = Invoke-Git -Arguments @('reset', '-q', $RemoteRef)
331
+ if ($resetResult.ExitCode -ne 0) {
332
+ Write-SyncLog -Level 'ERROR' -Message "realign skipped: mixed reset failed: $($resetResult.Output)"
333
+ return $false
334
+ }
335
+ $differResult = Invoke-Git -Arguments @('diff', '--name-only', '--no-renames', '-z')
336
+ $stashNote = 'every tracked file already matched'
337
+ $failure = if ($differResult.ExitCode -ne 0) { "cannot list the files that differ: $($differResult.Output)" }
338
+ if (-not $failure) {
339
+ $allDifferingPaths = @(Get-NulSeparatedPaths -Output $differResult.Output)
340
+ if ($allDifferingPaths.Count -gt 0) {
341
+ $realignStashMessage = 'mirror realign {0}: tree before moving {1} to {2}' -f (Get-Date -Format 'yyyy-MM-dd'), $LocalTip, $RemoteRef
342
+ $stashResult = Invoke-Git -Arguments @('stash', 'push', '-m', $realignStashMessage)
343
+ if ($stashResult.ExitCode -ne 0) {
344
+ $failure = "stashing $($allDifferingPaths.Count) differing file(s) failed: $($stashResult.Output)"
345
+ }
346
+ else {
347
+ $stashNote = "$($allDifferingPaths.Count) differing file(s) are stashed as '$realignStashMessage'"
348
+ }
349
+ }
350
+ }
351
+ if ($failure) {
352
+ $revertResult = Invoke-Git -Arguments @('reset', '-q', $LocalTip)
353
+ $revertNote = if ($revertResult.ExitCode -eq 0) { "HEAD is back at $LocalTip" } else { "putting HEAD back at $LocalTip also failed: $($revertResult.Output)" }
354
+ Write-SyncLog -Level 'ERROR' -Message "realign failed, $failure; $revertNote"
355
+ return $false
356
+ }
357
+ Write-SyncLog -Level 'MIRROR' -Message "realigned onto ${RemoteRef}: old tip $LocalTip is kept as $backupRef; $stashNote"
358
+ return $true
359
+ }
360
+
287
361
  function Get-RunLockName {
288
362
  $lockPath = [System.IO.Path]::TrimEndingDirectorySeparator([System.IO.Path]::GetFullPath($RepoPath))
289
363
  $resolveLinkTarget = [System.IO.Directory].GetMethod('ResolveLinkTarget', [type[]]([string], [bool]))
@@ -361,8 +435,17 @@ try {
361
435
  $ancestorResult = Invoke-Git -Arguments @('merge-base', '--is-ancestor', $Branch, "$Remote/$Branch")
362
436
  if ($ancestorResult.ExitCode -ne 0) {
363
437
  $countResult = Invoke-Git -Arguments @('rev-list', '--left-right', '--count', "${Branch}...${Remote}/${Branch}")
364
- Write-SyncLog -Level 'ERROR' -Message "diverged from $Remote/$Branch (counts=$($countResult.Output)); fast-forward refused. local=$localTip remote=$remoteTip"
365
- exit 4
438
+ if (-not $Mirror) {
439
+ Write-SyncLog -Level 'ERROR' -Message "diverged from $Remote/$Branch (counts=$($countResult.Output)); fast-forward refused. local=$localTip remote=$remoteTip"
440
+ exit 4
441
+ }
442
+ Write-SyncLog -Level 'MIRROR' -Message "diverged from $Remote/$Branch (counts=$($countResult.Output)); realigning the mirror. local=$localTip remote=$remoteTip"
443
+ if (-not (Invoke-MirrorRealign -LocalTip $localTip -RemoteRef "$Remote/$Branch")) {
444
+ exit 1
445
+ }
446
+ $subject = Get-GitDecoration -Arguments @('log', '-1', '--format=%h %s') -Placeholder '<subject unavailable>'
447
+ Write-SyncLog -Level 'OK' -Message "$Branch $localTip -> $remoteTip realigned | $subject"
448
+ exit 0
366
449
  }
367
450
 
368
451
  $didStash = $false
@@ -86,6 +86,23 @@ BeforeAll {
86
86
  Invoke-TestGit -RepoPath $Fixture.MirrorPath -Arguments @('commit', '-q', '-am', 'feature edit') | Out-Null
87
87
  return Invoke-TestGit -RepoPath $Fixture.MirrorPath -Arguments @('rev-parse', 'HEAD')
88
88
  }
89
+
90
+ function New-MirrorDivergedFromRemote {
91
+ <#
92
+ Builds the mirror from New-MirrorBehindRemote, then commits local-only.txt
93
+ on the mirror's main. The mirror then holds a commit the remote lacks and
94
+ misses the remote's newer commit, the way a mirror looks after the remote
95
+ history was rewritten.
96
+ #>
97
+ param([string]$Name)
98
+ $fixture = New-MirrorBehindRemote -Name $Name
99
+ Write-TestFile -RepoPath $fixture.MirrorPath -RelativePath 'local-only.txt' -Content "local commit`n"
100
+ Invoke-TestGit -RepoPath $fixture.MirrorPath -Arguments @('add', '-A') | Out-Null
101
+ Invoke-TestGit -RepoPath $fixture.MirrorPath -Arguments @('commit', '-q', '-m', 'local only') | Out-Null
102
+ $localTip = Invoke-TestGit -RepoPath $fixture.MirrorPath -Arguments @('rev-parse', 'HEAD')
103
+ $fixture | Add-Member -NotePropertyName LocalTip -NotePropertyValue $localTip
104
+ return $fixture
105
+ }
89
106
  }
90
107
 
91
108
  Describe 'Sync-RepoMain' {
@@ -149,6 +166,44 @@ Describe 'Sync-RepoMain' {
149
166
  [System.IO.File]::ReadAllText((Join-Path $fixture.MirrorPath 'tracked.txt')) | Should -Be "new`n"
150
167
  }
151
168
 
169
+ It 'refuses a diverged tree with exit 4 when -Mirror is absent' {
170
+ $fixture = New-MirrorDivergedFromRemote -Name 'diverged-no-mirror'
171
+
172
+ $exitCode = Invoke-SyncScript -Fixture $fixture
173
+
174
+ $exitCode | Should -Be 4
175
+ (Invoke-TestGit -RepoPath $fixture.MirrorPath -Arguments @('rev-parse', 'HEAD')) | Should -Be $fixture.LocalTip
176
+ }
177
+
178
+ It 'realigns a diverged mirror onto the remote tip and stashes a tracked file that differs' {
179
+ $fixture = New-MirrorDivergedFromRemote -Name 'diverged-mirror'
180
+ Write-TestFile -RepoPath $fixture.MirrorPath -RelativePath 'tracked.txt' -Content "local edit`n"
181
+ $backupRef = 'refs/mirror-backup/{0}-{1}' -f (Get-Date -Format 'yyyy-MM-dd'), $fixture.LocalTip.Substring(0, 12)
182
+
183
+ $exitCode = Invoke-MirrorSyncScript -Fixture $fixture
184
+
185
+ $exitCode | Should -Be 0
186
+ (Invoke-TestGit -RepoPath $fixture.MirrorPath -Arguments @('rev-parse', 'HEAD')) | Should -Be $fixture.RemoteTip
187
+ [System.IO.File]::ReadAllText((Join-Path $fixture.MirrorPath 'tracked.txt')) | Should -Be "new`n"
188
+ [System.IO.File]::ReadAllText((Join-Path $fixture.MirrorPath 'added.txt')) | Should -Be "added`n"
189
+ [System.IO.File]::ReadAllText((Join-Path $fixture.MirrorPath 'local-only.txt')) | Should -Be "local commit`n"
190
+ (Invoke-TestGit -RepoPath $fixture.MirrorPath -Arguments @('rev-parse', $backupRef)) | Should -Be $fixture.LocalTip
191
+ (Invoke-TestGit -RepoPath $fixture.MirrorPath -Arguments @('stash', 'list')) | Should -Match 'mirror realign'
192
+ (Invoke-TestGit -RepoPath $fixture.MirrorPath -Arguments @('show', 'stash@{0}:tracked.txt')) | Should -Be 'local edit'
193
+ }
194
+
195
+ It 'keeps the old tip when the index holds staged changes during a realign' {
196
+ $fixture = New-MirrorDivergedFromRemote -Name 'diverged-staged'
197
+ Write-TestFile -RepoPath $fixture.MirrorPath -RelativePath 'tracked.txt' -Content "staged edit`n"
198
+ Invoke-TestGit -RepoPath $fixture.MirrorPath -Arguments @('add', 'tracked.txt') | Out-Null
199
+
200
+ $exitCode = Invoke-MirrorSyncScript -Fixture $fixture
201
+
202
+ $exitCode | Should -Be 1
203
+ (Invoke-TestGit -RepoPath $fixture.MirrorPath -Arguments @('rev-parse', 'HEAD')) | Should -Be $fixture.LocalTip
204
+ (Get-Content -LiteralPath $fixture.LogPath -Raw) | Should -Match 'realign skipped: the index holds staged changes'
205
+ }
206
+
152
207
  It 'skips without fetching while another sync of the same repo holds the run lock' {
153
208
  $fixture = New-MirrorBehindRemote -Name 'lock-held'
154
209
  $lockPath = [System.IO.Path]::TrimEndingDirectorySeparator([System.IO.Path]::GetFullPath($fixture.MirrorPath))
@@ -11,6 +11,7 @@ _PWSH = shutil.which("pwsh") or "pwsh"
11
11
  _SKIPPED_EXIT_CODE = 3
12
12
  _SUCCESS_EXIT_CODE = 0
13
13
  _FAILURE_EXIT_CODE = 1
14
+ _DIVERGED_EXIT_CODE = 4
14
15
 
15
16
 
16
17
  def _git(repository_path: Path, *arguments: str) -> str:
@@ -74,6 +75,21 @@ def _mirror_on_feature_branch_behind_remote(
74
75
  return mirror_path, feature_tip, remote_tip
75
76
 
76
77
 
78
+ def _mirror_diverged_from_remote(root_path: Path) -> tuple[Path, str, str]:
79
+ mirror_path, _, _ = _mirror_on_feature_branch_behind_remote(
80
+ root_path, should_advance_remote=False
81
+ )
82
+ _git(mirror_path, "switch", "-q", "main")
83
+ (mirror_path / "tracked.txt").write_text("local\n", encoding="utf-8")
84
+ _git(mirror_path, "commit", "-q", "-am", "local only edit")
85
+ local_tip = _git(mirror_path, "rev-parse", "HEAD")
86
+ author_path = root_path / "author"
87
+ (author_path / "tracked.txt").write_text("new\n", encoding="utf-8")
88
+ _git(author_path, "commit", "-q", "-am", "second")
89
+ _git(author_path, "push", "-q", "origin", "main")
90
+ return mirror_path, local_tip, _git(author_path, "rev-parse", "HEAD")
91
+
92
+
77
93
  def _run_sync(mirror_path: Path, log_path: Path, *switches: str) -> int:
78
94
  completed = subprocess.run(
79
95
  [
@@ -224,3 +240,47 @@ def test_should_skip_a_checkout_with_staged_changes(tmp_path: Path) -> None:
224
240
  assert _git(mirror_path, "branch", "--show-current") == "feature"
225
241
  assert _git(mirror_path, "rev-parse", "HEAD") == feature_tip
226
242
  assert _git(mirror_path, "diff", "--cached", "--name-only") == "tracked.txt"
243
+
244
+
245
+ def test_should_exit_diverged_without_mirror(tmp_path: Path) -> None:
246
+ mirror_path, local_tip, _ = _mirror_diverged_from_remote(tmp_path)
247
+ log_path = tmp_path / "sync.log"
248
+
249
+ assert _run_sync(mirror_path, log_path, "-StashDirty") == _DIVERGED_EXIT_CODE
250
+ assert _git(mirror_path, "rev-parse", "HEAD") == local_tip
251
+ assert _git(mirror_path, "for-each-ref", "refs/mirror-backup") == ""
252
+
253
+
254
+ def test_should_realign_a_diverged_mirror_onto_the_remote(tmp_path: Path) -> None:
255
+ mirror_path, local_tip, remote_tip = _mirror_diverged_from_remote(tmp_path)
256
+ log_path = tmp_path / "sync.log"
257
+
258
+ assert (
259
+ _run_sync(mirror_path, log_path, "-StashDirty", "-Mirror")
260
+ == _SUCCESS_EXIT_CODE
261
+ )
262
+ assert _git(mirror_path, "rev-parse", "HEAD") == remote_tip
263
+ assert (mirror_path / "tracked.txt").read_text(encoding="utf-8") == "new\n"
264
+ assert _git(mirror_path, "status", "--porcelain") == ""
265
+ assert (
266
+ _git(mirror_path, "for-each-ref", "refs/mirror-backup", "--format=%(objectname)")
267
+ == local_tip
268
+ )
269
+ assert f"tree before moving {local_tip}" in _git(mirror_path, "stash", "list")
270
+ assert "realigning the mirror" in log_path.read_text(encoding="utf-8")
271
+
272
+
273
+ def test_should_skip_a_diverged_mirror_with_tracked_changes_without_stash_dirty(
274
+ tmp_path: Path,
275
+ ) -> None:
276
+ mirror_path, local_tip, _ = _mirror_diverged_from_remote(tmp_path)
277
+ (mirror_path / "tracked.txt").write_text("staged\n", encoding="utf-8")
278
+ _git(mirror_path, "add", "tracked.txt")
279
+ log_path = tmp_path / "sync.log"
280
+
281
+ assert _run_sync(mirror_path, log_path, "-Mirror") == _SKIPPED_EXIT_CODE
282
+ assert _git(mirror_path, "rev-parse", "HEAD") == local_tip
283
+ assert _git(mirror_path, "for-each-ref", "refs/mirror-backup") == ""
284
+ assert "tracked changes present; refusing sync" in log_path.read_text(
285
+ encoding="utf-8"
286
+ )