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
962pub fn tool_content_details(
963    content: &[ToolCallContent],
964    terminal_outputs: &[TerminalOutputRecord],
965    raw_output: Option<&serde_json::Value>,
966) -> Vec<String> {
967    let mut details = Vec::new();
968    let mut referenced: Vec<&str> = Vec::new();
969    for item in content {
970        let detail = match item {
971            ToolCallContent::Content(content) => content_block_text(&content.content),
972            ToolCallContent::Diff(_) => None,
973            // Kimi-style agents send a terminal reference and no textual copy
974            // of the output, so the record hel captured is the only thing a
975            // reader ever sees. Until the terminal is reaped there is none.
976            ToolCallContent::Terminal(terminal) => {
977                let terminal_id = terminal.terminal_id.0.as_ref();
978                referenced.push(terminal_id);
979                Some(
980                    terminal_outputs
981                        .iter()
982                        .find(|record| record.terminal_id.as_str() == terminal_id)
983                        .map(terminal_output_detail)
984                        .or_else(|| raw_output.and_then(raw_output_terminal_detail))
985                        .unwrap_or_else(|| format!("terminal {}", terminal.terminal_id)),
986                )
987            }
988            _ => None,
989        };
990        if let Some(detail) = detail {
991            details.push(sanitize_terminal_text(&detail));
992        }
993    }
994    // Grok-style agents name the terminal on a mid-flight update and then
995    // replace `content` wholesale without it, so the output hel captured has
996    // nothing in the final call pointing at it. Show it rather than lose it.
997    for record in terminal_outputs {
998        if referenced.contains(&record.terminal_id.as_str()) {
999            continue;
1000        }
1001        let output = sanitize_terminal_text(&record.output);
1002        if !output.is_empty() && details.iter().any(|detail| detail == &output) {
1003            // Kimi sends the captured stdout as ordinary tool content and in
1004            // its raw result. Keep the exit summary without printing those
1005            // same bytes a second time in Raw mode.
1006            details.push(terminal_exit_summary(record));
1007        } else {
1008            details.push(sanitize_terminal_text(&terminal_output_detail(record)));
1009        }
1010    }
1011    details
1012}
1013
1014/// The output codex reports for a terminal it ran itself. Codex names its own
1015/// server-side terminal, which hel never opened and has no record for, and
1016/// puts the text in `rawOutput`; reading it here keeps such a call from
1017/// rendering as a bare terminal id.
1018fn raw_output_terminal_detail(raw_output: &serde_json::Value) -> Option<String> {
1019    let output = raw_output.get("formatted_output")?.as_str()?;
1020    let Some(exit_code) = raw_output
1021        .get("exit_code")
1022        .and_then(serde_json::Value::as_i64)
1023    else {
1024        return Some(output.to_owned());
1025    };
1026    let summary = format!("exited {exit_code}");
1027    if output.is_empty() {
1028        return Some(summary);
1029    }
1030    Some(format!("{output}\n{summary}"))
1031}
1032
1033/// One terminal's output followed by how it ended.
1034pub fn terminal_output_detail(record: &TerminalOutputRecord) -> String {
1035    let summary = terminal_exit_summary(record);
1036    if record.output.is_empty() {
1037        return summary;
1038    }
1039    format!("{}\n{summary}", record.output)
1040}
1041
1042/// How a terminal ended, in one line.
1043fn terminal_exit_summary(record: &TerminalOutputRecord) -> String {
1044    let mut summary = match (record.exit_code, &record.signal) {
1045        (_, Some(signal)) => format!("killed by {signal}"),
1046        (Some(code), None) => format!("exited {code}"),
1047        (None, None) => "released before exit".to_owned(),
1048    };
1049    if record.truncated {
1050        summary.push_str(" · output truncated");
1051    }
1052    summary
1053}
1054
1055pub fn tool_diff_paths(content: &[ToolCallContent]) -> Vec<String> {
1056    content
1057        .iter()
1058        .filter_map(|item| match item {
1059            ToolCallContent::Diff(diff) => Some(diff.path.display().to_string()),
1060            _ => None,
1061        })
1062        .collect()
1063}
1064
1065pub fn tool_location_details(locations: &[ToolCallLocation]) -> Vec<String> {
1066    locations
1067        .iter()
1068        .map(|location| match location.line {
1069            Some(line) => format!("{}:{line}", location.path.display()),
1070            None => location.path.display().to_string(),
1071        })
1072        .collect()
1073}
1074
1075/// Append streamed agent or thought text to the transcript, merging it into
1076/// the entry it continues so a message arrives as one entry rather than one
1077/// per chunk.
1078pub(crate) fn push_streamed_entry(
1079    entries: &mut Vec<ChatEntry>,
1080    seq: u64,
1081    recorded_at_ms: Option<i64>,
1082    role: ChatRole,
1083    message_id: Option<String>,
1084    text: &str,
1085) {
1086    let text = sanitize_terminal_text(text);
1087    if let Some(last) = entries.last_mut()
1088        && last.role == role
1089        && (role == ChatRole::Thought || last.message_id == message_id)
1090    {
1091        last.touch(seq);
1092        if role == ChatRole::Thought
1093            && last.message_id != message_id
1094            && !last.text.is_empty()
1095            && !text.is_empty()
1096        {
1097            while last.text.ends_with('\n') {
1098                last.text.pop();
1099            }
1100            last.text.push('\n');
1101            last.text.push_str(text.trim_start_matches('\n'));
1102        } else {
1103            last.text.push_str(&text);
1104        }
1105        return;
1106    }
1107    let mut entry = ChatEntry::plain(seq, role, text).with_recorded_at(recorded_at_ms);
1108    entry.message_id = message_id;
1109    entries.push(entry);
1110}
1111
1112/// Apply the transcript-visible part of one ACP session update. Returns the
1113/// update again when it changes the session surface rather than the
1114/// transcript, so the chat view handles those without decoding twice.
1115pub fn apply_session_update_to_entries(
1116    entries: &mut Vec<ChatEntry>,
1117    seq: u64,
1118    recorded_at_ms: Option<i64>,
1119    update: SessionUpdate,
1120) -> Option<SessionUpdate> {
1121    match update {
1122        SessionUpdate::AgentMessageChunk(chunk) => {
1123            let message_id = chunk.message_id.map(|id| id.to_string());
1124            if let Some(text) = content_block_text(&chunk.content) {
1125                push_streamed_entry(
1126                    entries,
1127                    seq,
1128                    recorded_at_ms,
1129                    ChatRole::Agent,
1130                    message_id,
1131                    &text,
1132                );
1133            }
1134        }
1135        SessionUpdate::AgentThoughtChunk(chunk) => {
1136            let message_id = chunk.message_id.map(|id| id.to_string());
1137            if let Some(text) = content_block_text(&chunk.content) {
1138                push_streamed_entry(
1139                    entries,
1140                    seq,
1141                    recorded_at_ms,
1142                    ChatRole::Thought,
1143                    message_id,
1144                    &text,
1145                );
1146            }
1147        }
1148        // PromptAccepted is the canonical local user-message event. ACP
1149        // user chunks would duplicate it during replay.
1150        SessionUpdate::UserMessageChunk(_) => {}
1151        SessionUpdate::ToolCall(call) => {
1152            let presentation = tool_call_presentation(&call);
1153            let mut entry = ChatEntry::tool(
1154                seq,
1155                call.title,
1156                Some(call.tool_call_id.to_string()),
1157                tool_status(&call.status),
1158            );
1159            entry.tool_summary = Some(presentation.summary.clone());
1160            entry.tool_presentation = Some(presentation);
1161            entry.tool_content = tool_content_details(&call.content, &[], call.raw_output.as_ref());
1162            entry.tool_diffstats = tool_diff_paths(&call.content);
1163            entry.tool_locations = tool_location_details(&call.locations);
1164            entries.push(entry);
1165        }
1166        SessionUpdate::ToolCallUpdate(update) => {
1167            let tool_call_id = update.tool_call_id.to_string();
1168            let entry = entries.iter_mut().rev().find(|entry| {
1169                entry.role == ChatRole::Tool
1170                    && entry.tool_call_id.as_deref() == Some(tool_call_id.as_str())
1171            })?;
1172            entry.touch(seq);
1173            let kind = update.fields.kind;
1174            let raw_input = update.fields.raw_input.clone();
1175            let raw_output = update.fields.raw_output.clone();
1176            if let Some(title) = update.fields.title {
1177                entry.text = sanitize_terminal_text(&title);
1178            }
1179            if let Some(status) = update.fields.status {
1180                entry.tool_status = Some(tool_status(&status));
1181            }
1182            if let Some(content) = update.fields.content {
1183                entry.tool_content =
1184                    tool_content_details(&content, &[], update.fields.raw_output.as_ref());
1185                entry.tool_diffstats = tool_diff_paths(&content);
1186            }
1187            if let Some(locations) = update.fields.locations {
1188                entry.tool_locations = tool_location_details(&locations);
1189            }
1190            let presentation = update_tool_call_presentation(
1191                entry.tool_presentation.as_ref(),
1192                &entry.text,
1193                kind,
1194                raw_input.as_ref(),
1195                raw_output.as_ref(),
1196            );
1197            entry.tool_summary = Some(presentation.summary.clone());
1198            entry.tool_presentation = Some(presentation);
1199        }
1200        SessionUpdate::Plan(plan) => {
1201            let lines = plan
1202                .entries
1203                .into_iter()
1204                .map(|entry| PlanLine {
1205                    text: sanitize_terminal_text(&entry.content),
1206                    status: plan_status(&entry.status),
1207                })
1208                .collect();
1209            let latest_user_seq = entries
1210                .iter()
1211                .rev()
1212                .find(|entry| entry.role == ChatRole::User)
1213                .map_or(0, |entry| entry.seq);
1214            if let Some(entry) = entries
1215                .iter_mut()
1216                .rev()
1217                .find(|entry| entry.role == ChatRole::Plan && entry.seq > latest_user_seq)
1218            {
1219                entry.touch(seq);
1220                entry.plan = lines;
1221            } else {
1222                entries.push(ChatEntry::plan(seq, lines));
1223            }
1224        }
1225        other => return Some(other),
1226    }
1227    None
1228}
1229
1230/// Apply the transcript-visible part of one persisted runtime event. Returns
1231/// the event again when it only configures the session surface, which is the
1232/// chat view's business rather than the transcript's.
1233pub fn apply_runtime_event_to_entries(
1234    entries: &mut Vec<ChatEntry>,
1235    seq: u64,
1236    recorded_at_ms: Option<i64>,
1237    runtime: RuntimeEvent,
1238) -> Option<RuntimeEvent> {
1239    match runtime {
1240        RuntimeEvent::SessionUpdate { update } => {
1241            let parsed = match serde_json::from_value::<SessionUpdate>(update.clone()) {
1242                Ok(parsed) => parsed,
1243                Err(error) => {
1244                    tracing::debug!(%error, "ignoring invalid ACP session update");
1245                    return None;
1246                }
1247            };
1248            apply_session_update_to_entries(entries, seq, recorded_at_ms, parsed)
1249                .map(|_| RuntimeEvent::SessionUpdate { update })
1250        }
1251        RuntimeEvent::Warning { message } | RuntimeEvent::SessionFault { message } => {
1252            entries.push(ChatEntry::plain(
1253                seq,
1254                ChatRole::System,
1255                format!("warning: {message}"),
1256            ));
1257            None
1258        }
1259        RuntimeEvent::ConfigApplied { key, value, .. } => {
1260            entries.push(ChatEntry::plain(
1261                seq,
1262                ChatRole::System,
1263                format!("{key} set to {value}"),
1264            ));
1265            None
1266        }
1267        RuntimeEvent::SessionStarted { resumed: false, .. } => {
1268            entries.push(ChatEntry::plain(
1269                seq,
1270                ChatRole::System,
1271                "harness session started",
1272            ));
1273            None
1274        }
1275        RuntimeEvent::SessionStarted { resumed: true, .. } => None,
1276        RuntimeEvent::ElicitationResolved {
1277            reply: Some(reply), ..
1278        } => {
1279            let mut entry =
1280                ChatEntry::plain(seq, ChatRole::User, reply).with_recorded_at(recorded_at_ms);
1281            entry.message_id = Some(format!("{ELICITATION_REPLY_ITEM_PREFIX}{seq}"));
1282            entries.push(entry);
1283            None
1284        }
1285        other => Some(other),
1286    }
1287}
1288
1289/// One transcript item flattened to the text a reader would see.
1290///
1291/// A caller that wants the structure reads the body itself; this is the plain
1292/// reading, built from the same flatteners every other surface uses so that a
1293/// tool call reads as the command it ran rather than as JSON.
1294pub fn transcript_item_text(item: &TranscriptItem) -> String {
1295    match &item.body {
1296        TranscriptBody::User { content } => materialized_content_text(content),
1297        TranscriptBody::Agent { chunks, .. } | TranscriptBody::Thought { chunks, .. } => {
1298            materialized_chunks_text(chunks)
1299        }
1300        TranscriptBody::Tool {
1301            call,
1302            terminal_outputs,
1303            presentation,
1304            ..
1305        } => {
1306            let Ok(call) = ToolCall::deserialize(call) else {
1307                return "[invalid tool call]".to_owned();
1308            };
1309            let mut text = materialized_tool_call_presentation(presentation.as_deref(), &call)
1310                .summary
1311                .clone();
1312            if text.trim().is_empty() {
1313                text = call.title.clone();
1314            }
1315            for record in terminal_outputs {
1316                text.push('\n');
1317                text.push_str(&terminal_output_detail(record));
1318            }
1319            sanitize_terminal_text(&text)
1320        }
1321        TranscriptBody::TerminalOutput { record } => {
1322            sanitize_terminal_text(&terminal_output_detail(record))
1323        }
1324        TranscriptBody::Plan { plan } => {
1325            let Ok(plan) = agent_client_protocol::schema::v1::Plan::deserialize(plan) else {
1326                return String::new();
1327            };
1328            plan.entries
1329                .iter()
1330                .map(|entry| {
1331                    let status = match plan_status(&entry.status) {
1332                        PlanStatus::Pending => "pending",
1333                        PlanStatus::Running => "running",
1334                        PlanStatus::Completed => "completed",
1335                    };
1336                    format!("[{status}] {}", sanitize_terminal_text(&entry.content))
1337                })
1338                .collect::<Vec<_>>()
1339                .join("\n")
1340        }
1341        TranscriptBody::PlanProposal { plan, .. } => plan.clone(),
1342        TranscriptBody::System { text } => text.clone(),
1343    }
1344}
1345
1346pub(crate) fn compute_tool_diffstats(content: &[ToolCallContent]) -> Vec<String> {
1347    content
1348        .iter()
1349        .filter_map(|item| match item {
1350            ToolCallContent::Diff(diff) => Some(format_diffstat(diff)),
1351            _ => None,
1352        })
1353        .collect()
1354}
1355
1356pub fn materialized_tool_diffstats(item: &TranscriptItem) -> Option<Vec<String>> {
1357    let TranscriptBody::Tool { call, .. } = &item.body else {
1358        return None;
1359    };
1360    let call = match ToolCall::deserialize(call) {
1361        Ok(call) => call,
1362        Err(error) => {
1363            tracing::warn!(
1364                stable_id = %item.stable_id,
1365                %error,
1366                "could not decode a stored tool call while reading diff summary"
1367            );
1368            return None;
1369        }
1370    };
1371    if !matches!(
1372        tool_status(&call.status),
1373        ToolStatus::Completed | ToolStatus::Failed
1374    ) {
1375        return None;
1376    }
1377    let diffstats = compute_tool_diffstats(&call.content);
1378    (!diffstats.is_empty()).then_some(diffstats)
1379}
1380
1381fn format_diffstat(diff: &agent_client_protocol::schema::v1::Diff) -> String {
1382    // A diff recorded since `diff` landed already carries its counts, so
1383    // this is a lookup. An older record still holds both file copies and is
1384    // diffed here on demand.
1385    let patch = mj_core::diff::patch_of(diff);
1386    format!(
1387        "{}  +{} −{}",
1388        diff.path.display(),
1389        patch.insertions,
1390        patch.deletions
1391    )
1392}
1393
1394#[cfg(test)]
1395mod tests {
1396    use super::*;
1397    use agent_client_protocol::schema::v1::{ToolCall, ToolCallStatus};
1398    use serde_json::json;
1399
1400    /// I1-18: Claude's question tool is titled with the question itself. Its
1401    /// row showed only "Which"; it must show the whole question.
1402    // Hard-won: e570799ccc: a question-tool row displayed only its first word.
1403    #[test]
1404    fn a_question_tool_is_summarized_by_its_whole_question() {
1405        let call = ToolCall::new("ask", "Which file name should I use for the new file?")
1406            .raw_input(json!({"questions": [{"question": "Which file name should I use for the new file?", "header": "File name"}]}));
1407        assert_eq!(
1408            tool_call_presentation(&call).summary,
1409            "Which file name should I use for the new file?"
1410        );
1411        let read = ToolCall::new("read", "Read src/lib.rs");
1412        assert_eq!(tool_call_presentation(&read).summary, "Read");
1413        let stale = ToolCallPresentation {
1414            summary: "Which".into(),
1415            source: call.title.clone(),
1416            source_kind: ToolSummarySourceKind::Title,
1417            tool_kind: ToolKind::Other,
1418            summary_version: 1,
1419        };
1420        assert_eq!(
1421            materialized_tool_call_presentation(Some(&stale), &call).summary,
1422            "Which file name should I use for the new file?",
1423            "stored rows written by the old rules are repaired"
1424        );
1425    }
1426
1427    fn execute_summary(command: serde_json::Value) -> String {
1428        let call = ToolCall::new("argv", "Bash")
1429            .kind(ToolKind::Execute)
1430            .raw_input(command);
1431        tool_call_presentation(&call).summary
1432    }
1433
1434    #[test]
1435    fn unknown_leading_options_make_verb_position_ambiguous() {
1436        assert_eq!(
1437            execute_summary(json!({"command": ["git", "--mystery", "status"]})),
1438            "git"
1439        );
1440        assert_eq!(
1441            execute_summary(json!({"command": ["cargo", "--mystery", "test"]})),
1442            "cargo"
1443        );
1444    }
1445
1446    #[test]
1447    fn a_nested_shell_is_named_without_its_path_and_shows_its_script() {
1448        let cases = [
1449            ("bash -c 'python x.py'", "bash -c python"),
1450            ("/bin/bash -c \"python x.py\"", "bash -c python"),
1451            (
1452                "/usr/bin/zsh -lc 'git status && cargo test'",
1453                "zsh -c git status && cargo test",
1454            ),
1455            ("bash -c \"cd $dir && make\"", "bash -c cd && make"),
1456            ("bash -c \"$script\"", "bash -c"),
1457            ("/bin/bash script.sh", "bash"),
1458            (
1459                "bash -c 'bash -c \"uv run pytest\"'",
1460                "bash -c bash -c uv run",
1461            ),
1462        ];
1463        for (command, summary) in cases {
1464            assert_eq!(
1465                execute_summary(json!({"command": command})),
1466                summary,
1467                "{command}"
1468            );
1469        }
1470        // An argv shell call already stands for its script.
1471        assert_eq!(
1472            execute_summary(json!({"command": ["/bin/bash", "-lc", "python x.py"]})),
1473            "python"
1474        );
1475        assert_eq!(
1476            execute_summary(json!({"command": ["/bin/zsh", "script.sh"]})),
1477            "zsh"
1478        );
1479    }
1480
1481    #[test]
1482    fn quoted_and_dynamic_shell_verbs_are_distinguished() {
1483        let quoted = ToolCall::new("quoted", "Bash")
1484            .kind(ToolKind::Execute)
1485            .raw_input(json!({"command": "git \"status\""}));
1486        assert_eq!(tool_call_presentation(&quoted).summary, "git status");
1487
1488        let dynamic = ToolCall::new("dynamic", "Bash")
1489            .kind(ToolKind::Execute)
1490            .raw_input(json!({"command": "git \"$verb\""}));
1491        assert_eq!(tool_call_presentation(&dynamic).summary, "git");
1492
1493        let dynamic_name = ToolCall::new("dynamic-name", "Bash")
1494            .kind(ToolKind::Execute)
1495            .raw_input(json!({"command": "$command status"}));
1496        assert_eq!(tool_call_presentation(&dynamic_name).summary, "Bash");
1497    }
1498
1499    #[test]
1500    fn shell_summary_skips_assignments_arguments_and_nested_substitutions() {
1501        let call = ToolCall::new("call", "Bash")
1502            .kind(ToolKind::Execute)
1503            .raw_input(json!({
1504                "command": "FOO=bar env -i bash -c \"echo $(printf hi)\""
1505            }));
1506        assert_eq!(tool_call_presentation(&call).summary, "env");
1507
1508        let subshell = ToolCall::new("subshell", "Bash")
1509            .kind(ToolKind::Execute)
1510            .raw_input(json!({
1511                "command": "(cd dir && python x.py) | cat"
1512            }));
1513        assert_eq!(
1514            tool_call_presentation(&subshell).summary,
1515            "(cd && python) | cat"
1516        );
1517    }
1518
1519    #[test]
1520    fn shell_summary_keeps_list_pipeline_and_background_operators() {
1521        let simple = ToolCall::new("call-1", "Bash")
1522            .kind(ToolKind::Execute)
1523            .raw_input(json!({
1524                "command": "cd dir && python x.py | cat | wc ; print ok"
1525            }));
1526        let presentation = tool_call_presentation(&simple);
1527        assert_eq!(presentation.summary, "cd && python | cat | wc ; print");
1528        assert_eq!(presentation.source_kind, ToolSummarySourceKind::RawInput);
1529
1530        let call = ToolCall::new("operators", "Bash")
1531            .kind(ToolKind::Execute)
1532            .raw_input(json!({
1533                "command": "'printf' '%s' hi >out |& sed s/hi/bye/ || echo failed & wait; cat <in"
1534            }));
1535
1536        assert_eq!(
1537            tool_call_presentation(&call).summary,
1538            "printf |& sed || echo & wait ; cat"
1539        );
1540    }
1541
1542    #[test]
1543    fn shell_summary_removes_structural_loop_and_group_separators() {
1544        let call = ToolCall::new("compound", "Bash")
1545            .kind(ToolKind::Execute)
1546            .raw_input(json!({
1547                "command": "for file in a b; do rm \"$file\"; done; mkdir -p out; nice -n 10 python3 script.py"
1548            }));
1549
1550        assert_eq!(
1551            tool_call_presentation(&call).summary,
1552            "rm ; mkdir ; nice python3"
1553        );
1554
1555        let conditional = ToolCall::new("conditional", "Bash")
1556            .kind(ToolKind::Execute)
1557            .raw_input(json!({
1558                "command": "if test -f foo; then rm foo; fi; { mkdir bar; echo done; }"
1559            }));
1560        assert_eq!(
1561            tool_call_presentation(&conditional).summary,
1562            "test ; rm ; mkdir ; echo"
1563        );
1564
1565        let case_statement = ToolCall::new("case", "Bash")
1566            .kind(ToolKind::Execute)
1567            .raw_input(json!({
1568                "command": "echo start; case x in a|b) echo branch;; esac; echo done"
1569            }));
1570        assert_eq!(
1571            tool_call_presentation(&case_statement).summary,
1572            "echo ; echo ; echo"
1573        );
1574    }
1575
1576    #[test]
1577    fn shell_summary_handles_a_loop_with_a_leading_pipeline_and_nice() {
1578        let call = ToolCall::new("live-loop-shape", "Bash")
1579            .kind(ToolKind::Execute)
1580            .raw_input(json!({
1581                "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"
1582            }));
1583
1584        assert_eq!(
1585            tool_call_presentation(&call).summary,
1586            "cd && set ; rm ; mkdir ; nice ./bin/bifrost ; echo ; python3"
1587        );
1588    }
1589
1590    #[test]
1591    fn shell_summary_inserts_a_separator_after_a_heredoc() {
1592        let call = ToolCall::new("heredoc", "Bash")
1593            .kind(ToolKind::Execute)
1594            .raw_input(json!({
1595                "command": "python3 <<'PYEOF'\nprint(\"x\")\nPYEOF\ngrep -n x file | head"
1596            }));
1597
1598        assert_eq!(
1599            tool_call_presentation(&call).summary,
1600            "python3 ; grep | head"
1601        );
1602    }
1603
1604    #[test]
1605    fn materialized_summary_from_an_older_parser_is_repaired() {
1606        let source = "python3 <<'PYEOF'\nprint(\"x\")\nPYEOF\ngrep -n x file | head";
1607        let call = ToolCall::new("heredoc", "Bash")
1608            .kind(ToolKind::Execute)
1609            .raw_input(json!({ "command": source }));
1610        let stale = ToolCallPresentation {
1611            summary: "python3 grep | head".into(),
1612            source: source.into(),
1613            source_kind: ToolSummarySourceKind::RawInput,
1614            tool_kind: ToolKind::Execute,
1615            summary_version: 0,
1616        };
1617
1618        let repaired = materialized_tool_call_presentation(Some(&stale), &call);
1619        assert_eq!(repaired.summary, "python3 ; grep | head");
1620        assert_eq!(repaired.summary_version, TOOL_SUMMARY_VERSION);
1621
1622        let mut current = repaired;
1623        current.summary = "stored current summary".into();
1624        assert_eq!(
1625            materialized_tool_call_presentation(Some(&current), &call).summary,
1626            "stored current summary"
1627        );
1628    }
1629
1630    #[test]
1631    fn execute_summary_bounds_the_retained_source_before_parsing() {
1632        let command = format!("echo {}", "argument".repeat(TOOL_SUMMARY_SOURCE_BYTES));
1633        let call = ToolCall::new("bounded", "Bash")
1634            .kind(ToolKind::Execute)
1635            .raw_input(json!({ "command": command }));
1636
1637        let presentation = tool_call_presentation(&call);
1638        assert_eq!(presentation.source.len(), TOOL_SUMMARY_SOURCE_BYTES);
1639        assert_eq!(presentation.summary, "echo");
1640    }
1641
1642    #[test]
1643    fn title_wrappers_and_malformed_shell_fall_back_safely() {
1644        let wrapped = ToolCall::new("wrapped", "Running: ls -la").kind(ToolKind::Execute);
1645        assert_eq!(tool_call_presentation(&wrapped).summary, "ls");
1646
1647        let malformed = ToolCall::new("bad", "Bash")
1648            .kind(ToolKind::Execute)
1649            .raw_input(json!({"command": "cd && ("}));
1650        assert_eq!(tool_call_presentation(&malformed).summary, "Bash");
1651    }
1652
1653    #[test]
1654    fn explicit_empty_raw_input_drops_a_stale_raw_summary() {
1655        let initial = ToolCall::new("call", "Bash")
1656            .kind(ToolKind::Execute)
1657            .raw_input(json!({"command": "python script.py"}));
1658        let previous = tool_call_presentation(&initial);
1659        let empty_input = json!({"command": null});
1660        let updated = update_tool_call_presentation(
1661            Some(&previous),
1662            "Running: ls -la",
1663            None,
1664            Some(&empty_input),
1665            None,
1666        );
1667        assert_eq!(updated.summary, "ls");
1668        assert_eq!(updated.source_kind, ToolSummarySourceKind::Title);
1669
1670        let output = json!({"command": "cat result.txt"});
1671        let updated = update_tool_call_presentation(
1672            Some(&previous),
1673            "Running: ls -la",
1674            None,
1675            Some(&empty_input),
1676            Some(&output),
1677        );
1678        assert_eq!(updated.summary, "cat");
1679        assert_eq!(updated.source_kind, ToolSummarySourceKind::RawOutput);
1680
1681        let output_initial = ToolCall::new("output", "Bash")
1682            .kind(ToolKind::Execute)
1683            .raw_output(json!({"command": "python result.py"}));
1684        let output_previous = tool_call_presentation(&output_initial);
1685        let empty_output = json!({"command": null});
1686        let updated = update_tool_call_presentation(
1687            Some(&output_previous),
1688            "Running: ls -la",
1689            None,
1690            None,
1691            Some(&empty_output),
1692        );
1693        assert_eq!(updated.summary, "ls");
1694        assert_eq!(updated.source_kind, ToolSummarySourceKind::Title);
1695    }
1696
1697    fn rendered_tool_row(call: &ToolCall) -> String {
1698        let presentation = tool_call_presentation(call);
1699        let item = TranscriptItem {
1700            stable_id: "tool:golden".into(),
1701            position: 1,
1702            latest_content_event_ordinal: None,
1703            created_at_ms: 1,
1704            last_changed_at_ms: 1,
1705            body: TranscriptBody::Tool {
1706                call: serde_json::to_value(call).expect("serialize tool call"),
1707                terminal_outputs: Vec::new(),
1708                terminal_refs: Vec::new(),
1709                presentation: Some(Box::new(presentation)),
1710            },
1711        };
1712        transcript_item_text(&item)
1713    }
1714
1715    fn append_tool_row(output: &mut String, label: &str, call: &ToolCall) {
1716        use std::fmt::Write as _;
1717        if !output.is_empty() {
1718            output.push('\n');
1719        }
1720        writeln!(output, "=== {label} (transcript row) ===").unwrap();
1721        output.push_str(&rendered_tool_row(call));
1722        output.push('\n');
1723    }
1724
1725    #[test]
1726    fn golden_transcript_tool_row_summary() {
1727        use std::fmt::Write as _;
1728
1729        let mut output = String::new();
1730        let diff = agent_client_protocol::schema::v1::Diff::new("/workspace/new.txt", "one\ntwo\n");
1731        writeln!(output, "=== new file diff detail (transcript row) ===").unwrap();
1732        writeln!(output, "{}", format_diffstat(&diff)).unwrap();
1733
1734        let terminal = |exit_code, signal: Option<&str>, truncated, text: &str| {
1735            let record = TerminalOutputRecord {
1736                terminal_id: "term-1".into(),
1737                output: text.into(),
1738                truncated,
1739                exit_code,
1740                signal: signal.map(str::to_owned),
1741            };
1742            let item = TranscriptItem {
1743                stable_id: "terminal:golden".into(),
1744                position: 1,
1745                latest_content_event_ordinal: None,
1746                created_at_ms: 1,
1747                last_changed_at_ms: 1,
1748                body: TranscriptBody::TerminalOutput { record },
1749            };
1750            transcript_item_text(&item)
1751        };
1752        for (label, row) in [
1753            ("successful terminal", terminal(Some(0), None, false, "out")),
1754            ("truncated terminal", terminal(Some(1), None, true, "out")),
1755            (
1756                "signal termination",
1757                terminal(None, Some("SIGKILL"), false, "out"),
1758            ),
1759            ("released terminal", terminal(None, None, false, "out")),
1760            (
1761                "silent signal termination",
1762                terminal(None, Some("SIGTERM"), false, ""),
1763            ),
1764        ] {
1765            writeln!(output, "\n=== {label} (transcript row) ===\n{row}").unwrap();
1766        }
1767
1768        append_tool_row(
1769            &mut output,
1770            "shell command",
1771            &ToolCall::new("shell", "Terminal")
1772                .kind(ToolKind::Execute)
1773                .raw_input(json!({
1774                    "command": ["bash", "-lc", "cd dir && python x.py | cat"]
1775                })),
1776        );
1777        append_tool_row(
1778            &mut output,
1779            "ordinary argv command",
1780            &ToolCall::new("argv", "Execute")
1781                .kind(ToolKind::Execute)
1782                .raw_input(json!({"command": ["python", "-c", "print(1)"]})),
1783        );
1784
1785        let update_call = ToolCall::new("shell", "Bash")
1786            .kind(ToolKind::Execute)
1787            .raw_input(json!({"command": "cargo test"}));
1788        let original = tool_call_presentation(&update_call);
1789        let mut output_update = ToolCallUpdateFields::default();
1790        output_update.raw_output = Some(json!({"output": "x".repeat(128 * 1024)}));
1791        writeln!(output, "\n=== output-only update (transcript row) ===").unwrap();
1792        writeln!(
1793            output,
1794            "presentation changed: {}",
1795            tool_call_update_changes_presentation(&update_call, &output_update)
1796        )
1797        .unwrap();
1798        writeln!(output, "{}", original.summary).unwrap();
1799        let mut status_update = ToolCallUpdateFields::default();
1800        status_update.status = Some(ToolCallStatus::Completed);
1801        writeln!(
1802            output,
1803            "status-only update changes presentation: {}",
1804            tool_call_update_changes_presentation(&update_call, &status_update)
1805        )
1806        .unwrap();
1807        let output_call = ToolCall::new("output", "Bash").kind(ToolKind::Execute);
1808        writeln!(
1809            output,
1810            "output-only call changes presentation: {}",
1811            tool_call_update_changes_presentation(&output_call, &output_update)
1812        )
1813        .unwrap();
1814        let changed_input = json!({"command": "cargo check"});
1815        let mut input_update = ToolCallUpdateFields::default();
1816        input_update.raw_input = Some(changed_input.clone());
1817        writeln!(
1818            output,
1819            "changed command presentation: {}",
1820            tool_call_update_changes_presentation(&update_call, &input_update)
1821        )
1822        .unwrap();
1823        writeln!(
1824            output,
1825            "updated row: {}",
1826            update_tool_call_presentation(
1827                Some(&original),
1828                "Bash",
1829                Some(ToolKind::Execute),
1830                Some(&changed_input),
1831                None,
1832            )
1833            .summary
1834        )
1835        .unwrap();
1836
1837        for (label, command) in [
1838            (
1839                "git registered verb",
1840                json!({"command": ["git", "--no-pager", "status", "--short"]}),
1841            ),
1842            (
1843                "cargo registered verb",
1844                json!({"command": ["cargo", "+nightly", "test", "--package", "hel"]}),
1845            ),
1846            (
1847                "gh registered namespace",
1848                json!({"command": ["gh", "--hostname", "github.example", "pr", "list"]}),
1849            ),
1850            (
1851                "docker registered namespace",
1852                json!({"command": ["docker", "--context", "work", "compose", "up"]}),
1853            ),
1854            (
1855                "podman registered namespace",
1856                json!({"command": ["podman", "machine", "list"]}),
1857            ),
1858            (
1859                "uv registered namespace",
1860                json!({"command": ["uv", "--project", "app", "pip", "install", "ruff"]}),
1861            ),
1862            (
1863                "rustup registered namespace",
1864                json!({"command": ["rustup", "toolchain", "list"]}),
1865            ),
1866            (
1867                "npm registered namespace",
1868                json!({"command": ["npm", "--prefix", "web", "run", "build"]}),
1869            ),
1870        ] {
1871            append_tool_row(
1872                &mut output,
1873                label,
1874                &ToolCall::new("argv", "Bash")
1875                    .kind(ToolKind::Execute)
1876                    .raw_input(command),
1877            );
1878        }
1879
1880        let shell = ToolCall::new("string", "Bash")
1881            .kind(ToolKind::Execute)
1882            .raw_input(json!({"command": "git --no-pager status --short"}));
1883        let argv = ToolCall::new("argv", "Bash")
1884            .kind(ToolKind::Execute)
1885            .raw_input(json!({"command": ["git", "--no-pager", "status", "--short"]}));
1886        writeln!(
1887            output,
1888            "\n=== shell and argv invocation depth (transcript rows) ==="
1889        )
1890        .unwrap();
1891        writeln!(output, "shell: {}", rendered_tool_row(&shell)).unwrap();
1892        writeln!(output, "argv: {}", rendered_tool_row(&argv)).unwrap();
1893
1894        for (label, command) in [
1895            ("sudo wrapper", "sudo -n git status"),
1896            ("env wrapper", "env FOO=bar git status"),
1897            ("command wrapper", "command git status"),
1898        ] {
1899            append_tool_row(
1900                &mut output,
1901                label,
1902                &ToolCall::new("wrapper", "Bash")
1903                    .kind(ToolKind::Execute)
1904                    .raw_input(json!({"command": command})),
1905            );
1906        }
1907
1908        for (label, command) in [
1909            (
1910                "unlisted build tool",
1911                json!({"command": ["mytool", "build", "src"]}),
1912            ),
1913            (
1914                "unlisted script",
1915                json!({"command": ["mytool", "./script.sh"]}),
1916            ),
1917            ("python script", json!({"command": ["python", "script.py"]})),
1918            (
1919                "gh API namespace",
1920                json!({"command": ["gh", "api", "graphql"]}),
1921            ),
1922            (
1923                "docker run namespace",
1924                json!({"command": ["docker", "run", "ubuntu"]}),
1925            ),
1926            (
1927                "registered future git verb",
1928                json!({"command": ["git", "future-verb"]}),
1929            ),
1930            (
1931                "absolute git with attached directory",
1932                json!({"command": ["/usr/bin/git", "-Crepo", "status"]}),
1933            ),
1934            (
1935                "git short global option",
1936                json!({"command": ["git", "-c", "core.pager=cat", "status"]}),
1937            ),
1938            (
1939                "gh attached repository option",
1940                json!({"command": ["gh", "-Rorg/repo", "pr", "list"]}),
1941            ),
1942            (
1943                "cargo color option",
1944                json!({"command": ["cargo", "--color=always", "test"]}),
1945            ),
1946            (
1947                "cargo config option",
1948                json!({"command": ["cargo", "--config", "build.jobs=2", "test"]}),
1949            ),
1950        ] {
1951            append_tool_row(
1952                &mut output,
1953                label,
1954                &ToolCall::new("argv", "Bash")
1955                    .kind(ToolKind::Execute)
1956                    .raw_input(command),
1957            );
1958        }
1959
1960        for command in [
1961            vec!["nice", "-n", "10", "python3", "script.py"],
1962            vec!["nice", "--adjustment", "10", "python3", "script.py"],
1963            vec!["nice", "--adjustment=10", "python3", "script.py"],
1964            vec!["nice", "-10", "python3", "script.py"],
1965            vec!["nice", "-n10", "python3", "script.py"],
1966            vec!["nice", "--", "python3", "script.py"],
1967        ] {
1968            append_tool_row(
1969                &mut output,
1970                "nice command options",
1971                &ToolCall::new("nice", "Bash")
1972                    .kind(ToolKind::Execute)
1973                    .raw_input(json!({"command": command})),
1974            );
1975        }
1976        append_tool_row(
1977            &mut output,
1978            "nice shell command",
1979            &ToolCall::new("nice-shell", "Bash")
1980                .kind(ToolKind::Execute)
1981                .raw_input(json!({"command": "nice -n 10 python3 script.py"})),
1982        );
1983        append_tool_row(
1984            &mut output,
1985            "non-execute tool title",
1986            &ToolCall::new("read", "Read src/lib.rs").kind(ToolKind::Read),
1987        );
1988
1989        mj_core::golden::assert_golden(
1990            env!("CARGO_MANIFEST_DIR"),
1991            "transcript-tool-row-summary",
1992            &output,
1993        );
1994    }
1995}