Skip to main content

mj_transcript/
transcript.rs

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