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(),
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: tail(
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                    TOOL_TITLE_BYTES,
335                ),
336                status: e
337                    .tool
338                    .as_ref()
339                    .and_then(|t| t.get("status"))
340                    .and_then(|s| s.as_str())
341                    .unwrap_or("unknown")
342                    .to_owned(),
343            })
344            .collect();
345        let mut evidence = TurnEvidence {
346            authorization: None,
347            final_tool_calls,
348            background: Vec::new(),
349            harness,
350            phase,
351            silent_for_s: facts
352                .last_acp_activity_at_ms
353                .map_or(0, |last| now_ms.saturating_sub(last).max(0) as u64 / 1000),
354            tools_in_flight: facts
355                .tools_in_flight
356                .iter()
357                .take(IN_FLIGHT_TOOLS)
358                .map(|tool| ToolEvidence {
359                    title: tail(
360                        &state
361                            .summary
362                            .entries
363                            .iter()
364                            .find(|e| e.id == tool.tool_call_id)
365                            .map(|e| e.text.clone())
366                            .unwrap_or_else(|| "unknown tool".into()),
367                        TOOL_TITLE_BYTES,
368                    ),
369                    running_s: now_ms.saturating_sub(tool.started_at_ms).max(0) as u64 / 1000,
370                })
371                .collect(),
372            transcript_summary: summary.render(48 * 1024),
373            background_commands: facts.background_commands,
374            queued_commands: facts.queued_commands,
375            user_prompt_tail: state.user_prompt_tail.clone(),
376            assistant_text_tail: if state.assistant_text_tail.is_empty() {
377                state.last_completed_message.clone()
378            } else {
379                state.assistant_text_tail.clone()
380            },
381            completion: None,
382        };
383        let mut limit = 48 * 1024;
384        while limit > 0 && !mj_core::activity::verdict::request_fits(&evidence) {
385            limit /= 2;
386            evidence.transcript_summary = summary.render(limit);
387        }
388        evidence
389    }
390}
391
392fn complete_message(state: &mut TurnContextState) {
393    if !state.assistant_text_tail.is_empty() {
394        state.last_completed_message = std::mem::take(&mut state.assistant_text_tail);
395    }
396    state.message_id = None;
397}
398
399fn tail(text: &str, maximum_bytes: usize) -> String {
400    let start = text.floor_char_boundary(text.len().saturating_sub(maximum_bytes));
401    let mut value = text[start..].to_owned();
402    mj_core::transcript::truncate_string_start(&mut value, maximum_bytes);
403    value
404}
405
406#[cfg(test)]
407mod tests {
408    use super::*;
409    use mj_core::activity::InFlightToolCall;
410    use serde_json::json;
411    fn message(id: &str, text: &str) -> SessionUpdate {
412        serde_json::from_value(json!({"sessionUpdate":"agent_message_chunk","messageId":id,"content":{"type":"text","text":text}})).unwrap()
413    }
414
415    fn tool(title: &str) -> SessionUpdate {
416        serde_json::from_value(json!({"sessionUpdate":"tool_call","toolCallId":title,"title":title,"status":"in_progress"})).unwrap()
417    }
418
419    #[test]
420    fn diagnostic_logging_does_not_change_evidence_or_generation_and_survives_reset() {
421        let context = TurnContext::default();
422        context.reset(None, "Implement the parser");
423        let generation = context.generation();
424        let before = serde_json::to_value(context.evidence(
425            HarnessKind::Codex,
426            TurnPhase::Running,
427            &Default::default(),
428            0,
429        ))
430        .unwrap();
431        let dir = tempfile::tempdir().unwrap();
432        let log = mj_core::jev::DecisionLog::open(dir.path().into()).unwrap();
433        context.set_decision_log(log.clone());
434        let attempt = log.start("s", "activity", "Who acts?", "Current request");
435        attempt.finish("unchanged", "Kept runtime facts");
436        assert_eq!(context.generation(), generation);
437        assert_eq!(
438            serde_json::to_value(context.evidence(
439                HarnessKind::Codex,
440                TurnPhase::Running,
441                &Default::default(),
442                0
443            ))
444            .unwrap(),
445            before
446        );
447        context.reset(None, "New work");
448        assert!(context.decision_log().is_some());
449    }
450
451    #[test]
452    fn verdict_uses_latest_delivered_user_without_tool_history_but_keeps_live_facts() {
453        use mj_core::relay::RelayObservation;
454        let context = TurnContext::default();
455        let start = |id: &str| RelayObservation::CommandStarted {
456            command_id: id.into(),
457            started_at_ms: 0,
458        };
459        context.observe_relay(&start("old"), Some("OLD REQUEST"));
460        context.observe(&message("old", "OLD ANSWER"));
461        context.observe(&tool("active-build"));
462        context.observe_relay(&start("new"), Some("CURRENT REQUEST"));
463        let noisy: SessionUpdate = serde_json::from_value(json!({
464            "sessionUpdate":"tool_call", "toolCallId":"noisy", "title":"noisy", "status":"completed",
465            "rawInput":{"command":"TOOL_BODY".repeat(20_000)}
466        })).unwrap();
467        context.observe(&noisy);
468        context.observe(&message("new", "CURRENT ANSWER"));
469        let facts = ActivityFacts {
470            background_commands: 2,
471            queued_commands: 3,
472            tools_in_flight: vec![InFlightToolCall {
473                tool_call_id: "active-build".into(),
474                title: Some("active-build".into()),
475                status: agent_client_protocol::v1::schema::ToolCallStatus::InProgress,
476                started_at_ms: 1_000,
477            }],
478            ..Default::default()
479        };
480        let evidence = context.evidence(HarnessKind::Codex, TurnPhase::Running, &facts, 5_000);
481        assert!(evidence.transcript_summary.contains("CURRENT REQUEST"));
482        assert!(evidence.transcript_summary.contains("CURRENT ANSWER"));
483        for excluded in [
484            "OLD REQUEST",
485            "OLD ANSWER",
486            "TOOL_BODY",
487            "<tool",
488            "bytes omitted",
489        ] {
490            assert!(
491                !evidence.transcript_summary.contains(excluded),
492                "{excluded}"
493            );
494        }
495        assert_eq!(evidence.user_prompt_tail, "CURRENT REQUEST");
496        assert_eq!(evidence.assistant_text_tail, "CURRENT ANSWER");
497        assert_eq!(evidence.background_commands, 2);
498        assert_eq!(evidence.queued_commands, 3);
499        assert_eq!(evidence.tools_in_flight.len(), 1);
500        assert!(evidence.tools_in_flight[0].title.contains("active-build"));
501        assert_eq!(evidence.tools_in_flight[0].running_s, 4);
502        let full = context.0.lock().unwrap().summary.render(256 * 1024);
503        assert!(full.contains("OLD REQUEST") && full.contains("TOOL_BODY"));
504    }
505
506    #[test]
507    fn tool_calls_after_the_last_assistant_text_are_named_in_the_evidence() {
508        use mj_core::relay::RelayObservation;
509        let context = TurnContext::default();
510        context.observe_relay(
511            &RelayObservation::CommandStarted {
512                command_id: "audit".into(),
513                started_at_ms: 0,
514            },
515            Some("Audit the cache and hand back."),
516        );
517        context.observe(&message("m1", "I'm checking the update paths now."));
518        let handback: SessionUpdate = serde_json::from_value(json!({
519            "sessionUpdate":"tool_call", "toolCallId":"hb", "title":"mcp__mj-agents__handback",
520            "status":"completed", "rawInput":{"report":"done"}
521        }))
522        .unwrap();
523        context.observe(&handback);
524        let facts = ActivityFacts::default();
525        let evidence = context.evidence(HarnessKind::Codex, TurnPhase::Replied, &facts, 5_000);
526        assert_eq!(evidence.final_tool_calls.len(), 1);
527        assert!(evidence.final_tool_calls[0].name.contains("handback"));
528        assert_eq!(evidence.final_tool_calls[0].status, "completed");
529        // Text after the call closes the list again.
530        context.observe(&message("m2", "Handed back."));
531        let evidence = context.evidence(HarnessKind::Codex, TurnPhase::Replied, &facts, 5_000);
532        assert!(evidence.final_tool_calls.is_empty());
533    }
534
535    #[test]
536    fn evidence_caps_utf8_text_tools_and_durations() {
537        let context = TurnContext::default();
538        context.reset(None, &"é".repeat(20_000));
539        context.observe(&message("first", &"🦀".repeat(20_000)));
540        let first = context.evidence(
541            HarnessKind::Claude,
542            TurnPhase::Running,
543            &ActivityFacts::default(),
544            0,
545        );
546        assert_eq!(first.user_prompt_tail.len(), USER_PROMPT_BYTES);
547        assert_eq!(first.assistant_text_tail.len(), ASSISTANT_TEXT_BYTES);
548        for n in 0..20 {
549            context.observe(&tool(&format!("{n}{}", "é".repeat(300))));
550        }
551        let facts = ActivityFacts {
552            last_acp_activity_at_ms: Some(1_000),
553            background_commands: 3,
554            queued_commands: 2,
555            tools_in_flight: (0..100)
556                .map(|n| InFlightToolCall {
557                    tool_call_id: n.to_string(),
558                    title: Some("🦀".repeat(200)),
559                    status: agent_client_protocol::v1::schema::ToolCallStatus::InProgress,
560                    started_at_ms: 2_000,
561                })
562                .collect(),
563            ..Default::default()
564        };
565        let evidence = context.evidence(HarnessKind::Claude, TurnPhase::Running, &facts, 95_000);
566        assert_eq!(evidence.tools_in_flight.len(), IN_FLIGHT_TOOLS);
567        assert!(
568            evidence
569                .tools_in_flight
570                .iter()
571                .all(|tool| tool.title.len() <= TOOL_TITLE_BYTES && tool.running_s == 93)
572        );
573        assert!(evidence.transcript_summary.len() <= 48 * 1024);
574        assert_eq!(evidence.assistant_text_tail, first.assistant_text_tail);
575        assert_eq!(evidence.silent_for_s, 94);
576        let json = serde_json::to_value(evidence).unwrap();
577        assert_eq!(json["phase"], "running");
578        assert_eq!(json["harness"], "claude");
579        assert_eq!(json["background_commands"], 3);
580        assert_eq!(json["queued_commands"], 2);
581        assert!(serde_json::to_vec(&json).unwrap().len() < 64 * 1024);
582    }
583
584    #[test]
585    fn message_boundaries_and_prompt_reset_do_not_mix_answers() {
586        let context = TurnContext::default();
587        context.reset(None, "First prompt");
588        context.observe(&message("one", "Old answer"));
589        context.observe(&message("two", "New "));
590        context.observe(&message("two", "answer?"));
591        let evidence = context.evidence(
592            HarnessKind::Claude,
593            TurnPhase::Replied,
594            &ActivityFacts::default(),
595            0,
596        );
597        assert_eq!(evidence.assistant_text_tail, "New answer?");
598        let generation = context.generation();
599        context.set_counts(1, 2);
600        assert_ne!(context.generation(), generation);
601        let generation = context.generation();
602        context.set_counts(1, 2);
603        assert_eq!(context.generation(), generation);
604        assert_eq!(context.counts(), (1, 2));
605        context.invalidate();
606        assert_ne!(context.generation(), generation);
607        assert_eq!(context.counts(), (1, 2));
608        let generation = context.generation();
609        context.reset(None, "Second prompt");
610        assert_eq!(context.counts(), (1, 2));
611        assert_ne!(context.generation(), generation);
612        let evidence = context.evidence(
613            HarnessKind::Claude,
614            TurnPhase::Running,
615            &ActivityFacts::default(),
616            0,
617        );
618        assert_eq!(evidence.user_prompt_tail, "Second prompt");
619        assert!(evidence.assistant_text_tail.is_empty());
620        assert!(!evidence.transcript_summary.contains("<user>"));
621        // A prompt Mjolnir submitted is not the person's latest request.
622        context.reset(Some("mailbox-wake-1"), "A child finished its task.");
623        let evidence = context.evidence(
624            HarnessKind::Claude,
625            TurnPhase::Running,
626            &ActivityFacts::default(),
627            0,
628        );
629        assert!(evidence.user_prompt_tail.is_empty());
630    }
631}