@@ -112,6 +112,41 @@ const MAX_EPISODE_MESSAGES: usize = 512;
112112/// boundary rotation always wins for multi-turn episodes.
113113const FORCE_ROTATE_MESSAGES : usize = MAX_EPISODE_MESSAGES * 2 ;
114114
115+ /// How a transcript record supplied its turn-initiating text. Verbatim text
116+ /// can use the ledger's ordinary prefix match; a slash command reconstructed
117+ /// from tags needs the narrower command-separator normalization below.
118+ #[ derive( Debug , PartialEq , Eq ) ]
119+ enum TurnInitiatorText {
120+ Verbatim ( String ) ,
121+ ReconstructedSlashCommand ( String ) ,
122+ }
123+
124+ impl TurnInitiatorText {
125+ fn as_str ( & self ) -> & str {
126+ match self {
127+ Self :: Verbatim ( text) | Self :: ReconstructedSlashCommand ( text) => text,
128+ }
129+ }
130+ }
131+
132+ /// Reproduce the one lossy transformation made by [`slash_command_display`]:
133+ /// whitespace separating the command name from its arguments becomes one
134+ /// space. Whitespace *inside* the arguments remains byte-for-byte significant.
135+ fn reconstructed_slash_command_fingerprint ( text : & str ) -> Option < String > {
136+ let text = text. trim ( ) ;
137+ let name_end = text. find ( char:: is_whitespace) . unwrap_or ( text. len ( ) ) ;
138+ let name = & text[ ..name_end] ;
139+ if !name. starts_with ( '/' ) {
140+ return None ;
141+ }
142+ let args = text[ name_end..] . trim ( ) ;
143+ if args. is_empty ( ) {
144+ Some ( name. to_string ( ) )
145+ } else {
146+ Some ( format ! ( "{name} {args}" ) )
147+ }
148+ }
149+
115150/// Fingerprints of prompts codeg itself sent on this connection, so the
116151/// watcher can tell wire-rendered foreground turns apart from out-of-turn
117152/// activity. Shared between the connection loop (writer, on every
@@ -165,31 +200,45 @@ impl PromptLedger {
165200 /// Match `initiator_text` (the transcript turn's initiating user text)
166201 /// against the unconsumed fingerprints; on match the entry is consumed —
167202 /// exactly once per sent prompt, so a later same-text autonomous re-fire
168- /// finds no entry and classifies as out-of-turn. The record may carry
169- /// appended wrapper content after the sent text, hence prefix matching.
170- fn consume_matching ( & self , initiator_text : & str ) -> bool {
171- let text = initiator_text. trim ( ) ;
203+ /// finds no entry and classifies as out-of-turn. A verbatim record may
204+ /// carry appended wrapper content after the sent text, hence its prefix
205+ /// matching fallback.
206+ ///
207+ /// A slash command's initiator text is RECONSTRUCTED rather than read back:
208+ /// the CLI persists the invocation as command tags, and
209+ /// [`slash_command_display`] rebuilds it as `"/name" + ' ' + trimmed args`.
210+ /// For that record type only, reproduce the same separator normalization on
211+ /// the fingerprint. Normalizing every whitespace run would conflate
212+ /// semantically different ordinary prompts and command arguments, risking
213+ /// suppression of a genuine out-of-turn turn.
214+ fn consume_matching ( & self , initiator : & TurnInitiatorText ) -> bool {
215+ let text = initiator. as_str ( ) . trim ( ) ;
172216 if text. is_empty ( ) {
173217 return false ;
174218 }
175219 let mut entries = self . entries . lock ( ) . unwrap_or_else ( |p| p. into_inner ( ) ) ;
176220 entries. retain ( |e| e. recorded_at . elapsed ( ) < LEDGER_TTL ) ;
177- if let Some ( pos) = entries
178- . iter ( )
179- . position ( |e| text == e. fingerprint || text. starts_with ( e. fingerprint . as_str ( ) ) )
180- {
221+ if let Some ( pos) = entries. iter ( ) . position ( |e| match initiator {
222+ TurnInitiatorText :: Verbatim ( _) => {
223+ text == e. fingerprint || text. starts_with ( e. fingerprint . as_str ( ) )
224+ }
225+ TurnInitiatorText :: ReconstructedSlashCommand ( _) => {
226+ text == e. fingerprint
227+ || reconstructed_slash_command_fingerprint ( & e. fingerprint ) . as_deref ( )
228+ == Some ( text)
229+ }
230+ } ) {
181231 entries. remove ( pos) ;
182232 return true ;
183233 }
184234 false
185235 }
186236
187- /// Fingerprint a bare string. Used for `_session/steering` injections,
188- /// which reach the agent outside `session/prompt` yet still land in the
189- /// transcript as a user record that [`group_into_turns`] reads as the
190- /// start of a turn — one the wire is already rendering, so it must
191- /// classify foreground like any prompt (see the `Steer` arm in
192- /// `connection.rs`).
237+ /// Fingerprint a bare string — test convenience over
238+ /// [`Self::record_prompt_blocks`]. (The `_session/steering` arm in
239+ /// `connection.rs` used to be the production caller; it now records the
240+ /// steered blocks directly, since a steered draft can carry attachments.)
241+ #[ cfg( test) ]
193242 pub ( crate ) fn record_text ( & self , text : & str ) {
194243 self . record_prompt_blocks ( & [ crate :: acp:: types:: PromptInputBlock :: Text {
195244 text : text. to_string ( ) ,
@@ -1141,8 +1190,9 @@ impl WatchState {
11411190 self . foreground_awaiting_reply = false ;
11421191 }
11431192
1144- if let Some ( initiator_text) = turn_initiator_text ( value) {
1145- if ledger. consume_matching ( & initiator_text) {
1193+ if let Some ( initiator) = turn_initiator_text ( value) {
1194+ let initiator_text = initiator. as_str ( ) ;
1195+ if ledger. consume_matching ( & initiator) {
11461196 // A codeg-sent prompt: the wire renders this turn. Close any
11471197 // open episode first (flush its final state) and go silent.
11481198 tracing:: debug!( "[bg-watch] foreground turn matched ledger" ) ;
@@ -1161,7 +1211,7 @@ impl WatchState {
11611211 if self . foreground_awaiting_reply
11621212 && self . foreground_submission_id . is_some ( )
11631213 && record_submission_id ( value) == self . foreground_submission_id
1164- && task_notification_origin_id ( & initiator_text) . is_none ( )
1214+ && task_notification_origin_id ( initiator_text) . is_none ( )
11651215 {
11661216 // Still inside the matched prompt's own submission — command
11671217 // output, the instruction `/goal` injects, image metadata. None
@@ -1193,7 +1243,7 @@ impl WatchState {
11931243 self . file . clone ( ) . unwrap_or_else ( || PathBuf :: from ( "" ) ) ,
11941244 ) ,
11951245 emitted_hashes : HashMap :: new ( ) ,
1196- origin_task_id : task_notification_origin_id ( & initiator_text) ,
1246+ origin_task_id : task_notification_origin_id ( initiator_text) ,
11971247 } ) ;
11981248 }
11991249 self . mode = Mode :: Background ;
@@ -1315,7 +1365,7 @@ fn user_record_text(value: &serde_json::Value) -> Option<String> {
13151365/// still rendering it — never a boundary;
13161366/// * everything else user-typed/injected (real prompts, `<task-notification>`
13171367/// records, cron prompts) initiates.
1318- fn turn_initiator_text ( value : & serde_json:: Value ) -> Option < String > {
1368+ fn turn_initiator_text ( value : & serde_json:: Value ) -> Option < TurnInitiatorText > {
13191369 if value. get ( "type" ) . and_then ( |t| t. as_str ( ) ) != Some ( "user" ) {
13201370 return None ;
13211371 }
@@ -1328,9 +1378,9 @@ fn turn_initiator_text(value: &serde_json::Value) -> Option<String> {
13281378 // A slash command persists as command tags; codeg sent the display
13291379 // form ("/name args"), so match the ledger against that.
13301380 if let Some ( display) = slash_command_display ( s) {
1331- return Some ( display) ;
1381+ return Some ( TurnInitiatorText :: ReconstructedSlashCommand ( display) ) ;
13321382 }
1333- return Some ( s. to_string ( ) ) ;
1383+ return Some ( TurnInitiatorText :: Verbatim ( s. to_string ( ) ) ) ;
13341384 }
13351385
13361386 let arr = content. as_array ( ) ?;
@@ -1348,7 +1398,7 @@ fn turn_initiator_text(value: &serde_json::Value) -> Option<String> {
13481398 if text. starts_with ( CONTEXT_CONTINUATION_PREFIX ) {
13491399 return None ;
13501400 }
1351- Some ( text)
1401+ Some ( TurnInitiatorText :: Verbatim ( text) )
13521402}
13531403
13541404/// The submission a record belongs to. Claude Code stamps every user record it
@@ -1953,6 +2003,85 @@ mod tests {
19532003 ) ;
19542004 }
19552005
2006+ /// The command record is the only one the ledger can match, and its
2007+ /// initiator text is REBUILT from command tags — `slash_command_display`
2008+ /// joins the name and the trimmed args with a single space, whatever the
2009+ /// sender typed. The composer inserts a space after a command badge, so a
2010+ /// sender who types their own lands two, and the rebuilt text no longer
2011+ /// starts with the fingerprint. That miss leaves the submission window
2012+ /// unarmed and every following side record classifies out-of-turn, which
2013+ /// is the same duplicated `/goal` turn as above by a different route.
2014+ #[ test]
2015+ fn a_command_matches_the_ledger_despite_a_rebuilt_separator ( ) {
2016+ let dir = tempfile:: tempdir ( ) . unwrap ( ) ;
2017+ let path = temp_session ( & dir) ;
2018+ let ledger = PromptLedger :: shared ( ) ;
2019+ // As SENT: two spaces after the command badge.
2020+ ledger. record_text ( "/goal build a test page" ) ;
2021+
2022+ let mut ws = WatchState :: new ( ) ;
2023+ ws. session_id = Some ( "s1" . into ( ) ) ;
2024+ ws. epoch = Some ( epoch ( "2020-01-01T00:00:00Z" ) ) ;
2025+ ws. adopt_file ( path. clone ( ) ) ;
2026+
2027+ // As PERSISTED: the CLI trims the args, so the display form rebuilds
2028+ // with one space.
2029+ let command = r#"{"type":"user","timestamp":"2026-07-07T03:50:00.000Z","uuid":"u-cmd","promptId":"p1","message":{"role":"user","content":"<command-name>/goal</command-name>\n<command-args>build a test page</command-args>"}}"# ;
2030+ let hook = r#"{"type":"user","timestamp":"2026-07-07T03:50:00.200Z","uuid":"u-hook","promptId":"p1","isMeta":true,"userType":"external","message":{"role":"user","content":"A session-scoped Stop hook is now active with condition: build a test page."}}"# ;
2031+ write_lines ( & path, & [ command, hook, & assistant_text ( "a1" , "On it." ) ] ) ;
2032+ let event = tick_prompting ( & mut ws, & ledger) ;
2033+ assert ! (
2034+ event. is_none( ) || unpack( event. unwrap( ) ) . 0 . is_empty( ) ,
2035+ "the wire renders this turn — a rebuilt separator must not turn it \
2036+ into an overlay copy"
2037+ ) ;
2038+ }
2039+
2040+ #[ test]
2041+ fn ledger_normalizes_only_a_reconstructed_command_separator ( ) {
2042+ let ledger = PromptLedger :: shared ( ) ;
2043+ ledger. record_text ( "/goal build a test page" ) ;
2044+ assert ! (
2045+ !ledger. consume_matching( & TurnInitiatorText :: ReconstructedSlashCommand (
2046+ "/goal build a test page" . into( )
2047+ ) ) ,
2048+ "whitespace inside the arguments remains significant"
2049+ ) ;
2050+ assert ! (
2051+ ledger. consume_matching( & TurnInitiatorText :: ReconstructedSlashCommand (
2052+ "/goal build a test page" . into( )
2053+ ) )
2054+ ) ;
2055+ assert ! (
2056+ !ledger. consume_matching( & TurnInitiatorText :: ReconstructedSlashCommand (
2057+ "/goal build a test page" . into( )
2058+ ) ) ,
2059+ "a reconstructed match consumes the entry exactly once"
2060+ ) ;
2061+
2062+ let ledger = PromptLedger :: shared ( ) ;
2063+ ledger. record_text ( "build a test page" ) ;
2064+ assert ! (
2065+ !ledger. consume_matching( & TurnInitiatorText :: Verbatim ( "build a test page" . into( ) ) ) ,
2066+ "ordinary prompt whitespace must remain byte-for-byte significant"
2067+ ) ;
2068+ assert ! ( ledger. consume_matching( & TurnInitiatorText :: Verbatim ( "build a test page" . into( ) ) ) ) ;
2069+
2070+ let ledger = PromptLedger :: shared ( ) ;
2071+ ledger. record_text ( "/goal build" ) ;
2072+ assert ! (
2073+ !ledger. consume_matching( & TurnInitiatorText :: ReconstructedSlashCommand (
2074+ "/goal builder" . into( )
2075+ ) ) ,
2076+ "reconstructed command arguments do not use the verbatim prefix fallback"
2077+ ) ;
2078+ assert ! (
2079+ ledger. consume_matching( & TurnInitiatorText :: ReconstructedSlashCommand (
2080+ "/goal build" . into( )
2081+ ) )
2082+ ) ;
2083+ }
2084+
19562085 /// The window is scoped by SUBMISSION, not by time: an autonomous prompt
19572086 /// that lands in the same interval — after the ledger match, before the
19582087 /// model's first record — carries a different `promptId` and must still
@@ -2748,9 +2877,11 @@ mod tests {
27482877 fn ledger_prefix_matches_and_consumes_once ( ) {
27492878 let ledger = PromptLedger :: shared ( ) ;
27502879 ledger. record_text ( "deploy the app" ) ;
2751- assert ! ( ledger. consume_matching( "deploy the app\n <system-hint>extra</system-hint>" ) ) ;
2880+ assert ! ( ledger. consume_matching( & TurnInitiatorText :: Verbatim (
2881+ "deploy the app\n <system-hint>extra</system-hint>" . into( )
2882+ ) ) ) ;
27522883 assert ! (
2753- !ledger. consume_matching( "deploy the app" ) ,
2884+ !ledger. consume_matching( & TurnInitiatorText :: Verbatim ( "deploy the app" . into ( ) ) ) ,
27542885 "an entry is consumed exactly once"
27552886 ) ;
27562887 }
@@ -2766,11 +2897,15 @@ mod tests {
27662897 serde_json:: from_str ( & notification ( "x" , "completed" ) ) . unwrap ( ) ;
27672898 assert ! ( turn_initiator_text( & note)
27682899 . unwrap( )
2900+ . as_str( )
27692901 . starts_with( "<task-notification>" ) ) ;
27702902
27712903 // cron prompt (isMeta + string): initiates with the prompt text.
27722904 let cron: serde_json:: Value = serde_json:: from_str ( & cron_prompt ( "check weather" ) ) . unwrap ( ) ;
2773- assert_eq ! ( turn_initiator_text( & cron) . as_deref( ) , Some ( "check weather" ) ) ;
2905+ assert_eq ! (
2906+ turn_initiator_text( & cron) . as_ref( ) . map( |text| text. as_str( ) ) ,
2907+ Some ( "check weather" )
2908+ ) ;
27742909
27752910 // context-continuation summary: never a boundary.
27762911 let cont = format ! (
@@ -2783,7 +2918,12 @@ mod tests {
27832918 // slash command record matches via its display form.
27842919 let cmd = r#"{"type":"user","uuid":"u-cmd","message":{"role":"user","content":"<command-name>/init</command-name><command-args>now</command-args>"}}"# ;
27852920 let cmd: serde_json:: Value = serde_json:: from_str ( cmd) . unwrap ( ) ;
2786- assert_eq ! ( turn_initiator_text( & cmd) . as_deref( ) , Some ( "/init now" ) ) ;
2921+ assert_eq ! (
2922+ turn_initiator_text( & cmd) ,
2923+ Some ( TurnInitiatorText :: ReconstructedSlashCommand (
2924+ "/init now" . into( )
2925+ ) )
2926+ ) ;
27872927 }
27882928
27892929 /// The whole point of reading titles here: Claude Code's background
0 commit comments