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;
12/// Parser-rule version stored with cached tool summaries.
13pub const TOOL_SUMMARY_VERSION: u8 = 3;
14
15/// Reduce a tool call to what a reader still needs, once a verified checkpoint
16/// holds the whole of it.
17///
18/// Tool output is where a projection's bytes are: on one measured session,
19/// 561 MB of 635 MiB. Behind a checkpoint nothing reads it — the checkpoint
20/// archive carries the complete transcript, and restoring it brings the output
21/// back — so what stays here is what the transcript still shows: which tool
22/// ran, on what, with what result, and how many lines each edit changed.
23///
24/// Returns whether anything changed, so a caller can skip the write.
25pub fn compact_tool_call_for_retention(body: &mut TranscriptBody) -> bool {
26    let TranscriptBody::Tool {
27        call,
28        terminal_outputs,
29        terminal_refs,
30        ..
31    } = body
32    else {
33        return false;
34    };
35    let Some(object) = call.as_object_mut() else {
36        return false;
37    };
38    let mut changed = !terminal_outputs.is_empty() || !terminal_refs.is_empty();
39    terminal_outputs.clear();
40    terminal_refs.clear();
41    for field in ["rawInput", "rawOutput", "_meta"] {
42        changed |= object.remove(field).is_some();
43    }
44    let Some(content) = object
45        .get_mut("content")
46        .and_then(|value| value.as_array_mut())
47    else {
48        return changed;
49    };
50    let before = content.len();
51    // Diffs stay, because the transcript still shows their stat. Their patch
52    // text does not, and neither do the two file copies an older record holds
53    // instead of a patch: `diff::drop_patch_text` turns those into the
54    // counts `format_diffstat` reads before dropping them.
55    content.retain(|item| item.get("type").and_then(|kind| kind.as_str()) == Some("diff"));
56    changed |= content.len() != before;
57    for item in content.iter_mut() {
58        changed |= drop_diff_body(item);
59    }
60    changed
61}
62
63fn drop_diff_body(item: &mut serde_json::Value) -> bool {
64    use agent_client_protocol::schema::v1::ToolCallContent;
65
66    // Round-trip through `ToolCallContent`, not `Diff`: the variant tag lives
67    // on the enum, and writing back a bare `Diff` would strip it and make the
68    // whole tool call unreadable.
69    let mut content = match serde_json::from_value::<ToolCallContent>(item.clone()) {
70        Ok(content) => content,
71        // Content this cannot read is content it must not rewrite.
72        Err(error) => {
73            tracing::warn!(%error, "skipping unreadable tool content during retention");
74            return false;
75        }
76    };
77    let ToolCallContent::Diff(diff) = &mut content else {
78        return false;
79    };
80    if !mj_core::diff::drop_patch_text(diff) {
81        return false;
82    }
83    match serde_json::to_value(&content) {
84        Ok(value) => {
85            *item = value;
86            true
87        }
88        Err(error) => {
89            tracing::warn!(%error, "could not rewrite a diff during retention");
90            false
91        }
92    }
93}
94
95#[derive(Debug, Clone, PartialEq, Eq)]
96enum ToolSummarySource {
97    Shell(String),
98    Argv {
99        executable: String,
100        arguments: Vec<String>,
101    },
102}
103
104/// Whether a partial update changes inputs used to derive the tool summary.
105pub fn tool_call_update_changes_presentation(
106    call: &ToolCall,
107    fields: &ToolCallUpdateFields,
108) -> bool {
109    fields
110        .title
111        .as_ref()
112        .is_some_and(|title| title != &call.title)
113        || fields.kind.is_some_and(|kind| kind != call.kind)
114        || fields
115            .raw_input
116            .as_ref()
117            .is_some_and(|input| Some(input) != call.raw_input.as_ref())
118        || (call.kind == ToolKind::Execute
119            && fields
120                .raw_output
121                .as_ref()
122                .is_some_and(|output| Some(output) != call.raw_output.as_ref())
123            && command_source(call.raw_input.as_ref()).is_none())
124}
125
126/// Compute the stable presentation metadata for one complete ACP call.
127pub fn tool_call_presentation(call: &ToolCall) -> ToolCallPresentation {
128    let kind = call.kind;
129    if kind == ToolKind::Execute {
130        if let Some(source) = command_source(call.raw_input.as_ref()) {
131            return presentation_from_source(
132                source,
133                ToolSummarySourceKind::RawInput,
134                kind,
135                &call.title,
136            );
137        }
138        if let Some(source) = command_source(call.raw_output.as_ref()) {
139            return presentation_from_source(
140                source,
141                ToolSummarySourceKind::RawOutput,
142                kind,
143                &call.title,
144            );
145        }
146    }
147    presentation_from_title(&call.title, kind)
148}
149
150/// Use cached presentation data when it was produced by current parser rules,
151/// otherwise rebuild it from the complete stored call. This lets parser fixes
152/// repair existing transcripts while current summaries remain cheap to load.
153pub fn materialized_tool_call_presentation(
154    stored: Option<&ToolCallPresentation>,
155    call: &ToolCall,
156) -> ToolCallPresentation {
157    stored
158        .filter(|presentation| presentation.summary_version >= TOOL_SUMMARY_VERSION)
159        .cloned()
160        .unwrap_or_else(|| tool_call_presentation(call))
161}
162
163/// Apply the presentation-relevant portion of a partial ACP update to cached
164/// metadata. ACP updates replace only fields that are present, so a title
165/// update must not erase a summary selected from an earlier raw command.
166pub fn update_tool_call_presentation(
167    previous: Option<&ToolCallPresentation>,
168    title: &str,
169    kind: Option<ToolKind>,
170    raw_input: Option<&Value>,
171    raw_output: Option<&Value>,
172) -> ToolCallPresentation {
173    let next_kind = kind.unwrap_or_else(|| {
174        previous
175            .map(|presentation| presentation.tool_kind)
176            .unwrap_or_default()
177    });
178
179    if next_kind == ToolKind::Execute {
180        if let Some(source) = raw_input.and_then(|value| command_source(Some(value))) {
181            return presentation_from_source(
182                source,
183                ToolSummarySourceKind::RawInput,
184                next_kind,
185                title,
186            );
187        }
188        if let Some(source) = raw_output.and_then(|value| command_source(Some(value)))
189            && (raw_input.is_some()
190                || !previous.is_some_and(|previous| {
191                    previous.source_kind == ToolSummarySourceKind::RawInput
192                }))
193        {
194            return presentation_from_source(
195                source,
196                ToolSummarySourceKind::RawOutput,
197                next_kind,
198                title,
199            );
200        }
201        if let Some(previous) = previous
202            && previous.tool_kind == ToolKind::Execute
203            && ((raw_input.is_none() && previous.source_kind == ToolSummarySourceKind::RawInput)
204                || (raw_input.is_none()
205                    && raw_output.is_none()
206                    && previous.source_kind == ToolSummarySourceKind::RawOutput))
207        {
208            return ToolCallPresentation {
209                tool_kind: next_kind,
210                ..previous.clone()
211            };
212        }
213    }
214
215    presentation_from_title(title, next_kind)
216}
217
218fn command_source(raw: Option<&Value>) -> Option<ToolSummarySource> {
219    let command = raw?.get("command")?;
220    match command {
221        Value::String(command) if !command.trim().is_empty() => {
222            Some(ToolSummarySource::Shell(command.clone()))
223        }
224        Value::Array(argv) => {
225            let argv = argv.iter().map(Value::as_str).collect::<Option<Vec<_>>>()?;
226            let first = argv.first()?.trim();
227            if first.is_empty() {
228                return None;
229            }
230            if is_shell_interpreter(first)
231                && let Some(script) = shell_script_argument(&argv[1..])
232            {
233                return Some(ToolSummarySource::Shell(script.to_owned()));
234            }
235            Some(ToolSummarySource::Argv {
236                executable: first.to_owned(),
237                arguments: argv[1..]
238                    .iter()
239                    .map(|argument| (*argument).to_owned())
240                    .collect(),
241            })
242        }
243        _ => None,
244    }
245}
246
247fn is_shell_interpreter(value: &str) -> bool {
248    let executable = value.rsplit('/').next().unwrap_or(value);
249    matches!(executable, "sh" | "bash" | "dash" | "zsh")
250}
251
252fn shell_script_argument<'a>(arguments: &'a [&'a str]) -> Option<&'a str> {
253    let mut index = 0;
254    while index < arguments.len() {
255        let argument = arguments[index];
256        if argument == "--" {
257            return None;
258        }
259        if argument == "-c" || argument == "--command" {
260            return arguments.get(index + 1).copied();
261        }
262        if argument.starts_with('-') && !argument.starts_with("--") && argument[1..].contains('c') {
263            return arguments.get(index + 1).copied();
264        }
265        index += 1;
266    }
267    None
268}
269
270fn presentation_from_source(
271    source: ToolSummarySource,
272    source_kind: ToolSummarySourceKind,
273    tool_kind: ToolKind,
274    title: &str,
275) -> ToolCallPresentation {
276    let (source, summary) = match source {
277        ToolSummarySource::Shell(source) => {
278            let bounded = bound_summary_source(&source);
279            let summary = summarize_shell(&bounded)
280                .or_else(|| first_meaningful_token(title))
281                .unwrap_or_else(|| "tool".to_owned());
282            (bounded, summary)
283        }
284        ToolSummarySource::Argv {
285            executable,
286            arguments,
287        } => {
288            let source = std::iter::once(executable.as_str())
289                .chain(arguments.iter().map(String::as_str))
290                .collect::<Vec<_>>()
291                .join(" ");
292            let bounded = bound_summary_source(&source);
293            let summary = summarize_invocation(&executable, &arguments)
294                .or_else(|| first_meaningful_token(title))
295                .unwrap_or_else(|| "tool".to_owned());
296            (bounded, summary)
297        }
298    };
299    ToolCallPresentation {
300        summary,
301        source,
302        source_kind,
303        tool_kind,
304        summary_version: TOOL_SUMMARY_VERSION,
305    }
306}
307
308fn presentation_from_title(title: &str, tool_kind: ToolKind) -> ToolCallPresentation {
309    let source = title_source(title);
310    let bounded = bound_summary_source(&source);
311    let summary = if tool_kind == ToolKind::Execute {
312        summarize_shell(&bounded)
313            .or_else(|| first_meaningful_token(&bounded))
314            .unwrap_or_else(|| "tool".to_owned())
315    } else if bounded.trim_end().ends_with('?') {
316        // A question tool (Claude's AskUserQuestion) is titled with the
317        // question; its first word alone ("Which") says nothing.
318        bounded.trim().to_owned()
319    } else {
320        first_meaningful_token(&bounded).unwrap_or_else(|| "tool".to_owned())
321    };
322    ToolCallPresentation {
323        summary,
324        source: bounded,
325        source_kind: ToolSummarySourceKind::Title,
326        tool_kind,
327        summary_version: TOOL_SUMMARY_VERSION,
328    }
329}
330
331fn title_source(title: &str) -> String {
332    let title = title.trim();
333    let title = title
334        .strip_prefix("Running:")
335        .or_else(|| title.strip_prefix("Starting background:"))
336        .map(str::trim)
337        .unwrap_or(title);
338    if let Some(inner) = title
339        .strip_prefix("Execute `")
340        .and_then(|value| value.strip_suffix('`'))
341    {
342        return inner.to_owned();
343    }
344    title.to_owned()
345}
346
347fn first_meaningful_token(value: &str) -> Option<String> {
348    let token = value
349        .split_whitespace()
350        .next()?
351        .trim_matches(|character: char| {
352            !character.is_alphanumeric() && character != '/' && character != '.' && character != '_'
353        });
354    if token.is_empty() {
355        None
356    } else {
357        Some(token.trim_matches(['\'', '"', '`']).to_owned())
358    }
359}
360
361fn bound_summary_source(source: &str) -> String {
362    if source.len() <= TOOL_SUMMARY_SOURCE_BYTES {
363        return source.to_owned();
364    }
365    let mut end = TOOL_SUMMARY_SOURCE_BYTES;
366    while !source.is_char_boundary(end) {
367        end -= 1;
368    }
369    source[..end].to_owned()
370}
371
372fn summarize_shell(source: &str) -> Option<String> {
373    let mut parser = Parser::new();
374    parser
375        .set_language(&tree_sitter_bash::LANGUAGE.into())
376        .ok()?;
377    let tree = parser.parse(source, None)?;
378    let root = tree.root_node();
379    if root.has_error() {
380        return None;
381    }
382
383    let mut commands = Vec::new();
384    let mut operators = Vec::new();
385    let mut subshells = Vec::new();
386    if !collect_shell_tokens(root, source, &mut commands, &mut operators, &mut subshells) {
387        return None;
388    }
389    if commands.is_empty() {
390        return None;
391    }
392    commands.sort_by_key(|command| command.start);
393    operators.sort_by_key(|operator| operator.start);
394    subshells.sort_by_key(|subshell| subshell.start);
395
396    let mut tokens = Vec::new();
397    for (index, command) in commands.iter().enumerate() {
398        if index > 0 {
399            let previous = &commands[index - 1];
400            let separator = shell_separator_between(previous, command, &operators);
401            tokens.push(ShellToken {
402                start: separator.start,
403                text: separator.kind,
404                order: 1,
405            });
406        }
407        tokens.push(ShellToken {
408            start: command.start,
409            text: command.summary.clone(),
410            order: 2,
411        });
412    }
413
414    // Parentheses are meaningful only for subshells that contain a command we
415    // retained. Other punctuation, such as case arms and group delimiters,
416    // is structural and must not leak into the compact summary.
417    for subshell in subshells {
418        if !commands
419            .iter()
420            .any(|command| command.start >= subshell.start && command.end <= subshell.end)
421        {
422            continue;
423        }
424        let close = subshell.end.saturating_sub(1);
425        tokens.push(ShellToken {
426            start: subshell.start,
427            text: "(".to_owned(),
428            order: 0,
429        });
430        tokens.push(ShellToken {
431            start: close,
432            text: ")".to_owned(),
433            order: 3,
434        });
435    }
436
437    tokens.sort_by_key(|token| (token.start, token.order));
438    Some(join_shell_tokens(
439        tokens.into_iter().map(|token| token.text).collect(),
440    ))
441}
442
443#[derive(Debug, Clone)]
444struct ShellCommandToken {
445    start: usize,
446    end: usize,
447    summary: String,
448}
449
450#[derive(Debug, Clone)]
451struct ShellOperatorToken {
452    start: usize,
453    kind: String,
454}
455
456#[derive(Debug, Clone)]
457struct ShellSubshell {
458    start: usize,
459    end: usize,
460}
461
462#[derive(Debug, Clone)]
463struct ShellToken {
464    start: usize,
465    text: String,
466    order: u8,
467}
468
469fn collect_shell_tokens(
470    node: Node<'_>,
471    source: &str,
472    commands: &mut Vec<ShellCommandToken>,
473    operators: &mut Vec<ShellOperatorToken>,
474    subshells: &mut Vec<ShellSubshell>,
475) -> bool {
476    let kind = node.kind();
477    if matches!(kind, "command_substitution" | "process_substitution") {
478        return true;
479    }
480    if kind == "command" {
481        if let Some(summary) = summarize_command_node(node, source) {
482            commands.push(ShellCommandToken {
483                start: node.start_byte(),
484                end: node.end_byte(),
485                summary,
486            });
487            return true;
488        }
489        return false;
490    }
491    if is_shell_operator(node) {
492        operators.push(ShellOperatorToken {
493            start: node.start_byte(),
494            kind: kind.to_owned(),
495        });
496        return true;
497    }
498
499    if kind == "subshell" {
500        subshells.push(ShellSubshell {
501            start: node.start_byte(),
502            end: node.end_byte(),
503        });
504    }
505
506    let mut cursor = node.walk();
507    node.children(&mut cursor)
508        .all(|child| collect_shell_tokens(child, source, commands, operators, subshells))
509}
510
511fn shell_separator_between(
512    previous: &ShellCommandToken,
513    next: &ShellCommandToken,
514    operators: &[ShellOperatorToken],
515) -> ShellOperatorToken {
516    let mut candidates = operators
517        .iter()
518        .filter(|operator| operator.start >= previous.end && operator.start < next.start);
519    let structural = candidates.clone().find(|operator| operator.kind != ";");
520    if let Some(operator) = structural {
521        return operator.clone();
522    }
523    if let Some(operator) = candidates.find(|operator| operator.kind == ";") {
524        return operator.clone();
525    }
526    ShellOperatorToken {
527        start: previous.end,
528        kind: ";".to_owned(),
529    }
530}
531
532/// One argument of a parsed invocation. `value` is its text without matching
533/// quotes; `literal` is false when the text contains an expansion, so `value`
534/// is not what the program receives.
535#[derive(Debug, Clone)]
536struct InvocationArgument {
537    value: String,
538    literal: bool,
539}
540
541fn summarize_command_node(node: Node<'_>, source: &str) -> Option<String> {
542    let name = node.child_by_field_name("name")?;
543    let executable = shell_command_name(name, source)?;
544    let mut cursor = node.walk();
545    let arguments = node
546        .children_by_field_name("argument", &mut cursor)
547        .map(|argument| match shell_argument_value(argument, source) {
548            Some(value) => InvocationArgument {
549                value,
550                literal: true,
551            },
552            None => InvocationArgument {
553                value: strip_matching_quotes(source[argument.byte_range()].trim()).to_owned(),
554                literal: false,
555            },
556        })
557        .collect::<Vec<_>>();
558    summarize_invocation_with_literals(&executable, &arguments)
559}
560
561fn shell_command_name(node: Node<'_>, source: &str) -> Option<String> {
562    if contains_dynamic_shell_node(node) {
563        return None;
564    }
565    normalize_command_name(&source[node.byte_range()])
566}
567
568fn shell_argument_value(node: Node<'_>, source: &str) -> Option<String> {
569    if contains_dynamic_shell_node(node) {
570        return None;
571    }
572    let text = source[node.byte_range()].trim();
573    if text.is_empty() {
574        return None;
575    }
576    Some(strip_matching_quotes(text).to_owned())
577}
578
579fn contains_dynamic_shell_node(node: Node<'_>) -> bool {
580    if matches!(
581        node.kind(),
582        "expansion"
583            | "simple_expansion"
584            | "command_substitution"
585            | "process_substitution"
586            | "arithmetic_expansion"
587    ) {
588        return true;
589    }
590    let mut cursor = node.walk();
591    node.children(&mut cursor).any(contains_dynamic_shell_node)
592}
593
594fn summarize_invocation(executable: &str, arguments: &[String]) -> Option<String> {
595    summarize_invocation_with_literals(
596        executable,
597        &arguments
598            .iter()
599            .map(|value| InvocationArgument {
600                value: strip_matching_quotes(value).to_owned(),
601                literal: true,
602            })
603            .collect::<Vec<_>>(),
604    )
605}
606
607fn summarize_invocation_with_literals(
608    executable: &str,
609    arguments: &[InvocationArgument],
610) -> Option<String> {
611    let executable = normalize_command_name(executable)?;
612    let basename = executable
613        .rsplit(['/', '\\'])
614        .next()
615        .unwrap_or(&executable)
616        .to_owned();
617    if is_shell_interpreter(&basename) {
618        return Some(summarize_shell_invocation(&basename, arguments));
619    }
620    let mut words = vec![executable];
621    if !is_summary_executable(&basename) {
622        return Some(words.remove(0));
623    }
624    let mut index = 0;
625
626    if basename == "cargo"
627        && arguments.first().is_some_and(|argument| {
628            argument.literal && argument.value.starts_with('+') && argument.value.len() > 1
629        })
630    {
631        index += 1;
632    }
633
634    let first_verb = loop {
635        let Some(argument) = arguments.get(index) else {
636            return Some(words.remove(0));
637        };
638        if !argument.literal {
639            return Some(words.remove(0));
640        }
641        if argument.value == "--" || argument.value.starts_with('-') {
642            if let Some(consumed) = known_leading_option_arguments(&basename, arguments, index) {
643                index += consumed;
644                continue;
645            }
646            return Some(words.remove(0));
647        }
648        break argument.value.clone();
649    };
650    words.push(first_verb.clone());
651
652    if allows_second_verb(&basename, &first_verb) {
653        let first = index + 1;
654        if let Some(argument) = arguments.get(first)
655            && argument.literal
656            && !argument.value.starts_with('-')
657            && argument.value != "--"
658        {
659            words.push(argument.value.clone());
660        }
661    }
662    Some(words.join(" "))
663}
664
665/// A shell is named without its directory, and the script it runs with `-c`
666/// is summarized in its own right, so `/bin/bash -c "python x.py"` reads
667/// `bash -c python`. The script is parsed even when it contains an expansion,
668/// because only its command names matter here.
669fn summarize_shell_invocation(shell: &str, arguments: &[InvocationArgument]) -> String {
670    let values = arguments
671        .iter()
672        .map(|argument| argument.value.as_str())
673        .collect::<Vec<_>>();
674    let Some(script) = shell_script_argument(&values) else {
675        return shell.to_owned();
676    };
677    match summarize_shell(script) {
678        Some(inner) => format!("{shell} -c {inner}"),
679        None => format!("{shell} -c"),
680    }
681}
682
683fn is_summary_executable(basename: &str) -> bool {
684    matches!(
685        basename,
686        "git"
687            | "gh"
688            | "cargo"
689            | "rustup"
690            | "npm"
691            | "pnpm"
692            | "yarn"
693            | "bun"
694            | "uv"
695            | "pip"
696            | "pip3"
697            | "docker"
698            | "podman"
699            | "nice"
700    )
701}
702
703fn allows_second_verb(basename: &str, first_verb: &str) -> bool {
704    match basename {
705        "gh" => matches!(
706            first_verb,
707            "alias"
708                | "auth"
709                | "cache"
710                | "codespace"
711                | "config"
712                | "extension"
713                | "gist"
714                | "gpg-key"
715                | "issue"
716                | "label"
717                | "org"
718                | "pr"
719                | "project"
720                | "release"
721                | "repo"
722                | "ruleset"
723                | "run"
724                | "search"
725                | "secret"
726                | "ssh-key"
727                | "variable"
728                | "workflow"
729        ),
730        "docker" => matches!(
731            first_verb,
732            "buildx"
733                | "compose"
734                | "config"
735                | "context"
736                | "container"
737                | "image"
738                | "manifest"
739                | "network"
740                | "node"
741                | "plugin"
742                | "secret"
743                | "service"
744                | "stack"
745                | "swarm"
746                | "system"
747                | "trust"
748                | "volume"
749        ),
750        "podman" => matches!(
751            first_verb,
752            "artifact"
753                | "container"
754                | "farm"
755                | "generate"
756                | "image"
757                | "machine"
758                | "manifest"
759                | "network"
760                | "play"
761                | "pod"
762                | "secret"
763                | "system"
764                | "volume"
765        ),
766        "uv" => matches!(first_verb, "cache" | "pip" | "python" | "tool"),
767        "rustup" => matches!(
768            first_verb,
769            "component" | "override" | "target" | "toolchain"
770        ),
771        _ => false,
772    }
773}
774
775fn known_leading_option_arguments(
776    basename: &str,
777    arguments: &[InvocationArgument],
778    index: usize,
779) -> Option<usize> {
780    let option = arguments.get(index)?.value.as_str();
781    if option == "--" {
782        if basename == "nice" {
783            return Some(1);
784        }
785        return None;
786    }
787    let (option_name, attached_value) = option
788        .split_once('=')
789        .map_or((option, false), |(name, _)| (name, true));
790    if basename == "nice"
791        && option.starts_with('-')
792        && option.len() > 1
793        && option[1..].parse::<i32>().is_ok()
794    {
795        return Some(1);
796    }
797    if basename == "nice"
798        && option
799            .strip_prefix("-n")
800            .is_some_and(|value| !value.is_empty() && value.parse::<i32>().is_ok())
801    {
802        return Some(1);
803    }
804    let attached_short_value = match basename {
805        "git" => option.starts_with("-C") || option.starts_with("-c"),
806        "gh" => option.starts_with("-R"),
807        "docker" | "podman" => option.starts_with("-H"),
808        _ => false,
809    } && option.len() > 2;
810    let takes_value = match basename {
811        "git" => matches!(
812            option_name,
813            "-C" | "-c"
814                | "--config-env"
815                | "--exec-path"
816                | "--git-dir"
817                | "--namespace"
818                | "--super-prefix"
819                | "--work-tree"
820        ),
821        "gh" => matches!(
822            option_name,
823            "-R" | "--hostname" | "--repo" | "--jq" | "--template"
824        ),
825        "cargo" => matches!(
826            option_name,
827            "--manifest-path" | "--target-dir" | "--config" | "--color"
828        ),
829        "npm" | "pnpm" | "yarn" | "bun" => {
830            matches!(
831                option_name,
832                "--cwd" | "--dir" | "--prefix" | "--registry" | "--userconfig"
833            )
834        }
835        "uv" => matches!(option_name, "--directory" | "--project" | "--python"),
836        "rustup" => matches!(option_name, "--toolchain"),
837        "nice" => {
838            matches!(option_name, "-n" | "--adjustment")
839        }
840        "docker" | "podman" => matches!(
841            option_name,
842            "-H" | "--config" | "--connection" | "--context" | "--host" | "--log-level"
843        ),
844        _ => false,
845    };
846    if attached_short_value {
847        return Some(1);
848    }
849    if attached_value {
850        return takes_value.then_some(1);
851    }
852    if takes_value {
853        return arguments
854            .get(index + 1)
855            .filter(|argument| argument.literal)
856            .map(|_| 2);
857    }
858    let known_flag = match basename {
859        "git" => matches!(
860            option_name,
861            "-p" | "--paginate"
862                | "-P"
863                | "--no-pager"
864                | "--bare"
865                | "--literal-pathspecs"
866                | "--glob-pathspecs"
867                | "--noglob-pathspecs"
868                | "--icase-pathspecs"
869                | "--no-optional-locks"
870                | "--no-advice"
871        ),
872        "gh" => false,
873        "cargo" => matches!(
874            option_name,
875            "-q" | "--quiet" | "-v" | "--verbose" | "--locked" | "--offline" | "--frozen"
876        ),
877        "npm" | "pnpm" | "yarn" | "bun" => {
878            matches!(option_name, "-g" | "--global" | "--silent")
879        }
880        "uv" => matches!(
881            option_name,
882            "-q" | "--quiet" | "-v" | "--verbose" | "--offline"
883        ),
884        "rustup" => matches!(option_name, "-q" | "--quiet" | "-v" | "--verbose"),
885        "docker" | "podman" => matches!(option_name, "-D" | "--debug" | "--tls"),
886        "nice" => false,
887        _ => false,
888    };
889    known_flag.then_some(1)
890}
891
892fn strip_matching_quotes(value: &str) -> &str {
893    value
894        .strip_prefix('"')
895        .and_then(|value| value.strip_suffix('"'))
896        .or_else(|| {
897            value
898                .strip_prefix('\'')
899                .and_then(|value| value.strip_suffix('\''))
900        })
901        .unwrap_or(value)
902}
903
904fn is_shell_operator(node: Node<'_>) -> bool {
905    match node.kind() {
906        ";" => true,
907        "&&" | "||" => node.parent().is_some_and(|parent| parent.kind() == "list"),
908        "|" | "|&" => node
909            .parent()
910            .is_some_and(|parent| parent.kind() == "pipeline"),
911        "&" => node.parent().is_none_or(|parent| {
912            !matches!(
913                parent.kind(),
914                "binary_expression" | "unary_expression" | "postfix_expression"
915            )
916        }),
917        _ => false,
918    }
919}
920
921fn normalize_command_name(text: &str) -> Option<String> {
922    let text = text.trim();
923    if text.contains('$') || text.contains('`') {
924        return None;
925    }
926    let text = text
927        .strip_prefix('"')
928        .and_then(|value| value.strip_suffix('"'))
929        .or_else(|| {
930            text.strip_prefix('\'')
931                .and_then(|value| value.strip_suffix('\''))
932        })
933        .unwrap_or(text);
934    (!text.is_empty()).then(|| text.to_owned())
935}
936
937fn join_shell_tokens(tokens: Vec<String>) -> String {
938    let mut output = String::new();
939    for token in tokens {
940        match token.as_str() {
941            "(" => {
942                if !output.is_empty() && !output.ends_with(' ') {
943                    output.push(' ');
944                }
945                output.push('(');
946            }
947            ")" => {
948                output = output.trim_end().to_owned();
949                output.push(')');
950            }
951            _ => {
952                if !output.is_empty() && !output.ends_with(' ') && !output.ends_with('(') {
953                    output.push(' ');
954                }
955                output.push_str(&token);
956            }
957        }
958    }
959    output
960}
961
962/// Read string arguments as text, including their real line breaks. Other
963/// values keep their JSON structure; the renderer wraps rather than clips it.
964pub fn tool_input_text(input: &Value) -> String {
965    fn value_text(value: &Value) -> String {
966        match value {
967            Value::String(text) => text.clone(),
968            _ => serde_json::to_string_pretty(value)
969                .expect("tool arguments are serializable JSON values"),
970        }
971    }
972
973    let text = match input {
974        Value::Object(fields) if !fields.is_empty() => fields
975            .iter()
976            .map(|(name, value)| format!("{name}:\n{}", value_text(value)))
977            .collect::<Vec<_>>()
978            .join("\n\n"),
979        _ => value_text(input),
980    };
981    sanitize_terminal_text(&text)
982}
983
984pub fn tool_content_details(
985    content: &[ToolCallContent],
986    terminal_outputs: &[TerminalOutputRecord],
987    raw_output: Option<&serde_json::Value>,
988) -> Vec<String> {
989    let mut details = Vec::new();
990    let mut referenced: Vec<&str> = Vec::new();
991    for item in content {
992        let detail = match item {
993            ToolCallContent::Content(content) => content_block_text(&content.content),
994            ToolCallContent::Diff(_) => None,
995            // Kimi-style agents send a terminal reference and no textual copy
996            // of the output, so the record hel captured is the only thing a
997            // reader ever sees. Until the terminal is reaped there is none.
998            ToolCallContent::Terminal(terminal) => {
999                let terminal_id = terminal.terminal_id.0.as_ref();
1000                referenced.push(terminal_id);
1001                Some(
1002                    terminal_outputs
1003                        .iter()
1004                        .find(|record| record.terminal_id.as_str() == terminal_id)
1005                        .map(terminal_output_detail)
1006                        .or_else(|| raw_output.and_then(raw_output_terminal_detail))
1007                        .unwrap_or_else(|| format!("terminal {}", terminal.terminal_id)),
1008                )
1009            }
1010            _ => None,
1011        };
1012        if let Some(detail) = detail {
1013            details.push(sanitize_terminal_text(&detail));
1014        }
1015    }
1016    // Grok-style agents name the terminal on a mid-flight update and then
1017    // replace `content` wholesale without it, so the output hel captured has
1018    // nothing in the final call pointing at it. Show it rather than lose it.
1019    for record in terminal_outputs {
1020        if referenced.contains(&record.terminal_id.as_str()) {
1021            continue;
1022        }
1023        let output = sanitize_terminal_text(&record.output);
1024        if !output.is_empty() && details.iter().any(|detail| detail == &output) {
1025            // Kimi sends the captured stdout as ordinary tool content and in
1026            // its raw result. Keep the exit summary without printing those
1027            // same bytes a second time in Raw mode.
1028            details.push(terminal_exit_summary(record));
1029        } else {
1030            details.push(sanitize_terminal_text(&terminal_output_detail(record)));
1031        }
1032    }
1033    details
1034}
1035
1036/// The output codex reports for a terminal it ran itself. Codex names its own
1037/// server-side terminal, which hel never opened and has no record for, and
1038/// puts the text in `rawOutput`; reading it here keeps such a call from
1039/// rendering as a bare terminal id.
1040fn raw_output_terminal_detail(raw_output: &serde_json::Value) -> Option<String> {
1041    let output = raw_output.get("formatted_output")?.as_str()?;
1042    let Some(exit_code) = raw_output
1043        .get("exit_code")
1044        .and_then(serde_json::Value::as_i64)
1045    else {
1046        return Some(output.to_owned());
1047    };
1048    let summary = format!("exited {exit_code}");
1049    if output.is_empty() {
1050        return Some(summary);
1051    }
1052    Some(format!("{output}\n{summary}"))
1053}
1054
1055/// One terminal's output followed by how it ended.
1056pub fn terminal_output_detail(record: &TerminalOutputRecord) -> String {
1057    let summary = terminal_exit_summary(record);
1058    if record.output.is_empty() {
1059        return summary;
1060    }
1061    format!("{}\n{summary}", record.output)
1062}
1063
1064/// How a terminal ended, in one line.
1065fn terminal_exit_summary(record: &TerminalOutputRecord) -> String {
1066    let mut summary = match (record.exit_code, &record.signal) {
1067        (_, Some(signal)) => format!("killed by {signal}"),
1068        (Some(code), None) => format!("exited {code}"),
1069        (None, None) => "released before exit".to_owned(),
1070    };
1071    if record.truncated {
1072        summary.push_str(" · output truncated");
1073    }
1074    summary
1075}
1076
1077pub fn tool_diff_paths(content: &[ToolCallContent]) -> Vec<String> {
1078    content
1079        .iter()
1080        .filter_map(|item| match item {
1081            ToolCallContent::Diff(diff) => Some(diff.path.display().to_string()),
1082            _ => None,
1083        })
1084        .collect()
1085}
1086
1087pub fn tool_location_details(locations: &[ToolCallLocation]) -> Vec<String> {
1088    locations
1089        .iter()
1090        .map(|location| match location.line {
1091            Some(line) => format!("{}:{line}", location.path.display()),
1092            None => location.path.display().to_string(),
1093        })
1094        .collect()
1095}
1096
1097/// Append streamed agent or thought text to the transcript, merging it into
1098/// the entry it continues so a message arrives as one entry rather than one
1099/// per chunk.
1100pub(crate) fn push_streamed_entry(
1101    entries: &mut Vec<ChatEntry>,
1102    seq: u64,
1103    recorded_at_ms: Option<i64>,
1104    role: ChatRole,
1105    message_id: Option<String>,
1106    text: &str,
1107) {
1108    let text = sanitize_terminal_text(text);
1109    if let Some(last) = entries.last_mut()
1110        && last.role == role
1111        && (role == ChatRole::Thought || last.message_id == message_id)
1112    {
1113        last.touch(seq);
1114        if role == ChatRole::Thought
1115            && last.message_id != message_id
1116            && !last.text.is_empty()
1117            && !text.is_empty()
1118        {
1119            while last.text.ends_with('\n') {
1120                last.text.pop();
1121            }
1122            last.text.push('\n');
1123            last.text.push_str(text.trim_start_matches('\n'));
1124        } else {
1125            last.text.push_str(&text);
1126        }
1127        return;
1128    }
1129    let mut entry = ChatEntry::plain(seq, role, text).with_recorded_at(recorded_at_ms);
1130    entry.message_id = message_id;
1131    entries.push(entry);
1132}
1133
1134/// Apply the transcript-visible part of one ACP session update. Returns the
1135/// update again when it changes the session surface rather than the
1136/// transcript, so the chat view handles those without decoding twice.
1137pub fn apply_session_update_to_entries(
1138    entries: &mut Vec<ChatEntry>,
1139    seq: u64,
1140    recorded_at_ms: Option<i64>,
1141    update: SessionUpdate,
1142) -> Option<SessionUpdate> {
1143    match update {
1144        SessionUpdate::AgentMessageChunk(chunk) => {
1145            let message_id = chunk.message_id.map(|id| id.to_string());
1146            if let Some(text) = content_block_text(&chunk.content) {
1147                push_streamed_entry(
1148                    entries,
1149                    seq,
1150                    recorded_at_ms,
1151                    ChatRole::Agent,
1152                    message_id,
1153                    &text,
1154                );
1155            }
1156        }
1157        SessionUpdate::AgentThoughtChunk(chunk) => {
1158            let message_id = chunk.message_id.map(|id| id.to_string());
1159            if let Some(text) = content_block_text(&chunk.content) {
1160                push_streamed_entry(
1161                    entries,
1162                    seq,
1163                    recorded_at_ms,
1164                    ChatRole::Thought,
1165                    message_id,
1166                    &text,
1167                );
1168            }
1169        }
1170        // PromptAccepted is the canonical local user-message event. ACP
1171        // user chunks would duplicate it during replay.
1172        SessionUpdate::UserMessageChunk(_) => {}
1173        SessionUpdate::ToolCall(call) => {
1174            let presentation = tool_call_presentation(&call);
1175            let mut entry = ChatEntry::tool(
1176                seq,
1177                call.title,
1178                Some(call.tool_call_id.to_string()),
1179                tool_status(&call.status),
1180            );
1181            entry.tool_summary = Some(presentation.summary.clone());
1182            entry.tool_presentation = Some(presentation);
1183            entry.tool_input = call.raw_input;
1184            entry.tool_content = tool_content_details(&call.content, &[], call.raw_output.as_ref());
1185            entry.tool_diffstats = tool_diff_paths(&call.content);
1186            entry.tool_locations = tool_location_details(&call.locations);
1187            entries.push(entry);
1188        }
1189        SessionUpdate::ToolCallUpdate(update) => {
1190            let tool_call_id = update.tool_call_id.to_string();
1191            let entry = entries.iter_mut().rev().find(|entry| {
1192                entry.role == ChatRole::Tool
1193                    && entry.tool_call_id.as_deref() == Some(tool_call_id.as_str())
1194            })?;
1195            entry.touch(seq);
1196            let kind = update.fields.kind;
1197            let raw_input = update.fields.raw_input.clone();
1198            let raw_output = update.fields.raw_output.clone();
1199            if let Some(input) = &raw_input {
1200                entry.tool_input = Some(input.clone());
1201            }
1202            if let Some(title) = update.fields.title {
1203                entry.text = sanitize_terminal_text(&title);
1204            }
1205            if let Some(status) = update.fields.status {
1206                entry.tool_status = Some(tool_status(&status));
1207            }
1208            if let Some(content) = update.fields.content {
1209                entry.tool_content =
1210                    tool_content_details(&content, &[], update.fields.raw_output.as_ref());
1211                entry.tool_diffstats = tool_diff_paths(&content);
1212            }
1213            if let Some(locations) = update.fields.locations {
1214                entry.tool_locations = tool_location_details(&locations);
1215            }
1216            let presentation = update_tool_call_presentation(
1217                entry.tool_presentation.as_ref(),
1218                &entry.text,
1219                kind,
1220                raw_input.as_ref(),
1221                raw_output.as_ref(),
1222            );
1223            entry.tool_summary = Some(presentation.summary.clone());
1224            entry.tool_presentation = Some(presentation);
1225        }
1226        SessionUpdate::Plan(plan) => {
1227            let lines = plan
1228                .entries
1229                .into_iter()
1230                .map(|entry| PlanLine {
1231                    text: sanitize_terminal_text(&entry.content),
1232                    status: plan_status(&entry.status),
1233                })
1234                .collect();
1235            let latest_user_seq = entries
1236                .iter()
1237                .rev()
1238                .find(|entry| entry.role == ChatRole::User)
1239                .map_or(0, |entry| entry.seq);
1240            if let Some(entry) = entries
1241                .iter_mut()
1242                .rev()
1243                .find(|entry| entry.role == ChatRole::Plan && entry.seq > latest_user_seq)
1244            {
1245                entry.touch(seq);
1246                entry.plan = lines;
1247            } else {
1248                entries.push(ChatEntry::plan(seq, lines));
1249            }
1250        }
1251        other => return Some(other),
1252    }
1253    None
1254}
1255
1256/// Apply the transcript-visible part of one persisted runtime event. Returns
1257/// the event again when it only configures the session surface, which is the
1258/// chat view's business rather than the transcript's.
1259pub fn apply_runtime_event_to_entries(
1260    entries: &mut Vec<ChatEntry>,
1261    seq: u64,
1262    recorded_at_ms: Option<i64>,
1263    runtime: RuntimeEvent,
1264) -> Option<RuntimeEvent> {
1265    match runtime {
1266        RuntimeEvent::SessionUpdate { update } => {
1267            let parsed = match serde_json::from_value::<SessionUpdate>(update.clone()) {
1268                Ok(parsed) => parsed,
1269                Err(error) => {
1270                    tracing::debug!(%error, "ignoring invalid ACP session update");
1271                    return None;
1272                }
1273            };
1274            apply_session_update_to_entries(entries, seq, recorded_at_ms, parsed)
1275                .map(|_| RuntimeEvent::SessionUpdate { update })
1276        }
1277        RuntimeEvent::Warning { message } | RuntimeEvent::SessionFault { message } => {
1278            entries.push(ChatEntry::plain(
1279                seq,
1280                ChatRole::System,
1281                format!("warning: {message}"),
1282            ));
1283            None
1284        }
1285        RuntimeEvent::ConfigApplied { key, value, .. } => {
1286            entries.push(ChatEntry::plain(
1287                seq,
1288                ChatRole::System,
1289                format!("{key} set to {value}"),
1290            ));
1291            None
1292        }
1293        RuntimeEvent::SessionStarted { resumed: false, .. } => {
1294            entries.push(ChatEntry::plain(
1295                seq,
1296                ChatRole::System,
1297                "harness session started",
1298            ));
1299            None
1300        }
1301        RuntimeEvent::SessionStarted { resumed: true, .. } => None,
1302        RuntimeEvent::ElicitationResolved {
1303            reply: Some(reply), ..
1304        } => {
1305            let mut entry =
1306                ChatEntry::plain(seq, ChatRole::User, reply).with_recorded_at(recorded_at_ms);
1307            entry.message_id = Some(format!("{ELICITATION_REPLY_ITEM_PREFIX}{seq}"));
1308            entries.push(entry);
1309            None
1310        }
1311        other => Some(other),
1312    }
1313}
1314
1315/// One transcript item flattened to the text a reader would see.
1316///
1317/// A caller that wants the structure reads the body itself; this is the plain
1318/// reading, built from the same flatteners every other surface uses so that a
1319/// tool call reads as the command it ran rather than as JSON.
1320pub fn transcript_item_text(item: &TranscriptItem) -> String {
1321    match &item.body {
1322        TranscriptBody::User { content } => materialized_content_text(content),
1323        TranscriptBody::Agent { chunks, .. } | TranscriptBody::Thought { chunks, .. } => {
1324            materialized_chunks_text(chunks)
1325        }
1326        TranscriptBody::Tool {
1327            call,
1328            terminal_outputs,
1329            presentation,
1330            ..
1331        } => {
1332            let Ok(call) = ToolCall::deserialize(call) else {
1333                return "[invalid tool call]".to_owned();
1334            };
1335            let mut text = materialized_tool_call_presentation(presentation.as_deref(), &call)
1336                .summary
1337                .clone();
1338            if text.trim().is_empty() {
1339                text = call.title.clone();
1340            }
1341            for record in terminal_outputs {
1342                text.push('\n');
1343                text.push_str(&terminal_output_detail(record));
1344            }
1345            sanitize_terminal_text(&text)
1346        }
1347        TranscriptBody::TerminalOutput { record } => {
1348            sanitize_terminal_text(&terminal_output_detail(record))
1349        }
1350        TranscriptBody::Plan { plan } => {
1351            let Ok(plan) = agent_client_protocol::schema::v1::Plan::deserialize(plan) else {
1352                return String::new();
1353            };
1354            plan.entries
1355                .iter()
1356                .map(|entry| {
1357                    let status = match plan_status(&entry.status) {
1358                        PlanStatus::Pending => "pending",
1359                        PlanStatus::Running => "running",
1360                        PlanStatus::Completed => "completed",
1361                    };
1362                    format!("[{status}] {}", sanitize_terminal_text(&entry.content))
1363                })
1364                .collect::<Vec<_>>()
1365                .join("\n")
1366        }
1367        TranscriptBody::PlanProposal { plan, .. } => plan.clone(),
1368        TranscriptBody::System { text } => text.clone(),
1369    }
1370}
1371
1372pub(crate) fn compute_tool_diffstats(content: &[ToolCallContent]) -> Vec<String> {
1373    content
1374        .iter()
1375        .filter_map(|item| match item {
1376            ToolCallContent::Diff(diff) => Some(format_diffstat(diff)),
1377            _ => None,
1378        })
1379        .collect()
1380}
1381
1382pub fn materialized_tool_diffstats(item: &TranscriptItem) -> Option<Vec<String>> {
1383    let TranscriptBody::Tool { call, .. } = &item.body else {
1384        return None;
1385    };
1386    let call = match ToolCall::deserialize(call) {
1387        Ok(call) => call,
1388        Err(error) => {
1389            tracing::warn!(
1390                stable_id = %item.stable_id,
1391                %error,
1392                "could not decode a stored tool call while reading diff summary"
1393            );
1394            return None;
1395        }
1396    };
1397    if !matches!(
1398        tool_status(&call.status),
1399        ToolStatus::Completed | ToolStatus::Failed
1400    ) {
1401        return None;
1402    }
1403    let diffstats = compute_tool_diffstats(&call.content);
1404    (!diffstats.is_empty()).then_some(diffstats)
1405}
1406
1407fn format_diffstat(diff: &agent_client_protocol::schema::v1::Diff) -> String {
1408    // A diff recorded since `diff` landed already carries its counts, so
1409    // this is a lookup. An older record still holds both file copies and is
1410    // diffed here on demand.
1411    let patch = mj_core::diff::patch_of(diff);
1412    format!(
1413        "{}  +{} −{}",
1414        diff.path.display(),
1415        patch.insertions,
1416        patch.deletions
1417    )
1418}
1419
1420#[cfg(test)]
1421mod tests {
1422    use super::*;
1423    use agent_client_protocol::schema::v1::{ToolCall, ToolCallStatus};
1424    use serde_json::json;
1425
1426    /// I1-18: Claude's question tool is titled with the question itself. Its
1427    /// row showed only "Which"; it must show the whole question.
1428    // Hard-won: e570799ccc: a question-tool row displayed only its first word.
1429    #[test]
1430    fn a_question_tool_is_summarized_by_its_whole_question() {
1431        let call = ToolCall::new("ask", "Which file name should I use for the new file?")
1432            .raw_input(json!({"questions": [{"question": "Which file name should I use for the new file?", "header": "File name"}]}));
1433        assert_eq!(
1434            tool_call_presentation(&call).summary,
1435            "Which file name should I use for the new file?"
1436        );
1437        let read = ToolCall::new("read", "Read src/lib.rs");
1438        assert_eq!(tool_call_presentation(&read).summary, "Read");
1439        let stale = ToolCallPresentation {
1440            summary: "Which".into(),
1441            source: call.title.clone(),
1442            source_kind: ToolSummarySourceKind::Title,
1443            tool_kind: ToolKind::Other,
1444            summary_version: 1,
1445        };
1446        assert_eq!(
1447            materialized_tool_call_presentation(Some(&stale), &call).summary,
1448            "Which file name should I use for the new file?",
1449            "stored rows written by the old rules are repaired"
1450        );
1451    }
1452
1453    fn execute_summary(command: serde_json::Value) -> String {
1454        let call = ToolCall::new("argv", "Bash")
1455            .kind(ToolKind::Execute)
1456            .raw_input(command);
1457        tool_call_presentation(&call).summary
1458    }
1459
1460    #[test]
1461    fn unknown_leading_options_make_verb_position_ambiguous() {
1462        assert_eq!(
1463            execute_summary(json!({"command": ["git", "--mystery", "status"]})),
1464            "git"
1465        );
1466        assert_eq!(
1467            execute_summary(json!({"command": ["cargo", "--mystery", "test"]})),
1468            "cargo"
1469        );
1470    }
1471
1472    #[test]
1473    fn a_nested_shell_is_named_without_its_path_and_shows_its_script() {
1474        let cases = [
1475            ("bash -c 'python x.py'", "bash -c python"),
1476            ("/bin/bash -c \"python x.py\"", "bash -c python"),
1477            (
1478                "/usr/bin/zsh -lc 'git status && cargo test'",
1479                "zsh -c git status && cargo test",
1480            ),
1481            ("bash -c \"cd $dir && make\"", "bash -c cd && make"),
1482            ("bash -c \"$script\"", "bash -c"),
1483            ("/bin/bash script.sh", "bash"),
1484            (
1485                "bash -c 'bash -c \"uv run pytest\"'",
1486                "bash -c bash -c uv run",
1487            ),
1488        ];
1489        for (command, summary) in cases {
1490            assert_eq!(
1491                execute_summary(json!({"command": command})),
1492                summary,
1493                "{command}"
1494            );
1495        }
1496        // An argv shell call already stands for its script.
1497        assert_eq!(
1498            execute_summary(json!({"command": ["/bin/bash", "-lc", "python x.py"]})),
1499            "python"
1500        );
1501        assert_eq!(
1502            execute_summary(json!({"command": ["/bin/zsh", "script.sh"]})),
1503            "zsh"
1504        );
1505    }
1506
1507    #[test]
1508    fn quoted_and_dynamic_shell_verbs_are_distinguished() {
1509        let quoted = ToolCall::new("quoted", "Bash")
1510            .kind(ToolKind::Execute)
1511            .raw_input(json!({"command": "git \"status\""}));
1512        assert_eq!(tool_call_presentation(&quoted).summary, "git status");
1513
1514        let dynamic = ToolCall::new("dynamic", "Bash")
1515            .kind(ToolKind::Execute)
1516            .raw_input(json!({"command": "git \"$verb\""}));
1517        assert_eq!(tool_call_presentation(&dynamic).summary, "git");
1518
1519        let dynamic_name = ToolCall::new("dynamic-name", "Bash")
1520            .kind(ToolKind::Execute)
1521            .raw_input(json!({"command": "$command status"}));
1522        assert_eq!(tool_call_presentation(&dynamic_name).summary, "Bash");
1523    }
1524
1525    #[test]
1526    fn shell_summary_skips_assignments_arguments_and_nested_substitutions() {
1527        let call = ToolCall::new("call", "Bash")
1528            .kind(ToolKind::Execute)
1529            .raw_input(json!({
1530                "command": "FOO=bar env -i bash -c \"echo $(printf hi)\""
1531            }));
1532        assert_eq!(tool_call_presentation(&call).summary, "env");
1533
1534        let subshell = ToolCall::new("subshell", "Bash")
1535            .kind(ToolKind::Execute)
1536            .raw_input(json!({
1537                "command": "(cd dir && python x.py) | cat"
1538            }));
1539        assert_eq!(
1540            tool_call_presentation(&subshell).summary,
1541            "(cd && python) | cat"
1542        );
1543    }
1544
1545    #[test]
1546    fn shell_summary_keeps_list_pipeline_and_background_operators() {
1547        let simple = ToolCall::new("call-1", "Bash")
1548            .kind(ToolKind::Execute)
1549            .raw_input(json!({
1550                "command": "cd dir && python x.py | cat | wc ; print ok"
1551            }));
1552        let presentation = tool_call_presentation(&simple);
1553        assert_eq!(presentation.summary, "cd && python | cat | wc ; print");
1554        assert_eq!(presentation.source_kind, ToolSummarySourceKind::RawInput);
1555
1556        let call = ToolCall::new("operators", "Bash")
1557            .kind(ToolKind::Execute)
1558            .raw_input(json!({
1559                "command": "'printf' '%s' hi >out |& sed s/hi/bye/ || echo failed & wait; cat <in"
1560            }));
1561
1562        assert_eq!(
1563            tool_call_presentation(&call).summary,
1564            "printf |& sed || echo & wait ; cat"
1565        );
1566    }
1567
1568    #[test]
1569    fn shell_summary_removes_structural_loop_and_group_separators() {
1570        let call = ToolCall::new("compound", "Bash")
1571            .kind(ToolKind::Execute)
1572            .raw_input(json!({
1573                "command": "for file in a b; do rm \"$file\"; done; mkdir -p out; nice -n 10 python3 script.py"
1574            }));
1575
1576        assert_eq!(
1577            tool_call_presentation(&call).summary,
1578            "rm ; mkdir ; nice python3"
1579        );
1580
1581        let conditional = ToolCall::new("conditional", "Bash")
1582            .kind(ToolKind::Execute)
1583            .raw_input(json!({
1584                "command": "if test -f foo; then rm foo; fi; { mkdir bar; echo done; }"
1585            }));
1586        assert_eq!(
1587            tool_call_presentation(&conditional).summary,
1588            "test ; rm ; mkdir ; echo"
1589        );
1590
1591        let case_statement = ToolCall::new("case", "Bash")
1592            .kind(ToolKind::Execute)
1593            .raw_input(json!({
1594                "command": "echo start; case x in a|b) echo branch;; esac; echo done"
1595            }));
1596        assert_eq!(
1597            tool_call_presentation(&case_statement).summary,
1598            "echo ; echo ; echo"
1599        );
1600    }
1601
1602    #[test]
1603    fn shell_summary_handles_a_loop_with_a_leading_pipeline_and_nice() {
1604        let call = ToolCall::new("live-loop-shape", "Bash")
1605            .kind(ToolKind::Execute)
1606            .raw_input(json!({
1607                "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"
1608            }));
1609
1610        assert_eq!(
1611            tool_call_presentation(&call).summary,
1612            "cd && set ; rm ; mkdir ; nice ./bin/bifrost ; echo ; python3"
1613        );
1614    }
1615
1616    #[test]
1617    fn shell_summary_inserts_a_separator_after_a_heredoc() {
1618        let call = ToolCall::new("heredoc", "Bash")
1619            .kind(ToolKind::Execute)
1620            .raw_input(json!({
1621                "command": "python3 <<'PYEOF'\nprint(\"x\")\nPYEOF\ngrep -n x file | head"
1622            }));
1623
1624        assert_eq!(
1625            tool_call_presentation(&call).summary,
1626            "python3 ; grep | head"
1627        );
1628    }
1629
1630    #[test]
1631    fn materialized_summary_from_an_older_parser_is_repaired() {
1632        let source = "python3 <<'PYEOF'\nprint(\"x\")\nPYEOF\ngrep -n x file | head";
1633        let call = ToolCall::new("heredoc", "Bash")
1634            .kind(ToolKind::Execute)
1635            .raw_input(json!({ "command": source }));
1636        let stale = ToolCallPresentation {
1637            summary: "python3 grep | head".into(),
1638            source: source.into(),
1639            source_kind: ToolSummarySourceKind::RawInput,
1640            tool_kind: ToolKind::Execute,
1641            summary_version: 0,
1642        };
1643
1644        let repaired = materialized_tool_call_presentation(Some(&stale), &call);
1645        assert_eq!(repaired.summary, "python3 ; grep | head");
1646        assert_eq!(repaired.summary_version, TOOL_SUMMARY_VERSION);
1647
1648        let mut current = repaired;
1649        current.summary = "stored current summary".into();
1650        assert_eq!(
1651            materialized_tool_call_presentation(Some(&current), &call).summary,
1652            "stored current summary"
1653        );
1654    }
1655
1656    #[test]
1657    fn execute_summary_bounds_the_retained_source_before_parsing() {
1658        let command = format!("echo {}", "argument".repeat(TOOL_SUMMARY_SOURCE_BYTES));
1659        let call = ToolCall::new("bounded", "Bash")
1660            .kind(ToolKind::Execute)
1661            .raw_input(json!({ "command": command }));
1662
1663        let presentation = tool_call_presentation(&call);
1664        assert_eq!(presentation.source.len(), TOOL_SUMMARY_SOURCE_BYTES);
1665        assert_eq!(presentation.summary, "echo");
1666    }
1667
1668    #[test]
1669    fn title_wrappers_and_malformed_shell_fall_back_safely() {
1670        let wrapped = ToolCall::new("wrapped", "Running: ls -la").kind(ToolKind::Execute);
1671        assert_eq!(tool_call_presentation(&wrapped).summary, "ls");
1672
1673        let malformed = ToolCall::new("bad", "Bash")
1674            .kind(ToolKind::Execute)
1675            .raw_input(json!({"command": "cd && ("}));
1676        assert_eq!(tool_call_presentation(&malformed).summary, "Bash");
1677    }
1678
1679    #[test]
1680    fn explicit_empty_raw_input_drops_a_stale_raw_summary() {
1681        let initial = ToolCall::new("call", "Bash")
1682            .kind(ToolKind::Execute)
1683            .raw_input(json!({"command": "python script.py"}));
1684        let previous = tool_call_presentation(&initial);
1685        let empty_input = json!({"command": null});
1686        let updated = update_tool_call_presentation(
1687            Some(&previous),
1688            "Running: ls -la",
1689            None,
1690            Some(&empty_input),
1691            None,
1692        );
1693        assert_eq!(updated.summary, "ls");
1694        assert_eq!(updated.source_kind, ToolSummarySourceKind::Title);
1695
1696        let output = json!({"command": "cat result.txt"});
1697        let updated = update_tool_call_presentation(
1698            Some(&previous),
1699            "Running: ls -la",
1700            None,
1701            Some(&empty_input),
1702            Some(&output),
1703        );
1704        assert_eq!(updated.summary, "cat");
1705        assert_eq!(updated.source_kind, ToolSummarySourceKind::RawOutput);
1706
1707        let output_initial = ToolCall::new("output", "Bash")
1708            .kind(ToolKind::Execute)
1709            .raw_output(json!({"command": "python result.py"}));
1710        let output_previous = tool_call_presentation(&output_initial);
1711        let empty_output = json!({"command": null});
1712        let updated = update_tool_call_presentation(
1713            Some(&output_previous),
1714            "Running: ls -la",
1715            None,
1716            None,
1717            Some(&empty_output),
1718        );
1719        assert_eq!(updated.summary, "ls");
1720        assert_eq!(updated.source_kind, ToolSummarySourceKind::Title);
1721    }
1722
1723    fn rendered_tool_row(call: &ToolCall) -> String {
1724        let presentation = tool_call_presentation(call);
1725        let item = TranscriptItem {
1726            stable_id: "tool:golden".into(),
1727            position: 1,
1728            latest_content_event_ordinal: None,
1729            created_at_ms: 1,
1730            last_changed_at_ms: 1,
1731            body: TranscriptBody::Tool {
1732                call: serde_json::to_value(call).expect("serialize tool call"),
1733                terminal_outputs: Vec::new(),
1734                terminal_refs: Vec::new(),
1735                presentation: Some(Box::new(presentation)),
1736            },
1737        };
1738        transcript_item_text(&item)
1739    }
1740
1741    fn append_tool_row(output: &mut String, label: &str, call: &ToolCall) {
1742        use std::fmt::Write as _;
1743        if !output.is_empty() {
1744            output.push('\n');
1745        }
1746        writeln!(output, "=== {label} (transcript row) ===").unwrap();
1747        output.push_str(&rendered_tool_row(call));
1748        output.push('\n');
1749    }
1750
1751    #[test]
1752    fn golden_transcript_tool_row_summary() {
1753        use std::fmt::Write as _;
1754
1755        let mut output = String::new();
1756        let diff = agent_client_protocol::schema::v1::Diff::new("/workspace/new.txt", "one\ntwo\n");
1757        writeln!(output, "=== new file diff detail (transcript row) ===").unwrap();
1758        writeln!(output, "{}", format_diffstat(&diff)).unwrap();
1759
1760        let terminal = |exit_code, signal: Option<&str>, truncated, text: &str| {
1761            let record = TerminalOutputRecord {
1762                terminal_id: "term-1".into(),
1763                output: text.into(),
1764                truncated,
1765                exit_code,
1766                signal: signal.map(str::to_owned),
1767            };
1768            let item = TranscriptItem {
1769                stable_id: "terminal:golden".into(),
1770                position: 1,
1771                latest_content_event_ordinal: None,
1772                created_at_ms: 1,
1773                last_changed_at_ms: 1,
1774                body: TranscriptBody::TerminalOutput { record },
1775            };
1776            transcript_item_text(&item)
1777        };
1778        for (label, row) in [
1779            ("successful terminal", terminal(Some(0), None, false, "out")),
1780            ("truncated terminal", terminal(Some(1), None, true, "out")),
1781            (
1782                "signal termination",
1783                terminal(None, Some("SIGKILL"), false, "out"),
1784            ),
1785            ("released terminal", terminal(None, None, false, "out")),
1786            (
1787                "silent signal termination",
1788                terminal(None, Some("SIGTERM"), false, ""),
1789            ),
1790        ] {
1791            writeln!(output, "\n=== {label} (transcript row) ===\n{row}").unwrap();
1792        }
1793
1794        append_tool_row(
1795            &mut output,
1796            "shell command",
1797            &ToolCall::new("shell", "Terminal")
1798                .kind(ToolKind::Execute)
1799                .raw_input(json!({
1800                    "command": ["bash", "-lc", "cd dir && python x.py | cat"]
1801                })),
1802        );
1803        append_tool_row(
1804            &mut output,
1805            "ordinary argv command",
1806            &ToolCall::new("argv", "Execute")
1807                .kind(ToolKind::Execute)
1808                .raw_input(json!({"command": ["python", "-c", "print(1)"]})),
1809        );
1810
1811        let update_call = ToolCall::new("shell", "Bash")
1812            .kind(ToolKind::Execute)
1813            .raw_input(json!({"command": "cargo test"}));
1814        let original = tool_call_presentation(&update_call);
1815        let mut output_update = ToolCallUpdateFields::default();
1816        output_update.raw_output = Some(json!({"output": "x".repeat(128 * 1024)}));
1817        writeln!(output, "\n=== output-only update (transcript row) ===").unwrap();
1818        writeln!(
1819            output,
1820            "presentation changed: {}",
1821            tool_call_update_changes_presentation(&update_call, &output_update)
1822        )
1823        .unwrap();
1824        writeln!(output, "{}", original.summary).unwrap();
1825        let mut status_update = ToolCallUpdateFields::default();
1826        status_update.status = Some(ToolCallStatus::Completed);
1827        writeln!(
1828            output,
1829            "status-only update changes presentation: {}",
1830            tool_call_update_changes_presentation(&update_call, &status_update)
1831        )
1832        .unwrap();
1833        let output_call = ToolCall::new("output", "Bash").kind(ToolKind::Execute);
1834        writeln!(
1835            output,
1836            "output-only call changes presentation: {}",
1837            tool_call_update_changes_presentation(&output_call, &output_update)
1838        )
1839        .unwrap();
1840        let changed_input = json!({"command": "cargo check"});
1841        let mut input_update = ToolCallUpdateFields::default();
1842        input_update.raw_input = Some(changed_input.clone());
1843        writeln!(
1844            output,
1845            "changed command presentation: {}",
1846            tool_call_update_changes_presentation(&update_call, &input_update)
1847        )
1848        .unwrap();
1849        writeln!(
1850            output,
1851            "updated row: {}",
1852            update_tool_call_presentation(
1853                Some(&original),
1854                "Bash",
1855                Some(ToolKind::Execute),
1856                Some(&changed_input),
1857                None,
1858            )
1859            .summary
1860        )
1861        .unwrap();
1862
1863        for (label, command) in [
1864            (
1865                "git registered verb",
1866                json!({"command": ["git", "--no-pager", "status", "--short"]}),
1867            ),
1868            (
1869                "cargo registered verb",
1870                json!({"command": ["cargo", "+nightly", "test", "--package", "hel"]}),
1871            ),
1872            (
1873                "gh registered namespace",
1874                json!({"command": ["gh", "--hostname", "github.example", "pr", "list"]}),
1875            ),
1876            (
1877                "docker registered namespace",
1878                json!({"command": ["docker", "--context", "work", "compose", "up"]}),
1879            ),
1880            (
1881                "podman registered namespace",
1882                json!({"command": ["podman", "machine", "list"]}),
1883            ),
1884            (
1885                "uv registered namespace",
1886                json!({"command": ["uv", "--project", "app", "pip", "install", "ruff"]}),
1887            ),
1888            (
1889                "rustup registered namespace",
1890                json!({"command": ["rustup", "toolchain", "list"]}),
1891            ),
1892            (
1893                "npm registered namespace",
1894                json!({"command": ["npm", "--prefix", "web", "run", "build"]}),
1895            ),
1896        ] {
1897            append_tool_row(
1898                &mut output,
1899                label,
1900                &ToolCall::new("argv", "Bash")
1901                    .kind(ToolKind::Execute)
1902                    .raw_input(command),
1903            );
1904        }
1905
1906        let shell = ToolCall::new("string", "Bash")
1907            .kind(ToolKind::Execute)
1908            .raw_input(json!({"command": "git --no-pager status --short"}));
1909        let argv = ToolCall::new("argv", "Bash")
1910            .kind(ToolKind::Execute)
1911            .raw_input(json!({"command": ["git", "--no-pager", "status", "--short"]}));
1912        writeln!(
1913            output,
1914            "\n=== shell and argv invocation depth (transcript rows) ==="
1915        )
1916        .unwrap();
1917        writeln!(output, "shell: {}", rendered_tool_row(&shell)).unwrap();
1918        writeln!(output, "argv: {}", rendered_tool_row(&argv)).unwrap();
1919
1920        for (label, command) in [
1921            ("sudo wrapper", "sudo -n git status"),
1922            ("env wrapper", "env FOO=bar git status"),
1923            ("command wrapper", "command git status"),
1924        ] {
1925            append_tool_row(
1926                &mut output,
1927                label,
1928                &ToolCall::new("wrapper", "Bash")
1929                    .kind(ToolKind::Execute)
1930                    .raw_input(json!({"command": command})),
1931            );
1932        }
1933
1934        for (label, command) in [
1935            (
1936                "unlisted build tool",
1937                json!({"command": ["mytool", "build", "src"]}),
1938            ),
1939            (
1940                "unlisted script",
1941                json!({"command": ["mytool", "./script.sh"]}),
1942            ),
1943            ("python script", json!({"command": ["python", "script.py"]})),
1944            (
1945                "gh API namespace",
1946                json!({"command": ["gh", "api", "graphql"]}),
1947            ),
1948            (
1949                "docker run namespace",
1950                json!({"command": ["docker", "run", "ubuntu"]}),
1951            ),
1952            (
1953                "registered future git verb",
1954                json!({"command": ["git", "future-verb"]}),
1955            ),
1956            (
1957                "absolute git with attached directory",
1958                json!({"command": ["/usr/bin/git", "-Crepo", "status"]}),
1959            ),
1960            (
1961                "git short global option",
1962                json!({"command": ["git", "-c", "core.pager=cat", "status"]}),
1963            ),
1964            (
1965                "gh attached repository option",
1966                json!({"command": ["gh", "-Rorg/repo", "pr", "list"]}),
1967            ),
1968            (
1969                "cargo color option",
1970                json!({"command": ["cargo", "--color=always", "test"]}),
1971            ),
1972            (
1973                "cargo config option",
1974                json!({"command": ["cargo", "--config", "build.jobs=2", "test"]}),
1975            ),
1976        ] {
1977            append_tool_row(
1978                &mut output,
1979                label,
1980                &ToolCall::new("argv", "Bash")
1981                    .kind(ToolKind::Execute)
1982                    .raw_input(command),
1983            );
1984        }
1985
1986        for command in [
1987            vec!["nice", "-n", "10", "python3", "script.py"],
1988            vec!["nice", "--adjustment", "10", "python3", "script.py"],
1989            vec!["nice", "--adjustment=10", "python3", "script.py"],
1990            vec!["nice", "-10", "python3", "script.py"],
1991            vec!["nice", "-n10", "python3", "script.py"],
1992            vec!["nice", "--", "python3", "script.py"],
1993        ] {
1994            append_tool_row(
1995                &mut output,
1996                "nice command options",
1997                &ToolCall::new("nice", "Bash")
1998                    .kind(ToolKind::Execute)
1999                    .raw_input(json!({"command": command})),
2000            );
2001        }
2002        append_tool_row(
2003            &mut output,
2004            "nice shell command",
2005            &ToolCall::new("nice-shell", "Bash")
2006                .kind(ToolKind::Execute)
2007                .raw_input(json!({"command": "nice -n 10 python3 script.py"})),
2008        );
2009        append_tool_row(
2010            &mut output,
2011            "non-execute tool title",
2012            &ToolCall::new("read", "Read src/lib.rs").kind(ToolKind::Read),
2013        );
2014
2015        mj_core::golden::assert_golden(
2016            env!("CARGO_MANIFEST_DIR"),
2017            "transcript-tool-row-summary",
2018            &output,
2019        );
2020    }
2021}