Skip to main content

mj_transcript/
transcript.rs

1//! Transcript projection and presentation implementation.
2
3use agent_client_protocol::schema::v1::{
4    SessionUpdate, ToolCall, ToolCallContent, ToolCallLocation, ToolCallUpdateFields, ToolKind,
5};
6use mj_core::acp::RuntimeEvent;
7pub use mj_core::transcript::*;
8use serde::Deserialize;
9use serde_json::Value;
10use tree_sitter::{Node, Parser};
11const TOOL_SUMMARY_SOURCE_BYTES: usize = 64 * 1024;
12const TOOL_SUMMARY_MAX_NESTING: usize = 16;
13/// Stands for a command whose name is an expansion, such as `$E cargo test`.
14const UNNAMED_COMMAND_SUMMARY: &str = "…";
15/// Parser-rule version stored with cached tool summaries.
16pub const TOOL_SUMMARY_VERSION: u8 = 8;
17
18/// Reduce a tool call to what a reader still needs, once a verified checkpoint
19/// holds the whole of it.
20///
21/// Tool output is where a projection's bytes are: on one measured session,
22/// 561 MB of 635 MiB. Behind a checkpoint nothing reads it — the checkpoint
23/// archive carries the complete transcript, and restoring it brings the output
24/// back — so what stays here is what the transcript still shows: which tool
25/// ran, on what, with what result, and how many lines each edit changed.
26///
27/// Returns whether anything changed, so a caller can skip the write.
28pub fn compact_tool_call_for_retention(body: &mut TranscriptBody) -> bool {
29    let TranscriptBody::Tool {
30        call,
31        terminal_outputs,
32        terminal_refs,
33        ..
34    } = body
35    else {
36        return false;
37    };
38    let Some(object) = call.as_object_mut() else {
39        return false;
40    };
41    let mut changed = !terminal_outputs.is_empty() || !terminal_refs.is_empty();
42    terminal_outputs.clear();
43    terminal_refs.clear();
44    for field in ["rawInput", "rawOutput", "_meta"] {
45        changed |= object.remove(field).is_some();
46    }
47    let Some(content) = object
48        .get_mut("content")
49        .and_then(|value| value.as_array_mut())
50    else {
51        return changed;
52    };
53    let before = content.len();
54    // Diffs stay, because the transcript still shows their stat. Their patch
55    // text does not, and neither do the two file copies an older record holds
56    // instead of a patch: `diff::drop_patch_text` turns those into the
57    // counts `format_diffstat` reads before dropping them.
58    content.retain(|item| item.get("type").and_then(|kind| kind.as_str()) == Some("diff"));
59    changed |= content.len() != before;
60    for item in content.iter_mut() {
61        changed |= drop_diff_body(item);
62    }
63    changed
64}
65
66fn drop_diff_body(item: &mut serde_json::Value) -> bool {
67    use agent_client_protocol::schema::v1::ToolCallContent;
68
69    // Round-trip through `ToolCallContent`, not `Diff`: the variant tag lives
70    // on the enum, and writing back a bare `Diff` would strip it and make the
71    // whole tool call unreadable.
72    let mut content = match serde_json::from_value::<ToolCallContent>(item.clone()) {
73        Ok(content) => content,
74        // Content this cannot read is content it must not rewrite.
75        Err(error) => {
76            tracing::warn!(%error, "skipping unreadable tool content during retention");
77            return false;
78        }
79    };
80    let ToolCallContent::Diff(diff) = &mut content else {
81        return false;
82    };
83    if !mj_core::diff::drop_patch_text(diff) {
84        return false;
85    }
86    match serde_json::to_value(&content) {
87        Ok(value) => {
88            *item = value;
89            true
90        }
91        Err(error) => {
92            tracing::warn!(%error, "could not rewrite a diff during retention");
93            false
94        }
95    }
96}
97
98#[derive(Debug, Clone, PartialEq, Eq)]
99enum ToolSummarySource {
100    Shell(String),
101    Argv {
102        executable: String,
103        arguments: Vec<String>,
104    },
105}
106
107/// Whether a partial update changes inputs used to derive the tool summary.
108pub fn tool_call_update_changes_presentation(
109    call: &ToolCall,
110    fields: &ToolCallUpdateFields,
111) -> bool {
112    fields
113        .title
114        .as_ref()
115        .is_some_and(|title| title != &call.title)
116        || fields.kind.is_some_and(|kind| kind != call.kind)
117        || fields
118            .raw_input
119            .as_ref()
120            .is_some_and(|input| Some(input) != call.raw_input.as_ref())
121        || (call.kind == ToolKind::Execute
122            && fields
123                .raw_output
124                .as_ref()
125                .is_some_and(|output| Some(output) != call.raw_output.as_ref())
126            && command_source(call.raw_input.as_ref()).is_none())
127}
128
129/// Compute the stable presentation metadata for one complete ACP call.
130pub fn tool_call_presentation(call: &ToolCall) -> ToolCallPresentation {
131    let kind = call.kind;
132    if kind == ToolKind::Execute {
133        if let Some(source) = command_source(call.raw_input.as_ref()) {
134            return presentation_from_source(
135                source,
136                ToolSummarySourceKind::RawInput,
137                kind,
138                &call.title,
139            );
140        }
141        if let Some(source) = command_source(call.raw_output.as_ref()) {
142            return presentation_from_source(
143                source,
144                ToolSummarySourceKind::RawOutput,
145                kind,
146                &call.title,
147            );
148        }
149    }
150    presentation_from_title(&call.title, kind)
151}
152
153/// Use cached presentation data when it was produced by current parser rules,
154/// otherwise rebuild it from the complete stored call. This lets parser fixes
155/// repair existing transcripts while current summaries remain cheap to load.
156///
157/// Retention drops a finished call's raw input and output, so a summary made
158/// from them is kept: rebuilt from what remains, it could only get worse.
159pub fn materialized_tool_call_presentation(
160    stored: Option<&ToolCallPresentation>,
161    call: &ToolCall,
162) -> ToolCallPresentation {
163    stored
164        .filter(|presentation| {
165            presentation.summary_version >= TOOL_SUMMARY_VERSION
166                || match presentation.source_kind {
167                    ToolSummarySourceKind::RawInput => call.raw_input.is_none(),
168                    ToolSummarySourceKind::RawOutput => call.raw_output.is_none(),
169                    ToolSummarySourceKind::Title => false,
170                }
171        })
172        .cloned()
173        .unwrap_or_else(|| tool_call_presentation(call))
174}
175
176/// Apply the presentation-relevant portion of a partial ACP update to cached
177/// metadata. ACP updates replace only fields that are present, so a title
178/// update must not erase a summary selected from an earlier raw command.
179pub fn update_tool_call_presentation(
180    previous: Option<&ToolCallPresentation>,
181    title: &str,
182    kind: Option<ToolKind>,
183    raw_input: Option<&Value>,
184    raw_output: Option<&Value>,
185) -> ToolCallPresentation {
186    let next_kind = kind.unwrap_or_else(|| {
187        previous
188            .map(|presentation| presentation.tool_kind)
189            .unwrap_or_default()
190    });
191
192    if next_kind == ToolKind::Execute {
193        if let Some(source) = raw_input.and_then(|value| command_source(Some(value))) {
194            return presentation_from_source(
195                source,
196                ToolSummarySourceKind::RawInput,
197                next_kind,
198                title,
199            );
200        }
201        if let Some(source) = raw_output.and_then(|value| command_source(Some(value)))
202            && (raw_input.is_some()
203                || !previous.is_some_and(|previous| {
204                    previous.source_kind == ToolSummarySourceKind::RawInput
205                }))
206        {
207            return presentation_from_source(
208                source,
209                ToolSummarySourceKind::RawOutput,
210                next_kind,
211                title,
212            );
213        }
214        if let Some(previous) = previous
215            && previous.tool_kind == ToolKind::Execute
216            && ((raw_input.is_none() && previous.source_kind == ToolSummarySourceKind::RawInput)
217                || (raw_input.is_none()
218                    && raw_output.is_none()
219                    && previous.source_kind == ToolSummarySourceKind::RawOutput))
220        {
221            return ToolCallPresentation {
222                tool_kind: next_kind,
223                ..previous.clone()
224            };
225        }
226    }
227
228    presentation_from_title(title, next_kind)
229}
230
231fn command_source(raw: Option<&Value>) -> Option<ToolSummarySource> {
232    let command = raw?.get("command")?;
233    match command {
234        Value::String(command) if !command.trim().is_empty() => {
235            Some(ToolSummarySource::Shell(command.clone()))
236        }
237        Value::Array(argv) => {
238            let argv = argv.iter().map(Value::as_str).collect::<Option<Vec<_>>>()?;
239            let first = argv.first()?.trim();
240            if first.is_empty() {
241                return None;
242            }
243            if is_shell_interpreter(first)
244                && let Some(script) = shell_script_argument(&argv[1..])
245            {
246                return Some(ToolSummarySource::Shell(script.to_owned()));
247            }
248            Some(ToolSummarySource::Argv {
249                executable: first.to_owned(),
250                arguments: argv[1..]
251                    .iter()
252                    .map(|argument| (*argument).to_owned())
253                    .collect(),
254            })
255        }
256        _ => None,
257    }
258}
259
260fn is_shell_interpreter(value: &str) -> bool {
261    let executable = value.rsplit('/').next().unwrap_or(value);
262    matches!(executable, "sh" | "bash" | "dash" | "zsh")
263}
264
265fn shell_script_argument<'a>(arguments: &'a [&'a str]) -> Option<&'a str> {
266    arguments.get(shell_script_index(arguments)?).copied()
267}
268
269/// Where the script a shell runs with `-c` is among its arguments.
270fn shell_script_index(arguments: &[&str]) -> Option<usize> {
271    for (index, argument) in arguments.iter().enumerate() {
272        if *argument == "--" {
273            return None;
274        }
275        if *argument == "-c"
276            || *argument == "--command"
277            || (argument.starts_with('-')
278                && !argument.starts_with("--")
279                && argument[1..].contains('c'))
280        {
281            return (index + 1 < arguments.len()).then_some(index + 1);
282        }
283    }
284    None
285}
286
287/// The script of a command that is nothing but a shell running one `-c`
288/// script, such as `/bin/bash -lc "python3 x.py"`. Codex reports some commands
289/// with the shell it wraps every command in, as one string. The wrapper says
290/// no more there than it does in an argv call, which drops it the same way.
291fn wrapped_shell_script(command: &str) -> Option<String> {
292    let mut parser = Parser::new();
293    parser
294        .set_language(&tree_sitter_bash::LANGUAGE.into())
295        .ok()?;
296    let tree = parser.parse(command, None)?;
297    let root = tree.root_node();
298    if root.has_error() || root.named_child_count() != 1 {
299        return None;
300    }
301    let node = root.named_child(0)?;
302    if node.kind() != "command" {
303        return None;
304    }
305    let name = shell_command_name(node.child_by_field_name("name")?, command)?;
306    let mut cursor = node.walk();
307    let arguments = node
308        .children_by_field_name("argument", &mut cursor)
309        .collect::<Vec<_>>();
310    // Only the name and its arguments: an environment assignment before the
311    // shell is part of what the command does.
312    if !is_shell_interpreter(&name) || node.named_child_count() != arguments.len() + 1 {
313        return None;
314    }
315    let words = arguments
316        .iter()
317        .map(|argument| &command[argument.byte_range()])
318        .collect::<Vec<_>>();
319    shell_literal_text(arguments[shell_script_index(&words)?], command)
320}
321
322/// The text a shell passes on for a quoted or plain word. Codex quotes a
323/// script holding both kinds of quote as several quoted pieces in a row, such
324/// as `"rg '"'^fn'"' src"`, so a concatenation is the text of its pieces.
325fn shell_literal_text(node: Node<'_>, source: &str) -> Option<String> {
326    let text = &source[node.byte_range()];
327    match node.kind() {
328        "raw_string" => Some(text.strip_prefix('\'')?.strip_suffix('\'')?.to_owned()),
329        "string" => Some(unescape_double_quoted(
330            text.strip_prefix('"')?.strip_suffix('"')?,
331        )),
332        "word" => Some(unescape_word(text)),
333        "concatenation" => {
334            let mut cursor = node.walk();
335            let mut end = node.start_byte();
336            let mut joined = String::new();
337            for piece in node.children(&mut cursor) {
338                // Every byte must belong to a piece this reads.
339                if piece.start_byte() != end {
340                    return None;
341                }
342                end = piece.end_byte();
343                joined.push_str(&shell_literal_text(piece, source)?);
344            }
345            (end == node.end_byte()).then_some(joined)
346        }
347        _ => None,
348    }
349}
350
351/// The text of an unquoted word, where a backslash escapes any character and
352/// a backslash before a newline joins the lines.
353fn unescape_word(text: &str) -> String {
354    let mut unescaped = String::with_capacity(text.len());
355    let mut characters = text.chars();
356    while let Some(character) = characters.next() {
357        match character {
358            '\\' => match characters.next() {
359                Some('\n') | None => {}
360                Some(escaped) => unescaped.push(escaped),
361            },
362            character => unescaped.push(character),
363        }
364    }
365    unescaped
366}
367
368/// The text a shell reads from inside double quotes, where a backslash
369/// escapes only `$`, a backquote, `"`, a backslash, and a newline.
370fn unescape_double_quoted(text: &str) -> String {
371    let mut unescaped = String::with_capacity(text.len());
372    let mut characters = text.chars().peekable();
373    while let Some(character) = characters.next() {
374        if character == '\\' {
375            match characters.peek() {
376                Some('$' | '`' | '"' | '\\') => {
377                    unescaped.extend(characters.next());
378                    continue;
379                }
380                Some('\n') => {
381                    characters.next();
382                    continue;
383                }
384                _ => {}
385            }
386        }
387        unescaped.push(character);
388    }
389    unescaped
390}
391
392fn presentation_from_source(
393    source: ToolSummarySource,
394    source_kind: ToolSummarySourceKind,
395    tool_kind: ToolKind,
396    title: &str,
397) -> ToolCallPresentation {
398    let (source, summary) = match source {
399        ToolSummarySource::Shell(source) => {
400            let bounded = bound_summary_source(&source);
401            if let Some(script) = wrapped_shell_script(&bounded)
402                && let Some(summary) = summarize_shell(&script, 1)
403            {
404                (script, summary)
405            } else {
406                let summary = summarize_shell(&bounded, 0)
407                    .or_else(|| first_meaningful_token(title))
408                    .unwrap_or_else(|| "tool".to_owned());
409                (bounded, summary)
410            }
411        }
412        ToolSummarySource::Argv {
413            executable,
414            arguments,
415        } => {
416            let source = std::iter::once(executable.as_str())
417                .chain(arguments.iter().map(String::as_str))
418                .collect::<Vec<_>>()
419                .join(" ");
420            let bounded = bound_summary_source(&source);
421            let summary = summarize_invocation(&executable, &arguments)
422                .or_else(|| first_meaningful_token(title))
423                .unwrap_or_else(|| "tool".to_owned());
424            (bounded, summary)
425        }
426    };
427    ToolCallPresentation {
428        summary,
429        source,
430        source_kind,
431        tool_kind,
432        summary_version: TOOL_SUMMARY_VERSION,
433    }
434}
435
436fn presentation_from_title(title: &str, tool_kind: ToolKind) -> ToolCallPresentation {
437    let source = title_source(title);
438    let bounded = bound_summary_source(&source);
439    let summary = if tool_kind == ToolKind::Execute {
440        summarize_shell(&bounded, 0)
441            .or_else(|| first_meaningful_token(&bounded))
442            .unwrap_or_else(|| "tool".to_owned())
443    } else if bounded.trim_end().ends_with('?') {
444        // A question tool (Claude's AskUserQuestion) is titled with the
445        // question; its first word alone ("Which") says nothing.
446        bounded.trim().to_owned()
447    } else {
448        first_meaningful_token(&bounded).unwrap_or_else(|| "tool".to_owned())
449    };
450    ToolCallPresentation {
451        summary,
452        source: bounded,
453        source_kind: ToolSummarySourceKind::Title,
454        tool_kind,
455        summary_version: TOOL_SUMMARY_VERSION,
456    }
457}
458
459fn title_source(title: &str) -> String {
460    let title = title.trim();
461    let title = title
462        .strip_prefix("Running:")
463        .or_else(|| title.strip_prefix("Starting background:"))
464        .map(str::trim)
465        .unwrap_or(title);
466    if let Some(inner) = title
467        .strip_prefix("Execute `")
468        .and_then(|value| value.strip_suffix('`'))
469    {
470        return inner.to_owned();
471    }
472    title.to_owned()
473}
474
475fn first_meaningful_token(value: &str) -> Option<String> {
476    let token = value
477        .split_whitespace()
478        .next()?
479        .trim_matches(|character: char| {
480            !character.is_alphanumeric() && character != '/' && character != '.' && character != '_'
481        });
482    if token.is_empty() {
483        None
484    } else {
485        Some(token.trim_matches(['\'', '"', '`']).to_owned())
486    }
487}
488
489fn bound_summary_source(source: &str) -> String {
490    if source.len() <= TOOL_SUMMARY_SOURCE_BYTES {
491        return source.to_owned();
492    }
493    let mut end = TOOL_SUMMARY_SOURCE_BYTES;
494    while !source.is_char_boundary(end) {
495        end -= 1;
496    }
497    source[..end].to_owned()
498}
499
500fn summarize_shell(source: &str, nesting: usize) -> Option<String> {
501    // SSH chains need no quoting, so the byte bound alone cannot bound their
502    // recursive parsing. Keep nested shell scripts within the same budget.
503    if nesting >= TOOL_SUMMARY_MAX_NESTING {
504        return Some("…".to_owned());
505    }
506    let mut parser = Parser::new();
507    parser
508        .set_language(&tree_sitter_bash::LANGUAGE.into())
509        .ok()?;
510    let tree = parser.parse(source, None)?;
511    let root = tree.root_node();
512    if root.has_error() {
513        return None;
514    }
515
516    let mut commands = Vec::new();
517    let mut operators = Vec::new();
518    let mut subshells = Vec::new();
519    if !collect_shell_tokens(
520        root,
521        source,
522        nesting,
523        &mut commands,
524        &mut operators,
525        &mut subshells,
526    ) {
527        return None;
528    }
529    // A script whose every command is named by an expansion says nothing the
530    // tool's title does not.
531    if commands
532        .iter()
533        .all(|command| command.summary == UNNAMED_COMMAND_SUMMARY)
534    {
535        return None;
536    }
537    commands.sort_by_key(|command| command.start);
538    operators.sort_by_key(|operator| operator.start);
539    subshells.sort_by_key(|subshell| subshell.start);
540
541    let mut tokens = Vec::new();
542    for (index, command) in commands.iter().enumerate() {
543        if index > 0 {
544            let previous = &commands[index - 1];
545            let separator = shell_separator_between(previous, command, &operators);
546            tokens.push(ShellToken {
547                start: separator.start,
548                text: separator.kind,
549                order: 1,
550            });
551        }
552        tokens.push(ShellToken {
553            start: command.start,
554            text: command.summary.clone(),
555            order: 2,
556        });
557    }
558
559    // Parentheses are meaningful only for subshells that contain a command we
560    // retained. Other punctuation, such as case arms and group delimiters,
561    // is structural and must not leak into the compact summary.
562    for subshell in subshells {
563        if !commands
564            .iter()
565            .any(|command| command.start >= subshell.start && command.end <= subshell.end)
566        {
567            continue;
568        }
569        let close = subshell.end.saturating_sub(1);
570        tokens.push(ShellToken {
571            start: subshell.start,
572            text: "(".to_owned(),
573            order: 0,
574        });
575        tokens.push(ShellToken {
576            start: close,
577            text: ")".to_owned(),
578            order: 3,
579        });
580    }
581
582    tokens.sort_by_key(|token| (token.start, token.order));
583    Some(join_shell_tokens(
584        tokens.into_iter().map(|token| token.text).collect(),
585    ))
586}
587
588#[derive(Debug, Clone)]
589struct ShellCommandToken {
590    start: usize,
591    end: usize,
592    summary: String,
593}
594
595#[derive(Debug, Clone)]
596struct ShellOperatorToken {
597    start: usize,
598    kind: String,
599}
600
601#[derive(Debug, Clone)]
602struct ShellSubshell {
603    start: usize,
604    end: usize,
605}
606
607#[derive(Debug, Clone)]
608struct ShellToken {
609    start: usize,
610    text: String,
611    order: u8,
612}
613
614fn collect_shell_tokens(
615    node: Node<'_>,
616    source: &str,
617    nesting: usize,
618    commands: &mut Vec<ShellCommandToken>,
619    operators: &mut Vec<ShellOperatorToken>,
620    subshells: &mut Vec<ShellSubshell>,
621) -> bool {
622    let kind = node.kind();
623    if matches!(kind, "command_substitution" | "process_substitution") {
624        return true;
625    }
626    if kind == "command" {
627        commands.push(ShellCommandToken {
628            start: node.start_byte(),
629            end: node.end_byte(),
630            summary: summarize_command_node(node, source, nesting)
631                .unwrap_or_else(|| UNNAMED_COMMAND_SUMMARY.to_owned()),
632        });
633        return true;
634    }
635    if kind == "variable_assignment" {
636        return collect_assignment_substitutions(
637            node, source, nesting, commands, operators, subshells,
638        );
639    }
640    if is_shell_operator(node) {
641        operators.push(ShellOperatorToken {
642            start: node.start_byte(),
643            kind: kind.to_owned(),
644        });
645        return true;
646    }
647
648    if kind == "subshell" {
649        subshells.push(ShellSubshell {
650            start: node.start_byte(),
651            end: node.end_byte(),
652        });
653    }
654
655    let mut cursor = node.walk();
656    node.children(&mut cursor)
657        .all(|child| collect_shell_tokens(child, source, nesting, commands, operators, subshells))
658}
659
660/// An assignment that is a statement of its own, such as
661/// `T=$(git grep -l x)`, runs the commands substituted into its value.
662/// An assignment before a command is part of that command and never gets here.
663fn collect_assignment_substitutions(
664    node: Node<'_>,
665    source: &str,
666    nesting: usize,
667    commands: &mut Vec<ShellCommandToken>,
668    operators: &mut Vec<ShellOperatorToken>,
669    subshells: &mut Vec<ShellSubshell>,
670) -> bool {
671    let mut cursor = node.walk();
672    node.children(&mut cursor).all(|child| {
673        if child.kind() == "command_substitution" {
674            let mut cursor = child.walk();
675            child.children(&mut cursor).all(|grandchild| {
676                collect_shell_tokens(grandchild, source, nesting, commands, operators, subshells)
677            })
678        } else {
679            collect_assignment_substitutions(child, source, nesting, commands, operators, subshells)
680        }
681    })
682}
683
684fn shell_separator_between(
685    previous: &ShellCommandToken,
686    next: &ShellCommandToken,
687    operators: &[ShellOperatorToken],
688) -> ShellOperatorToken {
689    let mut candidates = operators
690        .iter()
691        .filter(|operator| operator.start >= previous.end && operator.start < next.start);
692    let structural = candidates.clone().find(|operator| operator.kind != ";");
693    if let Some(operator) = structural {
694        return operator.clone();
695    }
696    if let Some(operator) = candidates.find(|operator| operator.kind == ";") {
697        return operator.clone();
698    }
699    ShellOperatorToken {
700        start: previous.end,
701        kind: ";".to_owned(),
702    }
703}
704
705/// One argument of a parsed invocation. `value` is its text without matching
706/// quotes; `literal` is false when the text contains an expansion, so `value`
707/// is not what the program receives.
708#[derive(Debug, Clone)]
709struct InvocationArgument {
710    value: String,
711    literal: bool,
712}
713
714fn summarize_command_node(node: Node<'_>, source: &str, nesting: usize) -> Option<String> {
715    let name = node.child_by_field_name("name")?;
716    let executable = shell_command_name(name, source)?;
717    let mut cursor = node.walk();
718    let arguments = node
719        .children_by_field_name("argument", &mut cursor)
720        .map(|argument| match shell_argument_value(argument, source) {
721            Some(value) => InvocationArgument {
722                value,
723                literal: true,
724            },
725            None => InvocationArgument {
726                value: strip_matching_quotes(source[argument.byte_range()].trim()).to_owned(),
727                literal: false,
728            },
729        })
730        .collect::<Vec<_>>();
731    summarize_invocation_with_literals(&executable, &arguments, nesting)
732}
733
734fn shell_command_name(node: Node<'_>, source: &str) -> Option<String> {
735    if contains_dynamic_shell_node(node) {
736        return None;
737    }
738    normalize_command_name(&source[node.byte_range()])
739}
740
741fn shell_argument_value(node: Node<'_>, source: &str) -> Option<String> {
742    if contains_dynamic_shell_node(node) {
743        return None;
744    }
745    let text = source[node.byte_range()].trim();
746    if text.is_empty() {
747        return None;
748    }
749    Some(strip_matching_quotes(text).to_owned())
750}
751
752fn contains_dynamic_shell_node(node: Node<'_>) -> bool {
753    if matches!(
754        node.kind(),
755        "expansion"
756            | "simple_expansion"
757            | "command_substitution"
758            | "process_substitution"
759            | "arithmetic_expansion"
760    ) {
761        return true;
762    }
763    let mut cursor = node.walk();
764    node.children(&mut cursor).any(contains_dynamic_shell_node)
765}
766
767fn summarize_invocation(executable: &str, arguments: &[String]) -> Option<String> {
768    summarize_invocation_with_literals(
769        executable,
770        &arguments
771            .iter()
772            .map(|value| InvocationArgument {
773                value: strip_matching_quotes(value).to_owned(),
774                literal: true,
775            })
776            .collect::<Vec<_>>(),
777        0,
778    )
779}
780
781fn summarize_invocation_with_literals(
782    executable: &str,
783    arguments: &[InvocationArgument],
784    nesting: usize,
785) -> Option<String> {
786    let mut executable = normalize_command_name(executable)?;
787    let mut arguments = arguments;
788    let mut words = Vec::new();
789    // Reuse the invocation rules at each wrapper, consuming arguments rather
790    // than growing the call stack for long chains of nested commands.
791    'invocations: loop {
792        let basename = executable
793            .rsplit(['/', '\\'])
794            .next()
795            .unwrap_or(&executable)
796            .to_owned();
797        if is_shell_interpreter(&basename) {
798            words.push(summarize_shell_invocation(&basename, arguments, nesting));
799            break;
800        }
801        words.push(executable);
802        if !is_summary_executable(&basename) {
803            break;
804        }
805        let mut index = 0;
806
807        if matches!(basename.as_str(), "cargo" | "mbx")
808            && arguments.first().is_some_and(|argument| {
809                argument.literal && argument.value.starts_with('+') && argument.value.len() > 1
810            })
811        {
812            index += 1;
813        }
814
815        let mut first_verb = loop {
816            let Some(argument) = arguments.get(index) else {
817                break 'invocations;
818            };
819            if !argument.literal {
820                break 'invocations;
821            }
822            if argument.value == "--" || argument.value.starts_with('-') {
823                if let Some(consumed) = known_leading_option_arguments(&basename, arguments, index)
824                {
825                    index += consumed;
826                    continue;
827                }
828                break 'invocations;
829            }
830            break argument.value.as_str();
831        };
832
833        if basename == "ssh" {
834            words.push(first_verb.to_owned());
835            index += 1;
836            // OpenSSH also accepts options after the destination. The rest
837            // is joined with spaces and interpreted by the remote shell.
838            while let Some(argument) = arguments.get(index) {
839                if !argument.literal || !argument.value.starts_with('-') {
840                    break;
841                }
842                let Some(consumed) = known_leading_option_arguments("ssh", arguments, index) else {
843                    break 'invocations;
844                };
845                index += consumed;
846                if argument.value == "--" {
847                    break;
848                }
849            }
850            let script = arguments[index..]
851                .iter()
852                .map(|argument| argument.value.as_str())
853                .collect::<Vec<_>>()
854                .join(" ");
855            if !script.is_empty()
856                && let Some(inner) = summarize_shell(&script, nesting + 1)
857            {
858                words.push(inner);
859            }
860            break;
861        }
862
863        if basename == "timeout" {
864            let duration = first_verb
865                .strip_suffix(['s', 'm', 'h', 'd'])
866                .unwrap_or(first_verb);
867            if duration.parse::<f64>().is_ok() {
868                index += 1;
869                let Some(argument) = arguments.get(index).filter(|argument| argument.literal)
870                else {
871                    break;
872                };
873                first_verb = &argument.value;
874            }
875        }
876
877        if matches!(basename.as_str(), "nice" | "timeout") {
878            let Some(inner) = normalize_command_name(first_verb) else {
879                break;
880            };
881            executable = inner;
882            arguments = &arguments[index + 1..];
883            continue;
884        }
885        words.push(first_verb.to_owned());
886
887        if allows_second_verb(&basename, first_verb)
888            && let Some(argument) = arguments.get(index + 1)
889            && argument.literal
890            && !argument.value.starts_with('-')
891            && argument.value != "--"
892        {
893            // `uv run` is followed by a program, which may be given as a path.
894            if basename == "uv" && first_verb == "run" {
895                let name = argument.value.rsplit('/').next().unwrap_or(&argument.value);
896                let Some(inner) = normalize_command_name(name) else {
897                    break;
898                };
899                executable = inner;
900                arguments = &arguments[index + 2..];
901                continue;
902            }
903            words.push(argument.value.clone());
904        }
905        break;
906    }
907    Some(words.join(" "))
908}
909
910/// A shell is named without its directory, and the script it runs with `-c`
911/// is summarized in its own right, so `/bin/bash -c "python x.py"` reads
912/// `bash -c python`. The script is parsed even when it contains an expansion,
913/// because only its command names matter here.
914fn summarize_shell_invocation(
915    shell: &str,
916    arguments: &[InvocationArgument],
917    nesting: usize,
918) -> String {
919    let values = arguments
920        .iter()
921        .map(|argument| argument.value.as_str())
922        .collect::<Vec<_>>();
923    let Some(script) = shell_script_argument(&values) else {
924        return shell.to_owned();
925    };
926    match summarize_shell(script, nesting + 1) {
927        Some(inner) => format!("{shell} -c {inner}"),
928        None => format!("{shell} -c"),
929    }
930}
931
932fn is_summary_executable(basename: &str) -> bool {
933    matches!(
934        basename,
935        "git"
936            | "gh"
937            | "cargo"
938            | "rustup"
939            | "npm"
940            | "pnpm"
941            | "yarn"
942            | "bun"
943            | "uv"
944            | "pip"
945            | "pip3"
946            | "docker"
947            | "podman"
948            | "nice"
949            | "timeout"
950            | "ssh"
951            | "mbx"
952            | "mj"
953            | "tmux"
954    )
955}
956
957fn allows_second_verb(basename: &str, first_verb: &str) -> bool {
958    match basename {
959        // Only commands whose next word is always a subcommand: `git config`
960        // and `git reflog` also take a key or ref there.
961        "git" => matches!(
962            first_verb,
963            "bisect"
964                | "bundle"
965                | "hook"
966                | "lfs"
967                | "maintenance"
968                | "notes"
969                | "remote"
970                | "sparse-checkout"
971                | "stash"
972                | "submodule"
973                | "worktree"
974        ),
975        "gh" => matches!(
976            first_verb,
977            "alias"
978                | "auth"
979                | "cache"
980                | "codespace"
981                | "config"
982                | "extension"
983                | "gist"
984                | "gpg-key"
985                | "issue"
986                | "label"
987                | "org"
988                | "pr"
989                | "project"
990                | "release"
991                | "repo"
992                | "ruleset"
993                | "run"
994                | "search"
995                | "secret"
996                | "ssh-key"
997                | "variable"
998                | "workflow"
999        ),
1000        "docker" => matches!(
1001            first_verb,
1002            "buildx"
1003                | "compose"
1004                | "config"
1005                | "context"
1006                | "container"
1007                | "image"
1008                | "manifest"
1009                | "network"
1010                | "node"
1011                | "plugin"
1012                | "secret"
1013                | "service"
1014                | "stack"
1015                | "swarm"
1016                | "system"
1017                | "trust"
1018                | "volume"
1019        ),
1020        "podman" => matches!(
1021            first_verb,
1022            "artifact"
1023                | "container"
1024                | "farm"
1025                | "generate"
1026                | "image"
1027                | "machine"
1028                | "manifest"
1029                | "network"
1030                | "play"
1031                | "pod"
1032                | "secret"
1033                | "system"
1034                | "volume"
1035        ),
1036        "uv" => matches!(first_verb, "cache" | "pip" | "python" | "run" | "tool"),
1037        "npm" => matches!(first_verb, "run" | "run-script"),
1038        "pnpm" | "yarn" | "bun" => first_verb == "run",
1039        "mbx" => matches!(first_verb, "cache" | "explain" | "settings"),
1040        "mj" => matches!(
1041            first_verb,
1042            "daemon" | "import" | "recover" | "review" | "setup" | "workspaces"
1043        ),
1044        "rustup" => matches!(
1045            first_verb,
1046            "component" | "override" | "target" | "toolchain"
1047        ),
1048        _ => false,
1049    }
1050}
1051
1052fn known_leading_option_arguments(
1053    basename: &str,
1054    arguments: &[InvocationArgument],
1055    index: usize,
1056) -> Option<usize> {
1057    let option = arguments.get(index)?.value.as_str();
1058    if option == "--" {
1059        if matches!(basename, "nice" | "timeout" | "ssh") {
1060            return Some(1);
1061        }
1062        return None;
1063    }
1064    if basename == "ssh" {
1065        // Short flags can be bundled; a value-taking option consumes the
1066        // remainder of its bundle, or the next argument when there is none.
1067        let flags = option.strip_prefix('-')?;
1068        for (offset, flag) in flags.char_indices() {
1069            if "BbcDEeFIiJLlmOoPpQRSWw".contains(flag) {
1070                return if offset + flag.len_utf8() < flags.len() {
1071                    Some(1)
1072                } else {
1073                    arguments
1074                        .get(index + 1)
1075                        .filter(|argument| argument.literal)
1076                        .map(|_| 2)
1077                };
1078            }
1079            if !"46AaCfGgKkMNnqsTtVvXxYy".contains(flag) {
1080                return None;
1081            }
1082        }
1083        return (!flags.is_empty()).then_some(1);
1084    }
1085    let (option_name, attached_value) = option
1086        .split_once('=')
1087        .map_or((option, false), |(name, _)| (name, true));
1088    if basename == "nice"
1089        && option.starts_with('-')
1090        && option.len() > 1
1091        && option[1..].parse::<i32>().is_ok()
1092    {
1093        return Some(1);
1094    }
1095    if basename == "nice"
1096        && option
1097            .strip_prefix("-n")
1098            .is_some_and(|value| !value.is_empty() && value.parse::<i32>().is_ok())
1099    {
1100        return Some(1);
1101    }
1102    let attached_short_value = match basename {
1103        "git" => option.starts_with("-C") || option.starts_with("-c"),
1104        "gh" => option.starts_with("-R"),
1105        "docker" | "podman" => option.starts_with("-H"),
1106        "mj" => option.starts_with("-i"),
1107        "timeout" => option.starts_with("-s") || option.starts_with("-k"),
1108        "tmux" => ["-L", "-S", "-f", "-c", "-T"]
1109            .iter()
1110            .any(|prefix| option.starts_with(prefix)),
1111        _ => false,
1112    } && option.len() > 2;
1113    let takes_value = match basename {
1114        "git" => matches!(
1115            option_name,
1116            "-C" | "-c"
1117                | "--config-env"
1118                | "--exec-path"
1119                | "--git-dir"
1120                | "--namespace"
1121                | "--super-prefix"
1122                | "--work-tree"
1123        ),
1124        "gh" => matches!(
1125            option_name,
1126            "-R" | "--hostname" | "--repo" | "--jq" | "--template"
1127        ),
1128        "cargo" => matches!(
1129            option_name,
1130            "--manifest-path" | "--target-dir" | "--config" | "--color"
1131        ),
1132        "npm" | "pnpm" | "yarn" | "bun" => {
1133            matches!(
1134                option_name,
1135                "--cwd" | "--dir" | "--prefix" | "--registry" | "--userconfig"
1136            )
1137        }
1138        "uv" => matches!(option_name, "--directory" | "--project" | "--python"),
1139        "rustup" => matches!(option_name, "--toolchain"),
1140        "mj" => matches!(option_name, "-i" | "--instance" | "--workspace"),
1141        "tmux" => matches!(option_name, "-L" | "-S" | "-f" | "-c" | "-T"),
1142        "nice" => {
1143            matches!(option_name, "-n" | "--adjustment")
1144        }
1145        "timeout" => matches!(option_name, "-s" | "--signal" | "-k" | "--kill-after"),
1146        "docker" | "podman" => matches!(
1147            option_name,
1148            "-H" | "--config" | "--connection" | "--context" | "--host" | "--log-level"
1149        ),
1150        _ => false,
1151    };
1152    if attached_short_value {
1153        return Some(1);
1154    }
1155    if attached_value {
1156        return takes_value.then_some(1);
1157    }
1158    if takes_value {
1159        return arguments
1160            .get(index + 1)
1161            .filter(|argument| argument.literal)
1162            .map(|_| 2);
1163    }
1164    let known_flag = match basename {
1165        "git" => matches!(
1166            option_name,
1167            "-p" | "--paginate"
1168                | "-P"
1169                | "--no-pager"
1170                | "--bare"
1171                | "--literal-pathspecs"
1172                | "--glob-pathspecs"
1173                | "--noglob-pathspecs"
1174                | "--icase-pathspecs"
1175                | "--no-optional-locks"
1176                | "--no-advice"
1177        ),
1178        "gh" => false,
1179        "cargo" => matches!(
1180            option_name,
1181            "-q" | "--quiet" | "-v" | "--verbose" | "--locked" | "--offline" | "--frozen"
1182        ),
1183        "npm" | "pnpm" | "yarn" | "bun" => {
1184            matches!(option_name, "-g" | "--global" | "--silent")
1185        }
1186        "uv" => matches!(
1187            option_name,
1188            "-q" | "--quiet" | "-v" | "--verbose" | "--offline"
1189        ),
1190        "rustup" => matches!(option_name, "-q" | "--quiet" | "-v" | "--verbose"),
1191        "docker" | "podman" => matches!(option_name, "-D" | "--debug" | "--tls"),
1192        "tmux" => matches!(
1193            option_name,
1194            "-2" | "-C" | "-CC" | "-D" | "-l" | "-N" | "-u" | "-v"
1195        ),
1196        "nice" => false,
1197        "timeout" => matches!(
1198            option_name,
1199            "-f" | "--foreground" | "-p" | "--preserve-status" | "-v" | "--verbose"
1200        ),
1201        _ => false,
1202    };
1203    known_flag.then_some(1)
1204}
1205
1206fn strip_matching_quotes(value: &str) -> &str {
1207    value
1208        .strip_prefix('"')
1209        .and_then(|value| value.strip_suffix('"'))
1210        .or_else(|| {
1211            value
1212                .strip_prefix('\'')
1213                .and_then(|value| value.strip_suffix('\''))
1214        })
1215        .unwrap_or(value)
1216}
1217
1218fn is_shell_operator(node: Node<'_>) -> bool {
1219    match node.kind() {
1220        ";" => true,
1221        "&&" | "||" => node.parent().is_some_and(|parent| parent.kind() == "list"),
1222        "|" | "|&" => node
1223            .parent()
1224            .is_some_and(|parent| parent.kind() == "pipeline"),
1225        "&" => node.parent().is_none_or(|parent| {
1226            !matches!(
1227                parent.kind(),
1228                "binary_expression" | "unary_expression" | "postfix_expression"
1229            )
1230        }),
1231        _ => false,
1232    }
1233}
1234
1235fn normalize_command_name(text: &str) -> Option<String> {
1236    let text = text.trim();
1237    if text.contains('$') || text.contains('`') {
1238        return None;
1239    }
1240    let text = text
1241        .strip_prefix('"')
1242        .and_then(|value| value.strip_suffix('"'))
1243        .or_else(|| {
1244            text.strip_prefix('\'')
1245                .and_then(|value| value.strip_suffix('\''))
1246        })
1247        .unwrap_or(text);
1248    (!text.is_empty()).then(|| text.to_owned())
1249}
1250
1251fn join_shell_tokens(tokens: Vec<String>) -> String {
1252    let mut output = String::new();
1253    for token in tokens {
1254        match token.as_str() {
1255            "(" => {
1256                if !output.is_empty() && !output.ends_with(' ') {
1257                    output.push(' ');
1258                }
1259                output.push('(');
1260            }
1261            ")" => {
1262                output = output.trim_end().to_owned();
1263                output.push(')');
1264            }
1265            _ => {
1266                if !output.is_empty() && !output.ends_with(' ') && !output.ends_with('(') {
1267                    output.push(' ');
1268                }
1269                output.push_str(&token);
1270            }
1271        }
1272    }
1273    output
1274}
1275
1276/// Read string arguments as text, including their real line breaks. Other
1277/// values keep their JSON structure; the renderer wraps rather than clips it.
1278pub fn tool_input_text(input: &Value) -> String {
1279    fn value_text(value: &Value) -> String {
1280        match value {
1281            Value::String(text) => text.clone(),
1282            _ => serde_json::to_string_pretty(value)
1283                .expect("tool arguments are serializable JSON values"),
1284        }
1285    }
1286
1287    let text = match input {
1288        Value::Object(fields) if !fields.is_empty() => fields
1289            .iter()
1290            .map(|(name, value)| format!("{name}:\n{}", value_text(value)))
1291            .collect::<Vec<_>>()
1292            .join("\n\n"),
1293        _ => value_text(input),
1294    };
1295    sanitize_terminal_text(&text)
1296}
1297
1298pub fn tool_content_details(
1299    content: &[ToolCallContent],
1300    terminal_outputs: &[TerminalOutputRecord],
1301    raw_output: Option<&serde_json::Value>,
1302) -> Vec<String> {
1303    let mut details = Vec::new();
1304    let mut referenced: Vec<&str> = Vec::new();
1305    for item in content {
1306        let detail = match item {
1307            ToolCallContent::Content(content) => content_block_text(&content.content),
1308            ToolCallContent::Diff(_) => None,
1309            // Kimi-style agents send a terminal reference and no textual copy
1310            // of the output, so the record hel captured is the only thing a
1311            // reader ever sees. Until the terminal is reaped there is none.
1312            ToolCallContent::Terminal(terminal) => {
1313                let terminal_id = terminal.terminal_id.0.as_ref();
1314                referenced.push(terminal_id);
1315                Some(
1316                    terminal_outputs
1317                        .iter()
1318                        .find(|record| record.terminal_id.as_str() == terminal_id)
1319                        .map(terminal_output_detail)
1320                        .or_else(|| raw_output.and_then(raw_output_terminal_detail))
1321                        .unwrap_or_else(|| format!("terminal {}", terminal.terminal_id)),
1322                )
1323            }
1324            _ => None,
1325        };
1326        if let Some(detail) = detail {
1327            details.push(sanitize_terminal_text(&detail));
1328        }
1329    }
1330    // Grok-style agents name the terminal on a mid-flight update and then
1331    // replace `content` wholesale without it, so the output hel captured has
1332    // nothing in the final call pointing at it. Show it rather than lose it.
1333    for record in terminal_outputs {
1334        if referenced.contains(&record.terminal_id.as_str()) {
1335            continue;
1336        }
1337        let output = sanitize_terminal_text(&record.output);
1338        if !output.is_empty() && details.iter().any(|detail| detail == &output) {
1339            // Kimi sends the captured stdout as ordinary tool content and in
1340            // its raw result. Keep the exit summary without printing those
1341            // same bytes a second time in Raw mode.
1342            details.push(terminal_exit_summary(record));
1343        } else {
1344            details.push(sanitize_terminal_text(&terminal_output_detail(record)));
1345        }
1346    }
1347    details
1348}
1349
1350/// The output codex reports for a terminal it ran itself. Codex names its own
1351/// server-side terminal, which hel never opened and has no record for, and
1352/// puts the text in `rawOutput`; reading it here keeps such a call from
1353/// rendering as a bare terminal id.
1354fn raw_output_terminal_detail(raw_output: &serde_json::Value) -> Option<String> {
1355    let output = raw_output.get("formatted_output")?.as_str()?;
1356    let Some(exit_code) = raw_output
1357        .get("exit_code")
1358        .and_then(serde_json::Value::as_i64)
1359    else {
1360        return Some(output.to_owned());
1361    };
1362    let summary = format!("exited {exit_code}");
1363    if output.is_empty() {
1364        return Some(summary);
1365    }
1366    Some(format!("{output}\n{summary}"))
1367}
1368
1369/// One terminal's output followed by how it ended.
1370pub fn terminal_output_detail(record: &TerminalOutputRecord) -> String {
1371    let summary = terminal_exit_summary(record);
1372    if record.output.is_empty() {
1373        return summary;
1374    }
1375    format!("{}\n{summary}", record.output)
1376}
1377
1378/// How a terminal ended, in one line.
1379fn terminal_exit_summary(record: &TerminalOutputRecord) -> String {
1380    let mut summary = match (record.exit_code, &record.signal) {
1381        (_, Some(signal)) => format!("killed by {signal}"),
1382        (Some(code), None) => format!("exited {code}"),
1383        (None, None) => "released before exit".to_owned(),
1384    };
1385    if record.truncated {
1386        summary.push_str(" · output truncated");
1387    }
1388    summary
1389}
1390
1391pub fn tool_diff_paths(content: &[ToolCallContent]) -> Vec<String> {
1392    content
1393        .iter()
1394        .filter_map(|item| match item {
1395            ToolCallContent::Diff(diff) => Some(diff.path.display().to_string()),
1396            _ => None,
1397        })
1398        .collect()
1399}
1400
1401pub fn tool_location_details(locations: &[ToolCallLocation]) -> Vec<String> {
1402    locations
1403        .iter()
1404        .map(|location| match location.line {
1405            Some(line) => format!("{}:{line}", location.path.display()),
1406            None => location.path.display().to_string(),
1407        })
1408        .collect()
1409}
1410
1411/// Append streamed agent or thought text to the transcript, merging it into
1412/// the entry it continues so a message arrives as one entry rather than one
1413/// per chunk.
1414pub(crate) fn push_streamed_entry(
1415    entries: &mut Vec<ChatEntry>,
1416    seq: u64,
1417    recorded_at_ms: Option<i64>,
1418    role: ChatRole,
1419    message_id: Option<String>,
1420    text: &str,
1421) {
1422    let text = sanitize_terminal_text(text);
1423    if let Some(last) = entries.last_mut()
1424        && last.role == role
1425        && (role == ChatRole::Thought || last.message_id == message_id)
1426    {
1427        last.touch(seq);
1428        if role == ChatRole::Thought
1429            && last.message_id != message_id
1430            && !last.text.is_empty()
1431            && !text.is_empty()
1432        {
1433            while last.text.ends_with('\n') {
1434                last.text.pop();
1435            }
1436            last.text.push('\n');
1437            last.text.push_str(text.trim_start_matches('\n'));
1438        } else {
1439            last.text.push_str(&text);
1440        }
1441        return;
1442    }
1443    let mut entry = ChatEntry::plain(seq, role, text).with_recorded_at(recorded_at_ms);
1444    entry.message_id = message_id;
1445    entries.push(entry);
1446}
1447
1448/// Apply the transcript-visible part of one ACP session update. Returns the
1449/// update again when it changes the session surface rather than the
1450/// transcript, so the chat view handles those without decoding twice.
1451pub fn apply_session_update_to_entries(
1452    entries: &mut Vec<ChatEntry>,
1453    seq: u64,
1454    recorded_at_ms: Option<i64>,
1455    update: SessionUpdate,
1456) -> Option<SessionUpdate> {
1457    match update {
1458        SessionUpdate::AgentMessageChunk(chunk) => {
1459            let message_id = chunk.message_id.map(|id| id.to_string());
1460            if let Some(text) = content_block_text(&chunk.content) {
1461                push_streamed_entry(
1462                    entries,
1463                    seq,
1464                    recorded_at_ms,
1465                    ChatRole::Agent,
1466                    message_id,
1467                    &text,
1468                );
1469            }
1470        }
1471        SessionUpdate::AgentThoughtChunk(chunk) => {
1472            let message_id = chunk.message_id.map(|id| id.to_string());
1473            if let Some(text) = content_block_text(&chunk.content) {
1474                push_streamed_entry(
1475                    entries,
1476                    seq,
1477                    recorded_at_ms,
1478                    ChatRole::Thought,
1479                    message_id,
1480                    &text,
1481                );
1482            }
1483        }
1484        // PromptAccepted is the canonical local user-message event. ACP
1485        // user chunks would duplicate it during replay.
1486        SessionUpdate::UserMessageChunk(_) => {}
1487        SessionUpdate::ToolCall(call) => {
1488            let presentation = tool_call_presentation(&call);
1489            let mut entry = ChatEntry::tool(
1490                seq,
1491                call.title,
1492                Some(call.tool_call_id.to_string()),
1493                tool_status(&call.status),
1494            )
1495            .with_recorded_at(recorded_at_ms);
1496            mark_tool_end(&mut entry, recorded_at_ms);
1497            entry.tool_summary = Some(presentation.summary.clone());
1498            entry.tool_presentation = Some(presentation);
1499            entry.tool_input = call.raw_input;
1500            entry.tool_content = tool_content_details(&call.content, &[], call.raw_output.as_ref());
1501            entry.tool_diffstats = tool_diff_paths(&call.content);
1502            entry.tool_locations = tool_location_details(&call.locations);
1503            entries.push(entry);
1504        }
1505        SessionUpdate::ToolCallUpdate(update) => {
1506            let tool_call_id = update.tool_call_id.to_string();
1507            let entry = entries.iter_mut().rev().find(|entry| {
1508                entry.role == ChatRole::Tool
1509                    && entry.tool_call_id.as_deref() == Some(tool_call_id.as_str())
1510            })?;
1511            entry.touch(seq);
1512            let kind = update.fields.kind;
1513            let raw_input = update.fields.raw_input.clone();
1514            let raw_output = update.fields.raw_output.clone();
1515            if let Some(input) = &raw_input {
1516                entry.tool_input = Some(input.clone());
1517            }
1518            if let Some(title) = update.fields.title {
1519                entry.text = sanitize_terminal_text(&title);
1520            }
1521            if let Some(status) = update.fields.status {
1522                entry.tool_status = Some(tool_status(&status));
1523                mark_tool_end(entry, recorded_at_ms);
1524            }
1525            if let Some(content) = update.fields.content {
1526                entry.tool_content =
1527                    tool_content_details(&content, &[], update.fields.raw_output.as_ref());
1528                entry.tool_diffstats = tool_diff_paths(&content);
1529            }
1530            if let Some(locations) = update.fields.locations {
1531                entry.tool_locations = tool_location_details(&locations);
1532            }
1533            let presentation = update_tool_call_presentation(
1534                entry.tool_presentation.as_ref(),
1535                &entry.text,
1536                kind,
1537                raw_input.as_ref(),
1538                raw_output.as_ref(),
1539            );
1540            entry.tool_summary = Some(presentation.summary.clone());
1541            entry.tool_presentation = Some(presentation);
1542        }
1543        SessionUpdate::Plan(plan) => {
1544            let lines = plan
1545                .entries
1546                .into_iter()
1547                .map(|entry| PlanLine {
1548                    text: sanitize_terminal_text(&entry.content),
1549                    status: plan_status(&entry.status),
1550                })
1551                .collect();
1552            let latest_user_seq = entries
1553                .iter()
1554                .rev()
1555                .find(|entry| entry.role == ChatRole::User)
1556                .map_or(0, |entry| entry.seq);
1557            if let Some(entry) = entries
1558                .iter_mut()
1559                .rev()
1560                .find(|entry| entry.role == ChatRole::Plan && entry.seq > latest_user_seq)
1561            {
1562                entry.touch(seq);
1563                entry.plan = lines;
1564            } else {
1565                entries.push(ChatEntry::plan(seq, lines));
1566            }
1567        }
1568        other => return Some(other),
1569    }
1570    None
1571}
1572
1573/// Record when a tool call finished, the time of the event that finished it.
1574fn mark_tool_end(entry: &mut ChatEntry, recorded_at_ms: Option<i64>) {
1575    entry.tool_ended_at_ms = match entry.tool_status {
1576        Some(ToolStatus::Completed | ToolStatus::Failed) => recorded_at_ms,
1577        _ => None,
1578    };
1579}
1580
1581/// Apply the transcript-visible part of one persisted runtime event. Returns
1582/// the event again when it only configures the session surface, which is the
1583/// chat view's business rather than the transcript's.
1584pub fn apply_runtime_event_to_entries(
1585    entries: &mut Vec<ChatEntry>,
1586    seq: u64,
1587    recorded_at_ms: Option<i64>,
1588    runtime: RuntimeEvent,
1589) -> Option<RuntimeEvent> {
1590    match runtime {
1591        RuntimeEvent::SessionUpdate { update } => {
1592            let parsed = match serde_json::from_value::<SessionUpdate>(update.clone()) {
1593                Ok(parsed) => parsed,
1594                Err(error) => {
1595                    tracing::debug!(%error, "ignoring invalid ACP session update");
1596                    return None;
1597                }
1598            };
1599            apply_session_update_to_entries(entries, seq, recorded_at_ms, parsed)
1600                .map(|_| RuntimeEvent::SessionUpdate { update })
1601        }
1602        RuntimeEvent::Warning { message } | RuntimeEvent::SessionFault { message } => {
1603            entries.push(ChatEntry::plain(
1604                seq,
1605                ChatRole::System,
1606                format!("warning: {message}"),
1607            ));
1608            None
1609        }
1610        RuntimeEvent::ConfigApplied { key, value, .. } => {
1611            entries.push(ChatEntry::plain(
1612                seq,
1613                ChatRole::System,
1614                format!("{key} set to {value}"),
1615            ));
1616            None
1617        }
1618        RuntimeEvent::SessionStarted { resumed: false, .. } => {
1619            entries.push(ChatEntry::plain(
1620                seq,
1621                ChatRole::System,
1622                "harness session started",
1623            ));
1624            None
1625        }
1626        RuntimeEvent::SessionStarted { resumed: true, .. } => None,
1627        RuntimeEvent::ElicitationResolved {
1628            reply: Some(reply), ..
1629        } => {
1630            let mut entry =
1631                ChatEntry::plain(seq, ChatRole::User, reply).with_recorded_at(recorded_at_ms);
1632            entry.message_id = Some(format!("{ELICITATION_REPLY_ITEM_PREFIX}{seq}"));
1633            entries.push(entry);
1634            None
1635        }
1636        other => Some(other),
1637    }
1638}
1639
1640/// One transcript item flattened to the text a reader would see.
1641///
1642/// A caller that wants the structure reads the body itself; this is the plain
1643/// reading, built from the same flatteners every other surface uses so that a
1644/// tool call reads as the command it ran rather than as JSON.
1645pub fn transcript_item_text(item: &TranscriptItem) -> String {
1646    match &item.body {
1647        TranscriptBody::User { content } => materialized_content_text(content),
1648        TranscriptBody::Message { event } => format!(
1649            "{}\n\n{}",
1650            event.message_label(),
1651            mj_core::transcript::sanitize_terminal_text(
1652                event.message_text().expect("message entry metadata")
1653            )
1654        ),
1655        TranscriptBody::Agent { chunks, .. } | TranscriptBody::Thought { chunks, .. } => {
1656            materialized_chunks_text(chunks)
1657        }
1658        TranscriptBody::Tool {
1659            call,
1660            terminal_outputs,
1661            presentation,
1662            ..
1663        } => {
1664            let Ok(call) = ToolCall::deserialize(call) else {
1665                return "[invalid tool call]".to_owned();
1666            };
1667            let mut text = materialized_tool_call_presentation(presentation.as_deref(), &call)
1668                .summary
1669                .clone();
1670            if text.trim().is_empty() {
1671                text = call.title.clone();
1672            }
1673            for record in terminal_outputs {
1674                text.push('\n');
1675                text.push_str(&terminal_output_detail(record));
1676            }
1677            sanitize_terminal_text(&text)
1678        }
1679        TranscriptBody::TerminalOutput { record } => {
1680            sanitize_terminal_text(&terminal_output_detail(record))
1681        }
1682        TranscriptBody::Plan { plan } => {
1683            let Ok(plan) = agent_client_protocol::schema::v1::Plan::deserialize(plan) else {
1684                return String::new();
1685            };
1686            plan.entries
1687                .iter()
1688                .map(|entry| {
1689                    let status = match plan_status(&entry.status) {
1690                        PlanStatus::Pending => "pending",
1691                        PlanStatus::Running => "running",
1692                        PlanStatus::Completed => "completed",
1693                    };
1694                    format!("[{status}] {}", sanitize_terminal_text(&entry.content))
1695                })
1696                .collect::<Vec<_>>()
1697                .join("\n")
1698        }
1699        TranscriptBody::PlanProposal { plan, .. } => plan.clone(),
1700        TranscriptBody::System { text } => text.clone(),
1701    }
1702}
1703
1704pub(crate) fn compute_tool_diffstats(content: &[ToolCallContent]) -> Vec<String> {
1705    content
1706        .iter()
1707        .filter_map(|item| match item {
1708            ToolCallContent::Diff(diff) => Some(format_diffstat(diff)),
1709            _ => None,
1710        })
1711        .collect()
1712}
1713
1714pub fn materialized_tool_diffstats(item: &TranscriptItem) -> Option<Vec<String>> {
1715    let TranscriptBody::Tool { call, .. } = &item.body else {
1716        return None;
1717    };
1718    let call = match ToolCall::deserialize(call) {
1719        Ok(call) => call,
1720        Err(error) => {
1721            tracing::warn!(
1722                stable_id = %item.stable_id,
1723                %error,
1724                "could not decode a stored tool call while reading diff summary"
1725            );
1726            return None;
1727        }
1728    };
1729    if !matches!(
1730        tool_status(&call.status),
1731        ToolStatus::Completed | ToolStatus::Failed
1732    ) {
1733        return None;
1734    }
1735    let diffstats = compute_tool_diffstats(&call.content);
1736    (!diffstats.is_empty()).then_some(diffstats)
1737}
1738
1739fn format_diffstat(diff: &agent_client_protocol::schema::v1::Diff) -> String {
1740    // A diff recorded since `diff` landed already carries its counts, so
1741    // this is a lookup. An older record still holds both file copies and is
1742    // diffed here on demand.
1743    let patch = mj_core::diff::patch_of(diff);
1744    format!(
1745        "{}  +{} −{}",
1746        diff.path.display(),
1747        patch.insertions,
1748        patch.deletions
1749    )
1750}
1751
1752#[cfg(test)]
1753mod tests {
1754    use super::*;
1755    use agent_client_protocol::schema::v1::{ToolCall, ToolCallStatus, ToolCallUpdate};
1756    use serde_json::json;
1757
1758    #[test]
1759    fn a_live_tool_call_records_when_it_started_and_ended() {
1760        let mut entries = Vec::new();
1761        let call = ToolCall::new("tool-1", "cargo test").status(ToolCallStatus::InProgress);
1762        apply_session_update_to_entries(
1763            &mut entries,
1764            1,
1765            Some(1_000),
1766            SessionUpdate::ToolCall(call),
1767        );
1768        assert_eq!(entries[0].recorded_at_ms, Some(1_000));
1769        assert_eq!(entries[0].tool_ended_at_ms, None);
1770
1771        let finish = SessionUpdate::ToolCallUpdate(ToolCallUpdate::new(
1772            "tool-1",
1773            ToolCallUpdateFields::new().status(ToolCallStatus::Completed),
1774        ));
1775        apply_session_update_to_entries(&mut entries, 2, Some(91_000), finish);
1776        assert_eq!(entries[0].recorded_at_ms, Some(1_000));
1777        assert_eq!(entries[0].tool_ended_at_ms, Some(91_000));
1778    }
1779
1780    /// I1-18: Claude's question tool is titled with the question itself. Its
1781    /// row showed only "Which"; it must show the whole question.
1782    // Hard-won: e570799ccc: a question-tool row displayed only its first word.
1783    #[test]
1784    fn a_question_tool_is_summarized_by_its_whole_question() {
1785        let call = ToolCall::new("ask", "Which file name should I use for the new file?")
1786            .raw_input(json!({"questions": [{"question": "Which file name should I use for the new file?", "header": "File name"}]}));
1787        assert_eq!(
1788            tool_call_presentation(&call).summary,
1789            "Which file name should I use for the new file?"
1790        );
1791        let read = ToolCall::new("read", "Read src/lib.rs");
1792        assert_eq!(tool_call_presentation(&read).summary, "Read");
1793        let stale = ToolCallPresentation {
1794            summary: "Which".into(),
1795            source: call.title.clone(),
1796            source_kind: ToolSummarySourceKind::Title,
1797            tool_kind: ToolKind::Other,
1798            summary_version: 1,
1799        };
1800        assert_eq!(
1801            materialized_tool_call_presentation(Some(&stale), &call).summary,
1802            "Which file name should I use for the new file?",
1803            "stored rows written by the old rules are repaired"
1804        );
1805    }
1806
1807    fn execute_summary(command: serde_json::Value) -> String {
1808        let call = ToolCall::new("argv", "Bash")
1809            .kind(ToolKind::Execute)
1810            .raw_input(command);
1811        tool_call_presentation(&call).summary
1812    }
1813
1814    #[test]
1815    fn unknown_leading_options_make_verb_position_ambiguous() {
1816        assert_eq!(
1817            execute_summary(json!({"command": ["git", "--mystery", "status"]})),
1818            "git"
1819        );
1820        assert_eq!(
1821            execute_summary(json!({"command": ["cargo", "--mystery", "test"]})),
1822            "cargo"
1823        );
1824    }
1825
1826    #[test]
1827    fn git_commands_with_nested_subcommands_show_both_verbs() {
1828        let cases = [
1829            ("git worktree add ../x mj/session", "git worktree add"),
1830            ("git -C repo worktree list", "git worktree list"),
1831            ("git stash push -u -m tag", "git stash push"),
1832            ("git stash", "git stash"),
1833            ("git remote -v", "git remote"),
1834            ("git bisect good abc123", "git bisect good"),
1835            ("git stash -- src", "git stash"),
1836            ("git log origin/master", "git log"),
1837            ("git config user.name", "git config"),
1838        ];
1839        for (command, summary) in cases {
1840            assert_eq!(
1841                execute_summary(json!({"command": command})),
1842                summary,
1843                "{command}"
1844            );
1845        }
1846    }
1847
1848    #[test]
1849    fn project_tools_and_script_runners_show_their_subcommands() {
1850        let cases = [
1851            ("mbx nextest run -p brokk-mj-tui", "mbx nextest"),
1852            ("mbx +1.91 build bifrost", "mbx build"),
1853            ("mbx cache stats --json", "mbx cache stats"),
1854            ("mj daemon restart", "mj daemon restart"),
1855            (
1856                "mj -i test --workspace hel daemon status",
1857                "mj daemon status",
1858            ),
1859            ("mj transcript abc123", "mj transcript"),
1860            ("tmux -L mjv-e send-keys -t 0 q", "tmux send-keys"),
1861            ("tmux -Lmjv capture-pane -p", "tmux capture-pane"),
1862            ("tmux -S /tmp/sock -2 new-session -d", "tmux new-session"),
1863            ("uv run pytest -q", "uv run pytest"),
1864            ("uv run ./scripts/check.py", "uv run check.py"),
1865            ("uv run --with x pytest", "uv run"),
1866            ("npm run build", "npm run build"),
1867            ("npm run-script test:e2e", "npm run-script test:e2e"),
1868            ("pnpm run lint", "pnpm run lint"),
1869            ("npm test", "npm test"),
1870        ];
1871        for (command, summary) in cases {
1872            assert_eq!(
1873                execute_summary(json!({"command": command})),
1874                summary,
1875                "{command}"
1876            );
1877        }
1878    }
1879
1880    #[test]
1881    fn a_nested_shell_is_named_without_its_path_and_shows_its_script() {
1882        let cases = [
1883            ("cd dir && bash -c 'python x.py'", "cd && bash -c python"),
1884            (
1885                "/bin/bash -c \"python x.py\" | tee log",
1886                "bash -c python | tee",
1887            ),
1888            (
1889                "true; /usr/bin/zsh -lc 'git status && cargo test'",
1890                "true ; zsh -c git status && cargo test",
1891            ),
1892            ("bash -c \"$script\"", "bash -c"),
1893            ("/bin/bash script.sh", "bash"),
1894            (
1895                "bash -c 'bash -c \"uv run pytest\"'",
1896                "bash -c uv run pytest",
1897            ),
1898        ];
1899        for (command, summary) in cases {
1900            assert_eq!(
1901                execute_summary(json!({"command": command})),
1902                summary,
1903                "{command}"
1904            );
1905        }
1906        // An argv shell call already stands for its script.
1907        assert_eq!(
1908            execute_summary(json!({"command": ["/bin/bash", "-lc", "python x.py"]})),
1909            "python"
1910        );
1911        assert_eq!(
1912            execute_summary(json!({"command": ["/bin/zsh", "script.sh"]})),
1913            "zsh"
1914        );
1915    }
1916
1917    /// Codex reports a command that went through its approval path as one
1918    /// string with its shell wrapper. The same script reads the same whether
1919    /// the wrapper is there or not.
1920    #[test]
1921    fn a_command_that_is_only_a_shell_wrapper_stands_for_its_script() {
1922        let script = "python3 - <<'PY'\nprint(\"x\")\nPY";
1923        let wrapped = format!(
1924            "/bin/bash -lc \"{}\"",
1925            script.replace('\\', "\\\\").replace('"', "\\\"")
1926        );
1927        let presentation = |command: &str| {
1928            tool_call_presentation(
1929                &ToolCall::new("call", "Bash")
1930                    .kind(ToolKind::Execute)
1931                    .raw_input(json!({ "command": command })),
1932            )
1933        };
1934        assert_eq!(presentation(script).summary, "python3");
1935        assert_eq!(presentation(&wrapped).summary, "python3");
1936        assert_eq!(presentation(&wrapped).source, script);
1937
1938        let cases = [
1939            ("bash -c 'python x.py'", "python"),
1940            (
1941                "/usr/bin/zsh -lc 'git status && cargo test'",
1942                "git status && cargo test",
1943            ),
1944            ("bash -c \"cd $dir && make\"", "cd && make"),
1945            ("bash -c 'cargo test' arg0", "cargo test"),
1946            // Codex's quoting of a script with both kinds of quote.
1947            (
1948                "/bin/bash -lc \"rg -n '\"'^fn'\"' src | head\"",
1949                "rg | head",
1950            ),
1951            // An environment assignment is part of what the command does.
1952            ("FOO=1 bash -c 'cargo test'", "bash -c cargo test"),
1953        ];
1954        for (command, summary) in cases {
1955            assert_eq!(presentation(command).summary, summary, "{command}");
1956        }
1957    }
1958
1959    /// Retention drops a finished call's raw input. Rebuilding its summary
1960    /// from the title alone would lose what the input said.
1961    #[test]
1962    fn a_summary_whose_input_retention_dropped_is_kept() {
1963        let compacted = ToolCall::new("call", "Bash").kind(ToolKind::Execute);
1964        let stale = ToolCallPresentation {
1965            summary: "cargo test".into(),
1966            source: "cargo test --workspace".into(),
1967            source_kind: ToolSummarySourceKind::RawInput,
1968            tool_kind: ToolKind::Execute,
1969            summary_version: 0,
1970        };
1971        assert_eq!(
1972            materialized_tool_call_presentation(Some(&stale), &compacted),
1973            stale
1974        );
1975        let titled = ToolCallPresentation {
1976            source_kind: ToolSummarySourceKind::Title,
1977            ..stale
1978        };
1979        assert_eq!(
1980            materialized_tool_call_presentation(Some(&titled), &compacted).summary,
1981            "Bash"
1982        );
1983    }
1984
1985    #[test]
1986    fn quoted_and_dynamic_shell_verbs_are_distinguished() {
1987        let quoted = ToolCall::new("quoted", "Bash")
1988            .kind(ToolKind::Execute)
1989            .raw_input(json!({"command": "git \"status\""}));
1990        assert_eq!(tool_call_presentation(&quoted).summary, "git status");
1991
1992        let dynamic = ToolCall::new("dynamic", "Bash")
1993            .kind(ToolKind::Execute)
1994            .raw_input(json!({"command": "git \"$verb\""}));
1995        assert_eq!(tool_call_presentation(&dynamic).summary, "git");
1996
1997        let dynamic_name = ToolCall::new("dynamic-name", "Bash")
1998            .kind(ToolKind::Execute)
1999            .raw_input(json!({"command": "$command status"}));
2000        assert_eq!(tool_call_presentation(&dynamic_name).summary, "Bash");
2001    }
2002
2003    /// One command named by an expansion does not hide the rest of the
2004    /// script, and an assignment on its own reads as what it substitutes.
2005    #[test]
2006    fn shell_summary_keeps_the_commands_around_an_unnamed_one() {
2007        let presentation = |command: &str| {
2008            tool_call_presentation(
2009                &ToolCall::new("call", "Bash")
2010                    .kind(ToolKind::Execute)
2011                    .raw_input(json!({ "command": command })),
2012            )
2013            .summary
2014        };
2015        let cases = [
2016            (
2017                "T=$(git grep -l 'facts' -- tests | head -1); echo \"file: $T\"; \
2018                 S=$(echo $T | cut -d/ -f2); E=\"env -u CARGO\"; \
2019                 $E X=1 cargo nextest run --test $S 2>&1 | grep -E 'FAIL'; \
2020                 $E cargo clippy 2>&1 | grep -E '^error' | head -3",
2021                "git grep | head ; echo ; echo | cut ; … | grep ; … | grep | head",
2022            ),
2023            ("export T=\"$(git rev-parse HEAD)\"", "git rev-parse"),
2024            ("A=1 B=$(date)", "date"),
2025            ("cd dir && $runner test", "cd && …"),
2026            ("FOO=bar env -i echo $(printf hi)", "env"),
2027            ("E=x", "Bash"),
2028        ];
2029        for (command, summary) in cases {
2030            assert_eq!(presentation(command), summary, "{command}");
2031        }
2032    }
2033
2034    #[test]
2035    fn shell_summary_skips_assignments_arguments_and_nested_substitutions() {
2036        let call = ToolCall::new("call", "Bash")
2037            .kind(ToolKind::Execute)
2038            .raw_input(json!({
2039                "command": "FOO=bar env -i bash -c \"echo $(printf hi)\""
2040            }));
2041        assert_eq!(tool_call_presentation(&call).summary, "env");
2042
2043        let subshell = ToolCall::new("subshell", "Bash")
2044            .kind(ToolKind::Execute)
2045            .raw_input(json!({
2046                "command": "(cd dir && python x.py) | cat"
2047            }));
2048        assert_eq!(
2049            tool_call_presentation(&subshell).summary,
2050            "(cd && python) | cat"
2051        );
2052    }
2053
2054    #[test]
2055    fn shell_summary_keeps_list_pipeline_and_background_operators() {
2056        let simple = ToolCall::new("call-1", "Bash")
2057            .kind(ToolKind::Execute)
2058            .raw_input(json!({
2059                "command": "cd dir && python x.py | cat | wc ; print ok"
2060            }));
2061        let presentation = tool_call_presentation(&simple);
2062        assert_eq!(presentation.summary, "cd && python | cat | wc ; print");
2063        assert_eq!(presentation.source_kind, ToolSummarySourceKind::RawInput);
2064
2065        let call = ToolCall::new("operators", "Bash")
2066            .kind(ToolKind::Execute)
2067            .raw_input(json!({
2068                "command": "'printf' '%s' hi >out |& sed s/hi/bye/ || echo failed & wait; cat <in"
2069            }));
2070
2071        assert_eq!(
2072            tool_call_presentation(&call).summary,
2073            "printf |& sed || echo & wait ; cat"
2074        );
2075    }
2076
2077    #[test]
2078    fn shell_summary_removes_structural_loop_and_group_separators() {
2079        let call = ToolCall::new("compound", "Bash")
2080            .kind(ToolKind::Execute)
2081            .raw_input(json!({
2082                "command": "for file in a b; do rm \"$file\"; done; mkdir -p out; nice -n 10 python3 script.py"
2083            }));
2084
2085        assert_eq!(
2086            tool_call_presentation(&call).summary,
2087            "rm ; mkdir ; nice python3"
2088        );
2089
2090        let conditional = ToolCall::new("conditional", "Bash")
2091            .kind(ToolKind::Execute)
2092            .raw_input(json!({
2093                "command": "if test -f foo; then rm foo; fi; { mkdir bar; echo done; }"
2094            }));
2095        assert_eq!(
2096            tool_call_presentation(&conditional).summary,
2097            "test ; rm ; mkdir ; echo"
2098        );
2099
2100        let case_statement = ToolCall::new("case", "Bash")
2101            .kind(ToolKind::Execute)
2102            .raw_input(json!({
2103                "command": "echo start; case x in a|b) echo branch;; esac; echo done"
2104            }));
2105        assert_eq!(
2106            tool_call_presentation(&case_statement).summary,
2107            "echo ; echo ; echo"
2108        );
2109    }
2110
2111    #[test]
2112    fn shell_summary_handles_a_loop_with_a_leading_pipeline_and_nice() {
2113        let call = ToolCall::new("live-loop-shape", "Bash")
2114            .kind(ToolKind::Execute)
2115            .raw_input(json!({
2116                "command": "cd /tmp && for spec in a b; do set -- $spec; rm \"$spec\"; mkdir -p \"$spec\"; nice -n 10 ./bin/bifrost \"$spec\"; echo \"$spec\"; done; python3 script.py"
2117            }));
2118
2119        assert_eq!(
2120            tool_call_presentation(&call).summary,
2121            "cd && set ; rm ; mkdir ; nice ./bin/bifrost ; echo ; python3"
2122        );
2123    }
2124
2125    #[test]
2126    fn shell_summary_inserts_a_separator_after_a_heredoc() {
2127        let call = ToolCall::new("heredoc", "Bash")
2128            .kind(ToolKind::Execute)
2129            .raw_input(json!({
2130                "command": "python3 <<'PYEOF'\nprint(\"x\")\nPYEOF\ngrep -n x file | head"
2131            }));
2132
2133        assert_eq!(
2134            tool_call_presentation(&call).summary,
2135            "python3 ; grep | head"
2136        );
2137    }
2138
2139    #[test]
2140    fn materialized_summary_from_an_older_parser_is_repaired() {
2141        let source = "python3 <<'PYEOF'\nprint(\"x\")\nPYEOF\ngrep -n x file | head";
2142        let call = ToolCall::new("heredoc", "Bash")
2143            .kind(ToolKind::Execute)
2144            .raw_input(json!({ "command": source }));
2145        let stale = ToolCallPresentation {
2146            summary: "python3 grep | head".into(),
2147            source: source.into(),
2148            source_kind: ToolSummarySourceKind::RawInput,
2149            tool_kind: ToolKind::Execute,
2150            summary_version: 0,
2151        };
2152
2153        let repaired = materialized_tool_call_presentation(Some(&stale), &call);
2154        assert_eq!(repaired.summary, "python3 ; grep | head");
2155        assert_eq!(repaired.summary_version, TOOL_SUMMARY_VERSION);
2156
2157        let mut current = repaired;
2158        current.summary = "stored current summary".into();
2159        assert_eq!(
2160            materialized_tool_call_presentation(Some(&current), &call).summary,
2161            "stored current summary"
2162        );
2163    }
2164
2165    #[test]
2166    fn execute_summary_bounds_the_retained_source_before_parsing() {
2167        let command = format!("echo {}", "argument".repeat(TOOL_SUMMARY_SOURCE_BYTES));
2168        let call = ToolCall::new("bounded", "Bash")
2169            .kind(ToolKind::Execute)
2170            .raw_input(json!({ "command": command }));
2171
2172        let presentation = tool_call_presentation(&call);
2173        assert_eq!(presentation.source.len(), TOOL_SUMMARY_SOURCE_BYTES);
2174        assert_eq!(presentation.summary, "echo");
2175    }
2176
2177    #[test]
2178    fn title_wrappers_and_malformed_shell_fall_back_safely() {
2179        let wrapped = ToolCall::new("wrapped", "Running: ls -la").kind(ToolKind::Execute);
2180        assert_eq!(tool_call_presentation(&wrapped).summary, "ls");
2181
2182        let malformed = ToolCall::new("bad", "Bash")
2183            .kind(ToolKind::Execute)
2184            .raw_input(json!({"command": "cd && ("}));
2185        assert_eq!(tool_call_presentation(&malformed).summary, "Bash");
2186    }
2187
2188    #[test]
2189    fn explicit_empty_raw_input_drops_a_stale_raw_summary() {
2190        let initial = ToolCall::new("call", "Bash")
2191            .kind(ToolKind::Execute)
2192            .raw_input(json!({"command": "python script.py"}));
2193        let previous = tool_call_presentation(&initial);
2194        let empty_input = json!({"command": null});
2195        let updated = update_tool_call_presentation(
2196            Some(&previous),
2197            "Running: ls -la",
2198            None,
2199            Some(&empty_input),
2200            None,
2201        );
2202        assert_eq!(updated.summary, "ls");
2203        assert_eq!(updated.source_kind, ToolSummarySourceKind::Title);
2204
2205        let output = json!({"command": "cat result.txt"});
2206        let updated = update_tool_call_presentation(
2207            Some(&previous),
2208            "Running: ls -la",
2209            None,
2210            Some(&empty_input),
2211            Some(&output),
2212        );
2213        assert_eq!(updated.summary, "cat");
2214        assert_eq!(updated.source_kind, ToolSummarySourceKind::RawOutput);
2215
2216        let output_initial = ToolCall::new("output", "Bash")
2217            .kind(ToolKind::Execute)
2218            .raw_output(json!({"command": "python result.py"}));
2219        let output_previous = tool_call_presentation(&output_initial);
2220        let empty_output = json!({"command": null});
2221        let updated = update_tool_call_presentation(
2222            Some(&output_previous),
2223            "Running: ls -la",
2224            None,
2225            None,
2226            Some(&empty_output),
2227        );
2228        assert_eq!(updated.summary, "ls");
2229        assert_eq!(updated.source_kind, ToolSummarySourceKind::Title);
2230    }
2231
2232    fn rendered_tool_row(call: &ToolCall) -> String {
2233        let presentation = tool_call_presentation(call);
2234        let item = TranscriptItem {
2235            stable_id: "tool:golden".into(),
2236            position: 1,
2237            latest_content_event_ordinal: None,
2238            created_at_ms: 1,
2239            last_changed_at_ms: 1,
2240            body: TranscriptBody::Tool {
2241                call: serde_json::to_value(call).expect("serialize tool call"),
2242                terminal_outputs: Vec::new(),
2243                terminal_refs: Vec::new(),
2244                presentation: Some(Box::new(presentation)),
2245            },
2246        };
2247        transcript_item_text(&item)
2248    }
2249
2250    fn append_tool_row(output: &mut String, label: &str, call: &ToolCall) {
2251        use std::fmt::Write as _;
2252        if !output.is_empty() {
2253            output.push('\n');
2254        }
2255        writeln!(output, "=== {label} (transcript row) ===").unwrap();
2256        output.push_str(&rendered_tool_row(call));
2257        output.push('\n');
2258    }
2259
2260    #[test]
2261    fn golden_transcript_tool_row_summary() {
2262        use std::fmt::Write as _;
2263
2264        let mut output = String::new();
2265        let diff = agent_client_protocol::schema::v1::Diff::new("/workspace/new.txt", "one\ntwo\n");
2266        writeln!(output, "=== new file diff detail (transcript row) ===").unwrap();
2267        writeln!(output, "{}", format_diffstat(&diff)).unwrap();
2268
2269        let terminal = |exit_code, signal: Option<&str>, truncated, text: &str| {
2270            let record = TerminalOutputRecord {
2271                terminal_id: "term-1".into(),
2272                output: text.into(),
2273                truncated,
2274                exit_code,
2275                signal: signal.map(str::to_owned),
2276            };
2277            let item = TranscriptItem {
2278                stable_id: "terminal:golden".into(),
2279                position: 1,
2280                latest_content_event_ordinal: None,
2281                created_at_ms: 1,
2282                last_changed_at_ms: 1,
2283                body: TranscriptBody::TerminalOutput { record },
2284            };
2285            transcript_item_text(&item)
2286        };
2287        for (label, row) in [
2288            ("successful terminal", terminal(Some(0), None, false, "out")),
2289            ("truncated terminal", terminal(Some(1), None, true, "out")),
2290            (
2291                "signal termination",
2292                terminal(None, Some("SIGKILL"), false, "out"),
2293            ),
2294            ("released terminal", terminal(None, None, false, "out")),
2295            (
2296                "silent signal termination",
2297                terminal(None, Some("SIGTERM"), false, ""),
2298            ),
2299        ] {
2300            writeln!(output, "\n=== {label} (transcript row) ===\n{row}").unwrap();
2301        }
2302
2303        append_tool_row(
2304            &mut output,
2305            "shell command",
2306            &ToolCall::new("shell", "Terminal")
2307                .kind(ToolKind::Execute)
2308                .raw_input(json!({
2309                    "command": ["bash", "-lc", "cd dir && python x.py | cat"]
2310                })),
2311        );
2312        append_tool_row(
2313            &mut output,
2314            "ordinary argv command",
2315            &ToolCall::new("argv", "Execute")
2316                .kind(ToolKind::Execute)
2317                .raw_input(json!({"command": ["python", "-c", "print(1)"]})),
2318        );
2319
2320        let update_call = ToolCall::new("shell", "Bash")
2321            .kind(ToolKind::Execute)
2322            .raw_input(json!({"command": "cargo test"}));
2323        let original = tool_call_presentation(&update_call);
2324        let mut output_update = ToolCallUpdateFields::default();
2325        output_update.raw_output = Some(json!({"output": "x".repeat(128 * 1024)}));
2326        writeln!(output, "\n=== output-only update (transcript row) ===").unwrap();
2327        writeln!(
2328            output,
2329            "presentation changed: {}",
2330            tool_call_update_changes_presentation(&update_call, &output_update)
2331        )
2332        .unwrap();
2333        writeln!(output, "{}", original.summary).unwrap();
2334        let mut status_update = ToolCallUpdateFields::default();
2335        status_update.status = Some(ToolCallStatus::Completed);
2336        writeln!(
2337            output,
2338            "status-only update changes presentation: {}",
2339            tool_call_update_changes_presentation(&update_call, &status_update)
2340        )
2341        .unwrap();
2342        let output_call = ToolCall::new("output", "Bash").kind(ToolKind::Execute);
2343        writeln!(
2344            output,
2345            "output-only call changes presentation: {}",
2346            tool_call_update_changes_presentation(&output_call, &output_update)
2347        )
2348        .unwrap();
2349        let changed_input = json!({"command": "cargo check"});
2350        let mut input_update = ToolCallUpdateFields::default();
2351        input_update.raw_input = Some(changed_input.clone());
2352        writeln!(
2353            output,
2354            "changed command presentation: {}",
2355            tool_call_update_changes_presentation(&update_call, &input_update)
2356        )
2357        .unwrap();
2358        writeln!(
2359            output,
2360            "updated row: {}",
2361            update_tool_call_presentation(
2362                Some(&original),
2363                "Bash",
2364                Some(ToolKind::Execute),
2365                Some(&changed_input),
2366                None,
2367            )
2368            .summary
2369        )
2370        .unwrap();
2371
2372        for (label, command) in [
2373            (
2374                "git registered verb",
2375                json!({"command": ["git", "--no-pager", "status", "--short"]}),
2376            ),
2377            (
2378                "cargo registered verb",
2379                json!({"command": ["cargo", "+nightly", "test", "--package", "hel"]}),
2380            ),
2381            (
2382                "gh registered namespace",
2383                json!({"command": ["gh", "--hostname", "github.example", "pr", "list"]}),
2384            ),
2385            (
2386                "docker registered namespace",
2387                json!({"command": ["docker", "--context", "work", "compose", "up"]}),
2388            ),
2389            (
2390                "podman registered namespace",
2391                json!({"command": ["podman", "machine", "list"]}),
2392            ),
2393            (
2394                "uv registered namespace",
2395                json!({"command": ["uv", "--project", "app", "pip", "install", "ruff"]}),
2396            ),
2397            (
2398                "rustup registered namespace",
2399                json!({"command": ["rustup", "toolchain", "list"]}),
2400            ),
2401            (
2402                "npm registered namespace",
2403                json!({"command": ["npm", "--prefix", "web", "run", "build"]}),
2404            ),
2405        ] {
2406            append_tool_row(
2407                &mut output,
2408                label,
2409                &ToolCall::new("argv", "Bash")
2410                    .kind(ToolKind::Execute)
2411                    .raw_input(command),
2412            );
2413        }
2414
2415        let shell = ToolCall::new("string", "Bash")
2416            .kind(ToolKind::Execute)
2417            .raw_input(json!({"command": "git --no-pager status --short"}));
2418        let argv = ToolCall::new("argv", "Bash")
2419            .kind(ToolKind::Execute)
2420            .raw_input(json!({"command": ["git", "--no-pager", "status", "--short"]}));
2421        writeln!(
2422            output,
2423            "\n=== shell and argv invocation depth (transcript rows) ==="
2424        )
2425        .unwrap();
2426        writeln!(output, "shell: {}", rendered_tool_row(&shell)).unwrap();
2427        writeln!(output, "argv: {}", rendered_tool_row(&argv)).unwrap();
2428
2429        for (label, command) in [
2430            ("sudo wrapper", "sudo -n git status"),
2431            ("env wrapper", "env FOO=bar git status"),
2432            ("command wrapper", "command git status"),
2433        ] {
2434            append_tool_row(
2435                &mut output,
2436                label,
2437                &ToolCall::new("wrapper", "Bash")
2438                    .kind(ToolKind::Execute)
2439                    .raw_input(json!({"command": command})),
2440            );
2441        }
2442
2443        for (label, command) in [
2444            (
2445                "unlisted build tool",
2446                json!({"command": ["mytool", "build", "src"]}),
2447            ),
2448            (
2449                "unlisted script",
2450                json!({"command": ["mytool", "./script.sh"]}),
2451            ),
2452            ("python script", json!({"command": ["python", "script.py"]})),
2453            (
2454                "gh API namespace",
2455                json!({"command": ["gh", "api", "graphql"]}),
2456            ),
2457            (
2458                "docker run namespace",
2459                json!({"command": ["docker", "run", "ubuntu"]}),
2460            ),
2461            (
2462                "registered future git verb",
2463                json!({"command": ["git", "future-verb"]}),
2464            ),
2465            (
2466                "absolute git with attached directory",
2467                json!({"command": ["/usr/bin/git", "-Crepo", "status"]}),
2468            ),
2469            (
2470                "git short global option",
2471                json!({"command": ["git", "-c", "core.pager=cat", "status"]}),
2472            ),
2473            (
2474                "gh attached repository option",
2475                json!({"command": ["gh", "-Rorg/repo", "pr", "list"]}),
2476            ),
2477            (
2478                "cargo color option",
2479                json!({"command": ["cargo", "--color=always", "test"]}),
2480            ),
2481            (
2482                "cargo config option",
2483                json!({"command": ["cargo", "--config", "build.jobs=2", "test"]}),
2484            ),
2485        ] {
2486            append_tool_row(
2487                &mut output,
2488                label,
2489                &ToolCall::new("argv", "Bash")
2490                    .kind(ToolKind::Execute)
2491                    .raw_input(command),
2492            );
2493        }
2494
2495        for command in [
2496            vec!["nice", "-n", "10", "python3", "script.py"],
2497            vec!["nice", "--adjustment", "10", "python3", "script.py"],
2498            vec!["nice", "--adjustment=10", "python3", "script.py"],
2499            vec!["nice", "-10", "python3", "script.py"],
2500            vec!["nice", "-n10", "python3", "script.py"],
2501            vec!["nice", "--", "python3", "script.py"],
2502        ] {
2503            append_tool_row(
2504                &mut output,
2505                "nice command options",
2506                &ToolCall::new("nice", "Bash")
2507                    .kind(ToolKind::Execute)
2508                    .raw_input(json!({"command": command})),
2509            );
2510        }
2511        append_tool_row(
2512            &mut output,
2513            "nice shell command",
2514            &ToolCall::new("nice-shell", "Bash")
2515                .kind(ToolKind::Execute)
2516                .raw_input(json!({"command": "nice -n 10 python3 script.py"})),
2517        );
2518        for (label, command) in [
2519            ("timeout shell command", json!("timeout git status")),
2520            (
2521                "timeout argv command",
2522                json!(["timeout", "30s", "git", "-C", "repo", "worktree", "list"]),
2523            ),
2524            (
2525                "timeout command options",
2526                json!([
2527                    "timeout",
2528                    "--foreground",
2529                    "--preserve-status",
2530                    "--verbose",
2531                    "--signal",
2532                    "TERM",
2533                    "--kill-after=5s",
2534                    "1.5m",
2535                    "git",
2536                    "status"
2537                ]),
2538            ),
2539            (
2540                "timeout attached short options",
2541                json!("timeout -sTERM -k5s -- 30 git status"),
2542            ),
2543            (
2544                "nested command wrappers",
2545                json!("nice -n 10 timeout 5m nice -- cargo +nightly test -q"),
2546            ),
2547            (
2548                "recursive script runner",
2549                json!("uv run /usr/bin/timeout 5m git status"),
2550            ),
2551            (
2552                "wrapped shell command",
2553                json!("timeout 1h /bin/bash -lc 'git status && cargo test'"),
2554            ),
2555            (
2556                "timeout in a pipeline",
2557                json!("timeout 10 git status | cat && timeout 2m gh pr list"),
2558            ),
2559            (
2560                "timeout unknown option",
2561                json!("nice timeout --mystery 10 git status"),
2562            ),
2563            (
2564                "timeout dynamic duration",
2565                json!("timeout \"$duration\" git status"),
2566            ),
2567            (
2568                "timeout dynamic command",
2569                json!("timeout 30 \"$command\" status"),
2570            ),
2571            ("wrapped dynamic verb", json!("timeout 30 git \"$verb\"")),
2572            ("timeout without command", json!(["timeout", "30"])),
2573            (
2574                "script name is not an invocation",
2575                json!("timeout 30 npm run git status"),
2576            ),
2577            (
2578                "ordinary command arguments are not invocations",
2579                json!("timeout 30 python git status"),
2580            ),
2581            (
2582                "ssh remote command",
2583                json!("ssh builder git status --short"),
2584            ),
2585            (
2586                "ssh remote argv",
2587                json!(["ssh", "builder", "git", "-C", "repo", "worktree", "list"]),
2588            ),
2589            (
2590                "ssh quoted remote script",
2591                json!("ssh builder 'cd repo && git status | cat'"),
2592            ),
2593            (
2594                "ssh quoted remote argv script",
2595                json!(["ssh", "builder", "git status && cargo test -q"]),
2596            ),
2597            (
2598                "ssh connection options",
2599                json!(
2600                    "/usr/bin/ssh -vvT -p 2222 -o BatchMode=yes -i /keys/build builder git status"
2601                ),
2602            ),
2603            (
2604                "ssh attached options after destination",
2605                json!("ssh builder -Tp2222 -oBatchMode=yes -- uv run pytest -q"),
2606            ),
2607            (
2608                "ssh wrapped remote shell",
2609                json!("timeout 30 ssh -- builder 'bash -lc \"git status && cargo test\"'"),
2610            ),
2611            ("ssh without remote command", json!("ssh builder")),
2612            ("ssh dynamic destination", json!("ssh \"$host\" git status")),
2613            (
2614                "ssh dynamic remote script",
2615                json!("ssh builder \"cd $dir && git status\""),
2616            ),
2617            (
2618                "ssh dynamic remote command",
2619                json!("ssh builder \"$script\""),
2620            ),
2621            (
2622                "ssh unknown connection option",
2623                json!("ssh --mystery value builder git status"),
2624            ),
2625            (
2626                "ssh unknown option after destination",
2627                json!("ssh builder --mystery value git status"),
2628            ),
2629            ("ssh without destination", json!(["ssh", "-p", "2222"])),
2630            (
2631                "ssh nesting budget",
2632                json!(format!("{}git status", "ssh builder ".repeat(2_000))),
2633            ),
2634        ] {
2635            append_tool_row(
2636                &mut output,
2637                label,
2638                &ToolCall::new("recursive", "Bash")
2639                    .kind(ToolKind::Execute)
2640                    .raw_input(json!({"command": command})),
2641            );
2642        }
2643        for (label, command, summary, summary_version) in [
2644            (
2645                "cached wrapper summary",
2646                "nice -n 10 timeout 30 git status",
2647                "nice timeout",
2648                4,
2649            ),
2650            ("cached ssh summary", "ssh builder 'git status'", "ssh", 5),
2651        ] {
2652            let cached = ToolCall::new("cached-wrapper", "Bash")
2653                .kind(ToolKind::Execute)
2654                .raw_input(json!({"command": command}));
2655            let item = TranscriptItem {
2656                stable_id: "tool:cached-wrapper".into(),
2657                position: 1,
2658                latest_content_event_ordinal: None,
2659                created_at_ms: 1,
2660                last_changed_at_ms: 1,
2661                body: TranscriptBody::Tool {
2662                    call: serde_json::to_value(&cached).expect("serialize tool call"),
2663                    terminal_outputs: Vec::new(),
2664                    terminal_refs: Vec::new(),
2665                    presentation: Some(Box::new(ToolCallPresentation {
2666                        summary: summary.into(),
2667                        summary_version,
2668                        ..tool_call_presentation(&cached)
2669                    })),
2670                },
2671            };
2672            writeln!(
2673                output,
2674                "\n=== {label} (transcript row) ===\n{}",
2675                transcript_item_text(&item)
2676            )
2677            .unwrap();
2678        }
2679        append_tool_row(
2680            &mut output,
2681            "non-execute tool title",
2682            &ToolCall::new("read", "Read src/lib.rs").kind(ToolKind::Read),
2683        );
2684
2685        mj_core::golden::assert_golden(
2686            env!("CARGO_MANIFEST_DIR"),
2687            "transcript-tool-row-summary",
2688            &output,
2689        );
2690    }
2691}