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