1use 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 guardian_reviews: GuardianReviews,
27}
28
29#[derive(Debug, Default)]
33struct GuardianReviews {
34 consecutive_denials: u32,
35 recent: std::collections::VecDeque<bool>,
36 tripped: bool,
37}
38
39const MAX_CONSECUTIVE_GUARDIAN_DENIALS: u32 = 3;
40const MAX_RECENT_GUARDIAN_DENIALS: usize = 10;
41const GUARDIAN_DENIAL_WINDOW: usize = 50;
42
43pub fn delivered_prompt_command_id(observation: &mj_core::relay::RelayObservation) -> Option<&str> {
46 use mj_core::relay::{RelayCommandOutcome, RelayObservation};
47 match observation {
48 RelayObservation::CommandStarted { command_id, .. } => Some(command_id),
49 RelayObservation::CommandCompleted {
50 outcome: RelayCommandOutcome::Steered { queued_command_id },
51 ..
52 } => Some(queued_command_id),
53 RelayObservation::MailboxEventsDelivered {
54 steering: Some(steering),
55 ..
56 } => Some(&steering.queued_prompt_id),
57 _ => None,
58 }
59}
60
61#[derive(Debug, Default, Clone)]
63pub struct TurnContext(Arc<Mutex<TurnContextState>>);
64
65impl TurnContext {
66 pub fn mark_parent_activity(&self) {
68 self.mark_parent_activity_at(std::time::Instant::now());
69 }
70
71 pub fn mark_parent_activity_at(&self, at: std::time::Instant) {
73 self.0
74 .lock()
75 .expect("turn context lock poisoned")
76 .parent_activity = Some(at);
77 }
78
79 pub fn parent_activity(&self) -> Option<std::time::Instant> {
80 self.0
81 .lock()
82 .expect("turn context lock poisoned")
83 .parent_activity
84 }
85
86 pub fn set_decision_log(&self, log: mj_core::jev::DecisionLog) {
87 self.0
88 .lock()
89 .expect("turn context lock poisoned")
90 .decision_log = Some(log);
91 }
92 pub fn decision_log(&self) -> Option<mj_core::jev::DecisionLog> {
93 self.0
94 .lock()
95 .expect("turn context lock poisoned")
96 .decision_log
97 .clone()
98 }
99 pub fn reset(&self, command_id: Option<&str>, prompt: &str) {
105 self.reset_request(command_id, Some(prompt));
106 }
107
108 fn reset_request(&self, command_id: Option<&str>, prompt: Option<&str>) -> bool {
110 let recovery = command_id.is_some_and(mj_core::continuation::is_restart_continuation);
111 let user_prompt_tail = prompt.map(|prompt| {
112 if recovery || mj_core::continuation::is_user_authored_message(command_id, prompt) {
113 tail(prompt, USER_PROMPT_BYTES)
114 } else {
115 String::new()
116 }
117 });
118 let mut state = self.0.lock().expect("turn context lock poisoned");
119 let generation = state.generation.wrapping_add(1);
120 if recovery {
121 if state.user_prompt_tail.is_none()
122 && let (Some(user_prompt_tail), Some(prompt)) = (user_prompt_tail, prompt)
123 {
124 state.user_prompt_tail = Some(user_prompt_tail);
125 state.summary.push_user(prompt);
128 state.summary.entries.rotate_right(1);
129 }
130 complete_message(&mut state);
134 state.generation = generation;
135 state.parent_activity = Some(std::time::Instant::now());
136 return false;
137 }
138 *state = TurnContextState {
139 generation,
140 parent_activity: Some(std::time::Instant::now()),
141 decision_log: state.decision_log.clone(),
142 authorization: state.authorization.clone(),
143 user_prompt_tail,
144 background_commands: state.background_commands,
145 queued_commands: state.queued_commands,
146 background_inventory: std::mem::take(&mut state.background_inventory),
147 native_agent_ids: std::mem::take(&mut state.native_agent_ids),
148 session_id: std::mem::take(&mut state.session_id),
149 summary: std::mem::take(&mut state.summary),
150 ..Default::default()
151 };
152 true
153 }
154
155 pub fn observe_prompt_delivery(&self, command_id: Option<&str>, prompt: Option<&str>) {
157 if self.reset_request(command_id, prompt)
158 && let Some(prompt) = prompt
159 {
160 self.0
161 .lock()
162 .expect("turn context lock poisoned")
163 .summary
164 .push_user(prompt);
165 }
166 }
167
168 pub fn observe_autonomous_turn_start(&self) {
170 let mut state = self.0.lock().expect("turn context lock poisoned");
171 state.assistant_text_tail.clear();
172 state.last_completed_message.clear();
173 state.message_id = None;
174 state.generation = state.generation.wrapping_add(1);
175 }
176
177 pub fn observe_relay(
179 &self,
180 observation: &mj_core::relay::RelayObservation,
181 prompt: Option<&str>,
182 ) {
183 use mj_core::relay::{RelayCommandOutcome, RelayObservation};
184 match observation {
185 RelayObservation::CommandStarted { .. }
186 | RelayObservation::CommandCompleted {
187 outcome: RelayCommandOutcome::Steered { .. },
188 ..
189 }
190 | RelayObservation::MailboxEventsDelivered {
191 steering: Some(_), ..
192 } => {
193 if prompt.is_some()
197 || !matches!(observation, RelayObservation::CommandStarted { .. })
198 {
199 self.observe_prompt_delivery(delivered_prompt_command_id(observation), prompt);
200 }
201 }
202 RelayObservation::SessionRestarted
206 | RelayObservation::HarnessTurnSettled {
207 prompt_in_flight: false,
208 ..
209 } => {
210 complete_message(&mut self.0.lock().expect("turn context lock poisoned"));
211 }
212 RelayObservation::ElicitationResolved {
213 reply: Some(_),
214 action,
215 ..
216 } if action != mj_core::elicitation::OPERATOR_AWAY_ACTION => {
217 complete_message(&mut self.0.lock().expect("turn context lock poisoned"));
218 }
219 RelayObservation::SessionUpdate { update } => self.observe(update),
220 RelayObservation::TerminalOutput {
221 terminal_id,
222 output,
223 truncated,
224 exit_code,
225 signal,
226 } => {
227 self.observe_terminal(&mj_core::transcript::TerminalOutputRecord {
228 terminal_id: terminal_id.clone(),
229 output: output.clone().into(),
230 truncated: *truncated,
231 exit_code: *exit_code,
232 signal: signal.clone(),
233 });
234 }
235 RelayObservation::CommandCompleted {
236 outcome: RelayCommandOutcome::ContextCleared { .. },
237 ..
238 } => self.clear_history(),
239 _ => {}
240 }
241 }
242
243 pub fn invalidate(&self) {
245 let mut state = self.0.lock().expect("turn context lock poisoned");
246 state.generation = state.generation.wrapping_add(1);
247 }
248
249 pub fn generation(&self) -> u64 {
250 self.0
251 .lock()
252 .expect("turn context lock poisoned")
253 .generation
254 }
255
256 pub fn counts(&self) -> (usize, usize) {
257 let state = self.0.lock().expect("turn context lock poisoned");
258 (state.background_commands, state.queued_commands)
259 }
260
261 pub fn set_counts(&self, background_commands: usize, queued_commands: usize) {
262 let mut state = self.0.lock().expect("turn context lock poisoned");
263 if (state.background_commands, state.queued_commands)
264 != (background_commands, queued_commands)
265 {
266 state.generation = state.generation.wrapping_add(1);
267 state.background_commands = background_commands;
268 state.queued_commands = queued_commands;
269 }
270 }
271
272 pub fn set_session_id(&self, session_id: &str) {
273 self.0
274 .lock()
275 .expect("turn context lock poisoned")
276 .session_id = session_id.into();
277 }
278
279 pub fn session_id(&self) -> String {
280 self.0
281 .lock()
282 .expect("turn context lock poisoned")
283 .session_id
284 .clone()
285 }
286
287 pub fn set_authorization_context(
290 &self,
291 authorization: Option<mj_core::assessment::ContextHistory>,
292 ) {
293 let mut state = self.0.lock().expect("turn context lock poisoned");
294 if state.authorization != authorization {
295 state.authorization = authorization;
296 state.generation = state.generation.wrapping_add(1);
297 }
298 }
299
300 pub fn restore_user_prompt_tail(&self, history: &mj_core::assessment::ContextHistory) {
302 let mut state = self.0.lock().expect("turn context lock poisoned");
303 state.user_prompt_tail = Some(
304 history
305 .messages
306 .iter()
307 .rev()
308 .find(|message| message.role == "user")
309 .map(|message| tail(&message.text, USER_PROMPT_BYTES))
310 .unwrap_or_default(),
311 );
312 state.generation = state.generation.wrapping_add(1);
313 }
314
315 pub fn authorization_context(&self) -> Option<mj_core::assessment::ContextHistory> {
316 self.0
317 .lock()
318 .expect("turn context lock poisoned")
319 .authorization
320 .clone()
321 }
322
323 pub fn set_background_inventory(
325 &self,
326 mut commands: Vec<mj_core::relay::BackgroundCommand>,
327 mut native_agent_ids: Vec<String>,
328 ) {
329 commands.sort_by(|a, b| a.id.cmp(&b.id));
330 native_agent_ids.sort();
331 let mut state = self.0.lock().expect("turn context lock poisoned");
332 if state.background_inventory != commands || state.native_agent_ids != native_agent_ids {
333 state.background_inventory = commands;
334 state.native_agent_ids = native_agent_ids;
335 state.generation = state.generation.wrapping_add(1);
336 }
337 }
338
339 pub fn observe(&self, update: &SessionUpdate) {
340 let mut state = self.0.lock().expect("turn context lock poisoned");
341 state.parent_activity = Some(std::time::Instant::now());
342 if matches!(
343 update,
344 SessionUpdate::AgentMessageChunk(_)
345 | SessionUpdate::AgentThoughtChunk(_)
346 | SessionUpdate::ToolCall(_)
347 | SessionUpdate::ToolCallUpdate(_)
348 ) {
349 state.generation = state.generation.wrapping_add(1);
350 }
351 state.summary.observe(update);
352 match update {
353 SessionUpdate::AgentMessageChunk(chunk) => {
354 let id = chunk
357 .message_id
358 .as_ref()
359 .map(ToString::to_string)
360 .or_else(|| state.message_id.clone());
361 if id != state.message_id {
362 complete_message(&mut state);
363 state.message_id = id;
364 }
365 if let ContentBlock::Text(content) = &chunk.content {
366 state
368 .assistant_text_tail
369 .push_str(&tail(&content.text, ASSISTANT_TEXT_BYTES));
370 state.assistant_text_tail =
371 tail(&state.assistant_text_tail, ASSISTANT_TEXT_BYTES);
372 }
373 }
374 SessionUpdate::ToolCall(_) => {
375 complete_message(&mut state);
376 }
377 SessionUpdate::ToolCallUpdate(_) | SessionUpdate::AgentThoughtChunk(_) => {
378 complete_message(&mut state)
379 }
380 _ => {}
381 }
382 }
383
384 pub fn observe_terminal(&self, record: &mj_core::transcript::TerminalOutputRecord) {
385 let mut state = self.0.lock().expect("turn context lock poisoned");
386 state.summary.observe_terminal(record);
387 state.generation = state.generation.wrapping_add(1);
388 }
389
390 pub fn render_transcript(&self, limit: usize) -> String {
393 self.0
394 .lock()
395 .expect("turn context lock poisoned")
396 .summary
397 .render(limit)
398 }
399
400 pub fn guardian_tripped(&self) -> bool {
403 self.0
404 .lock()
405 .expect("turn context lock poisoned")
406 .guardian_reviews
407 .tripped
408 }
409
410 pub fn record_guardian_review(&self, denied: bool) -> bool {
413 let mut state = self.0.lock().expect("turn context lock poisoned");
414 let reviews = &mut state.guardian_reviews;
415 reviews.consecutive_denials = if denied {
416 reviews.consecutive_denials.saturating_add(1)
417 } else {
418 0
419 };
420 reviews.recent.push_back(denied);
421 if reviews.recent.len() > GUARDIAN_DENIAL_WINDOW {
422 reviews.recent.pop_front();
423 }
424 let recent_denials = reviews.recent.iter().filter(|denied| **denied).count();
425 let trips = denied
426 && !reviews.tripped
427 && (reviews.consecutive_denials >= MAX_CONSECUTIVE_GUARDIAN_DENIALS
428 || recent_denials >= MAX_RECENT_GUARDIAN_DENIALS);
429 reviews.tripped |= trips;
430 trips
431 }
432
433 pub fn mark_earlier_history_omitted(&self) {
434 self.0
435 .lock()
436 .expect("turn context lock poisoned")
437 .summary
438 .mark_earlier_history_omitted();
439 }
440
441 pub fn clear_history(&self) {
442 let mut state = self.0.lock().expect("turn context lock poisoned");
443 state.summary = Default::default();
444 state.user_prompt_tail = None;
445 state.assistant_text_tail.clear();
446 state.last_completed_message.clear();
447 state.message_id = None;
448 state.authorization = None;
449 state.generation = state.generation.wrapping_add(1);
450 }
451
452 pub fn evidence(
453 &self,
454 harness: HarnessKind,
455 phase: TurnPhase,
456 facts: &ActivityFacts,
457 now_ms: i64,
458 ) -> TurnEvidence {
459 let state = self.0.lock().expect("turn context lock poisoned");
460 let summary = state.summary.latest_user_messages();
461 let last_assistant = state
462 .summary
463 .entries
464 .iter()
465 .rposition(|e| e.role == crate::summary::SummaryRole::Assistant);
466 let final_tool_calls = state
467 .summary
468 .entries
469 .iter()
470 .skip(last_assistant.map_or(0, |i| i + 1))
471 .filter(|e| e.role == crate::summary::SummaryRole::Tool)
472 .take(IN_FLIGHT_TOOLS)
473 .map(|e| mj_core::activity::verdict::ToolOutcome {
474 name: tool_title(
475 e.tool
476 .as_ref()
477 .and_then(|t| t.get("name"))
478 .and_then(|n| n.as_str())
479 .unwrap_or(&e.text),
480 ),
481 status: e
482 .tool
483 .as_ref()
484 .and_then(|t| t.get("status"))
485 .and_then(|s| s.as_str())
486 .unwrap_or("unknown")
487 .to_owned(),
488 })
489 .collect();
490 TurnEvidence {
491 authorization: None,
492 final_tool_calls,
493 background: Vec::new(),
494 harness,
495 phase,
496 silent_for_s: facts
497 .last_acp_activity_at_ms
498 .map_or(0, |last| now_ms.saturating_sub(last).max(0) as u64 / 1000),
499 tools_in_flight: facts
500 .tools_in_flight
501 .iter()
502 .take(IN_FLIGHT_TOOLS)
503 .map(|tool| ToolEvidence {
504 title: tool_title(
505 state
506 .summary
507 .entries
508 .iter()
509 .find(|e| e.id == tool.tool_call_id)
510 .map_or("unknown tool", |e| e.text.as_str()),
511 ),
512 running_s: now_ms.saturating_sub(tool.started_at_ms).max(0) as u64 / 1000,
513 })
514 .collect(),
515 transcript_summary: summary.render(48 * 1024),
516 background_commands: facts.background_commands,
517 queued_commands: facts.queued_commands,
518 user_prompt_tail: state.user_prompt_tail.clone().unwrap_or_default(),
519 assistant_text_tail: if state.assistant_text_tail.is_empty() {
520 state.last_completed_message.clone()
521 } else {
522 state.assistant_text_tail.clone()
523 },
524 completion: None,
525 }
526 }
527}
528
529fn complete_message(state: &mut TurnContextState) {
530 if !state.assistant_text_tail.is_empty() {
531 state.last_completed_message = std::mem::take(&mut state.assistant_text_tail);
532 }
533 state.message_id = None;
534}
535
536pub fn tail(text: &str, maximum_bytes: usize) -> String {
539 let start = text.floor_char_boundary(text.len().saturating_sub(maximum_bytes));
540 let mut value = text[start..].to_owned();
541 mj_core::transcript::truncate_string_start(&mut value, maximum_bytes);
542 value
543}
544
545#[cfg(test)]
546mod tests {
547 use super::*;
548 use mj_core::activity::InFlightToolCall;
549 use serde_json::json;
550 fn message(id: &str, text: &str) -> SessionUpdate {
551 serde_json::from_value(json!({"sessionUpdate":"agent_message_chunk","messageId":id,"content":{"type":"text","text":text}})).unwrap()
552 }
553
554 fn tool(title: &str) -> SessionUpdate {
555 serde_json::from_value(json!({"sessionUpdate":"tool_call","toolCallId":title,"title":title,"status":"in_progress"})).unwrap()
556 }
557
558 #[test]
559 fn diagnostic_logging_does_not_change_evidence_or_generation_and_survives_reset() {
560 let context = TurnContext::default();
561 context.reset(None, "Implement the parser");
562 let generation = context.generation();
563 let before = serde_json::to_value(context.evidence(
564 HarnessKind::Codex,
565 TurnPhase::Running,
566 &Default::default(),
567 0,
568 ))
569 .unwrap();
570 let dir = tempfile::tempdir().unwrap();
571 let log = mj_core::jev::DecisionLog::open(dir.path().into()).unwrap();
572 context.set_decision_log(log.clone());
573 let attempt = log.start("s", "activity", "Who acts?", "Current request");
574 attempt.finish("unchanged", "Kept runtime facts");
575 assert_eq!(context.generation(), generation);
576 assert_eq!(
577 serde_json::to_value(context.evidence(
578 HarnessKind::Codex,
579 TurnPhase::Running,
580 &Default::default(),
581 0
582 ))
583 .unwrap(),
584 before
585 );
586 context.reset(None, "New work");
587 assert!(context.decision_log().is_some());
588 }
589
590 #[test]
591 fn verdict_uses_latest_delivered_user_without_tool_history_but_keeps_live_facts() {
592 use mj_core::relay::RelayObservation;
593 let context = TurnContext::default();
594 let start = |id: &str| RelayObservation::CommandStarted {
595 command_id: id.into(),
596 started_at_ms: 0,
597 };
598 context.observe_relay(&start("old"), Some("OLD REQUEST"));
599 context.observe(&message("old", "OLD ANSWER"));
600 context.observe(&tool("active-build"));
601 context.observe_relay(&start("new"), Some("CURRENT REQUEST"));
602 let noisy: SessionUpdate = serde_json::from_value(json!({
603 "sessionUpdate":"tool_call", "toolCallId":"noisy", "title":"noisy", "status":"completed",
604 "rawInput":{"command":"TOOL_BODY".repeat(20_000)}
605 })).unwrap();
606 context.observe(&noisy);
607 context.observe(&message("new", "CURRENT ANSWER"));
608 let facts = ActivityFacts {
609 background_commands: 2,
610 queued_commands: 3,
611 tools_in_flight: vec![InFlightToolCall {
612 tool_call_id: "active-build".into(),
613 title: Some("active-build".into()),
614 status: agent_client_protocol::v1::schema::ToolCallStatus::InProgress,
615 started_at_ms: 1_000,
616 }],
617 ..Default::default()
618 };
619 let evidence = context.evidence(HarnessKind::Codex, TurnPhase::Running, &facts, 5_000);
620 assert!(evidence.transcript_summary.contains("CURRENT REQUEST"));
621 assert!(evidence.transcript_summary.contains("CURRENT ANSWER"));
622 for excluded in [
623 "OLD REQUEST",
624 "OLD ANSWER",
625 "TOOL_BODY",
626 "<tool",
627 "bytes omitted",
628 ] {
629 assert!(
630 !evidence.transcript_summary.contains(excluded),
631 "{excluded}"
632 );
633 }
634 assert_eq!(evidence.user_prompt_tail, "CURRENT REQUEST");
635 assert_eq!(evidence.assistant_text_tail, "CURRENT ANSWER");
636 assert_eq!(evidence.background_commands, 2);
637 assert_eq!(evidence.queued_commands, 3);
638 assert_eq!(evidence.tools_in_flight.len(), 1);
639 assert!(evidence.tools_in_flight[0].title.contains("active-build"));
640 assert_eq!(evidence.tools_in_flight[0].running_s, 4);
641 let full = context.0.lock().unwrap().summary.render(256 * 1024);
642 assert!(full.contains("OLD REQUEST") && full.contains("TOOL_BODY"));
643 }
644
645 #[test]
646 fn tool_calls_after_the_last_assistant_text_are_named_in_the_evidence() {
647 use mj_core::relay::RelayObservation;
648 let context = TurnContext::default();
649 context.observe_relay(
650 &RelayObservation::CommandStarted {
651 command_id: "audit".into(),
652 started_at_ms: 0,
653 },
654 Some("Audit the cache and hand back."),
655 );
656 context.observe(&message("m1", "I'm checking the update paths now."));
657 let handback: SessionUpdate = serde_json::from_value(json!({
658 "sessionUpdate":"tool_call", "toolCallId":"hb", "title":"mcp__mj-agents__handback",
659 "status":"completed", "rawInput":{"report":"done"}
660 }))
661 .unwrap();
662 context.observe(&handback);
663 let facts = ActivityFacts::default();
664 let evidence = context.evidence(HarnessKind::Codex, TurnPhase::Replied, &facts, 5_000);
665 assert_eq!(evidence.final_tool_calls.len(), 1);
666 assert!(evidence.final_tool_calls[0].name.contains("handback"));
667 assert_eq!(evidence.final_tool_calls[0].status, "completed");
668 context.observe(&message("m2", "Handed back."));
670 let evidence = context.evidence(HarnessKind::Codex, TurnPhase::Replied, &facts, 5_000);
671 assert!(evidence.final_tool_calls.is_empty());
672 }
673
674 #[test]
675 fn evidence_caps_utf8_text_tools_and_durations() {
676 let context = TurnContext::default();
677 context.reset(None, &"é".repeat(20_000));
678 context.observe(&message("first", &"🦀".repeat(20_000)));
679 let first = context.evidence(
680 HarnessKind::Claude,
681 TurnPhase::Running,
682 &ActivityFacts::default(),
683 0,
684 );
685 assert_eq!(first.user_prompt_tail.len(), USER_PROMPT_BYTES);
686 assert_eq!(first.assistant_text_tail.len(), ASSISTANT_TEXT_BYTES);
687 for n in 0..20 {
688 context.observe(&tool(&format!("{n}{}", "é".repeat(300))));
689 }
690 let facts = ActivityFacts {
691 last_acp_activity_at_ms: Some(1_000),
692 background_commands: 3,
693 queued_commands: 2,
694 tools_in_flight: (0..100)
695 .map(|n| InFlightToolCall {
696 tool_call_id: n.to_string(),
697 title: Some("🦀".repeat(200)),
698 status: agent_client_protocol::v1::schema::ToolCallStatus::InProgress,
699 started_at_ms: 2_000,
700 })
701 .collect(),
702 ..Default::default()
703 };
704 let evidence = context.evidence(HarnessKind::Claude, TurnPhase::Running, &facts, 95_000);
705 assert_eq!(evidence.tools_in_flight.len(), IN_FLIGHT_TOOLS);
706 assert!(
707 evidence
708 .tools_in_flight
709 .iter()
710 .all(|tool| tool.title.len() <= TOOL_TITLE_BYTES && tool.running_s == 93)
711 );
712 assert!(evidence.transcript_summary.len() <= 48 * 1024);
713 assert_eq!(evidence.assistant_text_tail, first.assistant_text_tail);
714 assert_eq!(evidence.silent_for_s, 94);
715 let json = serde_json::to_value(evidence).unwrap();
716 assert_eq!(json["phase"], "running");
717 assert_eq!(json["harness"], "claude");
718 assert_eq!(json["background_commands"], 3);
719 assert_eq!(json["queued_commands"], 2);
720 assert!(serde_json::to_vec(&json).unwrap().len() < 64 * 1024);
721 }
722
723 #[test]
724 fn message_boundaries_and_prompt_reset_do_not_mix_answers() {
725 let context = TurnContext::default();
726 context.reset(None, "First prompt");
727 context.observe(&message("one", "Old answer"));
728 context.observe(&message("two", "New "));
729 context.observe(&message("two", "answer?"));
730 let evidence = context.evidence(
731 HarnessKind::Claude,
732 TurnPhase::Replied,
733 &ActivityFacts::default(),
734 0,
735 );
736 assert_eq!(evidence.assistant_text_tail, "New answer?");
737 let generation = context.generation();
738 context.set_counts(1, 2);
739 assert_ne!(context.generation(), generation);
740 let generation = context.generation();
741 context.set_counts(1, 2);
742 assert_eq!(context.generation(), generation);
743 assert_eq!(context.counts(), (1, 2));
744 context.invalidate();
745 assert_ne!(context.generation(), generation);
746 assert_eq!(context.counts(), (1, 2));
747 let generation = context.generation();
748 context.reset(None, "Second prompt");
749 assert_eq!(context.counts(), (1, 2));
750 assert_ne!(context.generation(), generation);
751 let evidence = context.evidence(
752 HarnessKind::Claude,
753 TurnPhase::Running,
754 &ActivityFacts::default(),
755 0,
756 );
757 assert_eq!(evidence.user_prompt_tail, "Second prompt");
758 assert!(evidence.assistant_text_tail.is_empty());
759 assert!(!evidence.transcript_summary.contains("<user>"));
760 context.reset(Some("mailbox-wake-1"), "A child finished its task.");
762 let evidence = context.evidence(
763 HarnessKind::Claude,
764 TurnPhase::Running,
765 &ActivityFacts::default(),
766 0,
767 );
768 assert!(evidence.user_prompt_tail.is_empty());
769 }
770 #[test]
772 fn recovery_initializes_missing_request_and_preserves_restored_corrections() {
773 use mj_core::relay::RelayObservation;
774 for restored in [false, true] {
775 let context = TurnContext::default();
776 if restored {
777 context.observe_relay(
778 &RelayObservation::CommandStarted {
779 command_id: "correction".into(),
780 started_at_ms: 1,
781 },
782 Some("Use the corrected approach"),
783 );
784 context.observe(&message("partial", "Partial work"));
785 } else {
786 context.mark_earlier_history_omitted();
787 context.observe(&message("suffix", "Only the tail survived"));
788 }
789 let recovery = mj_core::continuation::restart_continuation_id("original");
790 context.observe_relay(
791 &RelayObservation::CommandStarted {
792 command_id: recovery.clone(),
793 started_at_ms: 2,
794 },
795 Some("Original request"),
796 );
797 let evidence = context.evidence(
798 HarnessKind::Codex,
799 TurnPhase::Running,
800 &ActivityFacts::default(),
801 0,
802 );
803 assert_eq!(
804 evidence.user_prompt_tail,
805 if restored {
806 "Use the corrected approach"
807 } else {
808 "Original request"
809 }
810 );
811 assert!(evidence.transcript_summary.contains(if restored {
812 "Use the corrected approach"
813 } else {
814 "Original request"
815 }));
816 assert_eq!(
817 evidence.assistant_text_tail,
818 if restored {
819 "Partial work"
820 } else {
821 "Only the tail survived"
822 }
823 );
824 assert!(evidence.transcript_summary.contains(if restored {
825 "Partial work"
826 } else {
827 "Only the tail survived"
828 }));
829 let before = evidence.transcript_summary;
830 context.observe_relay(
831 &RelayObservation::CommandStarted {
832 command_id: mj_core::continuation::restart_continuation_id(&recovery),
833 started_at_ms: 3,
834 },
835 Some("Original request"),
836 );
837 assert_eq!(
838 context
839 .evidence(
840 HarnessKind::Codex,
841 TurnPhase::Running,
842 &ActivityFacts::default(),
843 0
844 )
845 .transcript_summary,
846 before
847 );
848 }
849 }
850}