aptu-coder 0.29.1

MCP server for multi-language code structure analysis
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
// SPDX-FileCopyrightText: 2026 aptu-coder contributors
// SPDX-License-Identifier: Apache-2.0
//! Free-function implementation of the `exec_command` tool handler.
//!
//! All logic that was previously in the `exec_command` method body of `CodeAnalyzer`
//! lives here, along with the five exclusive private helpers. The `#[tool(...)]`-decorated
//! shim in `lib.rs` extracts state from `&self` and delegates to `exec_command_impl`.

use std::fmt::Write as _;
use std::sync::Arc;

use rmcp::RoleServer;
use rmcp::model::{Annotations, CallToolResult, ContentBlock, ErrorData, TextContent};
use rmcp::service::RequestContext;
use tracing::instrument;

use crate::filters::{CompiledRule, maybe_inject_no_stat};
use crate::metrics::MetricsSender;
use crate::otel::{ClientMetadata, extract_and_set_trace_context};
use crate::shell_write;
use crate::tools::common::{err_to_tool_result, error_meta, no_cache_meta};
use crate::tools::exec_runtime::{DEFAULT_DRAIN_TIMEOUT_MS, run_exec_impl};
use crate::{ExecCommandParams, STDIN_MAX_BYTES, ShellOutput, validate_path};

/// State extracted from `&self` in the `exec_command` shim and passed to `exec_command_impl`.
pub(crate) struct ExecContext {
    pub(crate) seq: u32,
    pub(crate) sid: Option<String>,
    pub(crate) session_id: Option<String>,
    pub(crate) client_name: Option<String>,
    pub(crate) client_version: Option<String>,
    pub(crate) resolved_path: Option<String>,
    pub(crate) filter_table: std::sync::Arc<Vec<CompiledRule>>,
    pub(crate) metrics_tx: MetricsSender,
    pub(crate) t_start: std::time::Instant,
}

/// Phase 1: Resolve working directory and promote cd-prefix.
///
/// Canonicalizes the `working_dir` parameter, validates it is a directory, and
/// promotes a `cd <path> &&` prefix into the working directory when no explicit
/// `working_dir` was provided. Returns `(effective_command, resolved_working_dir_path)`.
#[allow(clippy::result_large_err)]
fn validate_working_dir_phase(
    params: &ExecCommandParams,
    span: &tracing::Span,
) -> Result<(String, Option<std::path::PathBuf>), CallToolResult> {
    // Validate working_dir if provided -- existence + is_dir only, no CWD confinement.
    // exec_command is a shell runner; CWD confinement applies only to edit_overwrite/edit_replace.
    let working_dir_path = if let Some(ref wd) = params.working_dir {
        match std::fs::canonicalize(wd) {
            Ok(p) => {
                if !p.is_dir() {
                    span.record("error", true);
                    span.record("error.type", "invalid_params");
                    let mut result = CallToolResult::error(vec![ContentBlock::text(
                        "working_dir is not a directory; provide an existing directory path"
                            .to_string(),
                    )])
                    .with_meta(Some(no_cache_meta()));
                    result.structured_content = Some(serde_json::json!({
                        "workingDir": wd,
                    }));
                    return Err(result);
                }
                Some(p)
            }
            Err(e) => {
                span.record("error", true);
                span.record("error.type", "invalid_params");
                let mut result = CallToolResult::error(vec![ContentBlock::text(
                    "working_dir is not valid; provide an existing directory path".to_string(),
                )])
                .with_meta(Some(no_cache_meta()));
                result.structured_content = Some(serde_json::json!({
                    "workingDir": wd,
                    "error": e.to_string(),
                }));
                return Err(result);
            }
        }
    } else {
        None
    };

    // Strip leading "cd <path> &&" prefix from command only when provably redundant.
    // - No working_dir: promote the cd path as working_dir (unambiguous).
    // - working_dir already set: strip only if the cd path resolves to the same
    //   directory; otherwise pass the command through unmodified (the cd is
    //   load-bearing, e.g. a multi-step chain like "cd sub && build && cd ../other && build").
    let (effective_command, cd_extracted_path) = strip_cd_prefix(&params.command);
    let (command, working_dir_path) = if let Some(cd_path) = cd_extracted_path {
        if working_dir_path.is_none() {
            // Only promote when the path is a plain absolute literal -- no shell
            // special characters (~, $, -). Relative paths and shell-expanded forms
            // (cd ~, cd $VAR, cd -) must reach the shell unmodified; validate_path
            // cannot resolve them correctly before execution.
            let is_plain_absolute = cd_path.starts_with('/')
                && !cd_path.contains('$')
                && !cd_path.contains('~')
                && cd_path != "-";
            if !is_plain_absolute {
                // Shell-special or relative -- pass through unmodified.
                (params.command.clone(), working_dir_path)
            } else {
                // Promote the cd path as working_dir, run through validation
                match validate_path(cd_path, true) {
                    Ok(p) if p.is_dir() => {
                        tracing::debug!(
                            "exec_command: promoting cd prefix path as working_dir: {}",
                            p.display()
                        );
                        (effective_command.to_owned(), Some(p))
                    }
                    Ok(_) => {
                        span.record("error", true);
                        span.record("error.type", "invalid_params");
                        let mut result = CallToolResult::error(vec![ContentBlock::text(
                            "cd prefix path is not a directory; set working_dir explicitly or use a valid directory path".to_string(),
                        )])
                        .with_meta(Some(no_cache_meta()));
                        result.structured_content = Some(serde_json::json!({
                            "cdPath": cd_path,
                        }));
                        return Err(result);
                    }
                    Err(_) => {
                        span.record("error", true);
                        span.record("error.type", "invalid_params");
                        let mut result = CallToolResult::error(vec![ContentBlock::text(
                            "cd prefix path does not exist or is outside CWD; set working_dir explicitly".to_string(),
                        )])
                        .with_meta(Some(no_cache_meta()));
                        result.structured_content = Some(serde_json::json!({
                            "cdPath": cd_path,
                        }));
                        return Err(result);
                    }
                }
            }
        } else {
            // working_dir is already set -- only strip if the cd path resolves to
            // the same directory (redundant). Otherwise keep the full original command.
            let cd_resolves_to_same = validate_path(cd_path, true)
                .ok()
                .map(|p| Some(&p) == working_dir_path.as_ref())
                .unwrap_or(false);
            if cd_resolves_to_same {
                tracing::debug!(
                    "exec_command: stripped redundant cd prefix; matches explicit working_dir"
                );
                (effective_command.to_owned(), working_dir_path)
            } else {
                // cd path differs from working_dir -- the cd is load-bearing; pass through.
                (params.command.clone(), working_dir_path)
            }
        }
    } else {
        (params.command.clone(), working_dir_path)
    };

    // Inject --no-stat for git pull if not already present
    let command = maybe_inject_no_stat(&command);

    Ok((command, working_dir_path))
}

/// Phase 2: Validate pre-spawn requirements (stdin size, heredocs, drain timeout).
#[allow(clippy::result_large_err)]
fn validate_pre_spawn_phase(
    params: &ExecCommandParams,
    command: &str,
    span: &tracing::Span,
) -> Result<std::time::Duration, CallToolResult> {
    // Validate stdin size cap (1 MB)
    if let Some(ref stdin_content) = params.stdin
        && stdin_content.len() > STDIN_MAX_BYTES
    {
        span.record("error", true);
        span.record("error.type", "invalid_params");
        let result = CallToolResult::error(vec![ContentBlock::text(
            ErrorData::new(
                rmcp::model::ErrorCode::INVALID_PARAMS,
                "stdin exceeds 1 MB limit".to_string(),
                Some(error_meta("validation", false, "reduce stdin content size")),
            )
            .message,
        )])
        .with_meta(Some(no_cache_meta()));
        return Err(result);
    }

    // Validate heredocs before spawning any process
    if let Err(e) = shell_write::validate_heredocs(command, params.stdin.is_some()) {
        span.record("error", true);
        span.record("error.type", "invalid_params");
        return Err(err_to_tool_result(e));
    }

    // Validate drain_timeout_secs: negative values are invalid.
    if let Some(n) = params.drain_timeout_secs
        && n < 0
    {
        span.record("error", true);
        span.record("error.type", "invalid_params");
        let result = CallToolResult::error(vec![ContentBlock::text(
            ErrorData::new(
                rmcp::model::ErrorCode::INVALID_PARAMS,
                "drain_timeout_secs must be >= 0".to_string(),
                Some(error_meta(
                    "validation",
                    false,
                    "use a non-negative value or omit it",
                )),
            )
            .message,
        )])
        .with_meta(Some(no_cache_meta()));
        return Err(result);
    }

    // Compute effective drain timeout
    let drain_dur = match params.drain_timeout_secs {
        Some(n) if n > 0 => std::time::Duration::from_millis(n as u64),
        _ => std::time::Duration::from_millis(DEFAULT_DRAIN_TIMEOUT_MS),
    };

    Ok(drain_dur)
}

/// Phase 3: Spawn and collect output.
///
/// Executes the command, handles timeout, and returns the raw output.
#[allow(clippy::too_many_arguments)]
async fn spawn_and_collect_phase(
    command: String,
    working_dir_path: Option<std::path::PathBuf>,
    params: &ExecCommandParams,
    seq: u32,
    resolved_path_str: Option<&str>,
    filter_table: &Arc<Vec<CompiledRule>>,
    drain_dur: std::time::Duration,
    span: &tracing::Span,
) -> Result<(ShellOutput, u64, u64), CallToolResult> {
    let (output, raw_stdout_bytes, raw_stderr_bytes) = run_exec_impl(
        command,
        working_dir_path,
        params.stdin.clone(),
        seq,
        resolved_path_str,
        filter_table,
        params.timeout_secs,
        drain_dur,
    )
    .await;

    // Short-circuit on timeout: return error before any output processing.
    if output.timed_out {
        span.record("error", true);
        span.record("error.type", "timeout");
        let mut result = CallToolResult::error(vec![ContentBlock::text(
            "Command execution timed out; the process was killed.".to_string(),
        )])
        .with_meta(Some(no_cache_meta()));
        result.structured_content = Some(serde_json::json!({
            "timed_out": true,
            "timeout_secs": params.timeout_secs,
        }));
        return Err(result);
    }

    Ok((output, raw_stdout_bytes, raw_stderr_bytes))
}

/// Phase 4: Format output text and apply truncation limits.
///
/// Returns the formatted output text string.
fn format_shell_output_phase(output: &ShellOutput, params: &ExecCommandParams) -> String {
    // Use interleaved if non-empty; fall back to separated stdout/stderr for empty-output commands
    let output_text = if output.interleaved.is_empty() {
        format!("Stdout:\n{}\n\nStderr:\n{}", output.stdout, output.stderr)
    } else {
        format!("Output:\n{}", output.interleaved)
    };

    // Build truncation notice with slot file paths if present
    let mut truncation_notice = String::new();
    if output.stdout_path.is_some()
        || output.stderr_path.is_some()
        || output.interleaved_path.is_some()
    {
        if let Some(ref p) = output.stdout_path {
            let _ = writeln!(truncation_notice, "Full output available at: {p}");
        }
        if let Some(ref p) = output.stderr_path {
            let _ = writeln!(truncation_notice, "Full stderr available at: {p}");
        }
        if let Some(ref p) = output.interleaved_path {
            let _ = writeln!(truncation_notice, "Full output available at: {p}");
        }
    }

    format!(
        "Command: {}\nExit code: {}\nOutput truncated: {}\n{}{}",
        params.command,
        output
            .exit_code
            .map(|c| c.to_string())
            .unwrap_or_else(|| "null".to_string()),
        output.output_truncated,
        truncation_notice,
        output_text,
    )
}

/// Free-function implementation of the `exec_command` tool handler.
///
/// The `#[tool(...)]`-decorated shim in `lib.rs` extracts state from `&self` into
/// [`ExecContext`] and calls this function.
#[instrument(
    name = "exec_command_impl",
    skip(params, context, ctx),
    fields(
        gen_ai.system = tracing::field::Empty,
        gen_ai.operation.name = tracing::field::Empty,
        gen_ai.tool.name = tracing::field::Empty,
        error = tracing::field::Empty,
        error.type = tracing::field::Empty,
        command = tracing::field::Empty,
        exit_code = tracing::field::Empty,
        output_truncated = tracing::field::Empty,
        mcp.session.id = tracing::field::Empty,
        client.name = tracing::field::Empty,
        client.version = tracing::field::Empty,
        mcp.client.session.id = tracing::field::Empty
    )
)]
pub(crate) async fn exec_command_impl(
    params: ExecCommandParams,
    context: RequestContext<RoleServer>,
    ctx: ExecContext,
) -> Result<CallToolResult, ErrorData> {
    let ExecContext {
        seq,
        sid,
        session_id,
        client_name,
        client_version,
        resolved_path,
        filter_table,
        metrics_tx,
        t_start,
    } = ctx;
    // Extract W3C Trace Context from request _meta if present
    extract_and_set_trace_context(
        Some(&context.meta),
        ClientMetadata {
            session_id,
            client_name,
            client_version,
        },
    );
    let span = tracing::Span::current();
    span.record("gen_ai.system", "mcp");
    span.record("gen_ai.operation.name", "execute_tool");
    span.record("gen_ai.tool.name", "exec_command");
    span.record("command", &params.command);

    let param_path = params.working_dir.clone();
    let working_dir_used = params.working_dir.is_some();
    let stdin_provided = params.stdin.is_some();
    let timeout_configured_ms = params.timeout_secs.map(|s| s * 1000);
    let drain_timeout_ms = params.drain_timeout_secs;

    // Phase 1: Validate working_dir and resolve cd-prefix
    let (command, working_dir_path) = match validate_working_dir_phase(&params, &span) {
        Ok((cmd, wd)) => {
            span.record("command", &cmd);
            (cmd, wd)
        }
        Err(result) => {
            let dur = t_start.elapsed().as_millis().try_into().unwrap_or(u64::MAX);
            metrics_tx.send(
                crate::metrics::MetricEventBuilder::new("exec_command", "error", dur)
                    .param_path_depth(crate::metrics::path_component_count(
                        param_path.as_deref().unwrap_or(""),
                    ))
                    .error_type(Some("invalid_params".to_string()))
                    .session_id(sid)
                    .seq(Some(seq))
                    .output_truncated(Some(false))
                    .stdin_provided(stdin_provided)
                    .timeout_configured_ms(timeout_configured_ms)
                    .drain_timeout_ms(drain_timeout_ms)
                    .working_dir_used(working_dir_used)
                    .build(),
            );
            return Ok(result);
        }
    };

    // Phase 2: Validate pre-spawn requirements
    let drain_dur = match validate_pre_spawn_phase(&params, &command, &span) {
        Ok(dur) => dur,
        Err(result) => {
            let dur = t_start.elapsed().as_millis().try_into().unwrap_or(u64::MAX);
            metrics_tx.send(
                crate::metrics::MetricEventBuilder::new("exec_command", "error", dur)
                    .param_path_depth(crate::metrics::path_component_count(
                        param_path.as_deref().unwrap_or(""),
                    ))
                    .error_type(Some("invalid_params".to_string()))
                    .session_id(sid)
                    .seq(Some(seq))
                    .output_truncated(Some(false))
                    .stdin_provided(stdin_provided)
                    .timeout_configured_ms(timeout_configured_ms)
                    .drain_timeout_ms(drain_timeout_ms)
                    .working_dir_used(working_dir_used)
                    .build(),
            );
            return Ok(result);
        }
    };

    // Phase 3: Spawn and collect
    let resolved_path_str = resolved_path.as_deref();
    let (mut output, raw_stdout_bytes, raw_stderr_bytes) = match spawn_and_collect_phase(
        command.clone(),
        working_dir_path.clone(),
        &params,
        seq,
        resolved_path_str,
        &filter_table,
        drain_dur,
        &span,
    )
    .await
    {
        Ok(o) => o,
        Err(result) => {
            let dur = t_start.elapsed().as_millis().try_into().unwrap_or(u64::MAX);
            metrics_tx.send(
                crate::metrics::MetricEventBuilder::new("exec_command", "error", dur)
                    .param_path_depth(crate::metrics::path_component_count(
                        param_path.as_deref().unwrap_or(""),
                    ))
                    .error_type(Some("timeout".to_string()))
                    .session_id(sid)
                    .seq(Some(seq))
                    .timed_out(true)
                    .output_truncated(Some(false))
                    .stdin_provided(stdin_provided)
                    .timeout_configured_ms(timeout_configured_ms)
                    .drain_timeout_ms(drain_timeout_ms)
                    .working_dir_used(working_dir_used)
                    .build(),
            );
            return Ok(result);
        }
    };

    let exit_code = output.exit_code;
    let output_truncated = output.output_truncated;

    // Record execution results on span
    if let Some(code) = exit_code {
        span.record("exit_code", code);
    }

    // Phase 4: Format output
    let text = format_shell_output_phase(&output, &params);

    // Sync output_truncated to the struct before serialization (fix #1266)
    output.output_truncated = output_truncated;

    span.record("output_truncated", output_truncated);

    // Emit debug event for truncation
    if output_truncated {
        tracing::debug!(truncated = true, message = "output truncated");
    }

    let content_blocks = vec![ContentBlock::Text(
        TextContent::new(text.clone()).with_annotations(Annotations::default().with_priority(0.0)),
    )];

    // Determine if command failed: non-zero exit code.
    // exit_code is None when the post-exit drain times out (background child
    // holding pipes -- command work was done, treat as success) or when the
    // process is externally killed; both cases use unwrap_or(false) to avoid
    // false negatives.
    let command_failed = exit_code.map(|c| c != 0).unwrap_or(false);

    let mut result = if command_failed {
        CallToolResult::error(content_blocks)
    } else {
        CallToolResult::success(content_blocks)
    }
    .with_meta(Some(no_cache_meta()));

    let structured = match serde_json::to_value(&output).map_err(|e| {
        ErrorData::new(
            rmcp::model::ErrorCode::INTERNAL_ERROR,
            format!("serialization failed: {e}"),
            Some(error_meta("internal", false, "report this as a bug")),
        )
    }) {
        Ok(v) => v,
        Err(e) => {
            span.record("error", true);
            span.record("error.type", "internal_error");
            let dur = t_start.elapsed().as_millis().try_into().unwrap_or(u64::MAX);
            metrics_tx.send(
                crate::metrics::MetricEventBuilder::new("exec_command", "error", dur)
                    .param_path_depth(crate::metrics::path_component_count(
                        param_path.as_deref().unwrap_or(""),
                    ))
                    .error_type(Some("internal_error".to_string()))
                    .session_id(sid.clone())
                    .seq(Some(seq))
                    .exit_code(exit_code)
                    .timed_out(output.timed_out)
                    .output_truncated(Some(output_truncated))
                    .stdin_provided(stdin_provided)
                    .timeout_configured_ms(timeout_configured_ms)
                    .drain_timeout_ms(drain_timeout_ms)
                    .working_dir_used(working_dir_used)
                    .build(),
            );
            return Ok(err_to_tool_result(e));
        }
    };

    result.structured_content = Some(structured);
    let dur = t_start.elapsed().as_millis().try_into().unwrap_or(u64::MAX);
    let mut metric_builder = crate::metrics::MetricEventBuilder::new("exec_command", "ok", dur)
        .output_chars(text.len())
        .param_path_depth(crate::metrics::path_component_count(
            param_path.as_deref().unwrap_or(""),
        ))
        .session_id(sid)
        .seq(Some(seq))
        .exit_code(exit_code)
        .timed_out(output.timed_out)
        .output_truncated(Some(output_truncated))
        .chars_threshold_breach(text.len() > 30_000)
        .filter_applied(output.filter_applied.clone())
        .stdin_provided(stdin_provided)
        .timeout_configured_ms(timeout_configured_ms)
        .drain_timeout_ms(drain_timeout_ms)
        .working_dir_used(working_dir_used);
    // Emit approximate raw byte counts only when output_truncated is true and the
    // truncation was not caused by a timeout or drain-abort. output_truncated covers
    // both byte-budget overflow and drain-timeout cases; the drain-abort path forces
    // counters to 0 (unknown), so output_collection_error guards against emitting
    // a misleading zero.
    if output_truncated && !output.timed_out && output.output_collection_error.is_none() {
        metric_builder = metric_builder
            .stdout_bytes_raw(raw_stdout_bytes)
            .stderr_bytes_raw(raw_stderr_bytes);
    }
    metrics_tx.send(metric_builder.build());
    Ok(result)
}

/// Build and configure a tokio::process::Command with stdio, working directory, and resource limits.
/// Strip a leading `cd <path> &&` prefix from a command string.
///
/// Returns `(stripped_command, Some(extracted_path))` when the command starts with
/// `cd <path> &&`. Returns `(cmd, None)` when no `cd ... &&` prefix is found.
///
/// Uses only `str` methods (no regex). Leading whitespace is trimmed before matching.
pub(crate) fn strip_cd_prefix(cmd: &str) -> (&str, Option<&str>) {
    let trimmed = cmd.trim_start();
    let Some(rest) = trimmed.strip_prefix("cd ") else {
        return (cmd, None);
    };
    // Find the && separator
    let Some((path_part, rest_part)) = rest.split_once("&&") else {
        return (cmd, None);
    };
    let path = path_part.trim();
    let stripped = rest_part.trim();
    (stripped, Some(path))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ShellOutput;

    #[test]
    fn test_format_shell_output_stdout_path_hint() {
        // Arrange: ShellOutput with stdout_path set, no stderr or interleaved paths
        let output = ShellOutput {
            stdout: "hello".to_string(),
            stderr: String::new(),
            interleaved: String::new(),
            exit_code: Some(0),
            output_truncated: true,
            output_collection_error: None,
            stdout_path: Some("/tmp/aptu-coder-overflow/slot-0/stdout".to_string()),
            stderr_path: None,
            interleaved_path: None,
            filter_applied: None,
            timed_out: false,
        };
        let params = ExecCommandParams {
            command: "echo hello".to_string(),
            working_dir: None,
            stdin: None,
            timeout_secs: None,
            drain_timeout_secs: None,
        };

        // Act
        let result = format_shell_output_phase(&output, &params);

        // Assert
        assert!(
            result.contains("Full output available at: /tmp/aptu-coder-overflow/slot-0/stdout"),
            "should contain stdout path hint: {result}"
        );
        assert!(
            !result.contains("Full stderr available at:"),
            "should not contain stderr hint when stderr_path is None"
        );
    }

    #[test]
    fn test_format_shell_output_stderr_path_hint() {
        // Arrange: ShellOutput with only stderr_path set
        let output = ShellOutput {
            stdout: String::new(),
            stderr: "error".to_string(),
            interleaved: String::new(),
            exit_code: Some(1),
            output_truncated: true,
            output_collection_error: None,
            stdout_path: None,
            stderr_path: Some("/tmp/aptu-coder-overflow/slot-1/stderr".to_string()),
            interleaved_path: None,
            filter_applied: None,
            timed_out: false,
        };
        let params = ExecCommandParams {
            command: "false".to_string(),
            working_dir: None,
            stdin: None,
            timeout_secs: None,
            drain_timeout_secs: None,
        };

        // Act
        let result = format_shell_output_phase(&output, &params);

        // Assert
        assert!(
            result.contains("Full stderr available at: /tmp/aptu-coder-overflow/slot-1/stderr"),
            "should contain stderr path hint: {result}"
        );
        assert!(
            !result.contains("Full output available at:"),
            "should not contain stdout hint when stdout_path is None"
        );
    }

    #[test]
    fn test_format_shell_output_interleaved_path_hint() {
        // Arrange: ShellOutput with only interleaved_path set
        let output = ShellOutput {
            stdout: String::new(),
            stderr: String::new(),
            interleaved: "output".to_string(),
            exit_code: Some(0),
            output_truncated: true,
            output_collection_error: None,
            stdout_path: None,
            stderr_path: None,
            interleaved_path: Some("/tmp/aptu-coder-overflow/slot-2/interleaved".to_string()),
            filter_applied: None,
            timed_out: false,
        };
        let params = ExecCommandParams {
            command: "echo test".to_string(),
            working_dir: None,
            stdin: None,
            timeout_secs: None,
            drain_timeout_secs: None,
        };

        // Act
        let result = format_shell_output_phase(&output, &params);

        // Assert
        assert!(
            result
                .contains("Full output available at: /tmp/aptu-coder-overflow/slot-2/interleaved"),
            "should contain interleaved path hint: {result}"
        );
    }
}