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: 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        let user_prompt_tail =
89            if mj_core::continuation::is_user_authored_message(command_id, prompt) {
90                tail(prompt, USER_PROMPT_BYTES)
91            } else {
92                String::new()
93            };
94        let mut state = self.0.lock().expect("turn context lock poisoned");
95        let generation = state.generation.wrapping_add(1);
96        *state = TurnContextState {
97            generation,
98            parent_activity: Some(std::time::Instant::now()),
99            decision_log: state.decision_log.clone(),
100            authorization: state.authorization.clone(),
101            user_prompt_tail,
102            background_commands: state.background_commands,
103            queued_commands: state.queued_commands,
104            background_inventory: std::mem::take(&mut state.background_inventory),
105            native_agent_ids: std::mem::take(&mut state.native_agent_ids),
106            session_id: std::mem::take(&mut state.session_id),
107            summary: std::mem::take(&mut state.summary),
108            ..Default::default()
109        };
110    }
111
112    /// Record durable transcript observations through the same path during live work and replay.
113    pub fn observe_relay(
114        &self,
115        observation: &mj_core::relay::RelayObservation,
116        prompt: Option<&str>,
117    ) {
118        use mj_core::relay::{RelayCommandOutcome, RelayObservation};
119        match observation {
120            RelayObservation::CommandStarted { .. }
121            | RelayObservation::CommandCompleted {
122                outcome: RelayCommandOutcome::Steered { .. },
123                ..
124            }
125            | RelayObservation::MailboxEventsDelivered {
126                steering: Some(_), ..
127            } => {
128                if let Some(prompt) = prompt {
129                    self.reset(delivered_prompt_command_id(observation), prompt);
130                    self.0
131                        .lock()
132                        .expect("turn context lock poisoned")
133                        .summary
134                        .push_user(prompt);
135                }
136            }
137            RelayObservation::SessionUpdate { update } => self.observe(update),
138            RelayObservation::TerminalOutput {
139                terminal_id,
140                output,
141                truncated,
142                exit_code,
143                signal,
144            } => {
145                self.observe_terminal(&mj_core::transcript::TerminalOutputRecord {
146                    terminal_id: terminal_id.clone(),
147                    output: output.clone().into(),
148                    truncated: *truncated,
149                    exit_code: *exit_code,
150                    signal: signal.clone(),
151                });
152            }
153            RelayObservation::CommandCompleted {
154                outcome: RelayCommandOutcome::ContextCleared { .. },
155                ..
156            } => self.clear_history(),
157            _ => {}
158        }
159    }
160
161    /// Invalidate a pending verdict at a lifecycle boundary without discarding evidence.
162    pub fn invalidate(&self) {
163        let mut state = self.0.lock().expect("turn context lock poisoned");
164        state.generation = state.generation.wrapping_add(1);
165    }
166
167    pub fn generation(&self) -> u64 {
168        self.0
169            .lock()
170            .expect("turn context lock poisoned")
171            .generation
172    }
173
174    pub fn counts(&self) -> (usize, usize) {
175        let state = self.0.lock().expect("turn context lock poisoned");
176        (state.background_commands, state.queued_commands)
177    }
178
179    pub fn set_counts(&self, background_commands: usize, queued_commands: usize) {
180        let mut state = self.0.lock().expect("turn context lock poisoned");
181        if (state.background_commands, state.queued_commands)
182            != (background_commands, queued_commands)
183        {
184            state.generation = state.generation.wrapping_add(1);
185            state.background_commands = background_commands;
186            state.queued_commands = queued_commands;
187        }
188    }
189
190    pub fn set_session_id(&self, session_id: &str) {
191        self.0
192            .lock()
193            .expect("turn context lock poisoned")
194            .session_id = session_id.into();
195    }
196
197    pub fn session_id(&self) -> String {
198        self.0
199            .lock()
200            .expect("turn context lock poisoned")
201            .session_id
202            .clone()
203    }
204
205    /// Publish the relay owner's durable user-instruction history to the ACP
206    /// classifier. A change invalidates any request built from older context.
207    pub fn set_authorization_context(
208        &self,
209        authorization: Option<mj_core::assessment::ContextHistory>,
210    ) {
211        let mut state = self.0.lock().expect("turn context lock poisoned");
212        if state.authorization != authorization {
213            state.authorization = authorization;
214            state.generation = state.generation.wrapping_add(1);
215        }
216    }
217
218    pub fn authorization_context(&self) -> Option<mj_core::assessment::ContextHistory> {
219        self.0
220            .lock()
221            .expect("turn context lock poisoned")
222            .authorization
223            .clone()
224    }
225
226    /// Compare identities as well as counts; identical level reports are not activity.
227    pub fn set_background_inventory(
228        &self,
229        mut commands: Vec<mj_core::relay::BackgroundCommand>,
230        mut native_agent_ids: Vec<String>,
231    ) {
232        commands.sort_by(|a, b| a.id.cmp(&b.id));
233        native_agent_ids.sort();
234        let mut state = self.0.lock().expect("turn context lock poisoned");
235        if state.background_inventory != commands || state.native_agent_ids != native_agent_ids {
236            state.background_inventory = commands;
237            state.native_agent_ids = native_agent_ids;
238            state.generation = state.generation.wrapping_add(1);
239        }
240    }
241
242    pub fn observe(&self, update: &SessionUpdate) {
243        let mut state = self.0.lock().expect("turn context lock poisoned");
244        state.parent_activity = Some(std::time::Instant::now());
245        if matches!(
246            update,
247            SessionUpdate::AgentMessageChunk(_)
248                | SessionUpdate::AgentThoughtChunk(_)
249                | SessionUpdate::ToolCall(_)
250                | SessionUpdate::ToolCallUpdate(_)
251        ) {
252            state.generation = state.generation.wrapping_add(1);
253        }
254        state.summary.observe(update);
255        match update {
256            SessionUpdate::AgentMessageChunk(chunk) => {
257                let id = chunk.message_id.as_ref().map(ToString::to_string);
258                if id != state.message_id {
259                    complete_message(&mut state);
260                    state.message_id = id;
261                }
262                if let ContentBlock::Text(content) = &chunk.content {
263                    // Trim each chunk before appending, so a huge chunk never grows retained state.
264                    state
265                        .assistant_text_tail
266                        .push_str(&tail(&content.text, ASSISTANT_TEXT_BYTES));
267                    state.assistant_text_tail =
268                        tail(&state.assistant_text_tail, ASSISTANT_TEXT_BYTES);
269                }
270            }
271            SessionUpdate::ToolCall(_) => {
272                complete_message(&mut state);
273            }
274            SessionUpdate::ToolCallUpdate(_) | SessionUpdate::AgentThoughtChunk(_) => {
275                complete_message(&mut state)
276            }
277            _ => {}
278        }
279    }
280
281    pub fn observe_terminal(&self, record: &mj_core::transcript::TerminalOutputRecord) {
282        let mut state = self.0.lock().expect("turn context lock poisoned");
283        state.summary.observe_terminal(record);
284        state.generation = state.generation.wrapping_add(1);
285    }
286
287    pub fn mark_earlier_history_omitted(&self) {
288        self.0
289            .lock()
290            .expect("turn context lock poisoned")
291            .summary
292            .mark_earlier_history_omitted();
293    }
294
295    pub fn clear_history(&self) {
296        let mut state = self.0.lock().expect("turn context lock poisoned");
297        state.summary = Default::default();
298        state.user_prompt_tail.clear();
299        state.assistant_text_tail.clear();
300        state.last_completed_message.clear();
301        state.message_id = None;
302        state.authorization = None;
303        state.generation = state.generation.wrapping_add(1);
304    }
305
306    pub fn evidence(
307        &self,
308        harness: HarnessKind,
309        phase: TurnPhase,
310        facts: &ActivityFacts,
311        now_ms: i64,
312    ) -> TurnEvidence {
313        let state = self.0.lock().expect("turn context lock poisoned");
314        let summary = state.summary.latest_user_messages();
315        let last_assistant = state
316            .summary
317            .entries
318            .iter()
319            .rposition(|e| e.role == crate::summary::SummaryRole::Assistant);
320        let final_tool_calls = state
321            .summary
322            .entries
323            .iter()
324            .skip(last_assistant.map_or(0, |i| i + 1))
325            .filter(|e| e.role == crate::summary::SummaryRole::Tool)
326            .take(IN_FLIGHT_TOOLS)
327            .map(|e| mj_core::activity::verdict::ToolOutcome {
328                name: tool_title(
329                    e.tool
330                        .as_ref()
331                        .and_then(|t| t.get("name"))
332                        .and_then(|n| n.as_str())
333                        .unwrap_or(&e.text),
334                ),
335                status: e
336                    .tool
337                    .as_ref()
338                    .and_then(|t| t.get("status"))
339                    .and_then(|s| s.as_str())
340                    .unwrap_or("unknown")
341                    .to_owned(),
342            })
343            .collect();
344        TurnEvidence {
345            authorization: None,
346            final_tool_calls,
347            background: Vec::new(),
348            harness,
349            phase,
350            silent_for_s: facts
351                .last_acp_activity_at_ms
352                .map_or(0, |last| now_ms.saturating_sub(last).max(0) as u64 / 1000),
353            tools_in_flight: facts
354                .tools_in_flight
355                .iter()
356                .take(IN_FLIGHT_TOOLS)
357                .map(|tool| ToolEvidence {
358                    title: tool_title(
359                        state
360                            .summary
361                            .entries
362                            .iter()
363                            .find(|e| e.id == tool.tool_call_id)
364                            .map_or("unknown tool", |e| e.text.as_str()),
365                    ),
366                    running_s: now_ms.saturating_sub(tool.started_at_ms).max(0) as u64 / 1000,
367                })
368                .collect(),
369            transcript_summary: summary.render(48 * 1024),
370            background_commands: facts.background_commands,
371            queued_commands: facts.queued_commands,
372            user_prompt_tail: state.user_prompt_tail.clone(),
373            assistant_text_tail: if state.assistant_text_tail.is_empty() {
374                state.last_completed_message.clone()
375            } else {
376                state.assistant_text_tail.clone()
377            },
378            completion: None,
379        }
380    }
381}
382
383fn complete_message(state: &mut TurnContextState) {
384    if !state.assistant_text_tail.is_empty() {
385        state.last_completed_message = std::mem::take(&mut state.assistant_text_tail);
386    }
387    state.message_id = None;
388}
389
390/// The last `maximum_bytes` of `text`, cut at a character boundary: the tail
391/// every turn classifier receives.
392pub fn tail(text: &str, maximum_bytes: usize) -> String {
393    let start = text.floor_char_boundary(text.len().saturating_sub(maximum_bytes));
394    let mut value = text[start..].to_owned();
395    mj_core::transcript::truncate_string_start(&mut value, maximum_bytes);
396    value
397}
398
399#[cfg(test)]
400mod tests {
401    use super::*;
402    use mj_core::activity::InFlightToolCall;
403    use serde_json::json;
404    fn message(id: &str, text: &str) -> SessionUpdate {
405        serde_json::from_value(json!({"sessionUpdate":"agent_message_chunk","messageId":id,"content":{"type":"text","text":text}})).unwrap()
406    }
407
408    fn tool(title: &str) -> SessionUpdate {
409        serde_json::from_value(json!({"sessionUpdate":"tool_call","toolCallId":title,"title":title,"status":"in_progress"})).unwrap()
410    }
411
412    #[test]
413    fn diagnostic_logging_does_not_change_evidence_or_generation_and_survives_reset() {
414        let context = TurnContext::default();
415        context.reset(None, "Implement the parser");
416        let generation = context.generation();
417        let before = serde_json::to_value(context.evidence(
418            HarnessKind::Codex,
419            TurnPhase::Running,
420            &Default::default(),
421            0,
422        ))
423        .unwrap();
424        let dir = tempfile::tempdir().unwrap();
425        let log = mj_core::jev::DecisionLog::open(dir.path().into()).unwrap();
426        context.set_decision_log(log.clone());
427        let attempt = log.start("s", "activity", "Who acts?", "Current request");
428        attempt.finish("unchanged", "Kept runtime facts");
429        assert_eq!(context.generation(), generation);
430        assert_eq!(
431            serde_json::to_value(context.evidence(
432                HarnessKind::Codex,
433                TurnPhase::Running,
434                &Default::default(),
435                0
436            ))
437            .unwrap(),
438            before
439        );
440        context.reset(None, "New work");
441        assert!(context.decision_log().is_some());
442    }
443
444    #[test]
445    fn verdict_uses_latest_delivered_user_without_tool_history_but_keeps_live_facts() {
446        use mj_core::relay::RelayObservation;
447        let context = TurnContext::default();
448        let start = |id: &str| RelayObservation::CommandStarted {
449            command_id: id.into(),
450            started_at_ms: 0,
451        };
452        context.observe_relay(&start("old"), Some("OLD REQUEST"));
453        context.observe(&message("old", "OLD ANSWER"));
454        context.observe(&tool("active-build"));
455        context.observe_relay(&start("new"), Some("CURRENT REQUEST"));
456        let noisy: SessionUpdate = serde_json::from_value(json!({
457            "sessionUpdate":"tool_call", "toolCallId":"noisy", "title":"noisy", "status":"completed",
458            "rawInput":{"command":"TOOL_BODY".repeat(20_000)}
459        })).unwrap();
460        context.observe(&noisy);
461        context.observe(&message("new", "CURRENT ANSWER"));
462        let facts = ActivityFacts {
463            background_commands: 2,
464            queued_commands: 3,
465            tools_in_flight: vec![InFlightToolCall {
466                tool_call_id: "active-build".into(),
467                title: Some("active-build".into()),
468                status: agent_client_protocol::v1::schema::ToolCallStatus::InProgress,
469                started_at_ms: 1_000,
470            }],
471            ..Default::default()
472        };
473        let evidence = context.evidence(HarnessKind::Codex, TurnPhase::Running, &facts, 5_000);
474        assert!(evidence.transcript_summary.contains("CURRENT REQUEST"));
475        assert!(evidence.transcript_summary.contains("CURRENT ANSWER"));
476        for excluded in [
477            "OLD REQUEST",
478            "OLD ANSWER",
479            "TOOL_BODY",
480            "<tool",
481            "bytes omitted",
482        ] {
483            assert!(
484                !evidence.transcript_summary.contains(excluded),
485                "{excluded}"
486            );
487        }
488        assert_eq!(evidence.user_prompt_tail, "CURRENT REQUEST");
489        assert_eq!(evidence.assistant_text_tail, "CURRENT ANSWER");
490        assert_eq!(evidence.background_commands, 2);
491        assert_eq!(evidence.queued_commands, 3);
492        assert_eq!(evidence.tools_in_flight.len(), 1);
493        assert!(evidence.tools_in_flight[0].title.contains("active-build"));
494        assert_eq!(evidence.tools_in_flight[0].running_s, 4);
495        let full = context.0.lock().unwrap().summary.render(256 * 1024);
496        assert!(full.contains("OLD REQUEST") && full.contains("TOOL_BODY"));
497    }
498
499    #[test]
500    fn tool_calls_after_the_last_assistant_text_are_named_in_the_evidence() {
501        use mj_core::relay::RelayObservation;
502        let context = TurnContext::default();
503        context.observe_relay(
504            &RelayObservation::CommandStarted {
505                command_id: "audit".into(),
506                started_at_ms: 0,
507            },
508            Some("Audit the cache and hand back."),
509        );
510        context.observe(&message("m1", "I'm checking the update paths now."));
511        let handback: SessionUpdate = serde_json::from_value(json!({
512            "sessionUpdate":"tool_call", "toolCallId":"hb", "title":"mcp__mj-agents__handback",
513            "status":"completed", "rawInput":{"report":"done"}
514        }))
515        .unwrap();
516        context.observe(&handback);
517        let facts = ActivityFacts::default();
518        let evidence = context.evidence(HarnessKind::Codex, TurnPhase::Replied, &facts, 5_000);
519        assert_eq!(evidence.final_tool_calls.len(), 1);
520        assert!(evidence.final_tool_calls[0].name.contains("handback"));
521        assert_eq!(evidence.final_tool_calls[0].status, "completed");
522        // Text after the call closes the list again.
523        context.observe(&message("m2", "Handed back."));
524        let evidence = context.evidence(HarnessKind::Codex, TurnPhase::Replied, &facts, 5_000);
525        assert!(evidence.final_tool_calls.is_empty());
526    }
527
528    #[test]
529    fn evidence_caps_utf8_text_tools_and_durations() {
530        let context = TurnContext::default();
531        context.reset(None, &"é".repeat(20_000));
532        context.observe(&message("first", &"🦀".repeat(20_000)));
533        let first = context.evidence(
534            HarnessKind::Claude,
535            TurnPhase::Running,
536            &ActivityFacts::default(),
537            0,
538        );
539        assert_eq!(first.user_prompt_tail.len(), USER_PROMPT_BYTES);
540        assert_eq!(first.assistant_text_tail.len(), ASSISTANT_TEXT_BYTES);
541        for n in 0..20 {
542            context.observe(&tool(&format!("{n}{}", "é".repeat(300))));
543        }
544        let facts = ActivityFacts {
545            last_acp_activity_at_ms: Some(1_000),
546            background_commands: 3,
547            queued_commands: 2,
548            tools_in_flight: (0..100)
549                .map(|n| InFlightToolCall {
550                    tool_call_id: n.to_string(),
551                    title: Some("🦀".repeat(200)),
552                    status: agent_client_protocol::v1::schema::ToolCallStatus::InProgress,
553                    started_at_ms: 2_000,
554                })
555                .collect(),
556            ..Default::default()
557        };
558        let evidence = context.evidence(HarnessKind::Claude, TurnPhase::Running, &facts, 95_000);
559        assert_eq!(evidence.tools_in_flight.len(), IN_FLIGHT_TOOLS);
560        assert!(
561            evidence
562                .tools_in_flight
563                .iter()
564                .all(|tool| tool.title.len() <= TOOL_TITLE_BYTES && tool.running_s == 93)
565        );
566        assert!(evidence.transcript_summary.len() <= 48 * 1024);
567        assert_eq!(evidence.assistant_text_tail, first.assistant_text_tail);
568        assert_eq!(evidence.silent_for_s, 94);
569        let json = serde_json::to_value(evidence).unwrap();
570        assert_eq!(json["phase"], "running");
571        assert_eq!(json["harness"], "claude");
572        assert_eq!(json["background_commands"], 3);
573        assert_eq!(json["queued_commands"], 2);
574        assert!(serde_json::to_vec(&json).unwrap().len() < 64 * 1024);
575    }
576
577    #[test]
578    fn message_boundaries_and_prompt_reset_do_not_mix_answers() {
579        let context = TurnContext::default();
580        context.reset(None, "First prompt");
581        context.observe(&message("one", "Old answer"));
582        context.observe(&message("two", "New "));
583        context.observe(&message("two", "answer?"));
584        let evidence = context.evidence(
585            HarnessKind::Claude,
586            TurnPhase::Replied,
587            &ActivityFacts::default(),
588            0,
589        );
590        assert_eq!(evidence.assistant_text_tail, "New answer?");
591        let generation = context.generation();
592        context.set_counts(1, 2);
593        assert_ne!(context.generation(), generation);
594        let generation = context.generation();
595        context.set_counts(1, 2);
596        assert_eq!(context.generation(), generation);
597        assert_eq!(context.counts(), (1, 2));
598        context.invalidate();
599        assert_ne!(context.generation(), generation);
600        assert_eq!(context.counts(), (1, 2));
601        let generation = context.generation();
602        context.reset(None, "Second prompt");
603        assert_eq!(context.counts(), (1, 2));
604        assert_ne!(context.generation(), generation);
605        let evidence = context.evidence(
606            HarnessKind::Claude,
607            TurnPhase::Running,
608            &ActivityFacts::default(),
609            0,
610        );
611        assert_eq!(evidence.user_prompt_tail, "Second prompt");
612        assert!(evidence.assistant_text_tail.is_empty());
613        assert!(!evidence.transcript_summary.contains("<user>"));
614        // A prompt Mjolnir submitted is not the person's latest request.
615        context.reset(Some("mailbox-wake-1"), "A child finished its task.");
616        let evidence = context.evidence(
617            HarnessKind::Claude,
618            TurnPhase::Running,
619            &ActivityFacts::default(),
620            0,
621        );
622        assert!(evidence.user_prompt_tail.is_empty());
623    }
624}