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 mj_core::guardian::{
7    DelegatedParentInstruction, MAX_PRIOR_GUARDIAN_REVIEWS, PriorGuardianReview, TrustedUserInput,
8};
9use std::collections::{HashMap, VecDeque};
10use std::sync::{Arc, Mutex};
11
12#[derive(Debug, Default)]
13struct TurnContextState {
14    generation: u64,
15    parent_activity: Option<std::time::Instant>,
16    decision_log: Option<mj_core::jev::DecisionLog>,
17    authorization: Option<mj_core::assessment::ContextHistory>,
18    user_prompt_tail: Option<String>,
19    message_id: Option<String>,
20    assistant_text_tail: String,
21    last_completed_message: String,
22    summary: crate::summary::TranscriptSummary,
23    background_commands: usize,
24    queued_commands: usize,
25    background_inventory: Vec<mj_core::relay::BackgroundCommand>,
26    native_agent_ids: Vec<String>,
27    session_id: String,
28    /// Mjolnir guardian reviews in this request. A new request starts with
29    /// none; a recovery continues the same request and keeps them.
30    guardian_reviews: GuardianReviews,
31    trusted_user_inputs: GuardianUserInputs,
32    delegated_parent_instructions: (Vec<DelegatedParentInstruction>, bool),
33    prior_guardian_reviews: Vec<PriorGuardianReview>,
34    // These verdicts have settled but their journal events have not arrived.
35    pending_prior_guardian_reviews: VecDeque<PriorGuardianReview>,
36}
37
38#[derive(Debug, Default)]
39struct GuardianUserInputs {
40    durable: Vec<TrustedUserInput>,
41    pending: Vec<TrustedUserInput>,
42    /// Retained journal records keep their live identity for in-flight reviews.
43    live_ids: HashMap<String, String>,
44    next_pending_id: u64,
45}
46
47/// Codex's per-turn guardian denial circuit breaker
48/// (`ext/guardian-reviewer/src/circuit_breaker.rs`): it trips once per request
49/// on 3 consecutive denials or 10 denials among the last 50 reviews.
50#[derive(Debug, Default)]
51struct GuardianReviews {
52    consecutive_denials: u32,
53    recent: VecDeque<bool>,
54    tripped: bool,
55}
56
57const MAX_CONSECUTIVE_GUARDIAN_DENIALS: u32 = 3;
58const MAX_RECENT_GUARDIAN_DENIALS: usize = 10;
59const GUARDIAN_DENIAL_WINDOW: usize = 50;
60
61/// The prompt that became visible to the harness at this durable observation.
62/// A queued or unconfirmed steering prompt has not been delivered yet.
63pub fn delivered_prompt_command_id(observation: &mj_core::relay::RelayObservation) -> Option<&str> {
64    use mj_core::relay::{RelayCommandOutcome, RelayObservation};
65    match observation {
66        RelayObservation::CommandStarted { command_id, .. } => Some(command_id),
67        RelayObservation::CommandCompleted {
68            outcome: RelayCommandOutcome::Steered { queued_command_id },
69            ..
70        } => Some(queued_command_id),
71        RelayObservation::MailboxEventsDelivered {
72            steering: Some(steering),
73            ..
74        } => Some(&steering.queued_prompt_id),
75        _ => None,
76    }
77}
78
79/// The relay and runtime share this small process-local evidence accumulator.
80#[derive(Debug, Default, Clone)]
81pub struct TurnContext(Arc<Mutex<TurnContextState>>);
82
83impl TurnContext {
84    /// Process-local parent clock; child traffic and inventory updates never mark it.
85    pub fn mark_parent_activity(&self) {
86        self.mark_parent_activity_at(std::time::Instant::now());
87    }
88
89    /// Record the monotonic time at which parent activity was observed.
90    pub fn mark_parent_activity_at(&self, at: std::time::Instant) {
91        self.0
92            .lock()
93            .expect("turn context lock poisoned")
94            .parent_activity = Some(at);
95    }
96
97    pub fn parent_activity(&self) -> Option<std::time::Instant> {
98        self.0
99            .lock()
100            .expect("turn context lock poisoned")
101            .parent_activity
102    }
103
104    pub fn set_decision_log(&self, log: mj_core::jev::DecisionLog) {
105        self.0
106            .lock()
107            .expect("turn context lock poisoned")
108            .decision_log = Some(log);
109    }
110    pub fn decision_log(&self) -> Option<mj_core::jev::DecisionLog> {
111        self.0
112            .lock()
113            .expect("turn context lock poisoned")
114            .decision_log
115            .clone()
116    }
117    /// Start a turn. `user_prompt_tail` carries the prompt only when the
118    /// person wrote it: a prompt Mjolnir submitted (a mailbox wake, a child
119    /// report, a continuation, a parent's message to a child) is not the
120    /// person's latest request, and Jev scored those turns better without it
121    /// (.agents/docs/jev-still-open-20261106.md).
122    pub fn reset(&self, command_id: Option<&str>, prompt: &str) {
123        self.reset_request(command_id, Some(prompt));
124    }
125
126    /// Returns whether this delivery establishes a request in the context.
127    fn reset_request(&self, command_id: Option<&str>, prompt: Option<&str>) -> bool {
128        let recovery = command_id.is_some_and(mj_core::continuation::is_restart_continuation);
129        let user_prompt_tail = prompt.map(|prompt| {
130            if recovery || mj_core::continuation::is_user_authored_message(command_id, prompt) {
131                tail(prompt, USER_PROMPT_BYTES)
132            } else {
133                String::new()
134            }
135        });
136        let mut state = self.0.lock().expect("turn context lock poisoned");
137        let generation = state.generation.wrapping_add(1);
138        if recovery {
139            if state.user_prompt_tail.is_none()
140                && let (Some(user_prompt_tail), Some(prompt)) = (user_prompt_tail, prompt)
141            {
142                state.user_prompt_tail = Some(user_prompt_tail);
143                // The carried request precedes the retained replay suffix.
144                // Preserve that suffix and its partially observed answer.
145                state.summary.push_user(prompt);
146                state.summary.entries.rotate_right(1);
147            }
148            // Recovery keeps the request, but delivery closes the interrupted
149            // message just as the transcript does. An unlabelled chunk from
150            // the new harness must not inherit the old message ID.
151            complete_message(&mut state);
152            state.generation = generation;
153            state.parent_activity = Some(std::time::Instant::now());
154            return false;
155        }
156        *state = TurnContextState {
157            generation,
158            parent_activity: Some(std::time::Instant::now()),
159            decision_log: state.decision_log.clone(),
160            authorization: state.authorization.clone(),
161            trusted_user_inputs: std::mem::take(&mut state.trusted_user_inputs),
162            delegated_parent_instructions: std::mem::take(&mut state.delegated_parent_instructions),
163            prior_guardian_reviews: std::mem::take(&mut state.prior_guardian_reviews),
164            pending_prior_guardian_reviews: std::mem::take(
165                &mut state.pending_prior_guardian_reviews,
166            ),
167            user_prompt_tail,
168            background_commands: state.background_commands,
169            queued_commands: state.queued_commands,
170            background_inventory: std::mem::take(&mut state.background_inventory),
171            native_agent_ids: std::mem::take(&mut state.native_agent_ids),
172            session_id: std::mem::take(&mut state.session_id),
173            summary: std::mem::take(&mut state.summary),
174            ..Default::default()
175        };
176        true
177    }
178
179    /// A known prompt delivery whose body may no longer be retained.
180    pub fn observe_prompt_delivery(&self, command_id: Option<&str>, prompt: Option<&str>) {
181        if self.reset_request(command_id, prompt)
182            && let Some(prompt) = prompt
183        {
184            self.0
185                .lock()
186                .expect("turn context lock poisoned")
187                .summary
188                .push_user(prompt);
189        }
190    }
191
192    /// Begin a turn the relay owner has identified as autonomous.
193    pub fn observe_autonomous_turn_start(&self) {
194        let mut state = self.0.lock().expect("turn context lock poisoned");
195        state.assistant_text_tail.clear();
196        state.last_completed_message.clear();
197        state.message_id = None;
198        state.generation = state.generation.wrapping_add(1);
199    }
200
201    /// Record durable transcript observations through the same path during live work and replay.
202    pub fn observe_relay(
203        &self,
204        observation: &mj_core::relay::RelayObservation,
205        prompt: Option<&str>,
206    ) {
207        use mj_core::relay::{RelayCommandOutcome, RelayObservation};
208        match observation {
209            RelayObservation::CommandStarted { .. }
210            | RelayObservation::CommandCompleted {
211                outcome: RelayCommandOutcome::Steered { .. },
212                ..
213            }
214            | RelayObservation::MailboxEventsDelivered {
215                steering: Some(_), ..
216            } => {
217                // A steering confirmation proves delivery even after its
218                // queue body was collected. Keep the reply boundary without
219                // inventing the missing prompt text.
220                if prompt.is_some()
221                    || !matches!(observation, RelayObservation::CommandStarted { .. })
222                {
223                    self.observe_prompt_delivery(delivered_prompt_command_id(observation), prompt);
224                }
225            }
226            // ACP completion may precede native execution's actual end.
227            // Deliveries, autonomous starts and these durable bridge/native
228            // boundaries own the reply stream instead.
229            RelayObservation::SessionRestarted
230            | RelayObservation::HarnessTurnSettled {
231                prompt_in_flight: false,
232                ..
233            } => {
234                complete_message(&mut self.0.lock().expect("turn context lock poisoned"));
235            }
236            RelayObservation::ElicitationResolved {
237                reply: Some(_),
238                action,
239                ..
240            } if action != mj_core::elicitation::OPERATOR_AWAY_ACTION => {
241                complete_message(&mut self.0.lock().expect("turn context lock poisoned"));
242            }
243            RelayObservation::SessionUpdate { update } => self.observe(update),
244            RelayObservation::TerminalOutput {
245                terminal_id,
246                output,
247                truncated,
248                exit_code,
249                signal,
250            } => {
251                self.observe_terminal(&mj_core::transcript::TerminalOutputRecord {
252                    terminal_id: terminal_id.clone(),
253                    output: output.clone().into(),
254                    truncated: *truncated,
255                    exit_code: *exit_code,
256                    signal: signal.clone(),
257                });
258            }
259            RelayObservation::CommandCompleted {
260                outcome: RelayCommandOutcome::ContextCleared { .. },
261                ..
262            } => self.clear_history(),
263            _ => {}
264        }
265    }
266
267    /// Invalidate a pending verdict at a lifecycle boundary without discarding evidence.
268    pub fn invalidate(&self) {
269        let mut state = self.0.lock().expect("turn context lock poisoned");
270        state.generation = state.generation.wrapping_add(1);
271    }
272
273    pub fn generation(&self) -> u64 {
274        self.0
275            .lock()
276            .expect("turn context lock poisoned")
277            .generation
278    }
279
280    pub fn counts(&self) -> (usize, usize) {
281        let state = self.0.lock().expect("turn context lock poisoned");
282        (state.background_commands, state.queued_commands)
283    }
284
285    pub fn set_counts(&self, background_commands: usize, queued_commands: usize) {
286        let mut state = self.0.lock().expect("turn context lock poisoned");
287        if (state.background_commands, state.queued_commands)
288            != (background_commands, queued_commands)
289        {
290            state.generation = state.generation.wrapping_add(1);
291            state.background_commands = background_commands;
292            state.queued_commands = queued_commands;
293        }
294    }
295
296    pub fn set_session_id(&self, session_id: &str) {
297        self.0
298            .lock()
299            .expect("turn context lock poisoned")
300            .session_id = session_id.into();
301    }
302
303    pub fn session_id(&self) -> String {
304        self.0
305            .lock()
306            .expect("turn context lock poisoned")
307            .session_id
308            .clone()
309    }
310
311    /// Publish the relay owner's durable user-instruction history to the ACP
312    /// classifier. A change invalidates any request built from older context.
313    pub fn set_authorization_context(
314        &self,
315        authorization: Option<mj_core::assessment::ContextHistory>,
316    ) {
317        let mut state = self.0.lock().expect("turn context lock poisoned");
318        if state.authorization != authorization {
319            state.authorization = authorization;
320            state.generation = state.generation.wrapping_add(1);
321        }
322    }
323
324    /// Restore the latest human instructions without changing replayed reply boundaries.
325    pub fn restore_user_prompt_tail(&self, history: &mj_core::assessment::ContextHistory) {
326        let mut state = self.0.lock().expect("turn context lock poisoned");
327        state.user_prompt_tail = Some(
328            history
329                .messages
330                .iter()
331                .rev()
332                .find(|message| message.role == "user")
333                .map(|message| tail(&message.text, USER_PROMPT_BYTES))
334                .unwrap_or_default(),
335        );
336        state.generation = state.generation.wrapping_add(1);
337    }
338
339    pub fn authorization_context(&self) -> Option<mj_core::assessment::ContextHistory> {
340        self.0
341            .lock()
342            .expect("turn context lock poisoned")
343            .authorization
344            .clone()
345    }
346
347    /// Compare identities as well as counts; identical level reports are not activity.
348    pub fn set_background_inventory(
349        &self,
350        mut commands: Vec<mj_core::relay::BackgroundCommand>,
351        mut native_agent_ids: Vec<String>,
352    ) {
353        commands.sort_by(|a, b| a.id.cmp(&b.id));
354        native_agent_ids.sort();
355        let mut state = self.0.lock().expect("turn context lock poisoned");
356        if state.background_inventory != commands || state.native_agent_ids != native_agent_ids {
357            state.background_inventory = commands;
358            state.native_agent_ids = native_agent_ids;
359            state.generation = state.generation.wrapping_add(1);
360        }
361    }
362
363    pub fn observe(&self, update: &SessionUpdate) {
364        let mut state = self.0.lock().expect("turn context lock poisoned");
365        state.parent_activity = Some(std::time::Instant::now());
366        if matches!(
367            update,
368            SessionUpdate::AgentMessageChunk(_)
369                | SessionUpdate::AgentThoughtChunk(_)
370                | SessionUpdate::ToolCall(_)
371                | SessionUpdate::ToolCallUpdate(_)
372        ) {
373            state.generation = state.generation.wrapping_add(1);
374        }
375        state.summary.observe(update);
376        match update {
377            SessionUpdate::AgentMessageChunk(chunk) => {
378                // Like authorization history, an omitted ID continues the
379                // current message; explicit IDs establish a new boundary.
380                let id = chunk
381                    .message_id
382                    .as_ref()
383                    .map(ToString::to_string)
384                    .or_else(|| state.message_id.clone());
385                if id != state.message_id {
386                    complete_message(&mut state);
387                    state.message_id = id;
388                }
389                if let ContentBlock::Text(content) = &chunk.content {
390                    // Trim each chunk before appending, so a huge chunk never grows retained state.
391                    state
392                        .assistant_text_tail
393                        .push_str(&tail(&content.text, ASSISTANT_TEXT_BYTES));
394                    state.assistant_text_tail =
395                        tail(&state.assistant_text_tail, ASSISTANT_TEXT_BYTES);
396                }
397            }
398            SessionUpdate::ToolCall(_) => {
399                complete_message(&mut state);
400            }
401            SessionUpdate::ToolCallUpdate(_) | SessionUpdate::AgentThoughtChunk(_) => {
402                complete_message(&mut state)
403            }
404            _ => {}
405        }
406    }
407
408    pub fn observe_terminal(&self, record: &mj_core::transcript::TerminalOutputRecord) {
409        let mut state = self.0.lock().expect("turn context lock poisoned");
410        state.summary.observe_terminal(record);
411        state.generation = state.generation.wrapping_add(1);
412    }
413
414    /// The retained transcript as the guardian reviewer reads it: recent
415    /// context first, within `limit` bytes.
416    pub fn render_transcript(&self, limit: usize) -> String {
417        self.0
418            .lock()
419            .expect("turn context lock poisoned")
420            .summary
421            .render(limit)
422    }
423
424    pub fn set_delegated_parent_instructions(&self, snapshot: &mj_core::relay::RelaySnapshot) {
425        self.0
426            .lock()
427            .expect("turn context lock poisoned")
428            .delegated_parent_instructions = (
429            snapshot.delegated_parent_instructions.clone(),
430            snapshot.delegated_parent_instructions_omitted,
431        );
432    }
433
434    pub fn delegated_parent_instructions(&self) -> (Vec<DelegatedParentInstruction>, bool) {
435        self.0
436            .lock()
437            .expect("turn context lock poisoned")
438            .delegated_parent_instructions
439            .clone()
440    }
441
442    pub fn set_trusted_user_inputs(&self, durable: Vec<TrustedUserInput>) {
443        let mut state = self.0.lock().expect("turn context lock poisoned");
444        let history = &mut state.trusted_user_inputs;
445        history.durable = durable;
446        history.pending.clear();
447        history.live_ids.clear();
448    }
449
450    /// Record the answer and enqueue its echo in the same order. The
451    /// callback must only publish into a channel slot already reserved.
452    pub fn record_pending_trusted_user_input(
453        &self,
454        elicitation_id: &str,
455        mut input: TrustedUserInput,
456        publish: impl FnOnce(),
457    ) {
458        let mut state = self.0.lock().expect("turn context lock poisoned");
459        let history = &mut state.trusted_user_inputs;
460        input.id = format!("pending:{}:{elicitation_id}", history.next_pending_id);
461        history.next_pending_id += 1;
462        history.pending.push(input);
463        let retained = TrustedUserInput::retained_count(history.pending.iter());
464        history.pending.drain(..history.pending.len() - retained);
465        publish();
466    }
467
468    pub fn sync_trusted_user_inputs(&self, durable: Vec<TrustedUserInput>) {
469        let mut state = self.0.lock().expect("turn context lock poisoned");
470        let history = &mut state.trusted_user_inputs;
471        history
472            .live_ids
473            .retain(|id, _| durable.iter().any(|input| &input.id == id));
474        // The journal retains a suffix. Match only newly appended entries to
475        // pending inputs: an older answer may have reused the same form ID.
476        let first_new = durable
477            .iter()
478            .rposition(|input| history.durable.iter().any(|old| old.id == input.id))
479            .map_or(0, |index| index + 1);
480        for input in &durable[first_new..] {
481            if let Some(elicitation_id) = input.elicitation_id()
482                && let Some(index) = history
483                    .pending
484                    .iter()
485                    .position(|pending| pending.elicitation_id() == Some(elicitation_id))
486            {
487                let pending = history.pending.remove(index);
488                history.live_ids.insert(input.id.clone(), pending.id);
489            }
490        }
491        history.durable = durable;
492    }
493
494    pub fn trusted_user_inputs(&self) -> Vec<TrustedUserInput> {
495        let state = self.0.lock().expect("turn context lock poisoned");
496        let history = &state.trusted_user_inputs;
497        let inputs = history.durable.iter().chain(&history.pending);
498        let retained = TrustedUserInput::retained_count(inputs.clone());
499        inputs
500            .skip(history.durable.len() + history.pending.len() - retained)
501            .map(|input| {
502                let mut input = input.clone();
503                if let Some(id) = history.live_ids.get(&input.id) {
504                    input.id.clone_from(id);
505                }
506                input
507            })
508            .collect()
509    }
510
511    pub fn record_prior_guardian_review(&self, review: PriorGuardianReview) {
512        let mut state = self.0.lock().expect("turn context lock poisoned");
513        let reviews = &mut state.pending_prior_guardian_reviews;
514        if reviews.len() == MAX_PRIOR_GUARDIAN_REVIEWS {
515            reviews.pop_front();
516        }
517        reviews.push_back(review);
518    }
519
520    pub fn prior_guardian_reviews(&self) -> Vec<PriorGuardianReview> {
521        let state = self.0.lock().expect("turn context lock poisoned");
522        let reviews = state
523            .prior_guardian_reviews
524            .iter()
525            .chain(&state.pending_prior_guardian_reviews);
526        let excess = (state.prior_guardian_reviews.len()
527            + state.pending_prior_guardian_reviews.len())
528        .saturating_sub(MAX_PRIOR_GUARDIAN_REVIEWS);
529        reviews.skip(excess).cloned().collect()
530    }
531
532    pub fn set_prior_guardian_reviews(&self, durable: Vec<PriorGuardianReview>) {
533        let mut state = self.0.lock().expect("turn context lock poisoned");
534        state.prior_guardian_reviews = durable;
535        state.pending_prior_guardian_reviews.clear();
536    }
537
538    pub fn sync_prior_guardian_reviews(&self, durable: Vec<PriorGuardianReview>) {
539        let mut state = self.0.lock().expect("turn context lock poisoned");
540        // Keep only unsettled journal deliveries. Merging the old durable
541        // history too would resurrect entries evicted by the snapshot's bound.
542        state.pending_prior_guardian_reviews.retain(|pending| {
543            !pending.review_id.as_ref().is_some_and(|id| {
544                durable
545                    .iter()
546                    .any(|review| review.review_id.as_ref() == Some(id))
547            })
548        });
549        state.prior_guardian_reviews = durable;
550    }
551
552    pub fn clear_prior_guardian_reviews(&self) {
553        self.set_prior_guardian_reviews(Vec::new());
554    }
555
556    /// Whether the guardian's denials tripped the breaker in this request, so
557    /// its remaining approvals go to the person.
558    pub fn guardian_tripped(&self) -> bool {
559        self.0
560            .lock()
561            .expect("turn context lock poisoned")
562            .guardian_reviews
563            .tripped
564    }
565
566    /// Record one completed guardian review in this request. Returns whether
567    /// this denial tripped the breaker.
568    pub fn record_guardian_review(&self, denied: bool) -> bool {
569        let mut state = self.0.lock().expect("turn context lock poisoned");
570        let reviews = &mut state.guardian_reviews;
571        reviews.consecutive_denials = if denied {
572            reviews.consecutive_denials.saturating_add(1)
573        } else {
574            0
575        };
576        reviews.recent.push_back(denied);
577        if reviews.recent.len() > GUARDIAN_DENIAL_WINDOW {
578            reviews.recent.pop_front();
579        }
580        let recent_denials = reviews.recent.iter().filter(|denied| **denied).count();
581        let trips = denied
582            && !reviews.tripped
583            && (reviews.consecutive_denials >= MAX_CONSECUTIVE_GUARDIAN_DENIALS
584                || recent_denials >= MAX_RECENT_GUARDIAN_DENIALS);
585        reviews.tripped |= trips;
586        trips
587    }
588
589    pub fn mark_earlier_history_omitted(&self) {
590        self.0
591            .lock()
592            .expect("turn context lock poisoned")
593            .summary
594            .mark_earlier_history_omitted();
595    }
596
597    pub fn clear_history(&self) {
598        let mut state = self.0.lock().expect("turn context lock poisoned");
599        state.summary = Default::default();
600        state.user_prompt_tail = None;
601        state.assistant_text_tail.clear();
602        state.last_completed_message.clear();
603        state.message_id = None;
604        state.authorization = None;
605        state.generation = state.generation.wrapping_add(1);
606    }
607
608    pub fn evidence(
609        &self,
610        harness: HarnessKind,
611        phase: TurnPhase,
612        facts: &ActivityFacts,
613        now_ms: i64,
614    ) -> TurnEvidence {
615        let state = self.0.lock().expect("turn context lock poisoned");
616        let summary = state.summary.latest_user_messages();
617        let last_assistant = state
618            .summary
619            .entries
620            .iter()
621            .rposition(|e| e.role == crate::summary::SummaryRole::Assistant);
622        let final_tool_calls = state
623            .summary
624            .entries
625            .iter()
626            .skip(last_assistant.map_or(0, |i| i + 1))
627            .filter(|e| e.role == crate::summary::SummaryRole::Tool)
628            .take(IN_FLIGHT_TOOLS)
629            .map(|e| mj_core::activity::verdict::ToolOutcome {
630                name: tool_title(
631                    e.tool
632                        .as_ref()
633                        .and_then(|t| t.get("name"))
634                        .and_then(|n| n.as_str())
635                        .unwrap_or(&e.text),
636                ),
637                status: e
638                    .tool
639                    .as_ref()
640                    .and_then(|t| t.get("status"))
641                    .and_then(|s| s.as_str())
642                    .unwrap_or("unknown")
643                    .to_owned(),
644            })
645            .collect();
646        TurnEvidence {
647            authorization: None,
648            final_tool_calls,
649            background: Vec::new(),
650            harness,
651            phase,
652            silent_for_s: facts
653                .last_acp_activity_at_ms
654                .map_or(0, |last| now_ms.saturating_sub(last).max(0) as u64 / 1000),
655            tools_in_flight: facts
656                .tools_in_flight
657                .iter()
658                .take(IN_FLIGHT_TOOLS)
659                .map(|tool| ToolEvidence {
660                    title: tool_title(
661                        state
662                            .summary
663                            .entries
664                            .iter()
665                            .find(|e| e.id == tool.tool_call_id)
666                            .map_or("unknown tool", |e| e.text.as_str()),
667                    ),
668                    running_s: now_ms.saturating_sub(tool.started_at_ms).max(0) as u64 / 1000,
669                })
670                .collect(),
671            transcript_summary: summary.render(48 * 1024),
672            background_commands: facts.background_commands,
673            queued_commands: facts.queued_commands,
674            user_prompt_tail: state.user_prompt_tail.clone().unwrap_or_default(),
675            assistant_text_tail: if state.assistant_text_tail.is_empty() {
676                state.last_completed_message.clone()
677            } else {
678                state.assistant_text_tail.clone()
679            },
680            completion: None,
681        }
682    }
683}
684
685fn complete_message(state: &mut TurnContextState) {
686    if !state.assistant_text_tail.is_empty() {
687        state.last_completed_message = std::mem::take(&mut state.assistant_text_tail);
688    }
689    state.message_id = None;
690}
691
692/// The last `maximum_bytes` of `text`, cut at a character boundary: the tail
693/// every turn classifier receives.
694pub fn tail(text: &str, maximum_bytes: usize) -> String {
695    let start = text.floor_char_boundary(text.len().saturating_sub(maximum_bytes));
696    let mut value = text[start..].to_owned();
697    mj_core::transcript::truncate_string_start(&mut value, maximum_bytes);
698    value
699}
700
701#[cfg(test)]
702mod tests {
703    use super::*;
704    use mj_core::activity::InFlightToolCall;
705    use serde_json::json;
706
707    #[test]
708    fn guardian_alignment_keeps_live_answer_identity_when_reused_form_ids_are_journaled() {
709        let context = TurnContext::default();
710        let elicitation = "form:with:colons";
711        let input = |ordinal| {
712            TrustedUserInput::from_elicitation(
713                format!("elicitation:{ordinal}:{elicitation}"),
714                elicitation,
715                None,
716                "accept",
717                None,
718                Some("Same reply"),
719                None,
720            )
721            .unwrap()
722        };
723        let older = input(1);
724        context.set_trusted_user_inputs(vec![older.clone()]);
725
726        context.record_pending_trusted_user_input(elicitation, input(2), || {});
727        let first_live_view = context.trusted_user_inputs();
728        assert_eq!(first_live_view.len(), 2);
729        assert_ne!(first_live_view[0].id, first_live_view[1].id);
730
731        context.sync_trusted_user_inputs(vec![older.clone(), input(2)]);
732        assert_eq!(context.trusted_user_inputs(), first_live_view);
733
734        context.record_pending_trusted_user_input(elicitation, input(3), || {});
735        let second_live_view = context.trusted_user_inputs();
736        assert_eq!(second_live_view.len(), 3);
737        assert_ne!(second_live_view[1].id, second_live_view[2].id);
738        context.sync_trusted_user_inputs(vec![older, input(2), input(3)]);
739        assert_eq!(context.trusted_user_inputs(), second_live_view);
740    }
741
742    #[test]
743    fn guardian_alignment_keeps_bounded_review_history_across_turns() {
744        let context = TurnContext::default();
745        assert!(!context.record_guardian_review(true));
746        assert!(!context.record_guardian_review(true));
747        assert!(context.record_guardian_review(true));
748        for index in 0..=GUARDIAN_DENIAL_WINDOW {
749            context.record_prior_guardian_review(PriorGuardianReview {
750                review_id: None,
751                tool: "shell".into(),
752                action_summary: index.to_string(),
753                outcome: mj_core::guardian::Outcome::Deny,
754                risk_level: None,
755                user_authorization: None,
756                rationale: None,
757            });
758        }
759        context.reset(Some("next"), "Next turn");
760        assert!(!context.guardian_tripped());
761        let reviews = context.prior_guardian_reviews();
762        assert_eq!(reviews.len(), GUARDIAN_DENIAL_WINDOW);
763        assert_eq!(reviews[0].action_summary, "1");
764        assert_eq!(
765            reviews.last().unwrap().action_summary,
766            GUARDIAN_DENIAL_WINDOW.to_string()
767        );
768        context.clear_prior_guardian_reviews();
769        assert!(context.prior_guardian_reviews().is_empty());
770    }
771
772    fn message(id: &str, text: &str) -> SessionUpdate {
773        serde_json::from_value(json!({"sessionUpdate":"agent_message_chunk","messageId":id,"content":{"type":"text","text":text}})).unwrap()
774    }
775
776    fn tool(title: &str) -> SessionUpdate {
777        serde_json::from_value(json!({"sessionUpdate":"tool_call","toolCallId":title,"title":title,"status":"in_progress"})).unwrap()
778    }
779
780    #[test]
781    fn diagnostic_logging_does_not_change_evidence_or_generation_and_survives_reset() {
782        let context = TurnContext::default();
783        context.reset(None, "Implement the parser");
784        let generation = context.generation();
785        let before = serde_json::to_value(context.evidence(
786            HarnessKind::Codex,
787            TurnPhase::Running,
788            &Default::default(),
789            0,
790        ))
791        .unwrap();
792        let dir = tempfile::tempdir().unwrap();
793        let log = mj_core::jev::DecisionLog::open(dir.path().into()).unwrap();
794        context.set_decision_log(log.clone());
795        let attempt = log.start("s", "activity", "Who acts?", "Current request");
796        attempt.finish("unchanged", "Kept runtime facts");
797        assert_eq!(context.generation(), generation);
798        assert_eq!(
799            serde_json::to_value(context.evidence(
800                HarnessKind::Codex,
801                TurnPhase::Running,
802                &Default::default(),
803                0
804            ))
805            .unwrap(),
806            before
807        );
808        context.reset(None, "New work");
809        assert!(context.decision_log().is_some());
810    }
811
812    #[test]
813    fn verdict_uses_latest_delivered_user_without_tool_history_but_keeps_live_facts() {
814        use mj_core::relay::RelayObservation;
815        let context = TurnContext::default();
816        let start = |id: &str| RelayObservation::CommandStarted {
817            command_id: id.into(),
818            started_at_ms: 0,
819        };
820        context.observe_relay(&start("old"), Some("OLD REQUEST"));
821        context.observe(&message("old", "OLD ANSWER"));
822        context.observe(&tool("active-build"));
823        context.observe_relay(&start("new"), Some("CURRENT REQUEST"));
824        let noisy: SessionUpdate = serde_json::from_value(json!({
825            "sessionUpdate":"tool_call", "toolCallId":"noisy", "title":"noisy", "status":"completed",
826            "rawInput":{"command":"TOOL_BODY".repeat(20_000)}
827        })).unwrap();
828        context.observe(&noisy);
829        context.observe(&message("new", "CURRENT ANSWER"));
830        let facts = ActivityFacts {
831            background_commands: 2,
832            queued_commands: 3,
833            tools_in_flight: vec![InFlightToolCall {
834                tool_call_id: "active-build".into(),
835                title: Some("active-build".into()),
836                status: agent_client_protocol::v1::schema::ToolCallStatus::InProgress,
837                started_at_ms: 1_000,
838            }],
839            ..Default::default()
840        };
841        let evidence = context.evidence(HarnessKind::Codex, TurnPhase::Running, &facts, 5_000);
842        assert!(evidence.transcript_summary.contains("CURRENT REQUEST"));
843        assert!(evidence.transcript_summary.contains("CURRENT ANSWER"));
844        for excluded in [
845            "OLD REQUEST",
846            "OLD ANSWER",
847            "TOOL_BODY",
848            "<tool",
849            "bytes omitted",
850        ] {
851            assert!(
852                !evidence.transcript_summary.contains(excluded),
853                "{excluded}"
854            );
855        }
856        assert_eq!(evidence.user_prompt_tail, "CURRENT REQUEST");
857        assert_eq!(evidence.assistant_text_tail, "CURRENT ANSWER");
858        assert_eq!(evidence.background_commands, 2);
859        assert_eq!(evidence.queued_commands, 3);
860        assert_eq!(evidence.tools_in_flight.len(), 1);
861        assert!(evidence.tools_in_flight[0].title.contains("active-build"));
862        assert_eq!(evidence.tools_in_flight[0].running_s, 4);
863        let full = context.0.lock().unwrap().summary.render(256 * 1024);
864        assert!(full.contains("OLD REQUEST") && full.contains("TOOL_BODY"));
865    }
866
867    #[test]
868    fn tool_calls_after_the_last_assistant_text_are_named_in_the_evidence() {
869        use mj_core::relay::RelayObservation;
870        let context = TurnContext::default();
871        context.observe_relay(
872            &RelayObservation::CommandStarted {
873                command_id: "audit".into(),
874                started_at_ms: 0,
875            },
876            Some("Audit the cache and hand back."),
877        );
878        context.observe(&message("m1", "I'm checking the update paths now."));
879        let handback: SessionUpdate = serde_json::from_value(json!({
880            "sessionUpdate":"tool_call", "toolCallId":"hb", "title":"mcp__mj-agents__handback",
881            "status":"completed", "rawInput":{"report":"done"}
882        }))
883        .unwrap();
884        context.observe(&handback);
885        let facts = ActivityFacts::default();
886        let evidence = context.evidence(HarnessKind::Codex, TurnPhase::Replied, &facts, 5_000);
887        assert_eq!(evidence.final_tool_calls.len(), 1);
888        assert!(evidence.final_tool_calls[0].name.contains("handback"));
889        assert_eq!(evidence.final_tool_calls[0].status, "completed");
890        // Text after the call closes the list again.
891        context.observe(&message("m2", "Handed back."));
892        let evidence = context.evidence(HarnessKind::Codex, TurnPhase::Replied, &facts, 5_000);
893        assert!(evidence.final_tool_calls.is_empty());
894    }
895
896    #[test]
897    fn evidence_caps_utf8_text_tools_and_durations() {
898        let context = TurnContext::default();
899        context.reset(None, &"é".repeat(20_000));
900        context.observe(&message("first", &"🦀".repeat(20_000)));
901        let first = context.evidence(
902            HarnessKind::Claude,
903            TurnPhase::Running,
904            &ActivityFacts::default(),
905            0,
906        );
907        assert_eq!(first.user_prompt_tail.len(), USER_PROMPT_BYTES);
908        assert_eq!(first.assistant_text_tail.len(), ASSISTANT_TEXT_BYTES);
909        for n in 0..20 {
910            context.observe(&tool(&format!("{n}{}", "é".repeat(300))));
911        }
912        let facts = ActivityFacts {
913            last_acp_activity_at_ms: Some(1_000),
914            background_commands: 3,
915            queued_commands: 2,
916            tools_in_flight: (0..100)
917                .map(|n| InFlightToolCall {
918                    tool_call_id: n.to_string(),
919                    title: Some("🦀".repeat(200)),
920                    status: agent_client_protocol::v1::schema::ToolCallStatus::InProgress,
921                    started_at_ms: 2_000,
922                })
923                .collect(),
924            ..Default::default()
925        };
926        let evidence = context.evidence(HarnessKind::Claude, TurnPhase::Running, &facts, 95_000);
927        assert_eq!(evidence.tools_in_flight.len(), IN_FLIGHT_TOOLS);
928        assert!(
929            evidence
930                .tools_in_flight
931                .iter()
932                .all(|tool| tool.title.len() <= TOOL_TITLE_BYTES && tool.running_s == 93)
933        );
934        assert!(evidence.transcript_summary.len() <= 48 * 1024);
935        assert_eq!(evidence.assistant_text_tail, first.assistant_text_tail);
936        assert_eq!(evidence.silent_for_s, 94);
937        let json = serde_json::to_value(evidence).unwrap();
938        assert_eq!(json["phase"], "running");
939        assert_eq!(json["harness"], "claude");
940        assert_eq!(json["background_commands"], 3);
941        assert_eq!(json["queued_commands"], 2);
942        assert!(serde_json::to_vec(&json).unwrap().len() < 64 * 1024);
943    }
944
945    #[test]
946    fn message_boundaries_and_prompt_reset_do_not_mix_answers() {
947        let context = TurnContext::default();
948        context.reset(None, "First prompt");
949        context.observe(&message("one", "Old answer"));
950        context.observe(&message("two", "New "));
951        context.observe(&message("two", "answer?"));
952        let evidence = context.evidence(
953            HarnessKind::Claude,
954            TurnPhase::Replied,
955            &ActivityFacts::default(),
956            0,
957        );
958        assert_eq!(evidence.assistant_text_tail, "New answer?");
959        let generation = context.generation();
960        context.set_counts(1, 2);
961        assert_ne!(context.generation(), generation);
962        let generation = context.generation();
963        context.set_counts(1, 2);
964        assert_eq!(context.generation(), generation);
965        assert_eq!(context.counts(), (1, 2));
966        context.invalidate();
967        assert_ne!(context.generation(), generation);
968        assert_eq!(context.counts(), (1, 2));
969        let generation = context.generation();
970        context.reset(None, "Second prompt");
971        assert_eq!(context.counts(), (1, 2));
972        assert_ne!(context.generation(), generation);
973        let evidence = context.evidence(
974            HarnessKind::Claude,
975            TurnPhase::Running,
976            &ActivityFacts::default(),
977            0,
978        );
979        assert_eq!(evidence.user_prompt_tail, "Second prompt");
980        assert!(evidence.assistant_text_tail.is_empty());
981        assert!(!evidence.transcript_summary.contains("<user>"));
982        // A prompt Mjolnir submitted is not the person's latest request.
983        context.reset(Some("mailbox-wake-1"), "A child finished its task.");
984        let evidence = context.evidence(
985            HarnessKind::Claude,
986            TurnPhase::Running,
987            &ActivityFacts::default(),
988            0,
989        );
990        assert!(evidence.user_prompt_tail.is_empty());
991    }
992    // Hard-won: 753b1f960: recovery lost its request when the original start left the hot journal.
993    #[test]
994    fn recovery_initializes_missing_request_and_preserves_restored_corrections() {
995        use mj_core::relay::RelayObservation;
996        for restored in [false, true] {
997            let context = TurnContext::default();
998            if restored {
999                context.observe_relay(
1000                    &RelayObservation::CommandStarted {
1001                        command_id: "correction".into(),
1002                        started_at_ms: 1,
1003                    },
1004                    Some("Use the corrected approach"),
1005                );
1006                context.observe(&message("partial", "Partial work"));
1007            } else {
1008                context.mark_earlier_history_omitted();
1009                context.observe(&message("suffix", "Only the tail survived"));
1010            }
1011            let recovery = mj_core::continuation::restart_continuation_id("original");
1012            context.observe_relay(
1013                &RelayObservation::CommandStarted {
1014                    command_id: recovery.clone(),
1015                    started_at_ms: 2,
1016                },
1017                Some("Original request"),
1018            );
1019            let evidence = context.evidence(
1020                HarnessKind::Codex,
1021                TurnPhase::Running,
1022                &ActivityFacts::default(),
1023                0,
1024            );
1025            assert_eq!(
1026                evidence.user_prompt_tail,
1027                if restored {
1028                    "Use the corrected approach"
1029                } else {
1030                    "Original request"
1031                }
1032            );
1033            assert!(evidence.transcript_summary.contains(if restored {
1034                "Use the corrected approach"
1035            } else {
1036                "Original request"
1037            }));
1038            assert_eq!(
1039                evidence.assistant_text_tail,
1040                if restored {
1041                    "Partial work"
1042                } else {
1043                    "Only the tail survived"
1044                }
1045            );
1046            assert!(evidence.transcript_summary.contains(if restored {
1047                "Partial work"
1048            } else {
1049                "Only the tail survived"
1050            }));
1051            let before = evidence.transcript_summary;
1052            context.observe_relay(
1053                &RelayObservation::CommandStarted {
1054                    command_id: mj_core::continuation::restart_continuation_id(&recovery),
1055                    started_at_ms: 3,
1056                },
1057                Some("Original request"),
1058            );
1059            assert_eq!(
1060                context
1061                    .evidence(
1062                        HarnessKind::Codex,
1063                        TurnPhase::Running,
1064                        &ActivityFacts::default(),
1065                        0
1066                    )
1067                    .transcript_summary,
1068                before
1069            );
1070        }
1071    }
1072}