Skip to main content

mj_transcript/
transcript.rs

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