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