Skip to main content

lean_ctx/tools/registered/
ctx_shell.rs

1use rmcp::ErrorData;
2use rmcp::model::Tool;
3use serde_json::{Map, Value, json};
4
5use crate::core::ocla::cache_types::{CacheKeyBuilder, ShellCommandKey};
6
7use crate::server::tool_trait::{
8    BackgroundJobState, BackgroundShellOutcome, McpTool, ShellOutcome, ToolContext, ToolOutput,
9    get_bool, get_int, get_str,
10};
11use crate::tool_defs::tool_def;
12
13use super::ctx_shell_background::{format_background_state, redact_shell_output_secrets};
14
15pub struct CtxShellTool;
16
17/// Shell execution must never wait through the general-purpose session-lock
18/// recovery window. The command can run without bookkeeping; cwd validation
19/// cannot, so it fails promptly and lets the client retry.
20const SESSION_LOCK_BUDGET: std::time::Duration = std::time::Duration::from_millis(250);
21
22impl McpTool for CtxShellTool {
23    fn name(&self) -> &'static str {
24        "ctx_shell"
25    }
26
27    fn tool_def(&self) -> Tool {
28        tool_def(
29            "ctx_shell",
30            "WORKFLOW: preferred — auto-compresses output (build/test/log).\n\
31              raw=true for verbatim output; inline=true for moderately-sized verbatim output.\n\
32             [exit:N] on errors (lossless).\n\
33             POLICY: allowlisted read-only path.\n\
34             A [BLOCKED] command is permanent; ctx_execute shares the same allowlist — fix with \
35             `lean-ctx allow <cmd>`.\n\
36             ANTIPATTERN: multi-line scripts, sh/bash script.sh, $var-as-command → ctx_execute \
37             (when exposed).",
38            json!({
39                "type": "object",
40                "properties": {
41                    "command": { "type": "string", "description": "Shell command" },
42                    "raw": { "type": "boolean", "description": "Skip compression (verbatim)" },
43                    "inline": { "type": "boolean", "description": "Return verbatim output inline up to archive.inline_max_bytes; larger output uses the archive/firewall" },
44                    "cwd": { "type": "string", "description": "Working dir (persists across calls)" },
45                    "timeout_ms": { "type": "integer", "description": "Job lifetime in ms (max 3600000) — NOT the inline wait. A command still running at the ~110s foreground cap detaches to a pollable shell_* job and keeps running up to timeout_ms. Overridden by LEAN_CTX_SHELL_TIMEOUT_MS." },
46                    "env": { "type": "object", "description": "Extra env vars", "additionalProperties": { "type": "string" } },
47                    "run_in_background": { "type": "boolean", "description": "Detach immediately and return a job id. The command keeps timeout_ms; poll or cancel with background_action and job_id." },
48                    "background_action": { "type": "string", "enum": ["status", "cancel"], "description": "Inspect or cancel a background ctx_shell job. Evicted/expired jobs return a structured lookup error." },
49                    "job_id": { "type": "string", "description": "Job id returned by run_in_background." }
50                }
51            }),
52        )
53    }
54
55    fn handle(
56        &self,
57        args: &Map<String, Value>,
58        ctx: &ToolContext,
59    ) -> Result<ToolOutput, ErrorData> {
60        if let Some(message) = shell_access_denial(ctx) {
61            return Ok(ToolOutput {
62                shell_outcome: Some(ShellOutcome::Blocked),
63                content_blocks: None,
64                ..ToolOutput::simple(message)
65            });
66        }
67
68        if let Some(action) = get_str(args, "background_action") {
69            let id = get_str(args, "job_id").ok_or_else(|| {
70                ErrorData::invalid_params("job_id is required with background_action", None)
71            })?;
72            let is_cancel = action == "cancel";
73            let state = match action.as_str() {
74                "status" => crate::server::background_shell::status(&id),
75                "cancel" => crate::server::background_shell::cancel(&id),
76                _ => {
77                    return Err(ErrorData::invalid_params(
78                        "background_action must be status or cancel",
79                        None,
80                    ));
81                }
82            };
83            let (text, outcome) = format_background_state(&id, is_cancel, state);
84            return Ok(ToolOutput {
85                shell_outcome: Some(outcome),
86                content_blocks: None,
87                ..ToolOutput::simple(text)
88            });
89        }
90        let command = get_str(args, "command")
91            .ok_or_else(|| ErrorData::invalid_params("command is required", None))?;
92        let timeout_ms = get_int(args, "timeout_ms").and_then(|n| u64::try_from(n).ok());
93
94        // The write-doctrine check (no `>`, `tee`, heredoc-to-file, curl -o, …)
95        // is an MCP-payload-safety convention, not a security boundary, so it is
96        // opt-out via `shell_allow_writes` (#523). The real command gating
97        // (`check_shell_allowlist`, below) is NOT affected by this flag.
98        let config = crate::core::config::Config::load();
99        let write_allow_paths = config.shell_write_allow_paths_effective();
100        let project_root = crate::core::config::Config::find_project_root();
101        if !config.shell_allow_writes_effective()
102            && let Some(rejection) =
103                crate::tools::ctx_shell::validate_command_with_write_allow_paths(
104                    &command,
105                    &write_allow_paths,
106                    project_root.as_deref(),
107                )
108        {
109            // The command never ran — report as a tool error so MCP clients
110            // (guards, retry logic) can detect it programmatically (#389).
111            return Ok(ToolOutput {
112                shell_outcome: Some(ShellOutcome::Blocked),
113                content_blocks: None,
114                ..ToolOutput::simple(rejection)
115            });
116        }
117
118        if let Some((lang, code, remainder)) = detect_heredoc_reroute(&command) {
119            return tokio::task::block_in_place(|| {
120                handle_interpreter_heredoc_reroute(args, ctx, &lang, &code, remainder)
121            });
122        }
123
124        if let Err(msg) = crate::core::shell_allowlist::check_shell_allowlist(&command) {
125            return Ok(ToolOutput {
126                shell_outcome: Some(ShellOutcome::Blocked),
127                content_blocks: None,
128                ..ToolOutput::simple(msg.to_string())
129            });
130        }
131
132        warn_shell_secret_paths(&command);
133
134        // #842: a bare `cat <file>` is better served by ctx_read — it delivers
135        // content inline instead of firewalling/archiving the output, avoiding
136        // a mandatory ctx_expand round-trip for agents with cat-muscle-memory.
137        if let Some(read_path) = detect_bare_cat_file(&command)
138            && let Some(cache_lock) = ctx.cache.as_ref()
139            && let Some(mut cache) = crate::server::bounded_lock::write(cache_lock, "cat_redirect")
140        {
141            let result = crate::tools::ctx_read::handle_with_task_resolved(
142                &mut cache,
143                &read_path,
144                "full",
145                crate::tools::CrpMode::Off,
146                None,
147            );
148            let note = format!(
149                "\n[ctx_shell: bare `cat` redirected to ctx_read for inline delivery. \
150                         Use ctx_read(path=\"{read_path}\") directly next time.]"
151            );
152            let out = format!("{}{note}", result.content);
153            let sent = crate::core::tokens::count_tokens(&out);
154            return Ok(ToolOutput {
155                text: out,
156                original_tokens: sent,
157                saved_tokens: 0,
158                mode: Some("cat-redirect".to_string()),
159                path: Some(read_path),
160                changed: false,
161                shell_outcome: Some(ShellOutcome::Exit(0)),
162                content_blocks: None,
163            });
164        }
165
166        tokio::task::block_in_place(|| {
167            let session_lock = ctx
168                .session
169                .as_ref()
170                .ok_or_else(|| ErrorData::internal_error("session not available", None))?;
171
172            let explicit_cwd = get_str(args, "cwd");
173            let had_explicit_cwd = explicit_cwd.is_some();
174            let guard = crate::server::bounded_lock::read_for(
175                session_lock,
176                "ctx_shell_cwd",
177                SESSION_LOCK_BUDGET,
178            );
179            let (effective_cwd, cwd_jail_reason) =
180                resolve_effective_cwd(guard, explicit_cwd.as_deref())?;
181            // A `cwd` rejected by the project-root jail is silently replaced with
182            // the root (deliberate sandboxing). Surface that swap as a one-line
183            // hint so the caller does not mistake the run dir for the requested
184            // one (#629); appended at the end of the output like the other hints.
185            let cwd_jail_reason_was_none = cwd_jail_reason.is_none();
186            let cwd_jail_hint = cwd_jail_reason.map_or_else(String::new, |reason| {
187                format!(
188                    "\n[cwd: requested path rejected by project-root jail ({reason}) \u{2014} ran in {effective_cwd} instead]"
189                )
190            });
191
192            {
193                let Some(mut session) = crate::server::bounded_lock::write_for(
194                    session_lock,
195                    "ctx_shell_write",
196                    SESSION_LOCK_BUDGET,
197                ) else {
198                    tracing::debug!("[ctx_shell: session lock timeout, proceeding without update]");
199                    let cmd_clone = command.clone();
200                    let cwd_clone = effective_cwd.clone();
201                    let extra_env: std::collections::HashMap<String, String> = args
202                        .get("env")
203                        .and_then(|v| v.as_object())
204                        .map(|obj| {
205                            obj.iter()
206                                .filter_map(|(k, v)| v.as_str().map(|s| (k.clone(), s.to_string())))
207                                .filter(|(k, _)| !is_dangerous_env_key(k))
208                                .collect()
209                        })
210                        .unwrap_or_default();
211                    let (raw_output, exit_code) = crate::server::execute::execute_command_with_env(
212                        &cmd_clone, &cwd_clone, &extra_env, timeout_ms,
213                    );
214                    let output = redact_shell_output_secrets(&raw_output);
215                    // Keep failure reporting consistent on this degraded path:
216                    // same [exit:N] footer and the same structured outcome (#389).
217                    let exit_suffix = match exit_code {
218                        0 => String::new(),
219                        124 => "\n[exit:124 — command timed out]".to_string(),
220                        _ => format!("\n[exit:{exit_code}]"),
221                    };
222                    return Ok(ToolOutput {
223                        shell_outcome: Some(ShellOutcome::Exit(exit_code)),
224                        content_blocks: None,
225                        ..ToolOutput::simple(format!("{output}{exit_suffix}"))
226                    });
227                };
228                // #707: a jail-accepted explicit `cwd` param is the client
229                // telling us where it now works (worktree switches arrive
230                // this way, not as `cd` commands) — persist it so path
231                // resolution's divergence check tracks the live checkout.
232                if had_explicit_cwd && cwd_jail_reason_was_none {
233                    session.note_explicit_cwd(&effective_cwd);
234                }
235                session.update_shell_cwd(&command);
236                let root_missing = session
237                    .project_root
238                    .as_deref()
239                    .is_none_or(|r| r.trim().is_empty());
240                if root_missing {
241                    let home = dirs::home_dir().map(|h| h.to_string_lossy().to_string());
242                    if let Some(root) = crate::core::protocol::detect_project_root(&effective_cwd)
243                        && home.as_deref() != Some(root.as_str())
244                    {
245                        session.project_root = Some(root.clone());
246                        crate::core::index_orchestrator::ensure_all_background(&root);
247                    }
248                }
249            }
250
251            let arg_raw = get_bool(args, "raw").unwrap_or(false);
252            let arg_bypass = get_bool(args, "bypass").unwrap_or(false);
253            let env_disabled = std::env::var("LEAN_CTX_DISABLED").is_ok();
254            let env_raw = std::env::var("LEAN_CTX_RAW").is_ok();
255            let (raw, bypass) = resolve_shell_raw_flags(arg_raw, arg_bypass, env_disabled, env_raw);
256
257            let crp_mode = ctx.crp_mode;
258            let cmd_clone = command.clone();
259            let cwd_clone = effective_cwd;
260            let proactive_block = if raw
261                || !crate::core::profiles::active_profile()
262                    .output_hints
263                    .proactive_context()
264            {
265                None
266            } else {
267                crate::core::relevance_tracker::proactive_context(&format!(
268                    "ctx_shell command={cmd_clone} cwd={cwd_clone}"
269                ))
270            };
271
272            let extra_env: std::collections::HashMap<String, String> = args
273                .get("env")
274                .and_then(|v| v.as_object())
275                .map(|obj| {
276                    obj.iter()
277                        .filter_map(|(k, v)| v.as_str().map(|s| (k.clone(), s.to_string())))
278                        .filter(|(k, _)| !is_dangerous_env_key(k))
279                        .collect()
280                })
281                .unwrap_or_default();
282
283            let inline = get_bool(args, "inline").unwrap_or(false);
284            let shell_cache_key = shell_cache_key(&cmd_clone, &cwd_clone, &extra_env);
285            if !raw
286                && !inline
287                && crate::core::config::Config::load()
288                    .cache
289                    .shell_cache_enabled
290                && let Some(key) = shell_cache_key.as_ref()
291                && let Some(cached) = crate::core::ocla::shell_cache_allowlist::SHELL_RESULT_CACHE
292                    .get(&key.cache_key())
293                    .map(|r| r.clone())
294                && let Ok(value) = serde_json::from_str::<Value>(&cached)
295                && let (Some(text), Some(exit_code)) = (
296                    value.get("text").and_then(Value::as_str),
297                    value.get("exit_code").and_then(Value::as_i64),
298                )
299            {
300                return Ok(ToolOutput {
301                    text: text.to_string(),
302                    original_tokens: crate::core::tokens::count_tokens(text),
303                    saved_tokens: 0,
304                    mode: Some("cross-agent-cache".to_string()),
305                    path: None,
306                    changed: false,
307                    shell_outcome: Some(ShellOutcome::Exit(exit_code as i32)),
308                    content_blocks: None,
309                });
310            }
311
312            // Cross-process delivery: check daemon for results from other IDE tabs
313            if let Some(ref key) = shell_cache_key {
314                let ck = key.cache_key();
315                let validator = key.validator();
316                if let Some(entry) =
317                    crate::core::ocla::cache_delivery::check(&ck, &validator, "ctx_shell")
318                {
319                    let stub = crate::core::ocla::cache_delivery::stub(&entry, "shell command");
320                    return Ok(ToolOutput {
321                        text: stub,
322                        original_tokens: entry.token_count as usize,
323                        saved_tokens: entry.token_count as usize,
324                        mode: Some("cross-agent-cache".to_string()),
325                        path: None,
326                        changed: false,
327                        shell_outcome: None,
328                        content_blocks: None,
329                    });
330                }
331            }
332
333            let auto_background = should_auto_background(&cmd_clone, timeout_ms);
334            if get_bool(args, "run_in_background").unwrap_or(false) || auto_background {
335                let job_id = crate::server::background_shell::start(
336                    cmd_clone, cwd_clone, extra_env, timeout_ms,
337                );
338                let mode = if auto_background {
339                    "auto-background"
340                } else {
341                    "background"
342                };
343                return Ok(ToolOutput {
344                    shell_outcome: Some(ShellOutcome::Background(BackgroundShellOutcome {
345                        state: BackgroundJobState::Running,
346                        exit_code: None,
347                        job_id: job_id.clone(),
348                        archive_id: None,
349                        archive_truncated: None,
350                        captured_chars: None,
351                        archived_chars: None,
352                        summary: format!("{mode} job started"),
353                        is_error: false,
354                        display: None,
355                    })),
356                    content_blocks: None,
357                    ..ToolOutput::simple(format!(
358                        "[{mode}:{job_id} started — use ctx_shell(background_action=\"status\", job_id=\"{job_id}\") to poll or background_action=\"cancel\" to stop it]"
359                    ))
360                });
361            }
362
363            // Foreground runs still detach onto a pollable job if they outlast
364            // the soft cap, so the MCP host's ~120s abort never strands the
365            // result behind an unresolvable task id (#1106).
366            //
367            // #1173: `timeout_ms` is the *job's* lifetime, never the foreground
368            // wait, so it must not raise this cap. Raising it bought no extra
369            // inline wait — the host aborts at ~120s regardless — it only
370            // suppressed our own detach, producing exactly the unresolvable
371            // task id the cap exists to prevent. Separate knobs, one direction:
372            // `LEAN_CTX_SHELL_FG_CAP_MS` moves the cap, `timeout_ms` does not.
373            let soft_cap = std::time::Duration::from_millis(foreground_soft_cap_ms());
374            let progress_sender = ctx.progress_sender.clone();
375            let progress_label: String = cmd_clone.chars().take(60).collect();
376            let cap_secs = soft_cap.as_secs_f64();
377            let on_tick = |elapsed: std::time::Duration| {
378                #[allow(clippy::unwrap_or_default)]
379                if let Some(ref ps) = progress_sender
380                    && let Some(sender) = ps
381                        .lock()
382                        .unwrap_or_else(std::sync::PoisonError::into_inner)
383                        .as_ref()
384                {
385                    sender.send(
386                        elapsed.as_secs_f64(),
387                        Some(cap_secs),
388                        Some(format!(
389                            "ctx_shell: {}s elapsed — {progress_label}",
390                            elapsed.as_secs()
391                        )),
392                    );
393                }
394            };
395            let (raw_output, exit_code) =
396                match crate::server::background_shell::run_foreground_or_detach(
397                    cmd_clone.clone(),
398                    cwd_clone.clone(),
399                    extra_env.clone(),
400                    timeout_ms,
401                    soft_cap,
402                    Some(&on_tick),
403                ) {
404                    crate::server::background_shell::ForegroundResult::Finished {
405                        output,
406                        exit_code,
407                    } => (output, exit_code),
408                    crate::server::background_shell::ForegroundResult::Detached { job_id } => {
409                        return Ok(ToolOutput {
410                            shell_outcome: Some(ShellOutcome::Background(BackgroundShellOutcome {
411                                state: BackgroundJobState::Running,
412                                exit_code: None,
413                                job_id: job_id.clone(),
414                                archive_id: None,
415                                archive_truncated: None,
416                                captured_chars: None,
417                                archived_chars: None,
418                                summary: "auto-detached job is still running".to_string(),
419                                is_error: false,
420                                display: None,
421                            })),
422                            content_blocks: None,
423                            // #1173: a detach is not a failure — the command is
424                            // alive and its output is recoverable, so say so
425                            // rather than leaving the caller to infer a hang.
426                            ..ToolOutput::simple(format!(
427                                "[auto-background:{job_id} still running — passed the {}s foreground cap, not an error; output is kept and delivered by ctx_shell(background_action=\"status\", job_id=\"{job_id}\"), or background_action=\"cancel\" to stop it]",
428                                soft_cap.as_secs()
429                            ))
430                        });
431                    }
432                };
433
434            // Structured diagnostics (#499) — same hook as the CLI path.
435            crate::core::diagnostics_store::record_from_shell(&cmd_clone, &raw_output, exit_code);
436
437            let output = redact_shell_output_secrets(&raw_output);
438
439            let (result_out, original, saved, tee_hint) = if raw || inline {
440                let tokens = crate::core::tokens::count_tokens(&output);
441                (output, tokens, 0, String::new())
442            } else {
443                let _mode_guard = crate::core::savings_footer::ModeGuard::new("shell");
444                let result =
445                    crate::tools::ctx_shell::handle(&cmd_clone, &output, exit_code, crp_mode);
446                let original = crate::core::tokens::count_tokens(&output);
447                let sent = crate::core::tokens::count_tokens(&result);
448                let saved = original.saturating_sub(sent);
449
450                let cfg = crate::core::config::Config::load();
451                // Shared tee policy (#811): identical decision to the CLI path —
452                // `Failures` keys off the real exit code, not a substring match.
453                let timeout_notice_only = is_timeout_notice_only(&output, exit_code);
454                let tee_hint = if crate::shell::tee_policy::should_tee(
455                    &cfg.tee_mode,
456                    exit_code,
457                    output.trim().is_empty() || timeout_notice_only,
458                    crate::shell::tee_policy::output_was_elided(&output, &result),
459                    original,
460                    sent,
461                ) {
462                    crate::shell::save_tee(&cmd_clone, &output)
463                        .map(|p| {
464                            if matches!(cfg.tee_mode, crate::core::config::TeeMode::HighCompression)
465                            {
466                                let pct = crate::shell::tee_policy::savings_pct(original, sent);
467                                // Recovery grammar is path-first: agents without ctx_expand
468                                // can still read the saved artifact directly (#936).
469                                format!(
470                                    "\n[compressed {pct:.0}%: full output at {p} — read it directly (no MCP), or ctx_expand(id=\"{p}\", search=\"…\"|head=N|json_path=\"…\") for a slice]"
471                                )
472                            } else {
473                                format!("\n[full output: {p} — read it directly (no MCP), or ctx_expand(id=\"{p}\")]")
474                            }
475                        })
476                        .unwrap_or_default()
477                } else {
478                    String::new()
479                };
480
481                (result, original, saved, tee_hint)
482            };
483
484            let mode = if bypass {
485                Some("bypass".to_string())
486            } else if raw {
487                Some("raw".to_string())
488            } else {
489                None
490            };
491
492            let shell_mismatch = if cfg!(windows) && !raw {
493                shell_mismatch_hint(&command, &result_out)
494            } else {
495                String::new()
496            };
497
498            let result_out = crate::core::redaction::redact_text_if_enabled(&result_out);
499            // #815: exit 124 = timeout signal (from timeout(1) / lean-ctx
500            // shell timeout). Make it explicit so agents don't confuse a
501            // timed-out command with a successful empty result.
502            let exit_suffix = match exit_code {
503                0 => String::new(),
504                124 => "\n[exit:124 — command timed out]".to_string(),
505                _ => format!("\n[exit:{exit_code}]"),
506            };
507            let nudge = if raw { "" } else { search_tool_nudge(&command) };
508            let final_out = format!(
509                "{result_out}{tee_hint}{shell_mismatch}{cwd_jail_hint}{nudge}{exit_suffix}"
510            );
511            let final_out = if let Some(block) = proactive_block {
512                format!("{final_out}{block}")
513            } else {
514                final_out
515            };
516
517            if !raw
518                && !inline
519                && crate::core::config::Config::load()
520                    .cache
521                    .shell_cache_enabled
522                && let Some(key) = shell_cache_key
523            {
524                let cached = json!({ "text": final_out, "exit_code": exit_code }).to_string();
525                crate::core::ocla::shell_cache_allowlist::SHELL_RESULT_CACHE
526                    .insert(key.cache_key(), cached);
527                // Propagate to cross-process daemon cache
528                crate::core::ocla::cache_delivery::record(
529                    key.cache_key(),
530                    crate::core::ocla::cache_types::DeliveryKind::ShellCommand,
531                    key.validator(),
532                    None,
533                    &final_out,
534                    "ctx_shell",
535                );
536            }
537
538            Ok(ToolOutput {
539                text: final_out,
540                original_tokens: original,
541                saved_tokens: saved,
542                mode,
543                path: None,
544                changed: false,
545                shell_outcome: Some(ShellOutcome::Exit(exit_code)),
546                content_blocks: None,
547            })
548        })
549    }
550}
551
552fn shell_cache_key(
553    command: &str,
554    cwd: &str,
555    env: &std::collections::HashMap<String, String>,
556) -> Option<ShellCommandKey> {
557    if !crate::core::ocla::shell_cache_allowlist::is_cacheable_command(command) {
558        return None;
559    }
560    let mut env_pairs = env.iter().collect::<Vec<_>>();
561    env_pairs.sort_unstable_by(|left, right| left.0.cmp(right.0));
562    let mut canonical_env = String::new();
563    for (name, value) in env_pairs {
564        canonical_env.push_str(name);
565        canonical_env.push('=');
566        canonical_env.push_str(value);
567        canonical_env.push('\n');
568    }
569    Some(ShellCommandKey {
570        command_normalized: crate::core::ocla::shell_cache_allowlist::normalize_command(command),
571        cwd: if std::path::Path::new(cwd).is_absolute() {
572            "$PROJECT_ROOT".to_string()
573        } else {
574            cwd.to_string()
575        },
576        env_hash: blake3::hash(canonical_env.as_bytes()).to_hex().to_string(),
577    })
578}
579
580/// Deny shell execution for explicitly restricted MCP clients. Missing client
581/// context remains allowed so existing integrations retain their current access.
582fn shell_access_denial(ctx: &ToolContext) -> Option<String> {
583    if let Some(role) = ctx.client_role.as_deref()
584        && (role.eq_ignore_ascii_case("untrusted") || role.eq_ignore_ascii_case("readonly"))
585    {
586        return Some(format!(
587            "[SHELL ACCESS DENIED] ctx_shell is unavailable to MCP clients with role '{role}'."
588        ));
589    }
590
591    if ctx.shell_access == Some(false) {
592        return Some(
593            "[SHELL ACCESS DENIED] ctx_shell requires shell_access=true in the MCP session/request context."
594                .to_string(),
595        );
596    }
597
598    None
599}
600
601fn resolve_effective_cwd(
602    session: Option<tokio::sync::OwnedRwLockReadGuard<crate::core::session::SessionState>>,
603    explicit_cwd: Option<&str>,
604) -> Result<(String, Option<String>), ErrorData> {
605    match session {
606        Some(session) => Ok(session.effective_cwd_checked(explicit_cwd)),
607        None => Err(ErrorData::internal_error(
608            "session lock timeout — cannot validate working directory",
609            None,
610        )),
611    }
612}
613
614#[allow(clippy::fn_params_excessive_bools)]
615fn resolve_shell_raw_flags(
616    arg_raw: bool,
617    arg_bypass: bool,
618    _env_disabled: bool,
619    env_raw: bool,
620) -> (bool, bool) {
621    let bypass = arg_bypass || env_raw;
622    let raw = arg_raw || bypass;
623    (raw, bypass)
624}
625
626/// A timeout notice is framework metadata, not recoverable command output. Do
627/// not archive it as a tee artifact: expanding it cannot recover any bytes (#995).
628///
629/// Keyed on what precedes the marker rather than on the notice's exact shape,
630/// so enriching it (the idle-timeout wording, the still-running segment list)
631/// cannot silently turn every timeout back into an archived artifact (#1173).
632fn is_timeout_notice_only(output: &str, exit_code: i32) -> bool {
633    exit_code == 124
634        && crate::server::execute::output_before_timeout_marker(output).is_some_and(str::is_empty)
635}
636
637fn search_tool_nudge(command: &str) -> &'static str {
638    let cmd = command.trim();
639    let first_word = cmd.split_whitespace().next().unwrap_or("");
640    if !cmd.contains('|') {
641        match first_word {
642            "grep" | "rg" | "egrep" | "fgrep" | "ag" => {
643                return "\n[hint: use ctx_search for structured, cached results with symbol/semantic modes]";
644            }
645            "find" => {
646                return "\n[hint: use ctx_glob or ctx_tree for structured file discovery]";
647            }
648            "ls" | "exa" | "eza" => {
649                return "\n[hint: use ctx_tree for structured directory listing]";
650            }
651            _ => {}
652        }
653    }
654    ""
655}
656
657fn shell_mismatch_hint(command: &str, output: &str) -> String {
658    let shell = crate::shell::shell_name();
659    let is_posix = matches!(shell.as_str(), "bash" | "sh" | "zsh" | "fish");
660    let has_error = output.contains("is not recognized")
661        || output.contains("not found")
662        || output.contains("command not found");
663
664    if !has_error {
665        return String::new();
666    }
667
668    let powershell_cmds = [
669        "Get-Content",
670        "Select-Object",
671        "Get-ChildItem",
672        "Set-Location",
673        "Where-Object",
674        "ForEach-Object",
675        "Select-String",
676        "Invoke-Expression",
677        "Write-Output",
678    ];
679    let uses_powershell = powershell_cmds
680        .iter()
681        .any(|c| command.contains(c) || command.contains(&c.to_lowercase()));
682
683    if is_posix && uses_powershell {
684        format!(
685            "\n[shell: {shell} — use POSIX commands (cat, head, grep, find, ls) not PowerShell cmdlets]"
686        )
687    } else {
688        String::new()
689    }
690}
691
692fn is_dangerous_env_key(key: &str) -> bool {
693    const BLOCKED: &[&str] = &[
694        // Dynamic linker injection
695        "LD_PRELOAD",
696        "LD_LIBRARY_PATH",
697        "DYLD_INSERT_LIBRARIES",
698        "DYLD_LIBRARY_PATH",
699        "DYLD_FRAMEWORK_PATH",
700        // Shell re-entry / startup injection
701        "BASH_ENV",
702        "ENV",
703        "PROMPT_COMMAND",
704        "SHELL",
705        "IFS",
706        "CDPATH",
707        // Binary resolution hijacking
708        "PATH",
709        "GIT_EXEC_PATH",
710        "GIT_SSH",
711        "GIT_SSH_COMMAND",
712        // Identity / home directory manipulation
713        "HOME",
714        "USER",
715        "LOGNAME",
716        "XDG_CONFIG_HOME",
717        "XDG_DATA_HOME",
718        "XDG_STATE_HOME",
719        "XDG_CACHE_HOME",
720        // Language runtime search path hijacking
721        "PYTHONPATH",
722        "PYTHONSTARTUP",
723        "PYTHONHOME",
724        "NODE_PATH",
725        "NODE_OPTIONS",
726        "RUBYOPT",
727        "RUBYLIB",
728        "GEM_PATH",
729        "GEM_HOME",
730        "PERL5LIB",
731        "PERL5OPT",
732        "CLASSPATH",
733        "JAVA_HOME",
734        "CARGO_HOME",
735        "RUSTUP_HOME",
736        "GOPATH",
737        "GOROOT",
738    ];
739    let upper = key.to_uppercase();
740    if BLOCKED.contains(&upper.as_str()) {
741        return true;
742    }
743    if upper.starts_with("LD_") && upper.ends_with("_PATH") {
744        return true;
745    }
746    // Block all lean-ctx config overrides from env
747    if upper.starts_with("LEAN_CTX_") || upper.starts_with("LCTX_") {
748        return true;
749    }
750    false
751}
752
753/// Warn when shell reads secret-like paths via cat/head/tail/less/more.
754/// WARN-ONLY: command still executes, this is purely observational.
755fn warn_shell_secret_paths(command: &str) {
756    const READ_CMDS: &[&str] = &["cat", "head", "tail", "less", "more", "bat"];
757    let segments = crate::core::shell_allowlist::extract_all_commands_pub(command);
758    for seg in &segments {
759        let trimmed = seg.trim();
760        let tokens = crate::core::shell_allowlist::shell_tokenize(trimmed);
761        if tokens.is_empty() {
762            continue;
763        }
764        let base = tokens[0]
765            .rsplit('/')
766            .next()
767            .unwrap_or(&tokens[0])
768            .to_string();
769        if !READ_CMDS.contains(&base.as_str()) {
770            continue;
771        }
772        for tok in &tokens[1..] {
773            if tok.starts_with('-') {
774                continue;
775            }
776            let path = std::path::Path::new(tok.as_str());
777            if crate::core::io_boundary::is_secret_like(path).is_some() {
778                tracing::warn!(
779                    "[SECURITY] Shell reading secret-like path: {tok} (command: {base})"
780                );
781            }
782        }
783    }
784}
785
786/// The Codex MCP client abandons a tool call after five minutes. A Cargo test
787/// with an explicit five-minute-or-longer shell timeout cannot reliably finish
788/// inside that transport deadline (and can wait on Cargo's target lock), so
789/// detach it and return a pollable job instead.
790fn should_auto_background(command: &str, timeout_ms: Option<u64>) -> bool {
791    timeout_ms.is_some_and(|timeout| timeout >= 300_000)
792        && command
793            .lines()
794            .any(|line| line.trim_start().starts_with("cargo test"))
795}
796
797/// Foreground wait budget before a still-running command is detached into a
798/// pollable background job. Kept below the MCP host's ~120s tool-call abort so
799/// the caller always receives a real `shell_*` job id instead of an
800/// unresolvable task id (#1106). Override with `LEAN_CTX_SHELL_FG_CAP_MS`.
801fn foreground_soft_cap_ms() -> u64 {
802    std::env::var("LEAN_CTX_SHELL_FG_CAP_MS")
803        .ok()
804        .and_then(|v| v.parse().ok())
805        .filter(|&ms| ms > 0)
806        .unwrap_or(110_000)
807}
808
809/// Map an interpreter binary to a `ctx_execute` language name.
810fn interpreter_to_execute_language(base: &str) -> Option<&'static str> {
811    match base {
812        "python" | "python2" | "python3" => Some("python"),
813        "node" => Some("javascript"),
814        "ruby" => Some("ruby"),
815        _ => None,
816    }
817}
818
819fn is_env_assignment_token(token: &str) -> bool {
820    let unquoted: String = token.chars().filter(|c| *c != '"' && *c != '\'').collect();
821    unquoted.contains('=')
822        && !unquoted.starts_with('-')
823        && !unquoted.starts_with('/')
824        && !unquoted.starts_with('.')
825}
826
827/// Quote-aware scan for compound operators that would invalidate a reroute.
828fn prelude_has_compound_operator(prelude: &str) -> bool {
829    let bytes = prelude.as_bytes();
830    let len = bytes.len();
831    let mut i = 0;
832    let mut in_single = false;
833    let mut in_double = false;
834    while i < len {
835        let ch = bytes[i];
836        if in_single {
837            if ch == b'\'' {
838                in_single = false;
839            }
840            i += 1;
841            continue;
842        }
843        if in_double {
844            if ch == b'\\' && i + 1 < len {
845                i += 2;
846            } else {
847                if ch == b'"' {
848                    in_double = false;
849                }
850                i += 1;
851            }
852            continue;
853        }
854        match ch {
855            b'\'' => {
856                in_single = true;
857                i += 1;
858            }
859            b'"' => {
860                in_double = true;
861                i += 1;
862            }
863            b';' | b'|' | b'&' | b'(' | b'{' => return true,
864            _ => i += 1,
865        }
866    }
867    false
868}
869
870/// Detect interpreter heredoc patterns and extract the language + code body.
871/// Returns `Some((language, code, remainder))` where remainder is any command
872/// after the heredoc terminator that still needs shell execution.
873fn detect_heredoc_reroute(command: &str) -> Option<(String, String, Option<String>)> {
874    if !command.contains("<<") {
875        return None;
876    }
877
878    let lines: Vec<&str> = command.lines().collect();
879    if lines.is_empty() {
880        return None;
881    }
882
883    let first_line = lines[0];
884    let delims = crate::core::shell_allowlist::heredoc_delims(first_line, false);
885    if delims.len() != 1 {
886        return None;
887    }
888    let delim = delims[0].clone();
889
890    let heredoc_pos = find_heredoc_operator(first_line)?;
891    let prelude = first_line[..heredoc_pos].trim();
892    if prelude_has_compound_operator(prelude) {
893        return None;
894    }
895
896    let language = parse_interpreter_heredoc_prelude(prelude)?.to_string();
897
898    if has_trailing_tokens_after_heredoc_delim(first_line, heredoc_pos) {
899        return None;
900    }
901
902    let mut body = String::new();
903    let mut remainder_start: Option<usize> = None;
904    for (idx, line) in lines.iter().enumerate().skip(1) {
905        if line.trim_start_matches('\t').trim() == delim {
906            remainder_start = Some(idx + 1);
907            break;
908        }
909        if !body.is_empty() {
910            body.push('\n');
911        }
912        body.push_str(line);
913    }
914    let remainder_start = remainder_start?;
915    let remainder = if remainder_start < lines.len() {
916        let rest = lines[remainder_start..].join("\n");
917        let rest = rest.trim();
918        if rest.is_empty() {
919            None
920        } else {
921            Some(rest.to_string())
922        }
923    } else {
924        None
925    };
926
927    Some((language, body, remainder))
928}
929
930fn find_heredoc_operator(line: &str) -> Option<usize> {
931    let bytes = line.as_bytes();
932    let len = bytes.len();
933    let mut i = 0;
934    let mut in_single = false;
935    let mut in_double = false;
936    while i < len {
937        let ch = bytes[i];
938        if in_single {
939            if ch == b'\'' {
940                in_single = false;
941            }
942            i += 1;
943            continue;
944        }
945        if in_double {
946            if ch == b'\\' && i + 1 < len {
947                i += 2;
948            } else {
949                if ch == b'"' {
950                    in_double = false;
951                }
952                i += 1;
953            }
954            continue;
955        }
956        match ch {
957            b'\'' => {
958                in_single = true;
959                i += 1;
960            }
961            b'"' => {
962                in_double = true;
963                i += 1;
964            }
965            b'<' if i + 1 < len && bytes[i + 1] == b'<' => {
966                if i + 2 < len && bytes[i + 2] == b'<' {
967                    i += 3;
968                    continue;
969                }
970                return Some(i);
971            }
972            _ => i += 1,
973        }
974    }
975    None
976}
977
978fn has_trailing_tokens_after_heredoc_delim(line: &str, heredoc_pos: usize) -> bool {
979    let bytes = line.as_bytes();
980    let mut i = heredoc_pos + 2;
981    if i < bytes.len() && bytes[i] == b'-' {
982        i += 1;
983    }
984    while i < bytes.len() && (bytes[i] == b' ' || bytes[i] == b'\t') {
985        i += 1;
986    }
987    let Some((_, _, next)) = crate::core::shell_allowlist::read_heredoc_delim(bytes, i) else {
988        return true;
989    };
990    !line[next..].trim().is_empty()
991}
992
993fn parse_interpreter_heredoc_prelude(prelude: &str) -> Option<&'static str> {
994    let tokens = crate::core::shell_allowlist::shell_tokenize(prelude.trim());
995    let mut idx = 0;
996    while idx < tokens.len() && is_env_assignment_token(&tokens[idx]) {
997        idx += 1;
998    }
999    if idx >= tokens.len() {
1000        return None;
1001    }
1002    let base = tokens[idx]
1003        .rsplit('/')
1004        .next()
1005        .unwrap_or(tokens[idx].as_str());
1006    let language = interpreter_to_execute_language(base)?;
1007    idx += 1;
1008    match tokens.get(idx) {
1009        None => Some(language),
1010        Some(dash) if dash == "-" => {
1011            if tokens.len() == idx + 1 {
1012                Some(language)
1013            } else {
1014                None
1015            }
1016        }
1017        Some(_) => None,
1018    }
1019}
1020
1021/// The one working directory both halves of a rerouted heredoc call run in.
1022///
1023/// Resolution goes through the session so an explicit `cwd` is validated
1024/// against the configured roots, exactly as the non-rerouted path does. A `cwd`
1025/// the caller named that cannot be validated is an error, never a silent
1026/// substitution (#1666).
1027///
1028/// `Ok(None)` means only that no directory could be established without a
1029/// session. The heredoc-only path never needed one and must keep working; the
1030/// shell remainder always required a session and keeps requiring it.
1031fn resolve_reroute_cwd(
1032    ctx: &ToolContext,
1033    explicit_cwd: Option<&str>,
1034) -> Result<Option<String>, ErrorData> {
1035    let Some(session_lock) = ctx.session.as_ref() else {
1036        if explicit_cwd.is_some() {
1037            return Err(ErrorData::internal_error(
1038                "session not available — cannot validate the requested working directory",
1039                None,
1040            ));
1041        }
1042        return Ok(None);
1043    };
1044    let guard =
1045        crate::server::bounded_lock::read_for(session_lock, "ctx_shell_cwd", SESSION_LOCK_BUDGET);
1046    let (cwd, _) = resolve_effective_cwd(guard, explicit_cwd)?;
1047    Ok(Some(cwd))
1048}
1049
1050fn handle_interpreter_heredoc_reroute(
1051    args: &Map<String, Value>,
1052    ctx: &ToolContext,
1053    language: &str,
1054    code: &str,
1055    remainder: Option<String>,
1056) -> Result<ToolOutput, ErrorData> {
1057    let timeout_ms = get_int(args, "timeout_ms").and_then(|n| u64::try_from(n).ok());
1058    let timeout_secs = timeout_ms.map(|ms| ms.div_ceil(1000).max(1));
1059
1060    // #1666: resolve the working directory *before* the interpreter runs. The
1061    // shell remainder below always ran in the call's `cwd`; the rerouted
1062    // interpreter ran wherever the server process happened to sit. One tool
1063    // call, two directories — and a script using relative paths silently read
1064    // and wrote the wrong tree while reporting success.
1065    let explicit_cwd = get_str(args, "cwd");
1066    let exec_cwd = resolve_reroute_cwd(ctx, explicit_cwd.as_deref())?;
1067
1068    let (exec_text, exec_outcome) = crate::tools::ctx_execute::handle_in(
1069        language,
1070        code,
1071        None,
1072        timeout_secs,
1073        exec_cwd.as_deref().map(std::path::Path::new),
1074    );
1075    let reroute_note = format!(
1076        "\n[ctx_shell: interpreter heredoc auto-rerouted to ctx_execute(language=\"{language}\")]"
1077    );
1078    let exec_text = crate::core::redaction::redact_text_if_enabled(&exec_text);
1079
1080    let Some(rest_cmd) = remainder else {
1081        return Ok(ToolOutput {
1082            text: format!("{exec_text}{reroute_note}"),
1083            original_tokens: crate::core::tokens::count_tokens(&exec_text),
1084            saved_tokens: 0,
1085            mode: Some("heredoc-reroute".to_string()),
1086            path: None,
1087            changed: false,
1088            shell_outcome: Some(exec_outcome),
1089            content_blocks: None,
1090        });
1091    };
1092
1093    if let Err(msg) = crate::core::shell_allowlist::check_shell_allowlist(&rest_cmd) {
1094        let blocked =
1095            format!("{exec_text}{reroute_note}\n\n[remainder blocked by shell allowlist]\n{msg}");
1096        return Ok(ToolOutput {
1097            shell_outcome: Some(ShellOutcome::Blocked),
1098            content_blocks: None,
1099            ..ToolOutput::simple(blocked)
1100        });
1101    }
1102
1103    // Unchanged from before #1666: running the shell remainder requires a
1104    // validated working directory.
1105    let effective_cwd =
1106        exec_cwd.ok_or_else(|| ErrorData::internal_error("session not available", None))?;
1107
1108    let extra_env: std::collections::HashMap<String, String> = args
1109        .get("env")
1110        .and_then(|v| v.as_object())
1111        .map(|obj| {
1112            obj.iter()
1113                .filter_map(|(k, v)| v.as_str().map(|s| (k.clone(), s.to_string())))
1114                .filter(|(k, _)| !is_dangerous_env_key(k))
1115                .collect()
1116        })
1117        .unwrap_or_default();
1118
1119    let (shell_raw, shell_exit) = crate::server::execute::execute_command_with_env(
1120        &rest_cmd,
1121        &effective_cwd,
1122        &extra_env,
1123        timeout_ms,
1124    );
1125    let shell_output = redact_shell_output_secrets(&shell_raw);
1126    let arg_raw = get_bool(args, "raw").unwrap_or(false);
1127    let arg_bypass = get_bool(args, "bypass").unwrap_or(false);
1128    let env_disabled = std::env::var("LEAN_CTX_DISABLED").is_ok();
1129    let env_raw = std::env::var("LEAN_CTX_RAW").is_ok();
1130    let (raw, _) = resolve_shell_raw_flags(arg_raw, arg_bypass, env_disabled, env_raw);
1131
1132    let shell_text = if raw {
1133        shell_output
1134    } else {
1135        crate::tools::ctx_shell::handle(&rest_cmd, &shell_output, shell_exit, ctx.crp_mode)
1136    };
1137    let shell_text = crate::core::redaction::redact_text_if_enabled(&shell_text);
1138    let exit_suffix = match shell_exit {
1139        0 => String::new(),
1140        124 => "\n[exit:124 — command timed out]".to_string(),
1141        _ => format!("\n[exit:{shell_exit}]"),
1142    };
1143
1144    let combined = format!(
1145        "{exec_text}{reroute_note}\n\n[heredoc remainder via ctx_shell]\n{shell_text}{exit_suffix}"
1146    );
1147    let token_count = crate::core::tokens::count_tokens(&combined);
1148    Ok(ToolOutput {
1149        text: combined,
1150        original_tokens: token_count,
1151        saved_tokens: 0,
1152        mode: Some("heredoc-reroute".to_string()),
1153        path: None,
1154        changed: false,
1155        shell_outcome: Some(ShellOutcome::Exit(shell_exit)),
1156        content_blocks: None,
1157    })
1158}
1159
1160/// #842: detect a bare `cat <single_file>` command (no pipes, redirects, flags).
1161fn detect_bare_cat_file(command: &str) -> Option<String> {
1162    let trimmed = command.trim();
1163    let rest = trimmed.strip_prefix("cat ")?;
1164    let rest = rest.trim();
1165    if rest.is_empty()
1166        || rest.contains('|')
1167        || rest.contains('>')
1168        || rest.contains('<')
1169        || rest.contains(';')
1170        || rest.contains('&')
1171        || rest.contains('$')
1172        || rest.starts_with('-')
1173    {
1174        return None;
1175    }
1176    let parts: Vec<&str> = rest.split_whitespace().collect();
1177    if parts.len() != 1 {
1178        return None;
1179    }
1180    let file_path = parts[0].trim_matches(|c: char| c == '\'' || c == '"');
1181    if file_path.is_empty() {
1182        return None;
1183    }
1184    Some(file_path.to_string())
1185}
1186
1187#[cfg(test)]
1188mod tests {
1189    use super::{
1190        CtxShellTool, detect_heredoc_reroute, format_background_state, is_timeout_notice_only,
1191        resolve_effective_cwd, shell_access_denial, should_auto_background,
1192    };
1193    use crate::server::background_shell::JobState;
1194    use crate::server::tool_trait::{
1195        BackgroundJobState, BackgroundShellOutcome, McpTool, ShellOutcome, ToolContext,
1196    };
1197
1198    fn background(outcome: ShellOutcome) -> BackgroundShellOutcome {
1199        let ShellOutcome::Background(outcome) = outcome else {
1200            panic!("expected a background outcome");
1201        };
1202        outcome
1203    }
1204
1205    /// #1246: a cancel must never come back as a tool error, and must not read
1206    /// like a status poll that did nothing.
1207    ///
1208    /// #1674: the second half of that only became true here. This asserted
1209    /// `Running` — the very value that made a cancel indistinguishable from a
1210    /// poll, against the intent stated one line above. #1246 fixed the
1211    /// error-reporting half and left the state; the state is the half the
1212    /// caller reads.
1213    #[test]
1214    fn cancel_is_acknowledged_and_never_reports_a_failure() {
1215        let running = JobState::Running {
1216            output: String::new(),
1217        };
1218        let (text, outcome) = format_background_state("shell_x", true, Some(running.clone()));
1219        let outcome = background(outcome);
1220        assert!(!outcome.is_error);
1221        assert_eq!(outcome.state, BackgroundJobState::Cancelled);
1222        assert_eq!(outcome.exit_code, None);
1223        assert!(text.is_empty());
1224        assert!(
1225            outcome
1226                .display
1227                .as_ref()
1228                .is_some_and(|display| display.header.contains("cancel requested"))
1229        );
1230
1231        // A status poll of the same state keeps the old wording.
1232        let (text, outcome) = format_background_state("shell_x", false, Some(running));
1233        let outcome = background(outcome);
1234        assert!(!outcome.is_error);
1235        assert_eq!(outcome.state, BackgroundJobState::Running);
1236        assert!(text.is_empty());
1237        assert!(
1238            outcome
1239                .display
1240                .as_ref()
1241                .is_some_and(|display| display.header == "[background:shell_x running]")
1242        );
1243
1244        // The terminal child code is data; the requested cancel remains a
1245        // successful tool action even though structuredContent keeps 130.
1246        let (text, outcome) = format_background_state(
1247            "shell_x",
1248            true,
1249            Some(JobState::Cancelled {
1250                output: "[cancelled: command stopped on request]".to_string(),
1251            }),
1252        );
1253        let outcome = background(outcome);
1254        assert!(!outcome.is_error);
1255        assert_eq!(outcome.state, BackgroundJobState::Cancelled);
1256        assert_eq!(outcome.exit_code, Some(130));
1257        assert!(text.contains("[cancelled: command stopped on request]"));
1258        assert!(
1259            outcome
1260                .display
1261                .as_ref()
1262                .and_then(|display| display.footer.as_deref())
1263                .is_some_and(|footer| footer == "[cancelled: shell_x, exit 130]")
1264        );
1265
1266        // Idempotent: already finished, or finished and pruned.
1267        let finished = JobState::Completed {
1268            output: "boom".to_string(),
1269            exit_code: 1,
1270        };
1271        let cancelled_finished =
1272            background(format_background_state("shell_x", true, Some(finished.clone())).1);
1273        assert!(!cancelled_finished.is_error);
1274        assert_eq!(cancelled_finished.state, BackgroundJobState::Failed);
1275        assert_eq!(cancelled_finished.exit_code, Some(1));
1276
1277        let polled_finished =
1278            background(format_background_state("shell_x", false, Some(finished)).1);
1279        assert!(polled_finished.is_error);
1280        assert_eq!(polled_finished.state, BackgroundJobState::Failed);
1281        assert_eq!(polled_finished.exit_code, Some(1));
1282
1283        let missing_cancel = format_background_state("shell_x", true, None).1;
1284        assert!(!missing_cancel.is_error());
1285        assert_eq!(missing_cancel, ShellOutcome::Exit(0));
1286
1287        let missing_status = format_background_state("shell_x", false, None).1;
1288        assert!(missing_status.is_error());
1289        assert!(matches!(
1290            missing_status,
1291            ShellOutcome::BackgroundLookupError(_)
1292        ));
1293    }
1294
1295    #[test]
1296    fn long_cargo_test_is_auto_backgrounded() {
1297        assert!(should_auto_background(
1298            "cargo test --lib a\ncargo test --lib b",
1299            Some(3_600_000)
1300        ));
1301        assert!(should_auto_background("cargo test --lib a", Some(300_000)));
1302        assert!(!should_auto_background("cargo test --lib a", Some(299_999)));
1303    }
1304
1305    #[test]
1306    fn timeout_notice_without_child_output_is_not_recoverable() {
1307        assert!(is_timeout_notice_only(
1308            "ERROR: command timed out after 200ms",
1309            124
1310        ));
1311        assert!(is_timeout_notice_only(
1312            "  ERROR: command timed out after 200ms\n",
1313            124
1314        ));
1315        assert!(!is_timeout_notice_only(
1316            "useful output\nERROR: command timed out after 200ms",
1317            124
1318        ));
1319        assert!(!is_timeout_notice_only(
1320            "ERROR: command timed out after 200ms",
1321            1
1322        ));
1323        // #1173: the notice now carries the idle wording and the still-running
1324        // segment list. It is still pure metadata — nothing to recover — so it
1325        // must not become a tee artifact just because it grew.
1326        assert!(is_timeout_notice_only(
1327            "ERROR: command timed out after 200ms without new output\n\
1328             [still running at timeout: sleep 300]",
1329            124
1330        ));
1331        assert!(!is_timeout_notice_only(
1332            "useful output\nERROR: command timed out after 200ms\n\
1333             [still running at timeout: sleep 300]",
1334            124
1335        ));
1336        // Exit 124 from something that is not our watchdog carries no marker.
1337        assert!(!is_timeout_notice_only("some tool output", 124));
1338    }
1339
1340    #[test]
1341    fn unavailable_session_lock_rejects_explicit_cwd() {
1342        let error = resolve_effective_cwd(None, Some("/tmp/unvalidated"))
1343            .expect_err("an unavailable session lock must reject an unvalidated cwd");
1344        assert!(
1345            error.message.contains("cannot validate working directory"),
1346            "{error:?}"
1347        );
1348    }
1349
1350    #[test]
1351    fn untrusted_and_readonly_clients_cannot_run_shell_commands() {
1352        for role in ["untrusted", "readonly"] {
1353            let ctx = ToolContext {
1354                client_role: Some(role.to_string()),
1355                ..ToolContext::default()
1356            };
1357            let output = CtxShellTool
1358                .handle(&serde_json::Map::new(), &ctx)
1359                .expect("role denial must be a tool result");
1360
1361            assert_eq!(output.shell_outcome, Some(ShellOutcome::Blocked));
1362            assert!(
1363                output.text.contains("SHELL ACCESS DENIED"),
1364                "{role}: {}",
1365                output.text
1366            );
1367            assert!(output.text.contains(role), "{role}: {}", output.text);
1368        }
1369    }
1370
1371    #[test]
1372    fn absent_shell_context_preserves_default_access() {
1373        assert!(shell_access_denial(&ToolContext::default()).is_none());
1374    }
1375
1376    #[test]
1377    fn explicitly_disabled_shell_access_blocks_the_request() {
1378        let ctx = ToolContext {
1379            shell_access: Some(false),
1380            ..ToolContext::default()
1381        };
1382        let output = CtxShellTool
1383            .handle(&serde_json::Map::new(), &ctx)
1384            .expect("shell-access denial must be a tool result");
1385
1386        assert_eq!(output.shell_outcome, Some(ShellOutcome::Blocked));
1387        assert!(output.text.contains("shell_access=true"), "{}", output.text);
1388    }
1389
1390    #[test]
1391    fn detect_heredoc_reroute_python_quoted() {
1392        let cmd = "python3 - <<'PY'\nprint(1)\nPY";
1393        let (lang, code, rest) = detect_heredoc_reroute(cmd).expect("must detect python heredoc");
1394        assert_eq!(lang, "python");
1395        assert_eq!(code, "print(1)");
1396        assert!(rest.is_none());
1397    }
1398
1399    #[test]
1400    fn detect_heredoc_reroute_python_with_remainder() {
1401        let cmd = "python3 <<'PY'\nprint(1)\nPY\nnode --test file.js";
1402        let (lang, code, rest) = detect_heredoc_reroute(cmd).expect("must detect split heredoc");
1403        assert_eq!(lang, "python");
1404        assert_eq!(code, "print(1)");
1405        assert_eq!(rest.as_deref(), Some("node --test file.js"));
1406    }
1407
1408    #[test]
1409    fn detect_heredoc_reroute_unquoted_and_tab_stripped() {
1410        let unquoted = "ruby <<EOF\nputs 1\nEOF";
1411        let (lang, code, rest) = detect_heredoc_reroute(unquoted).unwrap();
1412        assert_eq!(lang, "ruby");
1413        assert_eq!(code, "puts 1");
1414        assert!(rest.is_none());
1415
1416        let tabbed = "python3 <<-\tSCRIPT\n\tprint('ok')\nSCRIPT";
1417        let (lang, code, rest) = detect_heredoc_reroute(tabbed).unwrap();
1418        assert_eq!(lang, "python");
1419        assert_eq!(code, "\tprint('ok')");
1420        assert!(rest.is_none());
1421    }
1422
1423    #[test]
1424    fn detect_heredoc_reroute_rejects_compound_prefix() {
1425        assert!(detect_heredoc_reroute("echo hi; python3 <<'PY'\nx\nPY").is_none());
1426        assert!(detect_heredoc_reroute("python3 -c 'print(1)'").is_none());
1427        assert!(detect_heredoc_reroute("python3 <<'PY' | cat\nx\nPY").is_none());
1428    }
1429}