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