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