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        other => Some(other),
1277    }
1278}
1279
1280/// One transcript item flattened to the text a reader would see.
1281///
1282/// A caller that wants the structure reads the body itself; this is the plain
1283/// reading, built from the same flatteners every other surface uses so that a
1284/// tool call reads as the command it ran rather than as JSON.
1285pub fn transcript_item_text(item: &TranscriptItem) -> String {
1286    match &item.body {
1287        TranscriptBody::User { content } => materialized_content_text(content),
1288        TranscriptBody::Agent { chunks, .. } | TranscriptBody::Thought { chunks, .. } => {
1289            materialized_chunks_text(chunks)
1290        }
1291        TranscriptBody::Tool {
1292            call,
1293            terminal_outputs,
1294            presentation,
1295            ..
1296        } => {
1297            let Ok(call) = ToolCall::deserialize(call) else {
1298                return "[invalid tool call]".to_owned();
1299            };
1300            let mut text = materialized_tool_call_presentation(presentation.as_deref(), &call)
1301                .summary
1302                .clone();
1303            if text.trim().is_empty() {
1304                text = call.title.clone();
1305            }
1306            for record in terminal_outputs {
1307                text.push('\n');
1308                text.push_str(&terminal_output_detail(record));
1309            }
1310            sanitize_terminal_text(&text)
1311        }
1312        TranscriptBody::TerminalOutput { record } => {
1313            sanitize_terminal_text(&terminal_output_detail(record))
1314        }
1315        TranscriptBody::Plan { plan } => {
1316            let Ok(plan) = agent_client_protocol::schema::v1::Plan::deserialize(plan) else {
1317                return String::new();
1318            };
1319            plan.entries
1320                .iter()
1321                .map(|entry| {
1322                    let status = match plan_status(&entry.status) {
1323                        PlanStatus::Pending => "pending",
1324                        PlanStatus::Running => "running",
1325                        PlanStatus::Completed => "completed",
1326                    };
1327                    format!("[{status}] {}", sanitize_terminal_text(&entry.content))
1328                })
1329                .collect::<Vec<_>>()
1330                .join("\n")
1331        }
1332        TranscriptBody::PlanProposal { plan, .. } => plan.clone(),
1333        TranscriptBody::System { text } => text.clone(),
1334    }
1335}
1336
1337pub(crate) fn compute_tool_diffstats(content: &[ToolCallContent]) -> Vec<String> {
1338    content
1339        .iter()
1340        .filter_map(|item| match item {
1341            ToolCallContent::Diff(diff) => Some(format_diffstat(diff)),
1342            _ => None,
1343        })
1344        .collect()
1345}
1346
1347pub fn materialized_tool_diffstats(item: &TranscriptItem) -> Option<Vec<String>> {
1348    let TranscriptBody::Tool { call, .. } = &item.body else {
1349        return None;
1350    };
1351    let call = match ToolCall::deserialize(call) {
1352        Ok(call) => call,
1353        Err(error) => {
1354            tracing::warn!(
1355                stable_id = %item.stable_id,
1356                %error,
1357                "could not decode a stored tool call while reading diff summary"
1358            );
1359            return None;
1360        }
1361    };
1362    if !matches!(
1363        tool_status(&call.status),
1364        ToolStatus::Completed | ToolStatus::Failed
1365    ) {
1366        return None;
1367    }
1368    let diffstats = compute_tool_diffstats(&call.content);
1369    (!diffstats.is_empty()).then_some(diffstats)
1370}
1371
1372fn format_diffstat(diff: &agent_client_protocol::schema::v1::Diff) -> String {
1373    // A diff recorded since `diff` landed already carries its counts, so
1374    // this is a lookup. An older record still holds both file copies and is
1375    // diffed here on demand.
1376    let patch = mj_core::diff::patch_of(diff);
1377    format!(
1378        "{}  +{} −{}",
1379        diff.path.display(),
1380        patch.insertions,
1381        patch.deletions
1382    )
1383}
1384
1385#[cfg(test)]
1386mod tests {
1387    use super::*;
1388    use agent_client_protocol::schema::v1::{ToolCall, ToolCallStatus};
1389    use serde_json::json;
1390
1391    /// I1-18: Claude's question tool is titled with the question itself. Its
1392    /// row showed only "Which"; it must show the whole question.
1393    // Hard-won: e570799ccc: a question-tool row displayed only its first word.
1394    #[test]
1395    fn a_question_tool_is_summarized_by_its_whole_question() {
1396        let call = ToolCall::new("ask", "Which file name should I use for the new file?")
1397            .raw_input(json!({"questions": [{"question": "Which file name should I use for the new file?", "header": "File name"}]}));
1398        assert_eq!(
1399            tool_call_presentation(&call).summary,
1400            "Which file name should I use for the new file?"
1401        );
1402        let read = ToolCall::new("read", "Read src/lib.rs");
1403        assert_eq!(tool_call_presentation(&read).summary, "Read");
1404        let stale = ToolCallPresentation {
1405            summary: "Which".into(),
1406            source: call.title.clone(),
1407            source_kind: ToolSummarySourceKind::Title,
1408            tool_kind: ToolKind::Other,
1409            summary_version: 1,
1410        };
1411        assert_eq!(
1412            materialized_tool_call_presentation(Some(&stale), &call).summary,
1413            "Which file name should I use for the new file?",
1414            "stored rows written by the old rules are repaired"
1415        );
1416    }
1417
1418    fn execute_summary(command: serde_json::Value) -> String {
1419        let call = ToolCall::new("argv", "Bash")
1420            .kind(ToolKind::Execute)
1421            .raw_input(command);
1422        tool_call_presentation(&call).summary
1423    }
1424
1425    #[test]
1426    fn unknown_leading_options_make_verb_position_ambiguous() {
1427        assert_eq!(
1428            execute_summary(json!({"command": ["git", "--mystery", "status"]})),
1429            "git"
1430        );
1431        assert_eq!(
1432            execute_summary(json!({"command": ["cargo", "--mystery", "test"]})),
1433            "cargo"
1434        );
1435    }
1436
1437    #[test]
1438    fn a_nested_shell_is_named_without_its_path_and_shows_its_script() {
1439        let cases = [
1440            ("bash -c 'python x.py'", "bash -c python"),
1441            ("/bin/bash -c \"python x.py\"", "bash -c python"),
1442            (
1443                "/usr/bin/zsh -lc 'git status && cargo test'",
1444                "zsh -c git status && cargo test",
1445            ),
1446            ("bash -c \"cd $dir && make\"", "bash -c cd && make"),
1447            ("bash -c \"$script\"", "bash -c"),
1448            ("/bin/bash script.sh", "bash"),
1449            (
1450                "bash -c 'bash -c \"uv run pytest\"'",
1451                "bash -c bash -c uv run",
1452            ),
1453        ];
1454        for (command, summary) in cases {
1455            assert_eq!(
1456                execute_summary(json!({"command": command})),
1457                summary,
1458                "{command}"
1459            );
1460        }
1461        // An argv shell call already stands for its script.
1462        assert_eq!(
1463            execute_summary(json!({"command": ["/bin/bash", "-lc", "python x.py"]})),
1464            "python"
1465        );
1466        assert_eq!(
1467            execute_summary(json!({"command": ["/bin/zsh", "script.sh"]})),
1468            "zsh"
1469        );
1470    }
1471
1472    #[test]
1473    fn quoted_and_dynamic_shell_verbs_are_distinguished() {
1474        let quoted = ToolCall::new("quoted", "Bash")
1475            .kind(ToolKind::Execute)
1476            .raw_input(json!({"command": "git \"status\""}));
1477        assert_eq!(tool_call_presentation(&quoted).summary, "git status");
1478
1479        let dynamic = ToolCall::new("dynamic", "Bash")
1480            .kind(ToolKind::Execute)
1481            .raw_input(json!({"command": "git \"$verb\""}));
1482        assert_eq!(tool_call_presentation(&dynamic).summary, "git");
1483
1484        let dynamic_name = ToolCall::new("dynamic-name", "Bash")
1485            .kind(ToolKind::Execute)
1486            .raw_input(json!({"command": "$command status"}));
1487        assert_eq!(tool_call_presentation(&dynamic_name).summary, "Bash");
1488    }
1489
1490    #[test]
1491    fn shell_summary_skips_assignments_arguments_and_nested_substitutions() {
1492        let call = ToolCall::new("call", "Bash")
1493            .kind(ToolKind::Execute)
1494            .raw_input(json!({
1495                "command": "FOO=bar env -i bash -c \"echo $(printf hi)\""
1496            }));
1497        assert_eq!(tool_call_presentation(&call).summary, "env");
1498
1499        let subshell = ToolCall::new("subshell", "Bash")
1500            .kind(ToolKind::Execute)
1501            .raw_input(json!({
1502                "command": "(cd dir && python x.py) | cat"
1503            }));
1504        assert_eq!(
1505            tool_call_presentation(&subshell).summary,
1506            "(cd && python) | cat"
1507        );
1508    }
1509
1510    #[test]
1511    fn shell_summary_keeps_list_pipeline_and_background_operators() {
1512        let simple = ToolCall::new("call-1", "Bash")
1513            .kind(ToolKind::Execute)
1514            .raw_input(json!({
1515                "command": "cd dir && python x.py | cat | wc ; print ok"
1516            }));
1517        let presentation = tool_call_presentation(&simple);
1518        assert_eq!(presentation.summary, "cd && python | cat | wc ; print");
1519        assert_eq!(presentation.source_kind, ToolSummarySourceKind::RawInput);
1520
1521        let call = ToolCall::new("operators", "Bash")
1522            .kind(ToolKind::Execute)
1523            .raw_input(json!({
1524                "command": "'printf' '%s' hi >out |& sed s/hi/bye/ || echo failed & wait; cat <in"
1525            }));
1526
1527        assert_eq!(
1528            tool_call_presentation(&call).summary,
1529            "printf |& sed || echo & wait ; cat"
1530        );
1531    }
1532
1533    #[test]
1534    fn shell_summary_removes_structural_loop_and_group_separators() {
1535        let call = ToolCall::new("compound", "Bash")
1536            .kind(ToolKind::Execute)
1537            .raw_input(json!({
1538                "command": "for file in a b; do rm \"$file\"; done; mkdir -p out; nice -n 10 python3 script.py"
1539            }));
1540
1541        assert_eq!(
1542            tool_call_presentation(&call).summary,
1543            "rm ; mkdir ; nice python3"
1544        );
1545
1546        let conditional = ToolCall::new("conditional", "Bash")
1547            .kind(ToolKind::Execute)
1548            .raw_input(json!({
1549                "command": "if test -f foo; then rm foo; fi; { mkdir bar; echo done; }"
1550            }));
1551        assert_eq!(
1552            tool_call_presentation(&conditional).summary,
1553            "test ; rm ; mkdir ; echo"
1554        );
1555
1556        let case_statement = ToolCall::new("case", "Bash")
1557            .kind(ToolKind::Execute)
1558            .raw_input(json!({
1559                "command": "echo start; case x in a|b) echo branch;; esac; echo done"
1560            }));
1561        assert_eq!(
1562            tool_call_presentation(&case_statement).summary,
1563            "echo ; echo ; echo"
1564        );
1565    }
1566
1567    #[test]
1568    fn shell_summary_handles_a_loop_with_a_leading_pipeline_and_nice() {
1569        let call = ToolCall::new("live-loop-shape", "Bash")
1570            .kind(ToolKind::Execute)
1571            .raw_input(json!({
1572                "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"
1573            }));
1574
1575        assert_eq!(
1576            tool_call_presentation(&call).summary,
1577            "cd && set ; rm ; mkdir ; nice ./bin/bifrost ; echo ; python3"
1578        );
1579    }
1580
1581    #[test]
1582    fn shell_summary_inserts_a_separator_after_a_heredoc() {
1583        let call = ToolCall::new("heredoc", "Bash")
1584            .kind(ToolKind::Execute)
1585            .raw_input(json!({
1586                "command": "python3 <<'PYEOF'\nprint(\"x\")\nPYEOF\ngrep -n x file | head"
1587            }));
1588
1589        assert_eq!(
1590            tool_call_presentation(&call).summary,
1591            "python3 ; grep | head"
1592        );
1593    }
1594
1595    #[test]
1596    fn materialized_summary_from_an_older_parser_is_repaired() {
1597        let source = "python3 <<'PYEOF'\nprint(\"x\")\nPYEOF\ngrep -n x file | head";
1598        let call = ToolCall::new("heredoc", "Bash")
1599            .kind(ToolKind::Execute)
1600            .raw_input(json!({ "command": source }));
1601        let stale = ToolCallPresentation {
1602            summary: "python3 grep | head".into(),
1603            source: source.into(),
1604            source_kind: ToolSummarySourceKind::RawInput,
1605            tool_kind: ToolKind::Execute,
1606            summary_version: 0,
1607        };
1608
1609        let repaired = materialized_tool_call_presentation(Some(&stale), &call);
1610        assert_eq!(repaired.summary, "python3 ; grep | head");
1611        assert_eq!(repaired.summary_version, TOOL_SUMMARY_VERSION);
1612
1613        let mut current = repaired;
1614        current.summary = "stored current summary".into();
1615        assert_eq!(
1616            materialized_tool_call_presentation(Some(&current), &call).summary,
1617            "stored current summary"
1618        );
1619    }
1620
1621    #[test]
1622    fn execute_summary_bounds_the_retained_source_before_parsing() {
1623        let command = format!("echo {}", "argument".repeat(TOOL_SUMMARY_SOURCE_BYTES));
1624        let call = ToolCall::new("bounded", "Bash")
1625            .kind(ToolKind::Execute)
1626            .raw_input(json!({ "command": command }));
1627
1628        let presentation = tool_call_presentation(&call);
1629        assert_eq!(presentation.source.len(), TOOL_SUMMARY_SOURCE_BYTES);
1630        assert_eq!(presentation.summary, "echo");
1631    }
1632
1633    #[test]
1634    fn title_wrappers_and_malformed_shell_fall_back_safely() {
1635        let wrapped = ToolCall::new("wrapped", "Running: ls -la").kind(ToolKind::Execute);
1636        assert_eq!(tool_call_presentation(&wrapped).summary, "ls");
1637
1638        let malformed = ToolCall::new("bad", "Bash")
1639            .kind(ToolKind::Execute)
1640            .raw_input(json!({"command": "cd && ("}));
1641        assert_eq!(tool_call_presentation(&malformed).summary, "Bash");
1642    }
1643
1644    #[test]
1645    fn explicit_empty_raw_input_drops_a_stale_raw_summary() {
1646        let initial = ToolCall::new("call", "Bash")
1647            .kind(ToolKind::Execute)
1648            .raw_input(json!({"command": "python script.py"}));
1649        let previous = tool_call_presentation(&initial);
1650        let empty_input = json!({"command": null});
1651        let updated = update_tool_call_presentation(
1652            Some(&previous),
1653            "Running: ls -la",
1654            None,
1655            Some(&empty_input),
1656            None,
1657        );
1658        assert_eq!(updated.summary, "ls");
1659        assert_eq!(updated.source_kind, ToolSummarySourceKind::Title);
1660
1661        let output = json!({"command": "cat result.txt"});
1662        let updated = update_tool_call_presentation(
1663            Some(&previous),
1664            "Running: ls -la",
1665            None,
1666            Some(&empty_input),
1667            Some(&output),
1668        );
1669        assert_eq!(updated.summary, "cat");
1670        assert_eq!(updated.source_kind, ToolSummarySourceKind::RawOutput);
1671
1672        let output_initial = ToolCall::new("output", "Bash")
1673            .kind(ToolKind::Execute)
1674            .raw_output(json!({"command": "python result.py"}));
1675        let output_previous = tool_call_presentation(&output_initial);
1676        let empty_output = json!({"command": null});
1677        let updated = update_tool_call_presentation(
1678            Some(&output_previous),
1679            "Running: ls -la",
1680            None,
1681            None,
1682            Some(&empty_output),
1683        );
1684        assert_eq!(updated.summary, "ls");
1685        assert_eq!(updated.source_kind, ToolSummarySourceKind::Title);
1686    }
1687
1688    fn rendered_tool_row(call: &ToolCall) -> String {
1689        let presentation = tool_call_presentation(call);
1690        let item = TranscriptItem {
1691            stable_id: "tool:golden".into(),
1692            position: 1,
1693            latest_content_event_ordinal: None,
1694            created_at_ms: 1,
1695            last_changed_at_ms: 1,
1696            body: TranscriptBody::Tool {
1697                call: serde_json::to_value(call).expect("serialize tool call"),
1698                terminal_outputs: Vec::new(),
1699                terminal_refs: Vec::new(),
1700                presentation: Some(Box::new(presentation)),
1701            },
1702        };
1703        transcript_item_text(&item)
1704    }
1705
1706    fn append_tool_row(output: &mut String, label: &str, call: &ToolCall) {
1707        use std::fmt::Write as _;
1708        if !output.is_empty() {
1709            output.push('\n');
1710        }
1711        writeln!(output, "=== {label} (transcript row) ===").unwrap();
1712        output.push_str(&rendered_tool_row(call));
1713        output.push('\n');
1714    }
1715
1716    #[test]
1717    fn golden_transcript_tool_row_summary() {
1718        use std::fmt::Write as _;
1719
1720        let mut output = String::new();
1721        let diff = agent_client_protocol::schema::v1::Diff::new("/workspace/new.txt", "one\ntwo\n");
1722        writeln!(output, "=== new file diff detail (transcript row) ===").unwrap();
1723        writeln!(output, "{}", format_diffstat(&diff)).unwrap();
1724
1725        let terminal = |exit_code, signal: Option<&str>, truncated, text: &str| {
1726            let record = TerminalOutputRecord {
1727                terminal_id: "term-1".into(),
1728                output: text.into(),
1729                truncated,
1730                exit_code,
1731                signal: signal.map(str::to_owned),
1732            };
1733            let item = TranscriptItem {
1734                stable_id: "terminal:golden".into(),
1735                position: 1,
1736                latest_content_event_ordinal: None,
1737                created_at_ms: 1,
1738                last_changed_at_ms: 1,
1739                body: TranscriptBody::TerminalOutput { record },
1740            };
1741            transcript_item_text(&item)
1742        };
1743        for (label, row) in [
1744            ("successful terminal", terminal(Some(0), None, false, "out")),
1745            ("truncated terminal", terminal(Some(1), None, true, "out")),
1746            (
1747                "signal termination",
1748                terminal(None, Some("SIGKILL"), false, "out"),
1749            ),
1750            ("released terminal", terminal(None, None, false, "out")),
1751            (
1752                "silent signal termination",
1753                terminal(None, Some("SIGTERM"), false, ""),
1754            ),
1755        ] {
1756            writeln!(output, "\n=== {label} (transcript row) ===\n{row}").unwrap();
1757        }
1758
1759        append_tool_row(
1760            &mut output,
1761            "shell command",
1762            &ToolCall::new("shell", "Terminal")
1763                .kind(ToolKind::Execute)
1764                .raw_input(json!({
1765                    "command": ["bash", "-lc", "cd dir && python x.py | cat"]
1766                })),
1767        );
1768        append_tool_row(
1769            &mut output,
1770            "ordinary argv command",
1771            &ToolCall::new("argv", "Execute")
1772                .kind(ToolKind::Execute)
1773                .raw_input(json!({"command": ["python", "-c", "print(1)"]})),
1774        );
1775
1776        let update_call = ToolCall::new("shell", "Bash")
1777            .kind(ToolKind::Execute)
1778            .raw_input(json!({"command": "cargo test"}));
1779        let original = tool_call_presentation(&update_call);
1780        let mut output_update = ToolCallUpdateFields::default();
1781        output_update.raw_output = Some(json!({"output": "x".repeat(128 * 1024)}));
1782        writeln!(output, "\n=== output-only update (transcript row) ===").unwrap();
1783        writeln!(
1784            output,
1785            "presentation changed: {}",
1786            tool_call_update_changes_presentation(&update_call, &output_update)
1787        )
1788        .unwrap();
1789        writeln!(output, "{}", original.summary).unwrap();
1790        let mut status_update = ToolCallUpdateFields::default();
1791        status_update.status = Some(ToolCallStatus::Completed);
1792        writeln!(
1793            output,
1794            "status-only update changes presentation: {}",
1795            tool_call_update_changes_presentation(&update_call, &status_update)
1796        )
1797        .unwrap();
1798        let output_call = ToolCall::new("output", "Bash").kind(ToolKind::Execute);
1799        writeln!(
1800            output,
1801            "output-only call changes presentation: {}",
1802            tool_call_update_changes_presentation(&output_call, &output_update)
1803        )
1804        .unwrap();
1805        let changed_input = json!({"command": "cargo check"});
1806        let mut input_update = ToolCallUpdateFields::default();
1807        input_update.raw_input = Some(changed_input.clone());
1808        writeln!(
1809            output,
1810            "changed command presentation: {}",
1811            tool_call_update_changes_presentation(&update_call, &input_update)
1812        )
1813        .unwrap();
1814        writeln!(
1815            output,
1816            "updated row: {}",
1817            update_tool_call_presentation(
1818                Some(&original),
1819                "Bash",
1820                Some(ToolKind::Execute),
1821                Some(&changed_input),
1822                None,
1823            )
1824            .summary
1825        )
1826        .unwrap();
1827
1828        for (label, command) in [
1829            (
1830                "git registered verb",
1831                json!({"command": ["git", "--no-pager", "status", "--short"]}),
1832            ),
1833            (
1834                "cargo registered verb",
1835                json!({"command": ["cargo", "+nightly", "test", "--package", "hel"]}),
1836            ),
1837            (
1838                "gh registered namespace",
1839                json!({"command": ["gh", "--hostname", "github.example", "pr", "list"]}),
1840            ),
1841            (
1842                "docker registered namespace",
1843                json!({"command": ["docker", "--context", "work", "compose", "up"]}),
1844            ),
1845            (
1846                "podman registered namespace",
1847                json!({"command": ["podman", "machine", "list"]}),
1848            ),
1849            (
1850                "uv registered namespace",
1851                json!({"command": ["uv", "--project", "app", "pip", "install", "ruff"]}),
1852            ),
1853            (
1854                "rustup registered namespace",
1855                json!({"command": ["rustup", "toolchain", "list"]}),
1856            ),
1857            (
1858                "npm registered namespace",
1859                json!({"command": ["npm", "--prefix", "web", "run", "build"]}),
1860            ),
1861        ] {
1862            append_tool_row(
1863                &mut output,
1864                label,
1865                &ToolCall::new("argv", "Bash")
1866                    .kind(ToolKind::Execute)
1867                    .raw_input(command),
1868            );
1869        }
1870
1871        let shell = ToolCall::new("string", "Bash")
1872            .kind(ToolKind::Execute)
1873            .raw_input(json!({"command": "git --no-pager status --short"}));
1874        let argv = ToolCall::new("argv", "Bash")
1875            .kind(ToolKind::Execute)
1876            .raw_input(json!({"command": ["git", "--no-pager", "status", "--short"]}));
1877        writeln!(
1878            output,
1879            "\n=== shell and argv invocation depth (transcript rows) ==="
1880        )
1881        .unwrap();
1882        writeln!(output, "shell: {}", rendered_tool_row(&shell)).unwrap();
1883        writeln!(output, "argv: {}", rendered_tool_row(&argv)).unwrap();
1884
1885        for (label, command) in [
1886            ("sudo wrapper", "sudo -n git status"),
1887            ("env wrapper", "env FOO=bar git status"),
1888            ("command wrapper", "command git status"),
1889        ] {
1890            append_tool_row(
1891                &mut output,
1892                label,
1893                &ToolCall::new("wrapper", "Bash")
1894                    .kind(ToolKind::Execute)
1895                    .raw_input(json!({"command": command})),
1896            );
1897        }
1898
1899        for (label, command) in [
1900            (
1901                "unlisted build tool",
1902                json!({"command": ["mytool", "build", "src"]}),
1903            ),
1904            (
1905                "unlisted script",
1906                json!({"command": ["mytool", "./script.sh"]}),
1907            ),
1908            ("python script", json!({"command": ["python", "script.py"]})),
1909            (
1910                "gh API namespace",
1911                json!({"command": ["gh", "api", "graphql"]}),
1912            ),
1913            (
1914                "docker run namespace",
1915                json!({"command": ["docker", "run", "ubuntu"]}),
1916            ),
1917            (
1918                "registered future git verb",
1919                json!({"command": ["git", "future-verb"]}),
1920            ),
1921            (
1922                "absolute git with attached directory",
1923                json!({"command": ["/usr/bin/git", "-Crepo", "status"]}),
1924            ),
1925            (
1926                "git short global option",
1927                json!({"command": ["git", "-c", "core.pager=cat", "status"]}),
1928            ),
1929            (
1930                "gh attached repository option",
1931                json!({"command": ["gh", "-Rorg/repo", "pr", "list"]}),
1932            ),
1933            (
1934                "cargo color option",
1935                json!({"command": ["cargo", "--color=always", "test"]}),
1936            ),
1937            (
1938                "cargo config option",
1939                json!({"command": ["cargo", "--config", "build.jobs=2", "test"]}),
1940            ),
1941        ] {
1942            append_tool_row(
1943                &mut output,
1944                label,
1945                &ToolCall::new("argv", "Bash")
1946                    .kind(ToolKind::Execute)
1947                    .raw_input(command),
1948            );
1949        }
1950
1951        for command in [
1952            vec!["nice", "-n", "10", "python3", "script.py"],
1953            vec!["nice", "--adjustment", "10", "python3", "script.py"],
1954            vec!["nice", "--adjustment=10", "python3", "script.py"],
1955            vec!["nice", "-10", "python3", "script.py"],
1956            vec!["nice", "-n10", "python3", "script.py"],
1957            vec!["nice", "--", "python3", "script.py"],
1958        ] {
1959            append_tool_row(
1960                &mut output,
1961                "nice command options",
1962                &ToolCall::new("nice", "Bash")
1963                    .kind(ToolKind::Execute)
1964                    .raw_input(json!({"command": command})),
1965            );
1966        }
1967        append_tool_row(
1968            &mut output,
1969            "nice shell command",
1970            &ToolCall::new("nice-shell", "Bash")
1971                .kind(ToolKind::Execute)
1972                .raw_input(json!({"command": "nice -n 10 python3 script.py"})),
1973        );
1974        append_tool_row(
1975            &mut output,
1976            "non-execute tool title",
1977            &ToolCall::new("read", "Read src/lib.rs").kind(ToolKind::Read),
1978        );
1979
1980        mj_core::golden::assert_golden(
1981            env!("CARGO_MANIFEST_DIR"),
1982            "transcript-tool-row-summary",
1983            &output,
1984        );
1985    }
1986}