Skip to main content

mj_transcript/
summary.rs

1//! A deterministic model-facing view of history. Source transcripts stay lossless.
2use agent_client_protocol::v1::schema::{ContentBlock, SessionUpdate, ToolCall};
3use mj_core::archive::{CanonicalSessionSnapshot, CanonicalTranscriptBody};
4use mj_core::state::{MaterializedSession, TranscriptBody};
5use mj_core::transcript::{
6    ToolCallPresentation, materialized_chunks_text, materialized_content_text,
7};
8use serde_json::{Value, json};
9
10use crate::transcript::materialized_tool_call_presentation;
11
12/// Opening sentence of every handoff this module writes. Generation and
13/// detection share it so a later resume can always recognize its own prior
14/// handoff turns.
15pub const HANDOFF_PREAMBLE: &str =
16    "You are continuing a coding session previously run by another ACP harness.";
17/// Opening sentence of a hand-off written when an archived session is restored
18/// from the SessionWiki index. The restored session has no workspace from the
19/// old one, so it is marked apart from a cross-harness resume.
20pub const ARCHIVE_HANDOFF_PREAMBLE: &str = "Archived session restored from SessionWiki.";
21/// Opening sentence of the byte-truncating handoff this pipeline replaced.
22/// Sessions resumed by that build still carry it in their transcripts.
23pub const LEGACY_HANDOFF_PREAMBLE: &str =
24    "Continue this coding session from the portable transcript below.";
25/// What a prior handoff turn contributes to a new compaction. The transcript
26/// already carries the pre-resume lineage as ordinary turns, so repeating the
27/// handoff body would only spend budget on a summary of a summary.
28pub const HANDOFF_PLACEHOLDER: &str =
29    "[cross-harness resume handoff: continuing work from a prior harness]";
30/// Prior handoffs repeat history already represented in the lineage.
31fn user_text(text: String) -> String {
32    let trimmed = text.trim_start();
33    if [
34        HANDOFF_PREAMBLE,
35        ARCHIVE_HANDOFF_PREAMBLE,
36        LEGACY_HANDOFF_PREAMBLE,
37    ]
38    .iter()
39    .any(|p| trimmed.starts_with(p))
40    {
41        HANDOFF_PLACEHOLDER.into()
42    } else {
43        text
44    }
45}
46
47pub const FULL_TOOL_CALLS: usize = 8;
48/// Change when derived indexing content changes, even without a source update.
49pub const SUMMARY_VERSION: u32 = 3;
50pub const DEFAULT_SUMMARY_BYTES: usize = 256 * 1024;
51const LIVE_ITEMS: usize = 512;
52const LIVE_ITEM_BYTES: usize = 64 * 1024;
53
54#[derive(Debug, Clone, PartialEq, Eq)]
55pub enum SummaryRole {
56    User,
57    Assistant,
58    Message,
59    Tool,
60    Plan,
61}
62
63#[derive(Debug, Clone)]
64pub struct SummaryEntry {
65    pub id: String,
66    pub position: u64,
67    pub created_at_ms: i64,
68    pub role: SummaryRole,
69    pub text: String,
70    /// Full retained calls or a compact, outcome-only object. Never a presentation sidecar.
71    pub tool: Option<Value>,
72    terminal_refs: Vec<String>,
73}
74
75impl SummaryEntry {
76    pub fn body(&self) -> String {
77        self.tool
78            .as_ref()
79            .map_or_else(|| self.text.clone(), Value::to_string)
80    }
81
82    fn render(&self, body_limit: usize) -> String {
83        let role = match self.role {
84            SummaryRole::User => "user",
85            SummaryRole::Assistant => "assistant",
86            SummaryRole::Message => "message",
87            SummaryRole::Tool => "tool",
88            SummaryRole::Plan => "plan",
89        };
90        let body = self.body();
91        // Names and outcomes are outside the potentially large raw-body excerpt.
92        let label = if self.role == SummaryRole::Tool {
93            format!(" {}", self.text)
94        } else {
95            String::new()
96        };
97        format!(
98            "<{role}{label}>\n{}\n</{role}>\n",
99            excerpt(&body, body_limit)
100        )
101    }
102}
103
104#[derive(Debug, Default, Clone)]
105pub struct TranscriptSummary {
106    pub entries: Vec<SummaryEntry>,
107    next_position: u64,
108    open_message: Option<String>,
109    leading_omitted: bool,
110}
111
112/// A head/tail excerpt with an explicit byte omission count, never broken UTF-8.
113pub fn excerpt(text: &str, limit: usize) -> String {
114    if text.len() <= limit {
115        return text.to_owned();
116    }
117    let marker_budget = format!("\n[{} bytes omitted]\n", text.len()).len();
118    if limit < marker_budget {
119        return "[omitted]".chars().take(limit).collect();
120    }
121    let available = limit - marker_budget;
122    let mut head = available / 2;
123    while !text.is_char_boundary(head) {
124        head -= 1;
125    }
126    let mut tail = text.len() - (available - available / 2);
127    while !text.is_char_boundary(tail) {
128        tail += 1;
129    }
130    format!(
131        "{}\n[{} bytes omitted]\n{}",
132        &text[..head],
133        tail - head,
134        &text[tail..]
135    )
136}
137
138fn tool_value(call: &Value, presentation: Option<&ToolCallPresentation>, full: bool) -> Value {
139    let name = match serde_json::from_value::<ToolCall>(call.clone()) {
140        Ok(call) => materialized_tool_call_presentation(presentation, &call).summary,
141        Err(error) => {
142            tracing::warn!(%error, "could not decode tool for transcript summary");
143            "[invalid tool call]".into()
144        }
145    };
146    let mut compact = json!({
147        "toolCallId": call.get("toolCallId").and_then(Value::as_str).unwrap_or("unknown"),
148        "name": mj_core::activity::verdict::tool_title(&name),
149        "kind": call.get("kind").and_then(Value::as_str).unwrap_or("other"),
150        "status": call.get("status").and_then(Value::as_str).unwrap_or("pending"),
151    });
152    if let Some(code) = call.pointer("/rawOutput/exit_code").and_then(Value::as_i64) {
153        compact["exit_code"] = json!(code);
154    }
155    if let Some(signal) = call.pointer("/rawOutput/signal").and_then(Value::as_str) {
156        compact["signal"] = json!(signal);
157    }
158    if full {
159        compact["call"] = call.clone();
160    }
161    compact
162}
163
164/// Reconstruct indexed summary content without treating serialized detail as a tool name.
165/// Legacy indexes contain only titles and have no recoverable tool payload.
166pub fn indexed_tool_call(
167    text: &str,
168    fallback_id: &str,
169) -> (Value, Vec<mj_core::archive::CanonicalTerminalOutput>) {
170    if let Ok(value) = serde_json::from_str::<Value>(text)
171        && value.get("name").is_some_and(Value::is_string)
172        && value.get("status").is_some_and(Value::is_string)
173        && value.get("toolCallId").is_some_and(Value::is_string)
174    {
175        if let Some(call) = value.get("call")
176            && serde_json::from_value::<ToolCall>(call.clone()).is_ok()
177        {
178            let mut terminals = Vec::new();
179            if let Some(records) = value.get("terminals").and_then(Value::as_object) {
180                for (id, record) in records {
181                    let mut record = record.clone();
182                    if !record.is_object() {
183                        tracing::warn!("invalid indexed terminal summary");
184                        continue;
185                    }
186                    record["terminal_id"] = json!(id);
187                    match serde_json::from_value(record) {
188                        Ok(record) => terminals.push(record),
189                        Err(error) => tracing::warn!(%error, "invalid indexed terminal summary"),
190                    }
191                }
192            }
193            return (call.clone(), terminals);
194        }
195        let mut call = json!({"toolCallId":value["toolCallId"],"title":value["name"],"status":value["status"],"kind":value.get("kind").cloned().unwrap_or(json!("other"))});
196        for key in ["exit_code", "signal"] {
197            if let Some(outcome) = value.get(key) {
198                if !call["rawOutput"].is_object() {
199                    call["rawOutput"] = json!({});
200                }
201                call["rawOutput"][key] = outcome.clone();
202            }
203        }
204        return (call, Vec::new());
205    }
206    (
207        json!({"toolCallId":fallback_id,"title":text,"status":"completed"}),
208        Vec::new(),
209    )
210}
211
212fn tool_label(value: &Value) -> String {
213    let mut label = format!(
214        "{} [{}]",
215        value["name"].as_str().unwrap_or("tool"),
216        value["status"].as_str().unwrap_or("unknown")
217    );
218    if let Some(code) = value.get("exit_code") {
219        label.push_str(&format!(" exit={code}"));
220    }
221    if let Some(signal) = value.get("signal").and_then(Value::as_str) {
222        label.push_str(&format!(" signal={signal}"));
223    }
224    label
225}
226
227impl TranscriptSummary {
228    pub fn from_snapshot(snapshot: &CanonicalSessionSnapshot) -> Self {
229        Self::from_snapshot_keeping(snapshot, FULL_TOOL_CALLS)
230    }
231
232    /// Like [`Self::from_snapshot`], keeping the full call for the last
233    /// `full_tool_calls` tool calls instead of [`FULL_TOOL_CALLS`].
234    pub fn from_snapshot_keeping(
235        snapshot: &CanonicalSessionSnapshot,
236        full_tool_calls: usize,
237    ) -> Self {
238        let mut summary = Self::default();
239        let outputs =
240            mj_core::transcript::TerminalOutputs::of_canonical(snapshot.transcript.iter());
241        let start = snapshot.current_context_start();
242        let cutoff = snapshot
243            .transcript
244            .iter()
245            .filter(|i| start == 0 || i.position > start)
246            .filter(|i| matches!(i.body, CanonicalTranscriptBody::Tool { .. }))
247            .rev()
248            .take(full_tool_calls)
249            .map(|i| i.position)
250            .min()
251            .unwrap_or(u64::MAX);
252        for item in snapshot
253            .transcript
254            .iter()
255            .filter(|i| start == 0 || i.position > start)
256        {
257            let (role, text, tool) = match &item.body {
258                CanonicalTranscriptBody::User { content } => (
259                    SummaryRole::User,
260                    user_text(materialized_content_text(content)),
261                    None,
262                ),
263                CanonicalTranscriptBody::Message { event } => (
264                    SummaryRole::Message,
265                    mj_core::mailbox::render_mailbox_event(event),
266                    None,
267                ),
268                CanonicalTranscriptBody::Agent { chunks, .. } => (
269                    SummaryRole::Assistant,
270                    materialized_chunks_text(chunks),
271                    None,
272                ),
273                CanonicalTranscriptBody::Tool {
274                    call, presentation, ..
275                } => {
276                    let mut value =
277                        tool_value(call, presentation.as_ref(), item.position >= cutoff);
278                    attach_terminals(
279                        &mut value,
280                        outputs.for_tool(&item.stable_id).iter().map(|t| {
281                            (
282                                &t.terminal_id,
283                                t.output.as_str().into(),
284                                t.exit_code,
285                                t.signal.as_deref(),
286                                t.truncated,
287                            )
288                        }),
289                    );
290                    (SummaryRole::Tool, tool_label(&value), Some(value))
291                }
292                CanonicalTranscriptBody::Plan { plan } => {
293                    (SummaryRole::Plan, plan.to_string(), None)
294                }
295                _ => continue,
296            };
297            summary.entries.push(SummaryEntry {
298                id: item.stable_id.clone(),
299                position: item.position,
300                created_at_ms: item.created_at_ms,
301                role,
302                text,
303                terminal_refs: tool
304                    .as_ref()
305                    .and_then(|v| v.get("call"))
306                    .map(crate::projection::tool_call_terminal_ids)
307                    .unwrap_or_default(),
308                tool,
309            });
310        }
311        summary.next_position = snapshot.event_frontier.saturating_add(1);
312        summary
313    }
314
315    pub fn from_materialized(session: &MaterializedSession) -> Self {
316        Self::from_materialized_keeping(session, FULL_TOOL_CALLS)
317    }
318
319    /// Like [`Self::from_materialized`], keeping the full call for the last
320    /// `full_tool_calls` tool calls instead of [`FULL_TOOL_CALLS`].
321    pub fn from_materialized_keeping(
322        session: &MaterializedSession,
323        full_tool_calls: usize,
324    ) -> Self {
325        let start = session
326            .transcript
327            .iter()
328            .filter(|i| mj_core::archive::is_context_boundary(&i.stable_id))
329            .map(|i| i.position)
330            .max()
331            .unwrap_or(0);
332        let cutoff = session
333            .transcript
334            .iter()
335            .filter(|i| start == 0 || i.position > start)
336            .filter(|i| matches!(i.body, TranscriptBody::Tool { .. }))
337            .rev()
338            .take(full_tool_calls)
339            .map(|i| i.position)
340            .min()
341            .unwrap_or(u64::MAX);
342        let outputs =
343            mj_core::transcript::TerminalOutputs::of(session.transcript.iter().map(AsRef::as_ref));
344        let mut summary = Self::default();
345        for item in session
346            .transcript
347            .iter()
348            .filter(|i| start == 0 || i.position > start)
349        {
350            let (role, text, tool) = match &item.body {
351                TranscriptBody::User { content } => (
352                    SummaryRole::User,
353                    user_text(materialized_content_text(content)),
354                    None,
355                ),
356                TranscriptBody::Message { event } => (
357                    SummaryRole::Message,
358                    mj_core::mailbox::render_mailbox_event(event),
359                    None,
360                ),
361                TranscriptBody::Agent { chunks, .. } => (
362                    SummaryRole::Assistant,
363                    materialized_chunks_text(chunks),
364                    None,
365                ),
366                TranscriptBody::Tool {
367                    call, presentation, ..
368                } => {
369                    let mut value = tool_value(
370                        &call.value(),
371                        presentation.as_deref(),
372                        item.position >= cutoff,
373                    );
374                    attach_terminals(
375                        &mut value,
376                        outputs.for_tool(&item.stable_id).iter().map(|t| {
377                            (
378                                &t.terminal_id,
379                                t.output.text(),
380                                t.exit_code,
381                                t.signal.as_deref(),
382                                t.truncated,
383                            )
384                        }),
385                    );
386                    (SummaryRole::Tool, tool_label(&value), Some(value))
387                }
388                TranscriptBody::Plan { plan } => (SummaryRole::Plan, plan.to_string(), None),
389                _ => continue,
390            };
391            summary.entries.push(SummaryEntry {
392                id: item.stable_id.clone(),
393                position: item.position,
394                created_at_ms: item.created_at_ms,
395                role,
396                text,
397                terminal_refs: tool
398                    .as_ref()
399                    .and_then(|v| v.get("call"))
400                    .map(crate::projection::tool_call_terminal_ids)
401                    .unwrap_or_default(),
402                tool,
403            });
404        }
405        summary.next_position = session.applied_event_ordinal.saturating_add(1);
406        summary
407    }
408
409    pub fn mark_earlier_history_omitted(&mut self) {
410        self.leading_omitted = true;
411    }
412
413    pub fn push_user(&mut self, text: &str) {
414        self.open_message = None;
415        self.push(
416            SummaryRole::User,
417            String::new(),
418            user_text(text.to_owned()),
419            None,
420        );
421    }
422
423    fn push(&mut self, role: SummaryRole, id: String, text: String, tool: Option<Value>) {
424        self.next_position = self.next_position.saturating_add(1);
425        self.entries.push(SummaryEntry {
426            id,
427            position: self.next_position,
428            created_at_ms: 0,
429            role,
430            text: excerpt(&text, LIVE_ITEM_BYTES),
431            terminal_refs: tool
432                .as_ref()
433                .and_then(|v| v.get("call"))
434                .map(crate::projection::tool_call_terminal_ids)
435                .unwrap_or_default(),
436            tool,
437        });
438        if self.entries.len() > LIVE_ITEMS {
439            let full_tools = self
440                .entries
441                .iter()
442                .enumerate()
443                .rev()
444                .filter(|(_, e)| e.role == SummaryRole::Tool)
445                .take(FULL_TOOL_CALLS)
446                .map(|(i, _)| i)
447                .collect::<Vec<_>>();
448            let latest_user = self
449                .entries
450                .iter()
451                .rposition(|e| e.role == SummaryRole::User);
452            let remove = (0..self.entries.len())
453                .find(|i| !full_tools.contains(i) && Some(*i) != latest_user)
454                .unwrap_or(0);
455            self.entries.remove(remove);
456            self.leading_omitted = true;
457        }
458    }
459
460    pub fn observe(&mut self, update: &SessionUpdate) {
461        match update {
462            SessionUpdate::AgentMessageChunk(chunk) => {
463                let id = chunk
464                    .message_id
465                    .as_ref()
466                    .map(ToString::to_string)
467                    .unwrap_or_default();
468                if let ContentBlock::Text(text) = &chunk.content {
469                    if self.open_message.as_ref() == Some(&id) {
470                        if let Some(entry) = self.entries.last_mut() {
471                            entry.text.push_str(&excerpt(&text.text, LIVE_ITEM_BYTES));
472                            if entry.text.len() > LIVE_ITEM_BYTES {
473                                entry.text = excerpt(&entry.text, LIVE_ITEM_BYTES);
474                            }
475                        }
476                    } else {
477                        self.push(
478                            SummaryRole::Assistant,
479                            id.clone(),
480                            excerpt(&text.text, LIVE_ITEM_BYTES),
481                            None,
482                        );
483                    }
484                    self.open_message = Some(id);
485                }
486            }
487            SessionUpdate::ToolCall(call) => {
488                self.open_message = None;
489                let id = call.tool_call_id.to_string();
490                let raw = serde_json::to_value(call).expect("serialize ACP call");
491                let full = self
492                    .entries
493                    .iter()
494                    .find(|e| e.id == id)
495                    .is_none_or(|e| e.tool.as_ref().is_some_and(|v| v.get("call").is_some()));
496                let value = tool_value(&raw, None, full);
497                if let Some(entry) = self
498                    .entries
499                    .iter_mut()
500                    .find(|e| e.role == SummaryRole::Tool && e.id == id)
501                {
502                    for id in value
503                        .get("call")
504                        .map(crate::projection::tool_call_terminal_ids)
505                        .unwrap_or_default()
506                    {
507                        if !entry.terminal_refs.contains(&id) {
508                            entry.terminal_refs.push(id);
509                        }
510                    }
511                    entry.text = tool_label(&value);
512                    entry.tool = Some(value);
513                } else {
514                    self.push(SummaryRole::Tool, id, tool_label(&value), Some(value));
515                }
516                self.demote_tools();
517            }
518            SessionUpdate::ToolCallUpdate(update) => {
519                self.open_message = None;
520                if let Some(entry) = self.entries.iter_mut().find(|e| {
521                    e.role == SummaryRole::Tool && e.id == update.tool_call_id.to_string()
522                }) {
523                    let old = entry.tool.as_ref().expect("tool entry");
524                    let full = old.get("call").is_some();
525                    let mut call: ToolCall = old
526                        .get("call")
527                        .and_then(|v| serde_json::from_value(v.clone()).ok())
528                        .unwrap_or_else(|| {
529                            ToolCall::new(
530                                update.tool_call_id.clone(),
531                                old["name"].as_str().unwrap_or("tool"),
532                            )
533                        });
534                    let previous_name = old["name"].clone();
535                    let previous_status = old["status"].clone();
536                    call.update(update.fields.clone());
537                    let raw = serde_json::to_value(call).expect("serialize ACP call");
538                    let mut value = tool_value(&raw, None, full);
539                    if !full && update.fields.raw_input.is_none() {
540                        value["name"] = previous_name;
541                    }
542                    if update.fields.kind.is_none() {
543                        value["kind"] = old["kind"].clone();
544                    }
545                    if update.fields.status.is_none() {
546                        value["status"] = previous_status;
547                    }
548                    for key in ["exit_code", "signal", "terminals"] {
549                        if value.get(key).is_none()
550                            && let Some(old_value) = old.get(key)
551                        {
552                            value[key] = old_value.clone();
553                        }
554                    }
555                    for id in value
556                        .get("call")
557                        .map(crate::projection::tool_call_terminal_ids)
558                        .unwrap_or_default()
559                    {
560                        if !entry.terminal_refs.contains(&id) {
561                            entry.terminal_refs.push(id);
562                        }
563                    }
564                    entry.text = tool_label(&value);
565                    entry.tool = Some(value);
566                }
567            }
568            SessionUpdate::AgentThoughtChunk(_) => self.open_message = None,
569            SessionUpdate::Plan(plan) => {
570                self.open_message = None;
571                self.push(
572                    SummaryRole::Plan,
573                    String::new(),
574                    serde_json::to_string(plan).expect("serialize plan"),
575                    None,
576                );
577            }
578            _ => {}
579        }
580        // Bound retained live payloads, including strings nested in raw ACP records.
581        if matches!(
582            update,
583            SessionUpdate::ToolCall(_) | SessionUpdate::ToolCallUpdate(_)
584        ) {
585            for entry in &mut self.entries {
586                if let Some(value) = &mut entry.tool {
587                    bound_value(value, LIVE_ITEM_BYTES);
588                }
589            }
590        }
591    }
592
593    pub fn observe_terminal(&mut self, terminal: &mj_core::transcript::TerminalOutputRecord) {
594        for entry in &mut self.entries {
595            let Some(value) = &mut entry.tool else {
596                continue;
597            };
598            let refers = entry.terminal_refs.contains(&terminal.terminal_id);
599            if refers {
600                attach_terminals(
601                    value,
602                    std::iter::once((
603                        &terminal.terminal_id,
604                        terminal.output.text(),
605                        terminal.exit_code,
606                        terminal.signal.as_deref(),
607                        terminal.truncated,
608                    )),
609                );
610                bound_value(value, LIVE_ITEM_BYTES);
611                entry.text = tool_label(value);
612            }
613        }
614    }
615
616    fn demote_tools(&mut self) {
617        for entry in self
618            .entries
619            .iter_mut()
620            .rev()
621            .filter(|e| e.role == SummaryRole::Tool)
622            .skip(FULL_TOOL_CALLS)
623        {
624            if let Some(value) = entry.tool.as_mut().and_then(Value::as_object_mut) {
625                value.remove("call");
626                value.remove("terminals");
627            }
628        }
629    }
630
631    /// Jev's current-request conversation, without historical tool-call records.
632    /// Keep the available suffix and its coverage marker if replay lacks the user boundary.
633    pub fn latest_user_messages(&self) -> Self {
634        let user = self
635            .entries
636            .iter()
637            .rposition(|entry| entry.role == SummaryRole::User);
638        Self {
639            entries: self.entries[user.unwrap_or(0)..]
640                .iter()
641                .filter(|entry| entry.role != SummaryRole::Tool)
642                .cloned()
643                .collect(),
644            leading_omitted: self.leading_omitted && user.is_none(),
645            ..Default::default()
646        }
647    }
648
649    /// Exact retained context alongside a model-produced summary, newest-first selection.
650    pub fn retained(&self) -> Self {
651        let last_assistant = self
652            .entries
653            .iter()
654            .rposition(|e| e.role == SummaryRole::Assistant);
655        Self {
656            entries: self
657                .entries
658                .iter()
659                .enumerate()
660                .filter(|(i, e)| {
661                    matches!(e.role, SummaryRole::User | SummaryRole::Message)
662                        || Some(*i) == last_assistant
663                        || e.tool.as_ref().is_some_and(|v| v.get("call").is_some())
664                })
665                .map(|(_, e)| e.clone())
666                .collect(),
667            ..Default::default()
668        }
669    }
670
671    /// Preserve recent context first, then spend spare space on newest history.
672    /// Only after optional history is removed do oversized retained bodies shrink.
673    pub fn render(&self, limit: usize) -> String {
674        self.render_with_ids(limit).0
675    }
676
677    /// Return the retained entry identities as well as text, so offline evidence
678    /// selectors never ask about entries omitted by the rendering budget.
679    pub fn render_with_ids(&self, limit: usize) -> (String, Vec<String>) {
680        let history_marker = if self.leading_omitted {
681            "[Earlier transcript entries omitted]\n"
682        } else {
683            ""
684        };
685        if limit < history_marker.len() {
686            return (excerpt(history_marker, limit), Vec::new());
687        }
688        let all = history_marker.to_owned()
689            + &self
690                .entries
691                .iter()
692                .map(|e| e.render(usize::MAX))
693                .collect::<String>();
694        if all.len() <= limit {
695            return (
696                all,
697                self.entries.iter().map(|entry| entry.id.clone()).collect(),
698            );
699        }
700
701        let mut selected = std::collections::BTreeSet::new();
702        for role in [
703            SummaryRole::User,
704            SummaryRole::Message,
705            SummaryRole::Assistant,
706        ] {
707            if let Some(index) = self.entries.iter().rposition(|e| e.role == role) {
708                selected.insert(index);
709            }
710        }
711        selected.extend(
712            self.entries
713                .iter()
714                .enumerate()
715                .rev()
716                .filter(|(_, e)| e.role == SummaryRole::Tool)
717                .take(FULL_TOOL_CALLS)
718                .map(|(i, _)| i),
719        );
720        let mut used = selected
721            .iter()
722            .map(|i| self.entries[*i].render(usize::MAX).len())
723            .sum::<usize>();
724        // Reserve enough room for both coverage markers before adding optional items.
725        let available = limit.saturating_sub(history_marker.len() + 64);
726        if used < available {
727            // Recent requests and received messages take precedence over old activity.
728            for users in [true, false] {
729                for (index, entry) in self.entries.iter().enumerate().rev() {
730                    if selected.contains(&index)
731                        || matches!(entry.role, SummaryRole::User | SummaryRole::Message) != users
732                    {
733                        continue;
734                    }
735                    let size = entry.render(usize::MAX).len();
736                    if used.saturating_add(size) <= available {
737                        selected.insert(index);
738                        used += size;
739                    }
740                }
741            }
742        }
743        let omitted = self.entries.len() - selected.len();
744        let prefix = history_marker.to_owned()
745            + &if omitted > 0 {
746                format!("[{omitted} transcript entries omitted]\n")
747            } else {
748                String::new()
749            };
750        let render = |cap| {
751            prefix.clone()
752                + &selected
753                    .iter()
754                    .map(|i| self.entries[*i].render(cap))
755                    .collect::<String>()
756        };
757        let ids = selected
758            .iter()
759            .map(|i| self.entries[*i].id.clone())
760            .collect();
761        let full = render(usize::MAX);
762        if full.len() <= limit {
763            return (full, ids);
764        }
765        let minimum = render(0);
766        if minimum.len() > limit {
767            return (excerpt(&minimum, limit), Vec::new());
768        }
769        // A common cap leaves short messages intact and shares remaining space among long bodies.
770        let (mut low, mut high) = (0, limit);
771        while low < high {
772            let middle = low + (high - low).div_ceil(2);
773            if render(middle).len() <= limit {
774                low = middle;
775            } else {
776                high = middle - 1;
777            }
778        }
779        (render(low), ids)
780    }
781}
782
783fn attach_terminals<'a>(
784    value: &mut Value,
785    terminals: impl Iterator<
786        Item = (
787            &'a String,
788            std::borrow::Cow<'a, str>,
789            Option<u32>,
790            Option<&'a str>,
791            bool,
792        ),
793    >,
794) {
795    for (id, output, code, signal, truncated) in terminals {
796        if let Some(code) = code {
797            value["exit_code"] = json!(code);
798        }
799        if let Some(signal) = signal {
800            value["signal"] = json!(signal);
801        }
802        if value.get("call").is_some() {
803            if !value["terminals"].is_object() {
804                value["terminals"] = json!({});
805            }
806            value["terminals"][id] =
807                json!({"output":output,"exit_code":code,"signal":signal,"truncated":truncated});
808        }
809    }
810}
811
812fn bound_value(value: &mut Value, limit: usize) {
813    match value {
814        Value::String(text) if text.len() > limit => *text = excerpt(text, limit),
815        Value::Array(values) => {
816            for value in values {
817                bound_value(value, limit);
818            }
819        }
820        Value::Object(values) => {
821            for value in values.values_mut() {
822                bound_value(value, limit);
823            }
824        }
825        _ => {}
826    }
827}
828
829#[cfg(test)]
830mod tests {
831    use super::*;
832    use agent_client_protocol::v1::schema::{
833        ToolCallStatus, ToolCallUpdate, ToolCallUpdateFields, ToolKind,
834    };
835    use mj_core::state::TranscriptItem;
836    use std::sync::Arc;
837
838    fn call(n: usize) -> ToolCall {
839        ToolCall::new(format!("call-{n}"), "Run command")
840            .kind(ToolKind::Execute)
841            .status(ToolCallStatus::Completed)
842            .raw_input(json!({"command": format!("cargo test --marker=ARGUMENT_{n}")}))
843            .raw_output(json!({"exit_code": n, "formatted_output": format!("OUTPUT_{n}")}))
844    }
845
846    #[test]
847    fn legacy_persisted_index_title_uses_its_stable_fallback_id() {
848        let legacy_title =
849            include_str!("../tests/fixtures/legacy-indexed-tool-call.txt").trim_end();
850
851        let (call, terminals) = indexed_tool_call(legacy_title, "legacy-tool-17");
852
853        assert_eq!(
854            call,
855            json!({
856                "toolCallId": "legacy-tool-17",
857                "title": "Terminal",
858                "status": "completed"
859            })
860        );
861        assert!(terminals.is_empty());
862    }
863
864    #[test]
865    fn ninth_call_demotes_first_and_late_updates_do_not_promote_it() {
866        let mut summary = TranscriptSummary::default();
867        summary.push_user("test the change");
868        for n in 0..9 {
869            summary.observe(&SessionUpdate::ToolCall(call(n)));
870        }
871        summary.observe(&SessionUpdate::ToolCallUpdate(ToolCallUpdate::new(
872            "call-0",
873            ToolCallUpdateFields::new()
874                .status(ToolCallStatus::Failed)
875                .raw_output(json!({"exit_code": 42,"output":"LATE_PAYLOAD"})),
876        )));
877        let output = summary.render(DEFAULT_SUMMARY_BYTES);
878        assert!(!output.contains("ARGUMENT_0"));
879        assert!(!output.contains("OUTPUT_0"));
880        assert!(!output.contains("LATE_PAYLOAD"));
881        assert!(output.contains("cargo test [failed] exit=42"));
882        for n in 1..9 {
883            assert!(output.contains(&format!("ARGUMENT_{n}")));
884            assert!(output.contains(&format!("OUTPUT_{n}")));
885        }
886        assert_eq!(
887            summary
888                .entries
889                .iter()
890                .filter(|e| e.tool.as_ref().is_some_and(|v| v.get("call").is_some()))
891                .count(),
892            FULL_TOOL_CALLS
893        );
894    }
895
896    #[test]
897    fn huge_unicode_bodies_are_marked_and_preserve_recent_outcomes() {
898        let mut summary = TranscriptSummary::default();
899        summary.push_user("latest user requirement");
900        for n in 0..8 {
901            summary.observe(&SessionUpdate::ToolCall(
902                call(n).raw_output(json!({"exit_code":n,"output":"🦀\"\\\n".repeat(70_000)})),
903            ));
904        }
905        let output = summary.render(16 * 1024);
906        assert!(output.len() <= 16 * 1024);
907        assert!(output.contains("bytes omitted"));
908        assert!(output.contains("latest user requirement"));
909        for n in 0..8 {
910            assert!(output.contains(&format!("exit={n}")));
911        }
912        for limit in 0..100 {
913            let excerpt = excerpt("🦀".repeat(100).as_str(), limit);
914            assert!(excerpt.len() <= limit);
915        }
916    }
917
918    #[test]
919    fn context_boundary_discards_previous_conversation() {
920        let mut session = MaterializedSession::empty("summary-test");
921        for (position, id, body) in [
922            (
923                1,
924                "user:old",
925                TranscriptBody::User {
926                    content: vec![json!({"type":"text","text":"OLD_CONTEXT"})],
927                },
928            ),
929            (
930                2,
931                "context-clear:test",
932                TranscriptBody::System {
933                    text: "cleared".into(),
934                },
935            ),
936            (
937                3,
938                "user:new",
939                TranscriptBody::User {
940                    content: vec![json!({"type":"text","text":"NEW_CONTEXT"})],
941                },
942            ),
943        ] {
944            let id = if position == 2 {
945                format!("{}test", mj_core::archive::CONTEXT_BOUNDARY_PREFIX)
946            } else {
947                id.into()
948            };
949            session.transcript.push(Arc::new(TranscriptItem {
950                stable_id: id,
951                position,
952                latest_content_event_ordinal: None,
953                created_at_ms: 0,
954                last_changed_at_ms: 0,
955                body,
956            }));
957        }
958        let output = TranscriptSummary::from_materialized(&session).render(4096);
959        assert!(!output.contains("OLD_CONTEXT"));
960        assert!(output.contains("NEW_CONTEXT"));
961    }
962
963    #[test]
964    fn terminal_output_and_exit_are_attached_and_partial_updates_keep_name() {
965        let mut summary = TranscriptSummary::default();
966        let call: ToolCall = serde_json::from_value(json!({"toolCallId":"terminal","title":"Run command","kind":"execute","status":"in_progress","rawInput":{"command":"cargo test --secret argument"},"content":[{"type":"terminal","terminalId":"term-1"}]})).unwrap();
967        summary.observe(&SessionUpdate::ToolCall(call));
968        summary.observe_terminal(&mj_core::transcript::TerminalOutputRecord {
969            terminal_id: "term-1".into(),
970            output: "terminal result".into(),
971            truncated: false,
972            exit_code: Some(17),
973            signal: None,
974        });
975        summary.observe(&SessionUpdate::ToolCallUpdate(ToolCallUpdate::new(
976            "terminal",
977            ToolCallUpdateFields::new()
978                .title("Done")
979                .status(ToolCallStatus::Failed),
980        )));
981        let output = summary.render(4096);
982        assert!(output.contains("cargo test [failed] exit=17"));
983        assert!(output.contains("terminal result"));
984    }
985    #[test]
986    fn demoted_terminal_keeps_late_outcome_without_its_body() {
987        let mut summary = TranscriptSummary::default();
988        let terminal: ToolCall = serde_json::from_value(json!({"toolCallId":"terminal","title":"cargo test","kind":"execute","status":"in_progress","content":[{"type":"terminal","terminalId":"term"}]})).unwrap();
989        summary.observe(&SessionUpdate::ToolCall(terminal));
990        for n in 0..8 {
991            summary.observe(&SessionUpdate::ToolCall(call(n)));
992        }
993        summary.observe_terminal(&mj_core::transcript::TerminalOutputRecord {
994            terminal_id: "term".into(),
995            output: "OLD_TERMINAL_PAYLOAD".into(),
996            exit_code: Some(23),
997            signal: None,
998            truncated: false,
999        });
1000        let output = summary.render(DEFAULT_SUMMARY_BYTES);
1001        assert!(output.contains("exit=23"));
1002        assert!(!output.contains("OLD_TERMINAL_PAYLOAD"));
1003    }
1004
1005    #[test]
1006    fn malformed_older_calls_do_not_leak_their_titles_or_payloads() {
1007        let invalid =
1008            json!({"title":"SECRET_TITLE", "rawInput":"SECRET_INPUT", "status":"completed"});
1009        let compact = tool_value(&invalid, None, false).to_string();
1010        assert!(compact.contains("invalid tool call"));
1011        assert!(!compact.contains("SECRET"));
1012    }
1013}