Skip to main content

mj_transcript/
turn_context.rs

1//! Process-local classification evidence using the shared transcript summary.
2use agent_client_protocol::v1::schema::{ContentBlock, SessionUpdate};
3use mj_core::activity::ActivityFacts;
4use mj_core::activity::verdict::*;
5use mj_core::config::HarnessKind;
6use std::sync::{Arc, Mutex};
7
8#[derive(Debug, Default)]
9struct TurnContextState {
10    generation: u64,
11    parent_activity: Option<std::time::Instant>,
12    decision_log: Option<mj_core::jev::DecisionLog>,
13    authorization: Option<mj_core::assessment::ContextHistory>,
14    user_prompt_tail: Option<String>,
15    message_id: Option<String>,
16    assistant_text_tail: String,
17    last_completed_message: String,
18    summary: crate::summary::TranscriptSummary,
19    background_commands: usize,
20    queued_commands: usize,
21    background_inventory: Vec<mj_core::relay::BackgroundCommand>,
22    native_agent_ids: Vec<String>,
23    session_id: String,
24}
25
26/// The prompt that became visible to the harness at this durable observation.
27/// A queued or unconfirmed steering prompt has not been delivered yet.
28pub fn delivered_prompt_command_id(observation: &mj_core::relay::RelayObservation) -> Option<&str> {
29    use mj_core::relay::{RelayCommandOutcome, RelayObservation};
30    match observation {
31        RelayObservation::CommandStarted { command_id, .. } => Some(command_id),
32        RelayObservation::CommandCompleted {
33            outcome: RelayCommandOutcome::Steered { queued_command_id },
34            ..
35        } => Some(queued_command_id),
36        RelayObservation::MailboxEventsDelivered {
37            steering: Some(steering),
38            ..
39        } => Some(&steering.queued_prompt_id),
40        _ => None,
41    }
42}
43
44/// The relay and runtime share this small process-local evidence accumulator.
45#[derive(Debug, Default, Clone)]
46pub struct TurnContext(Arc<Mutex<TurnContextState>>);
47
48impl TurnContext {
49    /// Process-local parent clock; child traffic and inventory updates never mark it.
50    pub fn mark_parent_activity(&self) {
51        self.mark_parent_activity_at(std::time::Instant::now());
52    }
53
54    /// Record the monotonic time at which parent activity was observed.
55    pub fn mark_parent_activity_at(&self, at: std::time::Instant) {
56        self.0
57            .lock()
58            .expect("turn context lock poisoned")
59            .parent_activity = Some(at);
60    }
61
62    pub fn parent_activity(&self) -> Option<std::time::Instant> {
63        self.0
64            .lock()
65            .expect("turn context lock poisoned")
66            .parent_activity
67    }
68
69    pub fn set_decision_log(&self, log: mj_core::jev::DecisionLog) {
70        self.0
71            .lock()
72            .expect("turn context lock poisoned")
73            .decision_log = Some(log);
74    }
75    pub fn decision_log(&self) -> Option<mj_core::jev::DecisionLog> {
76        self.0
77            .lock()
78            .expect("turn context lock poisoned")
79            .decision_log
80            .clone()
81    }
82    /// Start a turn. `user_prompt_tail` carries the prompt only when the
83    /// person wrote it: a prompt Mjolnir submitted (a mailbox wake, a child
84    /// report, a continuation, a parent's message to a child) is not the
85    /// person's latest request, and Jev scored those turns better without it
86    /// (.agents/docs/jev-still-open-20261106.md).
87    pub fn reset(&self, command_id: Option<&str>, prompt: &str) {
88        self.reset_request(command_id, prompt);
89    }
90
91    /// Returns whether this delivery establishes a request in the context.
92    fn reset_request(&self, command_id: Option<&str>, prompt: &str) -> bool {
93        let recovery = command_id.is_some_and(mj_core::continuation::is_restart_continuation);
94        let user_prompt_tail =
95            if recovery || mj_core::continuation::is_user_authored_message(command_id, prompt) {
96                tail(prompt, USER_PROMPT_BYTES)
97            } else {
98                String::new()
99            };
100        let mut state = self.0.lock().expect("turn context lock poisoned");
101        let generation = state.generation.wrapping_add(1);
102        if recovery {
103            if state.user_prompt_tail.is_none() {
104                state.user_prompt_tail = Some(user_prompt_tail);
105                // The carried request precedes the retained replay suffix.
106                // Preserve that suffix and its partially observed answer.
107                state.summary.push_user(prompt);
108                state.summary.entries.rotate_right(1);
109            }
110            // Recovery continues the same request and partial answer. Advance
111            // generation to reject stale classifier replies without erasing
112            // the latest user correction or the evidence from before restart.
113            state.generation = generation;
114            state.parent_activity = Some(std::time::Instant::now());
115            return false;
116        }
117        *state = TurnContextState {
118            generation,
119            parent_activity: Some(std::time::Instant::now()),
120            decision_log: state.decision_log.clone(),
121            authorization: state.authorization.clone(),
122            user_prompt_tail: Some(user_prompt_tail),
123            background_commands: state.background_commands,
124            queued_commands: state.queued_commands,
125            background_inventory: std::mem::take(&mut state.background_inventory),
126            native_agent_ids: std::mem::take(&mut state.native_agent_ids),
127            session_id: std::mem::take(&mut state.session_id),
128            summary: std::mem::take(&mut state.summary),
129            ..Default::default()
130        };
131        true
132    }
133
134    /// Record durable transcript observations through the same path during live work and replay.
135    pub fn observe_relay(
136        &self,
137        observation: &mj_core::relay::RelayObservation,
138        prompt: Option<&str>,
139    ) {
140        use mj_core::relay::{RelayCommandOutcome, RelayObservation};
141        match observation {
142            RelayObservation::CommandStarted { .. }
143            | RelayObservation::CommandCompleted {
144                outcome: RelayCommandOutcome::Steered { .. },
145                ..
146            }
147            | RelayObservation::MailboxEventsDelivered {
148                steering: Some(_), ..
149            } => {
150                if let Some(prompt) = prompt
151                    && self.reset_request(delivered_prompt_command_id(observation), prompt)
152                {
153                    self.0
154                        .lock()
155                        .expect("turn context lock poisoned")
156                        .summary
157                        .push_user(prompt);
158                }
159            }
160            RelayObservation::SessionUpdate { update } => self.observe(update),
161            RelayObservation::TerminalOutput {
162                terminal_id,
163                output,
164                truncated,
165                exit_code,
166                signal,
167            } => {
168                self.observe_terminal(&mj_core::transcript::TerminalOutputRecord {
169                    terminal_id: terminal_id.clone(),
170                    output: output.clone().into(),
171                    truncated: *truncated,
172                    exit_code: *exit_code,
173                    signal: signal.clone(),
174                });
175            }
176            RelayObservation::CommandCompleted {
177                outcome: RelayCommandOutcome::ContextCleared { .. },
178                ..
179            } => self.clear_history(),
180            _ => {}
181        }
182    }
183
184    /// Invalidate a pending verdict at a lifecycle boundary without discarding evidence.
185    pub fn invalidate(&self) {
186        let mut state = self.0.lock().expect("turn context lock poisoned");
187        state.generation = state.generation.wrapping_add(1);
188    }
189
190    pub fn generation(&self) -> u64 {
191        self.0
192            .lock()
193            .expect("turn context lock poisoned")
194            .generation
195    }
196
197    pub fn counts(&self) -> (usize, usize) {
198        let state = self.0.lock().expect("turn context lock poisoned");
199        (state.background_commands, state.queued_commands)
200    }
201
202    pub fn set_counts(&self, background_commands: usize, queued_commands: usize) {
203        let mut state = self.0.lock().expect("turn context lock poisoned");
204        if (state.background_commands, state.queued_commands)
205            != (background_commands, queued_commands)
206        {
207            state.generation = state.generation.wrapping_add(1);
208            state.background_commands = background_commands;
209            state.queued_commands = queued_commands;
210        }
211    }
212
213    pub fn set_session_id(&self, session_id: &str) {
214        self.0
215            .lock()
216            .expect("turn context lock poisoned")
217            .session_id = session_id.into();
218    }
219
220    pub fn session_id(&self) -> String {
221        self.0
222            .lock()
223            .expect("turn context lock poisoned")
224            .session_id
225            .clone()
226    }
227
228    /// Publish the relay owner's durable user-instruction history to the ACP
229    /// classifier. A change invalidates any request built from older context.
230    pub fn set_authorization_context(
231        &self,
232        authorization: Option<mj_core::assessment::ContextHistory>,
233    ) {
234        let mut state = self.0.lock().expect("turn context lock poisoned");
235        if state.authorization != authorization {
236            state.authorization = authorization;
237            state.generation = state.generation.wrapping_add(1);
238        }
239    }
240
241    pub fn authorization_context(&self) -> Option<mj_core::assessment::ContextHistory> {
242        self.0
243            .lock()
244            .expect("turn context lock poisoned")
245            .authorization
246            .clone()
247    }
248
249    /// Compare identities as well as counts; identical level reports are not activity.
250    pub fn set_background_inventory(
251        &self,
252        mut commands: Vec<mj_core::relay::BackgroundCommand>,
253        mut native_agent_ids: Vec<String>,
254    ) {
255        commands.sort_by(|a, b| a.id.cmp(&b.id));
256        native_agent_ids.sort();
257        let mut state = self.0.lock().expect("turn context lock poisoned");
258        if state.background_inventory != commands || state.native_agent_ids != native_agent_ids {
259            state.background_inventory = commands;
260            state.native_agent_ids = native_agent_ids;
261            state.generation = state.generation.wrapping_add(1);
262        }
263    }
264
265    pub fn observe(&self, update: &SessionUpdate) {
266        let mut state = self.0.lock().expect("turn context lock poisoned");
267        state.parent_activity = Some(std::time::Instant::now());
268        if matches!(
269            update,
270            SessionUpdate::AgentMessageChunk(_)
271                | SessionUpdate::AgentThoughtChunk(_)
272                | SessionUpdate::ToolCall(_)
273                | SessionUpdate::ToolCallUpdate(_)
274        ) {
275            state.generation = state.generation.wrapping_add(1);
276        }
277        state.summary.observe(update);
278        match update {
279            SessionUpdate::AgentMessageChunk(chunk) => {
280                let id = chunk.message_id.as_ref().map(ToString::to_string);
281                if id != state.message_id {
282                    complete_message(&mut state);
283                    state.message_id = id;
284                }
285                if let ContentBlock::Text(content) = &chunk.content {
286                    // Trim each chunk before appending, so a huge chunk never grows retained state.
287                    state
288                        .assistant_text_tail
289                        .push_str(&tail(&content.text, ASSISTANT_TEXT_BYTES));
290                    state.assistant_text_tail =
291                        tail(&state.assistant_text_tail, ASSISTANT_TEXT_BYTES);
292                }
293            }
294            SessionUpdate::ToolCall(_) => {
295                complete_message(&mut state);
296            }
297            SessionUpdate::ToolCallUpdate(_) | SessionUpdate::AgentThoughtChunk(_) => {
298                complete_message(&mut state)
299            }
300            _ => {}
301        }
302    }
303
304    pub fn observe_terminal(&self, record: &mj_core::transcript::TerminalOutputRecord) {
305        let mut state = self.0.lock().expect("turn context lock poisoned");
306        state.summary.observe_terminal(record);
307        state.generation = state.generation.wrapping_add(1);
308    }
309
310    pub fn mark_earlier_history_omitted(&self) {
311        self.0
312            .lock()
313            .expect("turn context lock poisoned")
314            .summary
315            .mark_earlier_history_omitted();
316    }
317
318    pub fn clear_history(&self) {
319        let mut state = self.0.lock().expect("turn context lock poisoned");
320        state.summary = Default::default();
321        state.user_prompt_tail = None;
322        state.assistant_text_tail.clear();
323        state.last_completed_message.clear();
324        state.message_id = None;
325        state.authorization = None;
326        state.generation = state.generation.wrapping_add(1);
327    }
328
329    pub fn evidence(
330        &self,
331        harness: HarnessKind,
332        phase: TurnPhase,
333        facts: &ActivityFacts,
334        now_ms: i64,
335    ) -> TurnEvidence {
336        let state = self.0.lock().expect("turn context lock poisoned");
337        let summary = state.summary.latest_user_messages();
338        let last_assistant = state
339            .summary
340            .entries
341            .iter()
342            .rposition(|e| e.role == crate::summary::SummaryRole::Assistant);
343        let final_tool_calls = state
344            .summary
345            .entries
346            .iter()
347            .skip(last_assistant.map_or(0, |i| i + 1))
348            .filter(|e| e.role == crate::summary::SummaryRole::Tool)
349            .take(IN_FLIGHT_TOOLS)
350            .map(|e| mj_core::activity::verdict::ToolOutcome {
351                name: tool_title(
352                    e.tool
353                        .as_ref()
354                        .and_then(|t| t.get("name"))
355                        .and_then(|n| n.as_str())
356                        .unwrap_or(&e.text),
357                ),
358                status: e
359                    .tool
360                    .as_ref()
361                    .and_then(|t| t.get("status"))
362                    .and_then(|s| s.as_str())
363                    .unwrap_or("unknown")
364                    .to_owned(),
365            })
366            .collect();
367        TurnEvidence {
368            authorization: None,
369            final_tool_calls,
370            background: Vec::new(),
371            harness,
372            phase,
373            silent_for_s: facts
374                .last_acp_activity_at_ms
375                .map_or(0, |last| now_ms.saturating_sub(last).max(0) as u64 / 1000),
376            tools_in_flight: facts
377                .tools_in_flight
378                .iter()
379                .take(IN_FLIGHT_TOOLS)
380                .map(|tool| ToolEvidence {
381                    title: tool_title(
382                        state
383                            .summary
384                            .entries
385                            .iter()
386                            .find(|e| e.id == tool.tool_call_id)
387                            .map_or("unknown tool", |e| e.text.as_str()),
388                    ),
389                    running_s: now_ms.saturating_sub(tool.started_at_ms).max(0) as u64 / 1000,
390                })
391                .collect(),
392            transcript_summary: summary.render(48 * 1024),
393            background_commands: facts.background_commands,
394            queued_commands: facts.queued_commands,
395            user_prompt_tail: state.user_prompt_tail.clone().unwrap_or_default(),
396            assistant_text_tail: if state.assistant_text_tail.is_empty() {
397                state.last_completed_message.clone()
398            } else {
399                state.assistant_text_tail.clone()
400            },
401            completion: None,
402        }
403    }
404}
405
406fn complete_message(state: &mut TurnContextState) {
407    if !state.assistant_text_tail.is_empty() {
408        state.last_completed_message = std::mem::take(&mut state.assistant_text_tail);
409    }
410    state.message_id = None;
411}
412
413/// The last `maximum_bytes` of `text`, cut at a character boundary: the tail
414/// every turn classifier receives.
415pub fn tail(text: &str, maximum_bytes: usize) -> String {
416    let start = text.floor_char_boundary(text.len().saturating_sub(maximum_bytes));
417    let mut value = text[start..].to_owned();
418    mj_core::transcript::truncate_string_start(&mut value, maximum_bytes);
419    value
420}
421
422#[cfg(test)]
423mod tests {
424    use super::*;
425    use mj_core::activity::InFlightToolCall;
426    use serde_json::json;
427    fn message(id: &str, text: &str) -> SessionUpdate {
428        serde_json::from_value(json!({"sessionUpdate":"agent_message_chunk","messageId":id,"content":{"type":"text","text":text}})).unwrap()
429    }
430
431    fn tool(title: &str) -> SessionUpdate {
432        serde_json::from_value(json!({"sessionUpdate":"tool_call","toolCallId":title,"title":title,"status":"in_progress"})).unwrap()
433    }
434
435    #[test]
436    fn diagnostic_logging_does_not_change_evidence_or_generation_and_survives_reset() {
437        let context = TurnContext::default();
438        context.reset(None, "Implement the parser");
439        let generation = context.generation();
440        let before = serde_json::to_value(context.evidence(
441            HarnessKind::Codex,
442            TurnPhase::Running,
443            &Default::default(),
444            0,
445        ))
446        .unwrap();
447        let dir = tempfile::tempdir().unwrap();
448        let log = mj_core::jev::DecisionLog::open(dir.path().into()).unwrap();
449        context.set_decision_log(log.clone());
450        let attempt = log.start("s", "activity", "Who acts?", "Current request");
451        attempt.finish("unchanged", "Kept runtime facts");
452        assert_eq!(context.generation(), generation);
453        assert_eq!(
454            serde_json::to_value(context.evidence(
455                HarnessKind::Codex,
456                TurnPhase::Running,
457                &Default::default(),
458                0
459            ))
460            .unwrap(),
461            before
462        );
463        context.reset(None, "New work");
464        assert!(context.decision_log().is_some());
465    }
466
467    #[test]
468    fn verdict_uses_latest_delivered_user_without_tool_history_but_keeps_live_facts() {
469        use mj_core::relay::RelayObservation;
470        let context = TurnContext::default();
471        let start = |id: &str| RelayObservation::CommandStarted {
472            command_id: id.into(),
473            started_at_ms: 0,
474        };
475        context.observe_relay(&start("old"), Some("OLD REQUEST"));
476        context.observe(&message("old", "OLD ANSWER"));
477        context.observe(&tool("active-build"));
478        context.observe_relay(&start("new"), Some("CURRENT REQUEST"));
479        let noisy: SessionUpdate = serde_json::from_value(json!({
480            "sessionUpdate":"tool_call", "toolCallId":"noisy", "title":"noisy", "status":"completed",
481            "rawInput":{"command":"TOOL_BODY".repeat(20_000)}
482        })).unwrap();
483        context.observe(&noisy);
484        context.observe(&message("new", "CURRENT ANSWER"));
485        let facts = ActivityFacts {
486            background_commands: 2,
487            queued_commands: 3,
488            tools_in_flight: vec![InFlightToolCall {
489                tool_call_id: "active-build".into(),
490                title: Some("active-build".into()),
491                status: agent_client_protocol::v1::schema::ToolCallStatus::InProgress,
492                started_at_ms: 1_000,
493            }],
494            ..Default::default()
495        };
496        let evidence = context.evidence(HarnessKind::Codex, TurnPhase::Running, &facts, 5_000);
497        assert!(evidence.transcript_summary.contains("CURRENT REQUEST"));
498        assert!(evidence.transcript_summary.contains("CURRENT ANSWER"));
499        for excluded in [
500            "OLD REQUEST",
501            "OLD ANSWER",
502            "TOOL_BODY",
503            "<tool",
504            "bytes omitted",
505        ] {
506            assert!(
507                !evidence.transcript_summary.contains(excluded),
508                "{excluded}"
509            );
510        }
511        assert_eq!(evidence.user_prompt_tail, "CURRENT REQUEST");
512        assert_eq!(evidence.assistant_text_tail, "CURRENT ANSWER");
513        assert_eq!(evidence.background_commands, 2);
514        assert_eq!(evidence.queued_commands, 3);
515        assert_eq!(evidence.tools_in_flight.len(), 1);
516        assert!(evidence.tools_in_flight[0].title.contains("active-build"));
517        assert_eq!(evidence.tools_in_flight[0].running_s, 4);
518        let full = context.0.lock().unwrap().summary.render(256 * 1024);
519        assert!(full.contains("OLD REQUEST") && full.contains("TOOL_BODY"));
520    }
521
522    #[test]
523    fn tool_calls_after_the_last_assistant_text_are_named_in_the_evidence() {
524        use mj_core::relay::RelayObservation;
525        let context = TurnContext::default();
526        context.observe_relay(
527            &RelayObservation::CommandStarted {
528                command_id: "audit".into(),
529                started_at_ms: 0,
530            },
531            Some("Audit the cache and hand back."),
532        );
533        context.observe(&message("m1", "I'm checking the update paths now."));
534        let handback: SessionUpdate = serde_json::from_value(json!({
535            "sessionUpdate":"tool_call", "toolCallId":"hb", "title":"mcp__mj-agents__handback",
536            "status":"completed", "rawInput":{"report":"done"}
537        }))
538        .unwrap();
539        context.observe(&handback);
540        let facts = ActivityFacts::default();
541        let evidence = context.evidence(HarnessKind::Codex, TurnPhase::Replied, &facts, 5_000);
542        assert_eq!(evidence.final_tool_calls.len(), 1);
543        assert!(evidence.final_tool_calls[0].name.contains("handback"));
544        assert_eq!(evidence.final_tool_calls[0].status, "completed");
545        // Text after the call closes the list again.
546        context.observe(&message("m2", "Handed back."));
547        let evidence = context.evidence(HarnessKind::Codex, TurnPhase::Replied, &facts, 5_000);
548        assert!(evidence.final_tool_calls.is_empty());
549    }
550
551    #[test]
552    fn evidence_caps_utf8_text_tools_and_durations() {
553        let context = TurnContext::default();
554        context.reset(None, &"é".repeat(20_000));
555        context.observe(&message("first", &"🦀".repeat(20_000)));
556        let first = context.evidence(
557            HarnessKind::Claude,
558            TurnPhase::Running,
559            &ActivityFacts::default(),
560            0,
561        );
562        assert_eq!(first.user_prompt_tail.len(), USER_PROMPT_BYTES);
563        assert_eq!(first.assistant_text_tail.len(), ASSISTANT_TEXT_BYTES);
564        for n in 0..20 {
565            context.observe(&tool(&format!("{n}{}", "é".repeat(300))));
566        }
567        let facts = ActivityFacts {
568            last_acp_activity_at_ms: Some(1_000),
569            background_commands: 3,
570            queued_commands: 2,
571            tools_in_flight: (0..100)
572                .map(|n| InFlightToolCall {
573                    tool_call_id: n.to_string(),
574                    title: Some("🦀".repeat(200)),
575                    status: agent_client_protocol::v1::schema::ToolCallStatus::InProgress,
576                    started_at_ms: 2_000,
577                })
578                .collect(),
579            ..Default::default()
580        };
581        let evidence = context.evidence(HarnessKind::Claude, TurnPhase::Running, &facts, 95_000);
582        assert_eq!(evidence.tools_in_flight.len(), IN_FLIGHT_TOOLS);
583        assert!(
584            evidence
585                .tools_in_flight
586                .iter()
587                .all(|tool| tool.title.len() <= TOOL_TITLE_BYTES && tool.running_s == 93)
588        );
589        assert!(evidence.transcript_summary.len() <= 48 * 1024);
590        assert_eq!(evidence.assistant_text_tail, first.assistant_text_tail);
591        assert_eq!(evidence.silent_for_s, 94);
592        let json = serde_json::to_value(evidence).unwrap();
593        assert_eq!(json["phase"], "running");
594        assert_eq!(json["harness"], "claude");
595        assert_eq!(json["background_commands"], 3);
596        assert_eq!(json["queued_commands"], 2);
597        assert!(serde_json::to_vec(&json).unwrap().len() < 64 * 1024);
598    }
599
600    #[test]
601    fn message_boundaries_and_prompt_reset_do_not_mix_answers() {
602        let context = TurnContext::default();
603        context.reset(None, "First prompt");
604        context.observe(&message("one", "Old answer"));
605        context.observe(&message("two", "New "));
606        context.observe(&message("two", "answer?"));
607        let evidence = context.evidence(
608            HarnessKind::Claude,
609            TurnPhase::Replied,
610            &ActivityFacts::default(),
611            0,
612        );
613        assert_eq!(evidence.assistant_text_tail, "New answer?");
614        let generation = context.generation();
615        context.set_counts(1, 2);
616        assert_ne!(context.generation(), generation);
617        let generation = context.generation();
618        context.set_counts(1, 2);
619        assert_eq!(context.generation(), generation);
620        assert_eq!(context.counts(), (1, 2));
621        context.invalidate();
622        assert_ne!(context.generation(), generation);
623        assert_eq!(context.counts(), (1, 2));
624        let generation = context.generation();
625        context.reset(None, "Second prompt");
626        assert_eq!(context.counts(), (1, 2));
627        assert_ne!(context.generation(), generation);
628        let evidence = context.evidence(
629            HarnessKind::Claude,
630            TurnPhase::Running,
631            &ActivityFacts::default(),
632            0,
633        );
634        assert_eq!(evidence.user_prompt_tail, "Second prompt");
635        assert!(evidence.assistant_text_tail.is_empty());
636        assert!(!evidence.transcript_summary.contains("<user>"));
637        // A prompt Mjolnir submitted is not the person's latest request.
638        context.reset(Some("mailbox-wake-1"), "A child finished its task.");
639        let evidence = context.evidence(
640            HarnessKind::Claude,
641            TurnPhase::Running,
642            &ActivityFacts::default(),
643            0,
644        );
645        assert!(evidence.user_prompt_tail.is_empty());
646    }
647    // Hard-won: 753b1f960: recovery lost its request when the original start left the hot journal.
648    #[test]
649    fn recovery_initializes_missing_request_and_preserves_restored_corrections() {
650        use mj_core::relay::RelayObservation;
651        for restored in [false, true] {
652            let context = TurnContext::default();
653            if restored {
654                context.observe_relay(
655                    &RelayObservation::CommandStarted {
656                        command_id: "correction".into(),
657                        started_at_ms: 1,
658                    },
659                    Some("Use the corrected approach"),
660                );
661                context.observe(&message("partial", "Partial work"));
662            } else {
663                context.mark_earlier_history_omitted();
664                context.observe(&message("suffix", "Only the tail survived"));
665            }
666            let recovery = mj_core::continuation::restart_continuation_id("original");
667            context.observe_relay(
668                &RelayObservation::CommandStarted {
669                    command_id: recovery.clone(),
670                    started_at_ms: 2,
671                },
672                Some("Original request"),
673            );
674            let evidence = context.evidence(
675                HarnessKind::Codex,
676                TurnPhase::Running,
677                &ActivityFacts::default(),
678                0,
679            );
680            assert_eq!(
681                evidence.user_prompt_tail,
682                if restored {
683                    "Use the corrected approach"
684                } else {
685                    "Original request"
686                }
687            );
688            assert!(evidence.transcript_summary.contains(if restored {
689                "Use the corrected approach"
690            } else {
691                "Original request"
692            }));
693            assert_eq!(
694                evidence.assistant_text_tail,
695                if restored {
696                    "Partial work"
697                } else {
698                    "Only the tail survived"
699                }
700            );
701            assert!(evidence.transcript_summary.contains(if restored {
702                "Partial work"
703            } else {
704                "Only the tail survived"
705            }));
706            let before = evidence.transcript_summary;
707            context.observe_relay(
708                &RelayObservation::CommandStarted {
709                    command_id: mj_core::continuation::restart_continuation_id(&recovery),
710                    started_at_ms: 3,
711                },
712                Some("Original request"),
713            );
714            assert_eq!(
715                context
716                    .evidence(
717                        HarnessKind::Codex,
718                        TurnPhase::Running,
719                        &ActivityFacts::default(),
720                        0
721                    )
722                    .transcript_summary,
723                before
724            );
725        }
726    }
727}