Skip to main content

mj_transcript/
transcript.rs

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