Skip to main content

lean_ctx_server/tools/registered/
ctx_shell.rs

1// SPDX-License-Identifier: Apache-2.0
2use rmcp::ErrorData;
3use rmcp::model::Tool;
4use serde_json::{Map, Value, json};
5
6use crate::server::tool_trait::{
7    BackgroundJobState, BackgroundShellOutcome, McpTool, ShellOutcome, ToolContext, ToolOutput,
8    get_bool, get_int, get_str,
9};
10use lean_ctx::tool_defs::tool_def;
11
12use super::ctx_shell_background::{format_background_snapshot, redact_shell_output_secrets};
13
14pub struct CtxShellTool;
15
16/// Shell execution must never wait through the general-purpose session-lock
17/// recovery window. The command can run without bookkeeping; cwd validation
18/// cannot, so it fails promptly and lets the client retry.
19const SESSION_LOCK_BUDGET: std::time::Duration = std::time::Duration::from_millis(250);
20
21impl McpTool for CtxShellTool {
22    fn name(&self) -> &'static str {
23        "ctx_shell"
24    }
25
26    fn tool_def(&self) -> Tool {
27        tool_def(
28            "ctx_shell",
29            "WORKFLOW: preferred — auto-compresses output (build/test/log).\n\
30             Big logs: narrow the command (grep, sed -n, head/tail).\n\
31             [exit:N] on errors (lossless).\n\
32             POLICY: allowlisted read-only path.\n\
33             A [BLOCKED] command is permanent; ctx_execute shares the same allowlist — fix with \
34             `lean-ctx allow <cmd>`.\n\
35             ANTIPATTERN: multi-line scripts, sh/bash script.sh, $var-as-command → ctx_execute \
36             (when exposed).",
37            json!({
38                "type": "object",
39                "properties": {
40                    "command": { "type": "string", "description": "Shell command" },
41                    "raw": { "type": "boolean", "description": "Exact bytes; only for diffs to apply, hashes, encoded output" },
42                    "inline": { "type": "boolean", "description": "Verbatim up to archive.inline_max_bytes, else archived" },
43                    "cwd": { "type": "string", "description": "Working dir for this call only (not remembered; never moves the base of relative ctx_read/ctx_patch paths)" },
44                    "timeout_ms": { "type": "integer", "description": "Job lifetime in ms (max 3600000) — NOT the inline wait. A command still running at the ~90s foreground cap detaches to a pollable shell_* job and keeps running up to timeout_ms. Overridden by LEAN_CTX_SHELL_TIMEOUT_MS." },
45                    "env": { "type": "object", "description": "Extra env vars", "additionalProperties": { "type": "string" } },
46                    "run_in_background": { "type": "boolean", "description": "Detach immediately and return a job id. The command keeps timeout_ms (default here: the 1 h ceiling); poll or cancel with background_action and job_id." },
47                    "background_action": { "type": "string", "enum": ["status", "cancel"], "description": "Inspect or cancel a background ctx_shell job; terminal status may include archiveId. Evicted/expired jobs return a structured lookup error." },
48                    "job_id": { "type": "string", "description": "Job id returned by run_in_background." }
49                }
50            }),
51        )
52    }
53
54    fn handle(
55        &self,
56        args: &Map<String, Value>,
57        ctx: &ToolContext,
58    ) -> Result<ToolOutput, ErrorData> {
59        if let Some(message) = shell_access_denial(ctx) {
60            return Ok(ToolOutput {
61                shell_outcome: Some(ShellOutcome::Blocked),
62                content_blocks: None,
63                ..ToolOutput::simple(message)
64            });
65        }
66
67        if let Some(action) = get_str(args, "background_action") {
68            let id = get_str(args, "job_id").ok_or_else(|| {
69                ErrorData::invalid_params("job_id is required with background_action", None)
70            })?;
71            let is_cancel = action == "cancel";
72            let state = match action.as_str() {
73                "status" => crate::server::background_shell::snapshot(&id),
74                "cancel" => crate::server::background_shell::cancel_snapshot(&id),
75                _ => {
76                    return Err(ErrorData::invalid_params(
77                        "background_action must be status or cancel",
78                        None,
79                    ));
80                }
81            };
82            let (text, outcome) = format_background_snapshot(&id, is_cancel, state);
83            return Ok(ToolOutput {
84                shell_outcome: Some(outcome),
85                content_blocks: None,
86                // Looking after a running job is no new command: the session
87                // stats leave it out (`server_metrics::counts_in_session`).
88                mode: Some(crate::tools::server_metrics::BACKGROUND_POLL_MODE.to_string()),
89                ..ToolOutput::simple(text)
90            });
91        }
92        let command = get_str(args, "command")
93            .ok_or_else(|| ErrorData::invalid_params("command is required", None))?;
94        let timeout_ms = get_int(args, "timeout_ms").and_then(|n| u64::try_from(n).ok());
95
96        // #1811: the write-doctrine guard classifies the *destination*, so a
97        // relative redirect target only means something once it is placed
98        // against the directory the command runs in. That directory is not the
99        // `cwd` argument: `effective_cwd_checked` replaces a jail-rejected one
100        // with the project root, and falls back to the session cwd when none
101        // was passed. So it is resolved once, here, and the same value feeds
102        // both the guard and the run below — resolving it twice would let the
103        // two answers drift, and a guard that judged a directory the command
104        // never ran in is exactly the bug #1811 reports.
105        let explicit_cwd = get_str(args, "cwd");
106        // Without a session (one-shot CLI contexts) the run directory cannot be
107        // resolved here. That is not an error yet — the cat-redirect below never
108        // needs one — so the guard is simply told nothing and keeps its stricter
109        // pre-#1811 refusal, and the session requirement is raised further down,
110        // where running the command actually depends on it.
111        let resolved_cwd = match ctx.session.as_ref() {
112            Some(session_lock) => Some(tokio::task::block_in_place(|| {
113                let guard = crate::server::bounded_lock::read_for(
114                    session_lock,
115                    "ctx_shell_cwd",
116                    SESSION_LOCK_BUDGET,
117                );
118                resolve_effective_cwd(guard, explicit_cwd.as_deref())
119            })?),
120            None => None,
121        };
122        // pz21 §1.8: output from outside the repository is `tool_output`;
123        // a download also names the file it wrote.
124        note_tool_output(
125            &command,
126            resolved_cwd.as_ref().map(|(cwd, _)| cwd.as_str()),
127            &ctx.project_root,
128        );
129
130        // The write-doctrine check (no `>`, `tee`, heredoc-to-file, curl -o, …)
131        // is an MCP-payload-safety convention, not a security boundary, so it is
132        // opt-out via `shell_allow_writes` (#523). The real command gating
133        // (`check_shell_allowlist`, below) is NOT affected by this flag.
134        let config = lean_ctx::core::config::Config::load();
135        let mut write_allow_paths = config.shell_write_allow_paths_effective();
136        // The session's project and the jail's allow entries are capture
137        // targets too, so no project root is passed as a refusal below.
138        write_allow_paths.extend(crate::tools::ctx_shell::capture_roots(
139            &ctx.project_root,
140            &ctx.extra_roots,
141            &config,
142        ));
143        if !lean_ctx::core::config::shell_policy::allow_writes()
144            && let Some(rejection) = crate::tools::ctx_shell::validate_command_in_cwd(
145                &command,
146                &write_allow_paths,
147                None,
148                resolved_cwd.as_ref().map(|(cwd, _)| cwd.as_str()),
149            )
150        {
151            // The command never ran — report as a tool error so MCP clients
152            // (guards, retry logic) can detect it programmatically (#389).
153            return Ok(ToolOutput {
154                shell_outcome: Some(ShellOutcome::Blocked),
155                content_blocks: None,
156                ..ToolOutput::simple(rejection)
157            });
158        }
159
160        // The session's rights profile (process-v1 §9): every write the command
161        // line names stays in the role's write scope, never a locked path.
162        let rights_cwd = resolved_cwd
163            .as_ref()
164            .map_or_else(|| ctx.project_root.clone(), |(cwd, _)| cwd.clone());
165        // The `env` argument sets variables on the child, so the rights check
166        // sees its keys too (a namespace or command-valued variable there is
167        // refused just like the inline `KEY=value` form).
168        let env_keys: Vec<&str> = args
169            .get("env")
170            .and_then(Value::as_object)
171            .map(|obj| obj.keys().map(String::as_str).collect())
172            .unwrap_or_default();
173        if let Err(reason) = lean_ctx::core::session_rights::current().check_bash(
174            &command,
175            std::path::Path::new(&rights_cwd),
176            &env_keys,
177        ) {
178            return Ok(ToolOutput {
179                shell_outcome: Some(ShellOutcome::Blocked),
180                content_blocks: None,
181                ..ToolOutput::simple(reason)
182            });
183        }
184
185        let grant = crate::server::shell_approval::current_grant();
186        // Relative paths in the command resolve where it runs, not where
187        // this server runs.
188        let run_cwd = resolved_cwd
189            .as_ref()
190            .map(|(cwd, _)| std::path::PathBuf::from(cwd));
191        let shell_gate = || {
192            lean_ctx_shell_policy::with_run_cwd(run_cwd.clone(), || {
193                lean_ctx_shell_policy::check_shell_allowlist_granted(&command, &grant)
194            })
195        };
196
197        // GHSA-hqgc-cjh7-q3w4: an interpreter heredoc is rerouted to
198        // ctx_execute, so it runs only through ctx_execute's own gates (the
199        // session's rights, then the user's approval of the language) — the
200        // very function ctx_execute calls. When the language has no
201        // approval, the line is judged as the shell command it is: the
202        // shell gate refuses a heredoc into an interpreter as inline code
203        // unless the user allowed inline scripts, and only then does it run,
204        // as a shell command. Nothing runs before these checks.
205        if let Some((lang, code, remainder)) = detect_heredoc_reroute(&command) {
206            match super::ctx_execute::admit_code(ctx, &[(lang.as_str(), code.as_str())]) {
207                Ok(()) => {
208                    return tokio::task::block_in_place(|| {
209                        handle_interpreter_heredoc_reroute(
210                            args,
211                            ctx,
212                            &lang,
213                            &code,
214                            remainder.as_deref(),
215                        )
216                    });
217                }
218                Err(super::ctx_execute::CodeRefusal::Unapproved(message))
219                    if shell_gate().is_err() =>
220                {
221                    return Ok(ToolOutput {
222                        shell_outcome: Some(ShellOutcome::Blocked),
223                        content_blocks: None,
224                        ..ToolOutput::simple(message)
225                    });
226                }
227                Err(super::ctx_execute::CodeRefusal::Unapproved(_)) => {}
228                Err(super::ctx_execute::CodeRefusal::Rights(message)) => {
229                    return Ok(ToolOutput {
230                        shell_outcome: Some(ShellOutcome::Blocked),
231                        content_blocks: None,
232                        ..ToolOutput::simple(message)
233                    });
234                }
235            }
236        }
237
238        if let Err(msg) = shell_gate() {
239            // Independent `;`/newline statements: run the allowed ones and
240            // name each skipped one, instead of refusing the whole line.
241            if let Some(plan) = lean_ctx_shell_policy::partial_run(&command, &grant) {
242                let mut sub = args.clone();
243                sub.insert("command".into(), Value::String(plan.run));
244                let mut output = self.handle(&sub, ctx)?;
245                for note in &plan.skipped {
246                    output.text.push('\n');
247                    output.text.push_str(note);
248                }
249                // Part of the line did not run: never report the call as a
250                // success. 126 is the shell's "found but cannot execute"; a
251                // failure of the part that ran keeps its own code. The
252                // ShellBlocked event was counted by the refusal above.
253                if matches!(output.shell_outcome, None | Some(ShellOutcome::Exit(0))) {
254                    output.shell_outcome = Some(ShellOutcome::Exit(126));
255                }
256                return Ok(output);
257            }
258            return Ok(ToolOutput {
259                shell_outcome: Some(ShellOutcome::Blocked),
260                content_blocks: None,
261                ..ToolOutput::simple(msg.to_string())
262            });
263        }
264
265        warn_shell_secret_paths(&command);
266
267        // #842: a bare `cat <file>` is better served by ctx_read — it delivers
268        // content inline instead of firewalling/archiving the output, avoiding
269        // a mandatory ctx_expand round-trip for agents with cat-muscle-memory.
270        if let Some(read_path) = detect_bare_cat_file(&command)
271            && let Some(cache_lock) = ctx.cache.as_ref()
272            && let Some(mut cache) = crate::server::bounded_lock::write(cache_lock, "cat_redirect")
273        {
274            let result = crate::tools::ctx_read::handle_with_task_resolved(
275                &mut cache,
276                &read_path,
277                "full",
278                crate::tools::CrpMode::Off,
279                None,
280            );
281            let note = format!(
282                "\n[ctx_shell: bare `cat` redirected to ctx_read for inline delivery. \
283                         Use ctx_read(path=\"{read_path}\") directly next time.]"
284            );
285            let out = format!("{}{note}", result.content);
286            let sent = lean_ctx::core::tokens::count_tokens(&out);
287            return Ok(ToolOutput {
288                text: out,
289                original_tokens: sent,
290                saved_tokens: 0,
291                mode: Some("cat-redirect".to_string()),
292                path: Some(read_path),
293                changed: false,
294                shell_outcome: Some(ShellOutcome::Exit(0)),
295                content_blocks: None,
296            });
297        }
298
299        tokio::task::block_in_place(|| {
300            let session_lock = ctx
301                .session
302                .as_ref()
303                .ok_or_else(|| ErrorData::internal_error("session not available", None))?;
304            let Some((effective_cwd, cwd_jail_reason)) = resolved_cwd else {
305                return Err(ErrorData::internal_error("session not available", None));
306            };
307            // A `cwd` rejected by the project-root jail is silently replaced with
308            // the root (deliberate sandboxing). Surface that swap as a one-line
309            // hint so the caller does not mistake the run dir for the requested
310            // one (#629); appended at the end of the output like the other hints.
311            let cwd_jail_hint = cwd_jail_reason.map_or_else(String::new, |reason| {
312                format!(
313                    "\n[cwd: requested path rejected by project-root jail ({reason}) \u{2014} ran in {effective_cwd} instead]"
314                )
315            });
316            // #2262: a `cwd` in another checkout (e.g. an EnterWorktree
317            // worktree) does not move relative paths in the file tools. Say so,
318            // so an agent working there does not edit the main checkout.
319            let checkout_hint = if cwd_jail_hint.is_empty() && explicit_cwd.is_some() {
320                other_checkout_note(&ctx.project_root, &effective_cwd).unwrap_or_default()
321            } else {
322                String::new()
323            };
324            let cwd_jail_hint = format!("{cwd_jail_hint}{checkout_hint}");
325
326            // #2279: a busy session lock only skips the session update below.
327            // It used to run the command on a separate, bare path with no soft
328            // cap and no cancellation: under concurrent load a long command then
329            // held its handler for the full command timeout, after the host had
330            // given up on the call, and a cancelled call kept its child running.
331            // The command now runs on the one path below in every case.
332            if let Some(mut session) = crate::server::bounded_lock::write_for(
333                session_lock,
334                "ctx_shell_write",
335                SESSION_LOCK_BUDGET,
336            ) {
337                // #2262: neither the `cwd` argument nor a `cd` inside the
338                // command is stored on the session. Subagents share one MCP
339                // connection, so a stored directory let one agent move where
340                // another agent's commands ran and what its relative paths
341                // meant. Both apply to this call only.
342                //
343                // A session without a project root still learns one, but
344                // from the session's own start directory, never from this
345                // call's `cwd`: the root is shared by every agent on the
346                // connection, so one agent's worktree must not become it.
347                // An existing root is never replaced here.
348                let root_missing = session
349                    .project_root
350                    .as_deref()
351                    .is_none_or(|r| r.trim().is_empty());
352                if root_missing {
353                    let home = dirs::home_dir().map(|h| h.to_string_lossy().to_string());
354                    let start_dir = session.effective_cwd(None);
355                    if let Some(root) = lean_ctx::core::protocol::detect_project_root(&start_dir)
356                        && home.as_deref() != Some(root.as_str())
357                    {
358                        session.project_root = Some(root.clone());
359                        lean_ctx::core::index_orchestrator::ensure_all_background(&root);
360                    }
361                }
362            } else {
363                tracing::debug!("[ctx_shell: session lock timeout, proceeding without update]");
364            }
365
366            let arg_raw = get_bool(args, "raw").unwrap_or(false);
367            let arg_bypass = get_bool(args, "bypass").unwrap_or(false);
368            let env_disabled = std::env::var("LEAN_CTX_DISABLED").is_ok();
369            let env_raw = std::env::var("LEAN_CTX_RAW").is_ok();
370            let (raw, bypass) = resolve_shell_raw_flags(arg_raw, arg_bypass, env_disabled, env_raw);
371
372            let crp_mode = ctx.crp_mode;
373            let cmd_clone = command.clone();
374            let cwd_clone = effective_cwd;
375            let proactive_block = if raw
376                || !lean_ctx::core::profiles::active_profile()
377                    .output_hints
378                    .proactive_context()
379            {
380                None
381            } else {
382                lean_ctx::core::relevance_tracker::proactive_context(&format!(
383                    "ctx_shell command={cmd_clone} cwd={cwd_clone}"
384                ))
385            };
386
387            let extra_env = match collect_extra_env(args) {
388                Ok(env) => env,
389                Err(message) => {
390                    return Ok(ToolOutput {
391                        shell_outcome: Some(ShellOutcome::Blocked),
392                        content_blocks: None,
393                        ..ToolOutput::simple(message)
394                    });
395                }
396            };
397
398            let inline = get_bool(args, "inline").unwrap_or(false);
399
400            let auto_background = should_auto_background(&cmd_clone, timeout_ms);
401            let detached = get_bool(args, "run_in_background").unwrap_or(false);
402            if detached || auto_background {
403                // A job the agent detached on purpose is long work: without a
404                // stated lifetime it gets the ceiling, not the 2/10-minute
405                // foreground default (25.10.: a release install was killed
406                // after 10 of its ~35 minutes and nothing was installed).
407                let lifetime = if detached {
408                    timeout_ms.or(Some(lean_ctx::shell::exec::MAX_CALL_TIMEOUT_MS))
409                } else {
410                    timeout_ms
411                };
412                let job_id = crate::server::background_shell::start(
413                    cmd_clone, cwd_clone, extra_env, lifetime,
414                );
415                let mode = if auto_background {
416                    "auto-background"
417                } else {
418                    "background"
419                };
420                return Ok(ToolOutput {
421                    shell_outcome: Some(ShellOutcome::Background(BackgroundShellOutcome {
422                        state: BackgroundJobState::Running,
423                        exit_code: None,
424                        job_id: job_id.clone(),
425                        archive_id: None,
426                        archive_truncated: None,
427                        captured_chars: None,
428                        archived_chars: None,
429                        summary: format!("{mode} job started"),
430                        is_error: false,
431                        display: None,
432                    })),
433                    content_blocks: None,
434                    ..ToolOutput::simple(format!(
435                        "[{mode}:{job_id} started — use ctx_shell(background_action=\"status\", job_id=\"{job_id}\") to poll or background_action=\"cancel\" to stop it]"
436                    ))
437                });
438            }
439
440            // Foreground runs still detach onto a pollable job if they outlast
441            // the soft cap, so the MCP host's call abort (~105–120s) never strands the
442            // result behind an unresolvable task id (#1106).
443            //
444            // #1173: `timeout_ms` is the *job's* lifetime, never the foreground
445            // wait, so it must not raise this cap. Raising it bought no extra
446            // inline wait — hosts abort the call at ~105–120s regardless — it only
447            // suppressed our own detach, producing exactly the unresolvable
448            // task id the cap exists to prevent. Separate knobs, one direction:
449            // `LEAN_CTX_SHELL_FG_CAP_MS` moves the cap, `timeout_ms` does not.
450            let soft_cap = std::time::Duration::from_millis(foreground_soft_cap_ms());
451            let progress_sender = ctx.progress_sender.clone();
452            let progress_label: String = cmd_clone.chars().take(60).collect();
453            let cap_secs = soft_cap.as_secs_f64();
454            let on_tick = |elapsed: std::time::Duration| {
455                #[allow(clippy::unwrap_or_default)]
456                if let Some(ref ps) = progress_sender
457                    && let Some(sender) = ps
458                        .lock()
459                        .unwrap_or_else(std::sync::PoisonError::into_inner)
460                        .as_ref()
461                {
462                    sender.send(
463                        elapsed.as_secs_f64(),
464                        Some(cap_secs),
465                        Some(format!(
466                            "ctx_shell: {}s elapsed — {progress_label}",
467                            elapsed.as_secs()
468                        )),
469                    );
470                }
471            };
472            let (process_output, exit_code, completeness, retained_withheld, containment_notice) =
473                match crate::server::background_shell::run_foreground_or_detach_captured(
474                    cmd_clone.clone(),
475                    cwd_clone.clone(),
476                    extra_env.clone(),
477                    timeout_ms,
478                    soft_cap,
479                    Some(&on_tick),
480                    ctx.cancel.as_ref(),
481                ) {
482                    crate::server::background_shell::CapturedForegroundResult::Finished {
483                        output,
484                        exit_code,
485                        completeness,
486                        retained_withheld,
487                        notice,
488                    } => (output, exit_code, completeness, retained_withheld, notice),
489                    crate::server::background_shell::CapturedForegroundResult::Detached {
490                        job_id,
491                    } => {
492                        return Ok(ToolOutput {
493                            shell_outcome: Some(ShellOutcome::Background(BackgroundShellOutcome {
494                                state: BackgroundJobState::Running,
495                                exit_code: None,
496                                job_id: job_id.clone(),
497                                archive_id: None,
498                                archive_truncated: None,
499                                captured_chars: None,
500                                archived_chars: None,
501                                summary: "auto-detached job is still running".to_string(),
502                                is_error: false,
503                                display: None,
504                            })),
505                            content_blocks: None,
506                            // #1173: a detach is not a failure — the command is
507                            // alive and its output is recoverable, so say so
508                            // rather than leaving the caller to infer a hang.
509                            ..ToolOutput::simple(format!(
510                                "[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]",
511                                soft_cap.as_secs()
512                            ))
513                        });
514                    }
515                };
516
517            let display_input = if retained_withheld {
518                "[lean-ctx gateway: retained output withheld by storage policy]".to_string()
519            } else {
520                process_output.clone()
521            };
522            let admission =
523                lean_ctx::core::context_admission::admit_tool_output(&display_input, completeness);
524            let output = redact_shell_output_secrets(&admission.rendered());
525            let output = if raw {
526                crate::server::walk_hint::strip_walk_hint(&output).to_string()
527            } else {
528                output
529            };
530
531            // Persistent diagnostics and derived stores require a separate,
532            // pathless storage decision under one current policy epoch.
533            let store = lean_ctx::core::context_admission::stores::StoreAdmission::current();
534            let stored_command = store.admit_shell_command(&cmd_clone);
535            let stored_output = (!retained_withheld)
536                .then(|| store.admit_shell_output(&process_output, completeness))
537                .flatten();
538            let storage_allowed = !retained_withheld
539                && store.is_current()
540                && stored_command.is_some()
541                && stored_output.is_some();
542            let command_for_store = stored_command.as_deref().unwrap_or_default();
543            let output_for_store = stored_output.as_deref().unwrap_or_default();
544            if storage_allowed {
545                lean_ctx::core::diagnostics_store::record_from_shell(
546                    command_for_store,
547                    output_for_store,
548                    exit_code,
549                );
550            }
551
552            let (result_out, original, saved, tee_hint) = if raw || inline {
553                let tokens = lean_ctx::core::tokens::count_tokens(&output);
554                (output, tokens, 0, String::new())
555            } else {
556                let _mode_guard = lean_ctx::core::savings_footer::ModeGuard::new("shell");
557                let result =
558                    crate::tools::ctx_shell::handle(&cmd_clone, &output, exit_code, crp_mode);
559                let original = lean_ctx::core::tokens::count_tokens(&output);
560                let sent = lean_ctx::core::tokens::count_tokens(&result);
561                let saved = original.saturating_sub(sent);
562
563                let cfg = lean_ctx::core::config::Config::load();
564                // Shared tee policy (#811): identical decision to the CLI path —
565                // `Failures` keys off the real exit code, not a substring match.
566                let timeout_notice_only = is_timeout_notice_only(&output, exit_code);
567                let tee_hint = if storage_allowed
568                    && lean_ctx::shell::tee_policy::should_tee(
569                        &cfg.tee_mode,
570                        exit_code,
571                        output.trim().is_empty() || timeout_notice_only,
572                        lean_ctx::shell::tee_policy::output_was_elided(&output, &result),
573                        original,
574                        sent,
575                    ) {
576                    lean_ctx::shell::save_tee(command_for_store, output_for_store)
577                        .map(|p| {
578                            if lean_ctx::core::protected_store::enforce_protected_store_path(std::path::Path::new(&p)).is_err() {
579                                format!("\n[full output: ctx_expand(id=\"{p}\", search=\"…\"|head=N|json_path=\"…\")]")
580                            } else if matches!(cfg.tee_mode, lean_ctx::core::config::TeeMode::HighCompression)
581                            {
582                                let pct = lean_ctx::shell::tee_policy::savings_pct(original, sent);
583                                // Recovery grammar is path-first: agents without ctx_expand
584                                // `cat` the saved artifact for the exact original (#936),
585                                // the wording of the proxy's tee hint (`compress::tee_hint`).
586                                // The raw path stays right after "full output at": the
587                                // Claude Code mod parses it there (`register.ts`).
588                                format!(
589                                    "\n[compressed {pct:.0}%: full output at {p} — `cat` it to re-read it exactly (no MCP), or ctx_expand(id=\"{p}\", search=\"…\"|head=N|json_path=\"…\") for a slice]"
590                                )
591                            } else {
592                                format!("\n[full output: {p} — `cat` it to re-read it exactly (no MCP), or ctx_expand(id=\"{p}\")]")
593                            }
594                        })
595                        .unwrap_or_default()
596                } else {
597                    String::new()
598                };
599
600                (result, original, saved, tee_hint)
601            };
602
603            let mode = if bypass {
604                Some("bypass".to_string())
605            } else if raw {
606                Some("raw".to_string())
607            } else {
608                None
609            };
610
611            let shell_mismatch = if cfg!(windows) && !raw {
612                shell_mismatch_hint(&command, &result_out)
613            } else {
614                String::new()
615            };
616
617            let result_out = lean_ctx::core::redaction::redact_text_if_enabled(&result_out);
618            // #815: exit 124 = timeout signal (from timeout(1) / lean-ctx
619            // shell timeout). Make it explicit so agents don't confuse a
620            // timed-out command with a successful empty result.
621            let exit_suffix = lean_ctx::shell::exit_status::exit_footer(exit_code);
622            let nudge = if raw { "" } else { search_tool_nudge(&command) };
623            let final_out = format!(
624                "{result_out}{tee_hint}{shell_mismatch}{cwd_jail_hint}{nudge}{exit_suffix}"
625            );
626            let final_out = if let Some(block) = proactive_block {
627                format!("{final_out}{block}")
628            } else {
629                final_out
630            };
631            let final_admission =
632                lean_ctx::core::context_admission::admit_tool_output(&final_out, completeness);
633            let final_out = final_admission.rendered();
634
635            Ok(ToolOutput {
636                // Q13: the call's notice goes in front last — after admission,
637                // compression and the hints above, none of which has seen it.
638                text: crate::server::execute::with_notice(containment_notice, final_out),
639                original_tokens: original,
640                saved_tokens: saved,
641                mode,
642                path: None,
643                changed: false,
644                shell_outcome: Some(ShellOutcome::Exit(exit_code)),
645                content_blocks: None,
646            })
647        })
648    }
649}
650
651/// Deny shell execution for explicitly restricted MCP clients. Missing client
652/// context remains allowed so existing integrations retain their current access.
653/// `ctx_execute` runs code too and applies the same gate (GHSA-rxv5-4c3x-g4q6 B).
654pub(crate) fn shell_access_denial(ctx: &ToolContext) -> Option<String> {
655    if let Some(role) = ctx.client_role.as_deref()
656        && (role.eq_ignore_ascii_case("untrusted") || role.eq_ignore_ascii_case("readonly"))
657    {
658        return Some(format!(
659            "[SHELL ACCESS DENIED] ctx_shell is unavailable to MCP clients with role '{role}'."
660        ));
661    }
662
663    if ctx.shell_access == Some(false) {
664        return Some(
665            "[SHELL ACCESS DENIED] ctx_shell requires shell_access=true in the MCP session/request context."
666                .to_string(),
667        );
668    }
669
670    None
671}
672
673fn resolve_effective_cwd(
674    session: Option<tokio::sync::OwnedRwLockReadGuard<lean_ctx::core::session::SessionState>>,
675    explicit_cwd: Option<&str>,
676) -> Result<(String, Option<String>), ErrorData> {
677    match session {
678        // A rejected directory fails here, before the write guard, the run,
679        // a background job or the cache key see a substituted one.
680        Some(session) => session
681            .execution_cwd(explicit_cwd)
682            .map(|cwd| (cwd, None))
683            .map_err(|reason| {
684                ErrorData::invalid_params(
685                    format!("working directory rejected, command not run: {reason}"),
686                    None,
687                )
688            }),
689        None => Err(ErrorData::internal_error(
690            "session lock timeout — cannot validate working directory",
691            None,
692        )),
693    }
694}
695
696#[allow(clippy::fn_params_excessive_bools)]
697fn resolve_shell_raw_flags(
698    arg_raw: bool,
699    arg_bypass: bool,
700    _env_disabled: bool,
701    env_raw: bool,
702) -> (bool, bool) {
703    let bypass = arg_bypass || env_raw;
704    let raw = arg_raw || bypass;
705    (raw, bypass)
706}
707
708/// A timeout notice is framework metadata, not recoverable command output. Do
709/// not archive it as a tee artifact: expanding it cannot recover any bytes (#995).
710///
711/// Keyed on what precedes the marker rather than on the notice's exact shape,
712/// so enriching it (the idle-timeout wording, the still-running segment list)
713/// cannot silently turn every timeout back into an archived artifact (#1173).
714fn is_timeout_notice_only(output: &str, exit_code: i32) -> bool {
715    exit_code == 124
716        && crate::server::execute::output_before_timeout_marker(output).is_some_and(str::is_empty)
717}
718
719fn search_tool_nudge(command: &str) -> &'static str {
720    let cmd = command.trim();
721    let first_word = cmd.split_whitespace().next().unwrap_or("");
722    if !cmd.contains('|') {
723        match first_word {
724            "grep" | "rg" | "egrep" | "fgrep" | "ag" => {
725                return "\n[hint: use ctx_search for structured, cached results with symbol/semantic modes]";
726            }
727            "find" => {
728                return "\n[hint: use ctx_glob or ctx_tree for structured file discovery]";
729            }
730            "ls" | "exa" | "eza" => {
731                return "\n[hint: use ctx_tree for structured directory listing]";
732            }
733            _ => {}
734        }
735    }
736    ""
737}
738
739fn shell_mismatch_hint(command: &str, output: &str) -> String {
740    let shell = lean_ctx::shell::shell_name();
741    let is_posix = matches!(shell.as_str(), "bash" | "sh" | "zsh" | "fish");
742    let has_error = output.contains("is not recognized")
743        || output.contains("not found")
744        || output.contains("command not found");
745
746    if !has_error {
747        return String::new();
748    }
749
750    let powershell_cmds = [
751        "Get-Content",
752        "Select-Object",
753        "Get-ChildItem",
754        "Set-Location",
755        "Where-Object",
756        "ForEach-Object",
757        "Select-String",
758        "Invoke-Expression",
759        "Write-Output",
760    ];
761    let uses_powershell = powershell_cmds
762        .iter()
763        .any(|c| command.contains(c) || command.contains(&c.to_lowercase()));
764
765    if is_posix && uses_powershell {
766        format!(
767            "\n[shell: {shell} — use POSIX commands (cat, head, grep, find, ls) not PowerShell cmdlets]"
768        )
769    } else {
770        String::new()
771    }
772}
773
774/// Collect the caller's `env` overrides, refusing protected keys by name instead
775/// of dropping them silently (#1771).
776///
777/// The inline-override refusal in `crates/lean-ctx-shell-policy/src/enforcement.rs` points the
778/// caller at this parameter and uses `PATH` as its worked example — yet five of the
779/// nine variables it blocks inline (`PATH`, `GIT_SSH`, `GIT_SSH_COMMAND`,
780/// `LD_PRELOAD`, `DYLD_INSERT_LIBRARIES`) are also refused here, by the shared override
781/// policy [`lean_ctx_shell_policy::env_override_refused`].
782/// Filtering them away meant the recommended recovery ran the command with the
783/// ambient value and reported success, which is worse than the refusal it replaced:
784/// a wrong result that looks right. Naming the key is the only honest outcome.
785fn collect_extra_env(
786    args: &Map<String, Value>,
787) -> Result<std::collections::HashMap<String, String>, String> {
788    let mut accepted = std::collections::HashMap::new();
789    let Some(obj) = args.get("env").and_then(|v| v.as_object()) else {
790        return Ok(accepted);
791    };
792    let mut rejected: Vec<&str> = Vec::new();
793    for (key, value) in obj {
794        let Some(text) = value.as_str() else { continue };
795        if lean_ctx_shell_policy::env_override_refused(key, text) {
796            rejected.push(key.as_str());
797            continue;
798        }
799        accepted.insert(key.clone(), text.to_string());
800    }
801    if rejected.is_empty() {
802        return Ok(accepted);
803    }
804    rejected.sort_unstable();
805    let names = rejected
806        .iter()
807        .map(|k| format!("`{k}`"))
808        .collect::<Vec<_>>()
809        .join(", ");
810    let plural = if rejected.len() == 1 { "key" } else { "keys" };
811    Err(format!(
812        "ERROR: ctx_shell refuses the `env` {plural} {names} — nothing was run. These keys can \
813         redirect which binary executes, so lean-ctx never forwards them, and the command would \
814         otherwise have used the inherited value while appearing to honor yours. This is the \
815         same rule that blocks the inline `KEY=value cmd` form; `env` is not a way around it. \
816         Invoke the binary by its full path instead, or drop the override."
817    ))
818}
819
820/// Warn when shell reads secret-like paths via cat/head/tail/less/more.
821/// WARN-ONLY: command still executes, this is purely observational.
822fn warn_shell_secret_paths(command: &str) {
823    const READ_CMDS: &[&str] = &["cat", "head", "tail", "less", "more", "bat"];
824    let segments = lean_ctx_shell_policy::extract_all_commands_pub(command);
825    for seg in &segments {
826        let trimmed = seg.trim();
827        let tokens = lean_ctx_shell_policy::shell_tokenize(trimmed);
828        if tokens.is_empty() {
829            continue;
830        }
831        let base = tokens[0]
832            .rsplit('/')
833            .next()
834            .unwrap_or(&tokens[0])
835            .to_string();
836        if !READ_CMDS.contains(&base.as_str()) {
837            continue;
838        }
839        for tok in &tokens[1..] {
840            if tok.starts_with('-') {
841                continue;
842            }
843            let path = std::path::Path::new(tok.as_str());
844            if lean_ctx::core::io_boundary::is_secret_like(path).is_some() {
845                tracing::warn!(
846                    "[SECURITY] Shell reading secret-like path: {tok} (command: {base})"
847                );
848            }
849        }
850    }
851}
852
853/// The Codex MCP client abandons a tool call after five minutes. A Cargo test
854/// with an explicit five-minute-or-longer shell timeout cannot reliably finish
855/// inside that transport deadline (and can wait on Cargo's target lock), so
856/// detach it and return a pollable job instead.
857fn should_auto_background(command: &str, timeout_ms: Option<u64>) -> bool {
858    timeout_ms.is_some_and(|timeout| timeout >= 300_000)
859        && command
860            .lines()
861            .any(|line| line.trim_start().starts_with("cargo test"))
862}
863
864/// Foreground wait budget before a still-running command is detached into a
865/// pollable background job. Kept below the MCP host's tool-call abort so the
866/// caller always receives a real `shell_*` job id instead of an unresolvable
867/// task id (#1106). Override with `LEAN_CTX_SHELL_FG_CAP_MS`.
868///
869/// 90 s, not 110 s: hosts abort a call well before 120 s. A bench host closed
870/// the connection at 105–108 s on a plain `sleep 110`, so a 110 s cap never
871/// got to return its detach result; the host saw "Connection closed" and lost
872/// the command. 90 s leaves room for a slow host and for the result's own
873/// trip back.
874pub(crate) const DEFAULT_FOREGROUND_SOFT_CAP_MS: u64 = 90_000;
875
876fn foreground_soft_cap_ms() -> u64 {
877    std::env::var("LEAN_CTX_SHELL_FG_CAP_MS")
878        .ok()
879        .and_then(|v| v.parse().ok())
880        .filter(|&ms| ms > 0)
881        .unwrap_or(DEFAULT_FOREGROUND_SOFT_CAP_MS)
882}
883
884/// Map an interpreter binary to a `ctx_execute` language name.
885fn interpreter_to_execute_language(base: &str) -> Option<&'static str> {
886    match base {
887        "python" | "python2" | "python3" => Some("python"),
888        "node" => Some("javascript"),
889        "ruby" => Some("ruby"),
890        _ => None,
891    }
892}
893
894fn is_env_assignment_token(token: &str) -> bool {
895    let unquoted: String = token.chars().filter(|c| *c != '"' && *c != '\'').collect();
896    unquoted.contains('=')
897        && !unquoted.starts_with('-')
898        && !unquoted.starts_with('/')
899        && !unquoted.starts_with('.')
900}
901
902/// Quote-aware scan for compound operators that would invalidate a reroute.
903fn prelude_has_compound_operator(prelude: &str) -> bool {
904    let bytes = prelude.as_bytes();
905    let len = bytes.len();
906    let mut i = 0;
907    let mut in_single = false;
908    let mut in_double = false;
909    while i < len {
910        let ch = bytes[i];
911        if in_single {
912            if ch == b'\'' {
913                in_single = false;
914            }
915            i += 1;
916            continue;
917        }
918        if in_double {
919            if ch == b'\\' && i + 1 < len {
920                i += 2;
921            } else {
922                if ch == b'"' {
923                    in_double = false;
924                }
925                i += 1;
926            }
927            continue;
928        }
929        match ch {
930            b'\'' => {
931                in_single = true;
932                i += 1;
933            }
934            b'"' => {
935                in_double = true;
936                i += 1;
937            }
938            b';' | b'|' | b'&' | b'(' | b'{' => return true,
939            _ => i += 1,
940        }
941    }
942    false
943}
944
945/// Detect interpreter heredoc patterns and extract the language + code body.
946/// Returns `Some((language, code, remainder))` where remainder is any command
947/// after the heredoc terminator that still needs shell execution.
948pub(crate) fn detect_heredoc_reroute(command: &str) -> Option<(String, String, Option<String>)> {
949    if !command.contains("<<") {
950        return None;
951    }
952
953    let lines: Vec<&str> = command.lines().collect();
954    if lines.is_empty() {
955        return None;
956    }
957
958    let first_line = lines[0];
959    let delims = lean_ctx_shell_policy::heredoc_delims(first_line, false);
960    if delims.len() != 1 {
961        return None;
962    }
963    let delim = delims[0].clone();
964
965    let heredoc_pos = find_heredoc_operator(first_line)?;
966    let prelude = first_line[..heredoc_pos].trim();
967    if prelude_has_compound_operator(prelude) {
968        return None;
969    }
970
971    let language = parse_interpreter_heredoc_prelude(prelude)?.to_string();
972
973    if has_trailing_tokens_after_heredoc_delim(first_line, heredoc_pos) {
974        return None;
975    }
976
977    let mut body = String::new();
978    let mut remainder_start: Option<usize> = None;
979    for (idx, line) in lines.iter().enumerate().skip(1) {
980        if line.trim_start_matches('\t').trim() == delim {
981            remainder_start = Some(idx + 1);
982            break;
983        }
984        if !body.is_empty() {
985            body.push('\n');
986        }
987        body.push_str(line);
988    }
989    let remainder_start = remainder_start?;
990    let remainder = if remainder_start < lines.len() {
991        let rest = lines[remainder_start..].join("\n");
992        let rest = rest.trim();
993        if rest.is_empty() {
994            None
995        } else {
996            Some(rest.to_string())
997        }
998    } else {
999        None
1000    };
1001
1002    Some((language, body, remainder))
1003}
1004
1005fn find_heredoc_operator(line: &str) -> Option<usize> {
1006    let bytes = line.as_bytes();
1007    let len = bytes.len();
1008    let mut i = 0;
1009    let mut in_single = false;
1010    let mut in_double = false;
1011    while i < len {
1012        let ch = bytes[i];
1013        if in_single {
1014            if ch == b'\'' {
1015                in_single = false;
1016            }
1017            i += 1;
1018            continue;
1019        }
1020        if in_double {
1021            if ch == b'\\' && i + 1 < len {
1022                i += 2;
1023            } else {
1024                if ch == b'"' {
1025                    in_double = false;
1026                }
1027                i += 1;
1028            }
1029            continue;
1030        }
1031        match ch {
1032            b'\'' => {
1033                in_single = true;
1034                i += 1;
1035            }
1036            b'"' => {
1037                in_double = true;
1038                i += 1;
1039            }
1040            b'<' if i + 1 < len && bytes[i + 1] == b'<' => {
1041                if i + 2 < len && bytes[i + 2] == b'<' {
1042                    i += 3;
1043                    continue;
1044                }
1045                return Some(i);
1046            }
1047            _ => i += 1,
1048        }
1049    }
1050    None
1051}
1052
1053fn has_trailing_tokens_after_heredoc_delim(line: &str, heredoc_pos: usize) -> bool {
1054    let bytes = line.as_bytes();
1055    let mut i = heredoc_pos + 2;
1056    if i < bytes.len() && bytes[i] == b'-' {
1057        i += 1;
1058    }
1059    while i < bytes.len() && (bytes[i] == b' ' || bytes[i] == b'\t') {
1060        i += 1;
1061    }
1062    let Some((_, _, next)) = lean_ctx_shell_policy::read_heredoc_delim(bytes, i) else {
1063        return true;
1064    };
1065    !line[next..].trim().is_empty()
1066}
1067
1068fn parse_interpreter_heredoc_prelude(prelude: &str) -> Option<&'static str> {
1069    let tokens = lean_ctx_shell_policy::shell_tokenize(prelude.trim());
1070    let mut idx = 0;
1071    while idx < tokens.len() && is_env_assignment_token(&tokens[idx]) {
1072        idx += 1;
1073    }
1074    if idx >= tokens.len() {
1075        return None;
1076    }
1077    let base = tokens[idx]
1078        .rsplit('/')
1079        .next()
1080        .unwrap_or(tokens[idx].as_str());
1081    let language = interpreter_to_execute_language(base)?;
1082    idx += 1;
1083    match tokens.get(idx) {
1084        None => Some(language),
1085        Some(dash) if dash == "-" => {
1086            if tokens.len() == idx + 1 {
1087                Some(language)
1088            } else {
1089                None
1090            }
1091        }
1092        Some(_) => None,
1093    }
1094}
1095
1096/// The one working directory both halves of a rerouted heredoc call run in.
1097///
1098/// Resolution goes through the session so an explicit `cwd` is validated
1099/// against the configured roots, exactly as the non-rerouted path does. A `cwd`
1100/// the caller named that cannot be validated is an error, never a silent
1101/// substitution (#1666).
1102///
1103/// `Ok(None)` means only that no directory could be established without a
1104/// session. The heredoc-only path never needed one and must keep working; the
1105/// shell remainder always required a session and keeps requiring it.
1106fn resolve_reroute_cwd(
1107    ctx: &ToolContext,
1108    explicit_cwd: Option<&str>,
1109) -> Result<Option<String>, ErrorData> {
1110    let Some(session_lock) = ctx.session.as_ref() else {
1111        if explicit_cwd.is_some() {
1112            return Err(ErrorData::internal_error(
1113                "session not available — cannot validate the requested working directory",
1114                None,
1115            ));
1116        }
1117        return Ok(None);
1118    };
1119    let guard =
1120        crate::server::bounded_lock::read_for(session_lock, "ctx_shell_cwd", SESSION_LOCK_BUDGET);
1121    let (cwd, _) = resolve_effective_cwd(guard, explicit_cwd)?;
1122    Ok(Some(cwd))
1123}
1124
1125fn handle_interpreter_heredoc_reroute(
1126    args: &Map<String, Value>,
1127    ctx: &ToolContext,
1128    language: &str,
1129    code: &str,
1130    remainder: Option<&str>,
1131) -> Result<ToolOutput, ErrorData> {
1132    let timeout_ms = get_int(args, "timeout_ms").and_then(|n| u64::try_from(n).ok());
1133    let timeout_secs = timeout_ms.map(|ms| ms.div_ceil(1000).max(1));
1134
1135    // #1666: resolve the working directory *before* the interpreter runs. The
1136    // shell remainder below always ran in the call's `cwd`; the rerouted
1137    // interpreter ran wherever the server process happened to sit. One tool
1138    // call, two directories — and a script using relative paths silently read
1139    // and wrote the wrong tree while reporting success.
1140    let explicit_cwd = get_str(args, "cwd");
1141    let exec_cwd = resolve_reroute_cwd(ctx, explicit_cwd.as_deref())?;
1142
1143    // GHSA-hqgc-cjh7-q3w4: everything the shell remainder needs is settled
1144    // before the interpreter runs, so a refused remainder never leaves the
1145    // heredoc half executed behind a "blocked" answer.
1146    let remainder_run = match remainder {
1147        None => None,
1148        Some(rest_cmd) => {
1149            let run_cwd = exec_cwd.as_deref().map(std::path::PathBuf::from);
1150            if let Err(msg) = lean_ctx_shell_policy::with_run_cwd(run_cwd, || {
1151                lean_ctx_shell_policy::check_shell_allowlist_granted(
1152                    rest_cmd,
1153                    &crate::server::shell_approval::current_grant(),
1154                )
1155            }) {
1156                return Ok(ToolOutput {
1157                    shell_outcome: Some(ShellOutcome::Blocked),
1158                    content_blocks: None,
1159                    ..ToolOutput::simple(format!(
1160                        "[remainder blocked by shell allowlist; nothing ran, \
1161                         the heredoc included]\n{msg}"
1162                    ))
1163                });
1164            }
1165            // Unchanged from before #1666: running the shell remainder
1166            // requires a validated working directory.
1167            let effective_cwd = exec_cwd
1168                .clone()
1169                .ok_or_else(|| ErrorData::internal_error("session not available", None))?;
1170            let extra_env = match collect_extra_env(args) {
1171                Ok(env) => env,
1172                Err(message) => {
1173                    return Ok(ToolOutput {
1174                        shell_outcome: Some(ShellOutcome::Blocked),
1175                        content_blocks: None,
1176                        ..ToolOutput::simple(message)
1177                    });
1178                }
1179            };
1180            Some((rest_cmd.to_string(), effective_cwd, extra_env))
1181        }
1182    };
1183
1184    let (exec_text, exec_outcome) = crate::tools::ctx_execute::handle_in(
1185        language,
1186        code,
1187        None,
1188        timeout_secs,
1189        exec_cwd.as_deref().map(std::path::Path::new),
1190    );
1191    let reroute_note = format!(
1192        "\n[ctx_shell: interpreter heredoc auto-rerouted to ctx_execute(language=\"{language}\")]"
1193    );
1194    let exec_completeness = lean_ctx::core::context_admission::OutputCompleteness {
1195        reader_incomplete: true,
1196        ..lean_ctx::core::context_admission::OutputCompleteness::complete()
1197    };
1198    let exec_admission =
1199        lean_ctx::core::context_admission::admit_tool_output(&exec_text, exec_completeness);
1200    let exec_text = lean_ctx::core::redaction::redact_text_if_enabled(&exec_admission.rendered());
1201
1202    let Some((rest_cmd, effective_cwd, extra_env)) = remainder_run else {
1203        let final_text = format!("{exec_text}{reroute_note}");
1204        let final_admission =
1205            lean_ctx::core::context_admission::admit_tool_output(&final_text, exec_completeness);
1206        let text = final_admission.rendered();
1207        return Ok(ToolOutput {
1208            original_tokens: lean_ctx::core::tokens::count_tokens(&text),
1209            text,
1210            saved_tokens: 0,
1211            mode: Some("heredoc-reroute".to_string()),
1212            path: None,
1213            changed: false,
1214            shell_outcome: Some(exec_outcome),
1215            content_blocks: None,
1216        });
1217    };
1218
1219    // The remainder is an ordinary shell command and gets the same foreground
1220    // contract as the non-rerouted path: the caller's cancel stops it, and the
1221    // foreground soft cap detaches it to a background job instead of holding
1222    // the call past the host's abort (#1106, #1173).
1223    let soft_cap = std::time::Duration::from_millis(foreground_soft_cap_ms());
1224    let (remainder_output, shell_exit, remainder_completeness, retained_withheld, remainder_notice) =
1225        match crate::server::background_shell::run_foreground_or_detach_captured(
1226            rest_cmd.clone(),
1227            effective_cwd,
1228            extra_env,
1229            timeout_ms,
1230            soft_cap,
1231            None,
1232            ctx.cancel.as_ref(),
1233        ) {
1234            crate::server::background_shell::CapturedForegroundResult::Finished {
1235                output,
1236                exit_code,
1237                completeness,
1238                retained_withheld,
1239                notice,
1240            } => (output, exit_code, completeness, retained_withheld, notice),
1241            crate::server::background_shell::CapturedForegroundResult::Detached { job_id } => {
1242                let text = format!(
1243                    "{exec_text}{reroute_note}\n\n[heredoc remainder via ctx_shell]\n\
1244                     [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]",
1245                    soft_cap.as_secs()
1246                );
1247                return Ok(ToolOutput {
1248                    original_tokens: lean_ctx::core::tokens::count_tokens(&text),
1249                    text,
1250                    saved_tokens: 0,
1251                    mode: Some("heredoc-reroute".to_string()),
1252                    path: None,
1253                    changed: false,
1254                    shell_outcome: Some(ShellOutcome::Background(BackgroundShellOutcome {
1255                        state: BackgroundJobState::Running,
1256                        exit_code: None,
1257                        job_id,
1258                        archive_id: None,
1259                        archive_truncated: None,
1260                        captured_chars: None,
1261                        archived_chars: None,
1262                        summary: "auto-detached heredoc remainder is still running".to_string(),
1263                        is_error: false,
1264                        display: None,
1265                    })),
1266                    content_blocks: None,
1267                });
1268            }
1269        };
1270    let remainder_display = if retained_withheld {
1271        "[lean-ctx gateway: retained output withheld by storage policy]".to_string()
1272    } else {
1273        remainder_output
1274    };
1275    let shell_admission = lean_ctx::core::context_admission::admit_tool_output(
1276        &remainder_display,
1277        remainder_completeness,
1278    );
1279    let shell_output = redact_shell_output_secrets(&shell_admission.rendered());
1280    let arg_raw = get_bool(args, "raw").unwrap_or(false);
1281    let arg_bypass = get_bool(args, "bypass").unwrap_or(false);
1282    let env_disabled = std::env::var("LEAN_CTX_DISABLED").is_ok();
1283    let env_raw = std::env::var("LEAN_CTX_RAW").is_ok();
1284    let (raw, _) = resolve_shell_raw_flags(arg_raw, arg_bypass, env_disabled, env_raw);
1285
1286    let shell_text = if raw {
1287        shell_output
1288    } else {
1289        crate::tools::ctx_shell::handle(&rest_cmd, &shell_output, shell_exit, ctx.crp_mode)
1290    };
1291    let shell_text = lean_ctx::core::redaction::redact_text_if_enabled(&shell_text);
1292    let exit_suffix = lean_ctx::shell::exit_status::exit_footer(shell_exit);
1293
1294    let combined = format!(
1295        "{exec_text}{reroute_note}\n\n[heredoc remainder via ctx_shell]\n{shell_text}{exit_suffix}"
1296    );
1297    let mut completeness = remainder_completeness;
1298    // ctx_execute currently exposes no raw-byte capture flags for the heredoc
1299    // half, so the combined output cannot claim full inspection coverage.
1300    completeness.reader_incomplete = true;
1301    let final_admission =
1302        lean_ctx::core::context_admission::admit_tool_output(&combined, completeness);
1303    // Q13: the shell half's notice goes in front last, after admission.
1304    let text = crate::server::execute::with_notice(remainder_notice, final_admission.rendered());
1305    let token_count = lean_ctx::core::tokens::count_tokens(&text);
1306    Ok(ToolOutput {
1307        text,
1308        original_tokens: token_count,
1309        saved_tokens: 0,
1310        mode: Some("heredoc-reroute".to_string()),
1311        path: None,
1312        changed: false,
1313        shell_outcome: Some(ShellOutcome::Exit(shell_exit)),
1314        content_blocks: None,
1315    })
1316}
1317
1318/// #842: detect a bare `cat <single_file>` command (no pipes, redirects, flags).
1319fn detect_bare_cat_file(command: &str) -> Option<String> {
1320    let trimmed = command.trim();
1321    let rest = trimmed.strip_prefix("cat ")?;
1322    let rest = rest.trim();
1323    if rest.is_empty()
1324        || rest.contains('|')
1325        || rest.contains('>')
1326        || rest.contains('<')
1327        || rest.contains(';')
1328        || rest.contains('&')
1329        || rest.contains('$')
1330        || rest.starts_with('-')
1331    {
1332        return None;
1333    }
1334    let parts: Vec<&str> = rest.split_whitespace().collect();
1335    if parts.len() != 1 {
1336        return None;
1337    }
1338    let file_path = parts[0].trim_matches(|c: char| c == '\'' || c == '"');
1339    if file_path.is_empty() {
1340        return None;
1341    }
1342    Some(file_path.to_string())
1343}
1344
1345/// The nearest directory at or above `start` that holds a `.git` entry (a
1346/// directory in a main checkout, a file in a worktree), by the shared
1347/// `promote_to_git_root` walk; `None` when there is none.
1348fn nearest_git_boundary(start: &std::path::Path) -> Option<std::path::PathBuf> {
1349    let start = lean_ctx::core::pathutil::safe_canonicalize_or_self(start);
1350    let found = std::path::PathBuf::from(lean_ctx::core::command_root::promote_to_git_root(
1351        &start.to_string_lossy(),
1352    ));
1353    found.join(".git").exists().then_some(found)
1354}
1355
1356/// #2262: one stable line when `cwd` lies in a different git checkout than
1357/// `project_root` (an EnterWorktree worktree, say). A monorepo subdirectory
1358/// shares the root's boundary and gets no line; so does a side without `.git`.
1359fn other_checkout_note(project_root: &str, cwd: &str) -> Option<String> {
1360    if project_root.trim().is_empty() || project_root == "." {
1361        return None;
1362    }
1363    let root_boundary = nearest_git_boundary(std::path::Path::new(project_root))?;
1364    let cwd_boundary = nearest_git_boundary(std::path::Path::new(cwd))?;
1365    (root_boundary != cwd_boundary).then(|| {
1366        format!(
1367            "\n[note: relative paths in ctx_read/ctx_patch resolve to {project_root}; use absolute paths for {}]",
1368            cwd_boundary.display()
1369        )
1370    })
1371}
1372
1373/// Classify `command` by the `tool_output` table (pz21 §1.8). A match makes
1374/// every command output this call admits `tool_output` (fenced, the session
1375/// tainted) and taints the session at once with each file it downloads, so
1376/// a later `ctx_read` of exactly that file is fenced too.
1377fn note_tool_output(command: &str, cwd: Option<&str>, project_root: &str) {
1378    use lean_ctx::core::context_admission::{capture, origin};
1379    let Some(found) = lean_ctx::core::context_admission::tool_output::classify(command) else {
1380        // The project's own command: said explicitly, since an unclassified
1381        // output is admitted as of unknown origin.
1382        if let Some(capture) = capture::current() {
1383            capture.set_output_class(lean_ctx::core::patterns::output_class(command));
1384        }
1385        return;
1386    };
1387    let class = found.class();
1388    if let Some(capture) = capture::current() {
1389        capture.set_output_class(class.clone());
1390    }
1391    capture::note_origin(&class);
1392    let root = std::path::Path::new(project_root);
1393    let base = cwd.map_or(root, std::path::Path::new);
1394    for download in &found.downloads {
1395        let class = origin::download_origin(root, base, std::path::Path::new(download)).map_or(
1396            origin::SourceClass::Unclassified { tool: "download" },
1397            origin::SourceClass::External,
1398        );
1399        capture::note_origin(&class);
1400    }
1401}
1402
1403#[cfg(test)]
1404#[path = "ctx_shell_tests.rs"]
1405mod tests;