Skip to main content

vtcode_core/tools/registry/
executors.rs

1use std::path::PathBuf;
2use std::time::{Duration, SystemTime};
3
4use anyhow::{Context, Result, anyhow, bail};
5#[cfg(test)]
6use cargo_failure_diagnostics::{
7    CargoTestCommandKind, attach_exec_recovery_guidance, attach_failure_diagnostics_metadata,
8    cargo_selector_error_diagnostics, cargo_test_failure_diagnostics, cargo_test_rerun_hint,
9};
10use chrono;
11use exec_support::*;
12use futures::future::BoxFuture;
13use hashbrown::HashMap;
14use sandbox_runtime::*;
15use serde::de::DeserializeOwned;
16use serde_json::{Value, json};
17
18use super::{ExecSettlementMode, ToolRegistry};
19use crate::config::constants::tools;
20use crate::tools::file_tracker::FileTracker;
21use crate::tools::registry::unified_actions::CommandSessionAction;
22use crate::tools::{native_memory, tool_intent};
23
24mod cargo_failure_diagnostics;
25mod exec_command;
26mod exec_output;
27mod exec_sessions;
28mod exec_support;
29mod matrix;
30mod patch_pipeline;
31mod sandbox_runtime;
32mod search_introspection;
33mod subagents;
34
35pub use sandbox_runtime::sandbox_policy_from_runtime_config;
36
37#[derive(Clone, Copy)]
38enum ExecRunBackendKind {
39    Pty,
40    Pipe,
41}
42
43struct PreparedExecRunRequest {
44    prepared_command: PreparedExecCommand,
45    working_dir_path: PathBuf,
46    output_config: ExecRunOutputConfig,
47    yield_duration: Duration,
48    session_id: String,
49    shell_program: String,
50    env_overrides: HashMap<String, String>,
51    is_git_diff: bool,
52    confirm: bool,
53    rows: Option<u16>,
54    cols: Option<u16>,
55    sandbox_active: bool,
56    background: bool,
57    stdin: bool,
58}
59
60struct ResolvedExecSandboxRequest {
61    working_dir_path: PathBuf,
62    sandbox_permissions: crate::sandboxing::SandboxPermissions,
63    additional_permissions: Option<crate::sandboxing::AdditionalPermissions>,
64}
65
66fn set_payload_default(payload: &mut serde_json::Map<String, Value>, key: &str, value: Value) {
67    payload.entry(key.to_string()).or_insert(value);
68}
69
70pub(super) fn normalize_command_session_run_alias_args(args: &Value, tty: bool) -> Result<Value> {
71    let mut args = crate::tools::command_args::normalize_shell_args(args).map_err(|error| anyhow!(error))?;
72    if let Some(payload) = args.as_object_mut() {
73        set_payload_default(payload, "action", json!("run"));
74        if tty {
75            set_payload_default(payload, "tty", json!(true));
76        }
77    }
78    Ok(args)
79}
80
81fn with_command_session_action_default(mut args: Value, action: &'static str) -> Value {
82    if let Some(payload) = args.as_object_mut() {
83        set_payload_default(payload, "action", json!(action));
84    }
85    args
86}
87
88pub(super) fn normalize_write_stdin_args(
89    args: &Value,
90) -> Result<(Value, crate::tools::command_args::WriteStdinDispatch)> {
91    let dispatch = crate::tools::command_args::write_stdin_dispatch(args).map_err(|error| anyhow!(error))?;
92    let mut args = crate::tools::command_args::normalize_shell_args(args).map_err(|error| anyhow!(error))?;
93    let payload = args
94        .as_object_mut()
95        .ok_or_else(|| anyhow!("write_stdin requires a JSON object"))?;
96    payload.insert("action".to_string(), json!(dispatch.command_session_action()));
97    if dispatch == crate::tools::command_args::WriteStdinDispatch::Poll {
98        payload.remove("input");
99    }
100    Ok((args, dispatch))
101}
102
103fn annotate_exec_run_response(response: &mut Value, is_git_diff: bool) {
104    if is_git_diff {
105        response["no_spool"] = json!(true);
106        response["content_type"] = json!("git_diff");
107    }
108}
109
110fn acquire_executor_rate_limit(bucket: &str, multiplier: f64) -> Result<()> {
111    let mut guard = crate::tools::rate_limiter::PER_TOOL_RATE_LIMITER
112        .lock()
113        .map_err(|err| anyhow!("per-tool rate limiter poisoned: {err}"))?;
114    guard
115        .try_acquire_for_scaled(bucket, multiplier)
116        .map_err(|e| anyhow!("tool rate limit exceeded for {bucket}: {e}"))
117}
118
119fn parse_action<T>(action_str: &str) -> Result<T>
120where
121    T: DeserializeOwned,
122{
123    serde_json::from_value(json!(action_str)).with_context(|| format!("Invalid action: {action_str}"))
124}
125
126/// Generate an executor that delegates to a cloned tool instance from the inventory.
127macro_rules! delegate_to_tool {
128    ($name:ident, $tool_accessor:ident, $method:ident) => {
129        pub(super) fn $name(&self, args: Value) -> BoxFuture<'_, Result<Value>> {
130            let tool = self.inventory.$tool_accessor().clone();
131            Box::pin(async move { tool.$method(args).await })
132        }
133    };
134}
135
136/// Generate an executor that delegates to an async method on `self`.
137macro_rules! delegate_to_self {
138    ($name:ident, $method:ident) => {
139        pub(super) fn $name(&self, args: Value) -> BoxFuture<'_, Result<Value>> {
140            Box::pin(async move { self.$method(args).await })
141        }
142    };
143}
144
145impl ToolRegistry {
146    pub(super) fn record_decision_executor(&self, args: Value) -> BoxFuture<'_, Result<Value>> {
147        Box::pin(async move {
148            let decision = crate::core::agent::events::validate_decision_input(args)?;
149            let task = self
150                .harness_context_snapshot()
151                .task_id
152                .context("decision recording requires current task identity")?;
153            let validator = self
154                .harness_context
155                .decision_validator
156                .read()
157                .clone()
158                .context("canonical decision recording is unavailable")?;
159            validator(task, decision.evidence_ids).await?;
160            Ok(json!({"recorded":true,"rationale_source":"agent-reported"}))
161        })
162    }
163    /// Unified `cron` executor: dispatches on `action` (create | list | delete).
164    /// For legacy alias calls that omit `action`, the action is inferred from
165    /// the argument shape: `prompt` implies create, `id` implies delete,
166    /// otherwise list.
167    #[cfg_attr(
168        not(test),
169        allow(
170            dead_code,
171            reason = "Legacy executor aliases remain available for compatibility tests."
172        )
173    )]
174    pub(super) fn cron_executor(&self, args: Value) -> BoxFuture<'_, Result<Value>> {
175        Box::pin(async move {
176            let action = args
177                .get("action")
178                .and_then(Value::as_str)
179                .map(str::to_ascii_lowercase)
180                .unwrap_or_else(|| {
181                    if args.get("prompt").is_some() {
182                        "create".to_string()
183                    } else if args.get("id").is_some() {
184                        "delete".to_string()
185                    } else {
186                        "list".to_string()
187                    }
188                });
189            match action.as_str() {
190                "create" => self.cron_create_executor(args).await,
191                "list" => self.cron_list_executor(args).await,
192                "delete" => self.cron_delete_executor(args).await,
193                other => bail!(
194                    "cron: unknown action '{other}'. Use action='create' (schedule a prompt), 'list', or 'delete' (requires id)."
195                ),
196            }
197        })
198    }
199
200    fn cron_create_executor(&self, args: Value) -> BoxFuture<'_, Result<Value>> {
201        Box::pin(async move {
202            let prompt = args
203                .get("prompt")
204                .and_then(Value::as_str)
205                .map(str::trim)
206                .filter(|value| !value.is_empty())
207                .ok_or_else(|| anyhow!("cron_create requires a non-empty prompt"))?
208                .to_string();
209            let name = args.get("name").and_then(Value::as_str).map(ToOwned::to_owned);
210            let cron = args.get("cron").and_then(Value::as_str);
211            let delay_minutes = args.get("delay_minutes").and_then(Value::as_u64);
212            let run_at = args.get("run_at").and_then(Value::as_str);
213
214            let schedule = match (cron, delay_minutes, run_at) {
215                (Some(expression), None, None) => crate::scheduler::ScheduleSpec::cron5(expression)?,
216                (None, Some(minutes), None) => crate::scheduler::ScheduleSpec::fixed_interval(Duration::from_secs(
217                    minutes.checked_mul(60).ok_or_else(|| anyhow!("delay_minutes is too large"))?,
218                ))?,
219                (None, None, Some(raw)) => crate::scheduler::ScheduleSpec::one_shot(
220                    crate::scheduler::parse_local_datetime(raw, chrono::Local::now())?,
221                ),
222                _ => bail!("Choose exactly one of cron, delay_minutes, or run_at"),
223            };
224
225            let summary = self
226                .create_session_prompt_task(name, prompt, schedule, chrono::Utc::now())
227                .await?;
228            serde_json::to_value(summary).context("Failed to serialize cron_create response")
229        })
230    }
231
232    fn cron_list_executor(&self, _args: Value) -> BoxFuture<'_, Result<Value>> {
233        Box::pin(async move {
234            Ok(json!({
235                "tasks": self.list_session_tasks().await,
236            }))
237        })
238    }
239
240    fn cron_delete_executor(&self, args: Value) -> BoxFuture<'_, Result<Value>> {
241        Box::pin(async move {
242            let id = args
243                .get("id")
244                .and_then(Value::as_str)
245                .map(str::trim)
246                .filter(|value| !value.is_empty())
247                .ok_or_else(|| anyhow!("cron_delete requires id"))?;
248            let deleted = self.delete_session_task(id).await;
249            Ok(json!({
250                "deleted": deleted.is_some(),
251                "task": deleted,
252            }))
253        })
254    }
255
256    pub(super) fn memory_executor(&self, args: Value) -> BoxFuture<'_, Result<Value>> {
257        Box::pin(async move {
258            let workspace_root = self.workspace_root_owned();
259            native_memory::execute_with_persistent_memory_config(
260                &workspace_root,
261                self.persistent_memory_config.as_ref(),
262                self.persistent_memory_enabled,
263                args,
264            )
265            .await
266        })
267    }
268
269    pub async fn shell_run_approval_reason(
270        &self,
271        tool_name: &str,
272        tool_args: Option<&Value>,
273    ) -> Result<Option<String>> {
274        let resolved_tool_name = self
275            .resolve_public_tool_name_sync(tool_name)
276            .unwrap_or_else(|_| tool_name.to_string());
277        let Some(payload) = shell_run_payload(&resolved_tool_name, tool_args) else {
278            return Ok(None);
279        };
280
281        let (requested_command, raw_command) = parse_command_parts(
282            payload,
283            "shell run request requires a command",
284            "shell run request command cannot be empty",
285        )?;
286        let shell_script = shell_script_text(payload, raw_command.as_deref(), &requested_command);
287        let sandbox_request = self.resolve_exec_sandbox_request(payload).await?;
288        let sandbox_config = self.sandbox_config();
289        let plan = build_shell_execution_plan(
290            &sandbox_config,
291            self.workspace_root(),
292            &sandbox_request.working_dir_path,
293            &requested_command,
294            Some(&shell_script),
295            sandbox_request.sandbox_permissions,
296            sandbox_request.additional_permissions.as_ref(),
297        )?;
298
299        Ok(plan.approval_reason)
300    }
301
302    pub(super) fn code_search_executor(&self, args: Value) -> BoxFuture<'_, Result<Value>> {
303        Box::pin(async move { self.execute_code_search(args).await })
304    }
305
306    async fn prepare_exec_run_request(
307        &self,
308        args: &Value,
309        backend: ExecRunBackendKind,
310        missing_error: &str,
311        empty_error: &str,
312    ) -> Result<PreparedExecRunRequest> {
313        acquire_executor_rate_limit("exec_command:run", 2.0)?;
314
315        // Direct registry callers do not necessarily run model preflight.
316        // Normalize here as well so every pipe/PTY launch reports the same
317        // truthful verifier status the gate classifies. This is idempotent.
318        let executed_args = tool_intent::shell_args_as_executed(tools::EXEC_COMMAND, args);
319        let payload = executed_args
320            .as_object()
321            .ok_or_else(|| anyhow!("command execution requires a JSON object"))?;
322        let background = payload.get("background").and_then(Value::as_bool).unwrap_or(false);
323        let stdin = match payload.get("stdin") {
324            None => false,
325            Some(value) => value.as_bool().ok_or_else(|| anyhow!("stdin must be a boolean"))?,
326        };
327
328        let (command, auto_raw_command) = parse_command_parts(payload, missing_error, empty_error)?;
329        let shell_program = match backend {
330            ExecRunBackendKind::Pty => resolve_shell_preference_with_zsh_fork(
331                payload.get("shell").and_then(|value| value.as_str()),
332                self.pty_config(),
333            )?,
334            ExecRunBackendKind::Pipe => {
335                resolve_shell_preference(payload.get("shell").and_then(|value| value.as_str()), self.pty_config())
336            }
337        };
338        let login_shell = payload.get("login").and_then(|value| value.as_bool()).unwrap_or(false);
339        let confirm = payload.get("confirm").and_then(|value| value.as_bool()).unwrap_or(false);
340
341        let mut prepared_command =
342            prepare_exec_command(payload, &shell_program, login_shell, command, auto_raw_command);
343        let is_git_diff = is_git_diff_command(&prepared_command.requested_command);
344
345        // Evaluate the concrete invocation so raw shell fragments retain their
346        // original quoting. An explicitly supplied shell argv is already a
347        // policy boundary; keep that request intact when the runtime's
348        // preferred shell differs and would otherwise add a nested wrapper.
349        let policy_command = if crate::tools::command_policy::is_shell_argv(&prepared_command.requested_command) {
350            &prepared_command.requested_command
351        } else {
352            &prepared_command.command
353        };
354        if !self.inventory.command_policy_allows(policy_command) {
355            return Err(anyhow!(
356                "Execution policy violation: command '{}' is not permitted by the execution policy",
357                prepared_command.requested_command_display
358            ));
359        }
360
361        let inspection_cwd = self
362            .pty_manager()
363            .working_dir_candidate(crate::tools::command_args::working_dir_text(args))?;
364        self.edited_file_monitor_ref()
365            .source_inspection()
366            .check_shell(args, &inspection_cwd)?;
367        let sandbox_request = self.resolve_exec_sandbox_request(payload).await?;
368        let output_config = exec_run_output_config(payload, &prepared_command.display_command);
369
370        enforce_pty_command_policy(&prepared_command.display_command, confirm)?;
371        let sandbox_config = self.sandbox_config();
372        let sandbox_plan = build_shell_execution_plan(
373            &sandbox_config,
374            self.workspace_root(),
375            &sandbox_request.working_dir_path,
376            &prepared_command.requested_command,
377            Some(&prepared_command.shell_script),
378            sandbox_request.sandbox_permissions,
379            sandbox_request.additional_permissions.as_ref(),
380        )?;
381        let sandbox_active = sandbox_plan.sandbox_policy.is_some();
382        prepared_command.command = apply_runtime_sandbox_to_command(
383            prepared_command.command,
384            &prepared_command.requested_command,
385            &sandbox_request.working_dir_path,
386            sandbox_plan.sandbox_policy,
387        )?;
388
389        let rows = match backend {
390            ExecRunBackendKind::Pty => {
391                Some(parse_pty_dimension("rows", payload.get("rows"), self.pty_config().default_rows)?)
392            }
393            ExecRunBackendKind::Pipe => None,
394        };
395        let cols = match backend {
396            ExecRunBackendKind::Pty => {
397                Some(parse_pty_dimension("cols", payload.get("cols"), self.pty_config().default_cols)?)
398            }
399            ExecRunBackendKind::Pipe => None,
400        };
401
402        Ok(PreparedExecRunRequest {
403            prepared_command,
404            working_dir_path: sandbox_request.working_dir_path,
405            output_config,
406            yield_duration: Duration::from_millis(
407                clamp_exec_yield_ms(
408                    payload.get("yield_time_ms").and_then(Value::as_u64),
409                    if background { 250 } else { 10_000 },
410                )
411                .min(if background { 1_000 } else { 30_000 }),
412            ),
413            session_id: resolve_exec_run_session_id(payload)?,
414            shell_program,
415            env_overrides: parse_exec_env_overrides(payload)?,
416            is_git_diff,
417            confirm,
418            rows,
419            cols,
420            sandbox_active,
421            background,
422            stdin,
423        })
424    }
425
426    pub(super) async fn execute_command_session(&self, args: Value) -> Result<Value> {
427        self.execute_command_session_internal(args, ExecSettlementMode::Manual).await
428    }
429
430    pub(super) async fn execute_harness_command_session_terminal_run_raw(&self, args: Value) -> Result<Value> {
431        let args = normalize_command_session_run_alias_args(&args, true)?;
432        self.execute_command_session_run_pty(args, true).await
433    }
434
435    fn dispatch_command_session_alias(&self, args: Value) -> BoxFuture<'_, Result<Value>> {
436        Box::pin(async move { self.execute_command_session(args).await.map(super::normalize_tool_output) })
437    }
438
439    fn dispatch_command_session_run_alias(&self, args: Value, tty: bool) -> BoxFuture<'_, Result<Value>> {
440        Box::pin(async move {
441            let args = normalize_command_session_run_alias_args(&args, tty)?;
442            self.execute_command_session(args).await.map(super::normalize_tool_output)
443        })
444    }
445
446    fn dispatch_command_session_action_alias(&self, args: Value, action: &'static str) -> BoxFuture<'_, Result<Value>> {
447        self.dispatch_command_session_alias(with_command_session_action_default(args, action))
448    }
449
450    pub(super) async fn execute_command_session_internal(
451        &self,
452        args: Value,
453        exec_settlement_mode: ExecSettlementMode,
454    ) -> Result<Value> {
455        let launch = self.begin_completion_verifier(&args);
456        let result = self.execute_command_session_observed(args.clone(), exec_settlement_mode).await;
457        self.observe_completion_verifier(launch, &args, &result);
458        result
459    }
460
461    async fn execute_command_session_observed(
462        &self,
463        args: Value,
464        exec_settlement_mode: ExecSettlementMode,
465    ) -> Result<Value> {
466        let args = crate::tools::command_args::normalize_shell_args(&args).map_err(|error| anyhow!(error))?;
467
468        let action_str =
469            tool_intent::command_session_action(&args).ok_or_else(|| missing_command_session_action_error(&args))?;
470        let action: CommandSessionAction = parse_action(action_str)?;
471
472        match action {
473            CommandSessionAction::Run => self.execute_command_session_run_internal(args, exec_settlement_mode).await,
474            CommandSessionAction::Write => self.execute_command_session_write(args).await,
475            CommandSessionAction::Poll => self.execute_command_session_poll_internal(args, exec_settlement_mode).await,
476            CommandSessionAction::Wait => self.execute_command_session_wait(args).await,
477            CommandSessionAction::Continue => {
478                self.execute_command_session_continue_internal(args, exec_settlement_mode).await
479            }
480            CommandSessionAction::Inspect => self.execute_command_session_inspect(args).await,
481            CommandSessionAction::List => self.execute_command_session_list().await,
482            CommandSessionAction::Close => self.execute_command_session_close(args).await,
483            CommandSessionAction::Code => self.execute_code(args).await,
484        }
485    }
486
487    async fn execute_command_session_run_internal(
488        &self,
489        args: Value,
490        exec_settlement_mode: ExecSettlementMode,
491    ) -> Result<Value> {
492        let tty = args.get("tty").and_then(Value::as_bool).unwrap_or(false);
493        if tty {
494            self.execute_command_session_run_pty(args, false).await
495        } else {
496            self.execute_run_pipe_cmd(args, exec_settlement_mode).await
497        }
498    }
499
500    async fn execute_code_search(&self, args: Value) -> Result<Value> {
501        let request = serde_json::from_value(args).context("invalid code_search request")?;
502        let response = crate::tools::code_search::execute(self.workspace_root(), request).await?;
503        serde_json::to_value(response).context("failed to serialise code_search response")
504    }
505
506    async fn execute_code(&self, args: Value) -> Result<Value> {
507        acquire_executor_rate_limit("unified_exec:code", 2.0)?;
508
509        let code = args
510            .get("command")
511            .or_else(|| args.get("code"))
512            .and_then(|v| v.as_str())
513            .ok_or_else(|| anyhow!("Missing code/command in execute_code"))?;
514
515        let cwd = self.workspace_root();
516        // Arbitrary interpreter code has the same file-writing authority as a
517        // shell script. It cannot be a route around guarded file mutations.
518        self.edited_file_monitor_ref().source_inspection().check_shell(&args, cwd)?;
519        let language = code_language_from_args(&args);
520
521        // The `code` action spawns the interpreter directly, so it must clear
522        // the same command policy as `run`: a policy that excludes
523        // `python3`/`node` must not be bypassed through code mode.
524        let interpreter = language.interpreter().to_string();
525        if !self.inventory.command_policy_allows(std::slice::from_ref(&interpreter)) {
526            return Err(anyhow!("code execution via '{interpreter}' is not permitted by the execution policy"));
527        }
528
529        let track_files = args.get("track_files").and_then(|v| v.as_bool()).unwrap_or(false);
530
531        let mcp_client = self.mcp_client().ok_or_else(|| anyhow!("MCP client not available"))?;
532
533        let workspace_root = self.workspace_root_owned();
534        // Expose built-in tools to the snippet as callable library functions
535        // (curated, non-recursive subset) when a weak self-reference was
536        // installed at session bootstrap.
537        let builtin_executor = self.builtin_executor_for_code();
538        let executor =
539            crate::exec::code_executor::CodeExecutor::new(language, mcp_client.clone(), workspace_root.clone())
540                .with_builtin_executor(builtin_executor);
541        let execution_start = SystemTime::now();
542
543        let result = executor.execute(code).await?;
544
545        let mut response = json!(result);
546
547        if track_files {
548            let tracker = FileTracker::new(workspace_root);
549            match tracker.detect_new_files(execution_start).await {
550                Ok(changes) => {
551                    response["generated_files"] = json!({
552                        "count": changes.len(),
553                        "files": changes,
554                        "summary": tracker.generate_file_summary(&changes),
555                    });
556                }
557                Err(e) => {
558                    tracing::warn!(
559                        error = %e,
560                        "FileTracker failed to detect new files after code execution"
561                    );
562                }
563            }
564        }
565
566        Ok(response)
567    }
568
569    async fn execute_apply_patch(&self, args: Value) -> Result<Value> {
570        let (patch_args, patch_input_bytes, patch_base64) = self.prepare_apply_patch_args(args)?;
571        let context = self.harness_context_snapshot();
572        tracing::debug!(
573            tool = tools::APPLY_PATCH,
574            payload_bytes = serialized_payload_size_bytes(&patch_args),
575            patch_input_bytes,
576            patch_base64,
577            patch_decoded_bytes = patch_args
578                .get("input")
579                .and_then(|v| v.as_str())
580                .map(|s| s.len())
581                .unwrap_or(0),
582            session_id = %context.session_id,
583            task_id = %context.task_id.as_deref().unwrap_or(""),
584            "Prepared apply_patch payload"
585        );
586
587        self.execute_apply_patch_internal(patch_args).await
588    }
589
590    fn prepare_apply_patch_args(&self, args: Value) -> Result<(Value, usize, bool)> {
591        let patch_input = crate::tools::apply_patch::decode_apply_patch_input(&args)?
592            .ok_or_else(|| anyhow!("Missing patch input {}", crate::tools::error_helpers::PATCH_PARAMETER_HINT))?;
593        let patch_input_bytes = patch_input.source_bytes;
594        let patch_base64 = patch_input.was_base64;
595
596        // Guard against a bare-string `args` (some callers pass the patch text
597        // directly as a JSON string rather than an object). Indexing a
598        // `Value::String` with `["input"]` panics in serde_json, so normalize
599        // to an object first.
600        let mut patch_args = if args.is_object() { args } else { json!({}) };
601        patch_args["input"] = json!(patch_input.text);
602        Ok((patch_args, patch_input_bytes, patch_base64))
603    }
604
605    async fn resolve_exec_sandbox_request(
606        &self,
607        payload: &serde_json::Map<String, Value>,
608    ) -> Result<ResolvedExecSandboxRequest> {
609        let working_dir_path = self.pty_manager().resolve_working_dir(shell_working_dir_value(payload)).await?;
610        let sandbox_config = self.sandbox_config();
611        let (sandbox_permissions, additional_permissions) =
612            parse_requested_sandbox_permissions(payload, self.workspace_root(), &working_dir_path, &sandbox_config)
613                .await?;
614
615        Ok(ResolvedExecSandboxRequest {
616            working_dir_path,
617            sandbox_permissions,
618            additional_permissions,
619        })
620    }
621
622    // ============================================================
623    // SPECIALIZED EXECUTORS (Hidden from LLM, used by unified tools)
624    // ============================================================
625
626    // File operation executors -- delegate to the file_ops_tool from inventory
627    delegate_to_tool!(read_file_executor, file_ops_tool, read_file);
628    delegate_to_tool!(write_file_executor, file_ops_tool, write_file);
629
630    // Self-delegating executors -- forward to async methods on ToolRegistry
631    delegate_to_self!(list_files_executor, list_files);
632    delegate_to_self!(edit_file_executor, edit_file);
633    delegate_to_self!(get_errors_executor, execute_get_errors);
634    delegate_to_self!(search_tools_executor, execute_search_tools);
635    delegate_to_self!(mcp_search_tools_executor, execute_mcp_search_tools);
636    delegate_to_self!(mcp_get_tool_details_executor, execute_mcp_get_tool_details);
637    delegate_to_self!(mcp_list_servers_executor, execute_mcp_list_servers);
638    delegate_to_self!(mcp_connect_server_executor, execute_mcp_connect_server);
639    delegate_to_self!(mcp_disconnect_server_executor, execute_mcp_disconnect_server);
640    delegate_to_self!(apply_patch_executor, execute_apply_patch);
641
642    /// Unified `mcp` executor: dispatches on `action`
643    /// (search_tools | get_tool_details | list_servers | connect | disconnect).
644    /// For legacy alias calls that omit `action`, the action is inferred from
645    /// the argument shape: `query` implies search_tools, `name` implies
646    /// get_tool_details, otherwise list_servers. `connect`/`disconnect` require
647    /// an explicit `action` since the schema marks it required, and are
648    /// evaluated under the action-qualified policy keys `mcp:connect` /
649    /// `mcp:disconnect` so they keep their Prompt confirmation even though
650    /// `mcp` itself is `ToolPolicy::Allow`.
651    #[cfg_attr(
652        not(test),
653        allow(
654            dead_code,
655            reason = "Legacy executor aliases remain available for compatibility tests."
656        )
657    )]
658    pub(super) fn mcp_executor(&self, args: Value) -> BoxFuture<'_, Result<Value>> {
659        Box::pin(async move {
660            let action = args
661                .get("action")
662                .and_then(Value::as_str)
663                .map(str::to_ascii_lowercase)
664                .unwrap_or_else(|| {
665                    if args.get("query").is_some() {
666                        "search_tools".to_string()
667                    } else if args.get("name").is_some() {
668                        "get_tool_details".to_string()
669                    } else {
670                        "list_servers".to_string()
671                    }
672                });
673            match action.as_str() {
674                "search_tools" => self.mcp_search_tools_executor(args).await,
675                "get_tool_details" => self.mcp_get_tool_details_executor(args).await,
676                "list_servers" => self.mcp_list_servers_executor(args).await,
677                "connect" => self.mcp_connect_server_executor(args).await,
678                "disconnect" => self.mcp_disconnect_server_executor(args).await,
679                other => Err(anyhow!(
680                    "mcp: unknown action '{other}'. Use action='search_tools' (query), 'get_tool_details' (name), 'list_servers', 'connect' (name), or 'disconnect' (name)."
681                )),
682            }
683        })
684    }
685
686    // PTY executors -- distinct signatures, kept explicit.
687    // `run_pty_cmd` and `create_pty_session` are intentional aliases: both
688    // create a PTY session and run a command. The separate names exist for
689    // backward compatibility with existing tool registrations.
690    pub(super) fn run_pty_cmd_executor(&self, args: Value) -> BoxFuture<'_, Result<Value>> {
691        self.dispatch_command_session_run_alias(args, true)
692    }
693
694    pub(super) fn exec_command_executor(&self, args: Value) -> BoxFuture<'_, Result<Value>> {
695        self.dispatch_command_session_run_alias(args, false)
696    }
697
698    pub(super) fn write_stdin_executor(&self, args: Value) -> BoxFuture<'_, Result<Value>> {
699        Box::pin(self.execute_write_stdin(args, ExecSettlementMode::Manual))
700    }
701
702    pub(super) async fn execute_write_stdin(&self, args: Value, settlement_mode: ExecSettlementMode) -> Result<Value> {
703        let (args, dispatch) = normalize_write_stdin_args(&args)?;
704
705        let observed_args = args.clone();
706        let result = async {
707            let response = match dispatch {
708                crate::tools::command_args::WriteStdinDispatch::Write => {
709                    self.execute_command_session_write_for_tool(args, tools::WRITE_STDIN).await
710                }
711                crate::tools::command_args::WriteStdinDispatch::Poll => {
712                    self.execute_command_session_poll_for_tool(args, settlement_mode, tools::WRITE_STDIN)
713                        .await
714                }
715                crate::tools::command_args::WriteStdinDispatch::Wait => self.execute_command_session_wait(args).await,
716                crate::tools::command_args::WriteStdinDispatch::Inspect => {
717                    self.execute_command_session_inspect(args).await
718                }
719                crate::tools::command_args::WriteStdinDispatch::Terminate => {
720                    self.execute_command_session_terminate(args).await
721                }
722                crate::tools::command_args::WriteStdinDispatch::Close => self.execute_command_session_close(args).await,
723            }?;
724            Ok(response)
725        }
726        .await;
727        self.observe_completion_verifier(None, &observed_args, &result);
728        result
729    }
730
731    pub(super) fn send_pty_input_executor(&self, args: Value) -> BoxFuture<'_, Result<Value>> {
732        self.dispatch_command_session_action_alias(args, "write")
733    }
734
735    pub(super) fn read_pty_session_executor(&self, args: Value) -> BoxFuture<'_, Result<Value>> {
736        self.dispatch_command_session_action_alias(args, "poll")
737    }
738
739    pub(super) fn create_pty_session_executor(&self, args: Value) -> BoxFuture<'_, Result<Value>> {
740        self.dispatch_command_session_run_alias(args, true)
741    }
742
743    pub(super) fn list_pty_sessions_executor(&self, _args: Value) -> BoxFuture<'_, Result<Value>> {
744        self.dispatch_command_session_alias(json!({"action": "list"}))
745    }
746
747    pub(super) fn close_pty_session_executor(&self, args: Value) -> BoxFuture<'_, Result<Value>> {
748        self.dispatch_command_session_action_alias(args, "close")
749    }
750
751    // ============================================================
752    // INTERNAL IMPLEMENTATIONS
753    // ============================================================
754}
755
756#[cfg(test)]
757mod execute_code_tests {
758    use serde_json::json;
759
760    use super::code_language_from_args;
761    use crate::exec::code_executor::Language;
762
763    #[test]
764    fn code_language_uses_language_field_instead_of_action() {
765        assert_eq!(
766            code_language_from_args(&json!({
767                "action": "code",
768                "language": "javascript",
769            })),
770            Language::JavaScript
771        );
772        assert_eq!(
773            code_language_from_args(&json!({
774                "action": "code",
775                "lang": "js",
776            })),
777            Language::JavaScript
778        );
779        assert_eq!(
780            code_language_from_args(&json!({
781                "action": "code",
782            })),
783            Language::Python3
784        );
785    }
786}
787
788#[cfg(test)]
789mod subagent_tool_output_tests {
790    use serde_json::json;
791    use tempfile::TempDir;
792
793    use super::sanitize_subagent_tool_output_paths;
794
795    #[test]
796    fn strips_transcript_paths_outside_workspace() {
797        let temp = TempDir::new().expect("tempdir");
798        let mut value = json!({
799            "completed": true,
800            "entry": {
801                "id": "agent-1",
802                "transcript_path": "/Users/example/.vtcode/sessions/agent-1.json",
803            }
804        });
805
806        sanitize_subagent_tool_output_paths(temp.path(), &mut value);
807
808        assert!(value["entry"].get("transcript_path").is_none());
809    }
810
811    #[test]
812    fn keeps_transcript_paths_inside_workspace() {
813        let temp = TempDir::new().expect("tempdir");
814        let transcript_path = temp.path().join(".vtcode/context/subagents/agent-1.json");
815        let mut value = json!({
816            "id": "agent-1",
817            "transcript_path": transcript_path,
818        });
819
820        sanitize_subagent_tool_output_paths(temp.path(), &mut value);
821
822        assert_eq!(value["transcript_path"].as_str(), transcript_path.to_str());
823    }
824}
825
826#[cfg(test)]
827mod shell_preference_tests {
828    use super::{resolve_shell_preference, resolve_shell_preference_with_zsh_fork};
829    use crate::config::PtyConfig;
830    use crate::tools::shell::resolve_fallback_shell;
831
832    #[test]
833    fn explicit_shell_overrides_config_preference() {
834        let config = PtyConfig {
835            preferred_shell: Some("/bin/bash".to_string()),
836            ..Default::default()
837        };
838
839        let resolved = resolve_shell_preference(Some(" /bin/zsh "), &config);
840        assert_eq!(resolved, "/bin/zsh");
841    }
842
843    #[test]
844    fn config_preferred_shell_used_when_explicit_missing() {
845        let config = PtyConfig {
846            preferred_shell: Some("zsh".to_string()),
847            ..Default::default()
848        };
849
850        let resolved = resolve_shell_preference(None, &config);
851        assert_eq!(resolved, "zsh");
852    }
853
854    #[test]
855    fn blank_explicit_shell_falls_back_to_config_preference() {
856        let config = PtyConfig {
857            preferred_shell: Some("bash".to_string()),
858            ..Default::default()
859        };
860
861        let resolved = resolve_shell_preference(Some("   "), &config);
862        assert_eq!(resolved, "bash");
863    }
864
865    #[test]
866    fn blank_config_shell_falls_back_to_default_resolver() {
867        let config = PtyConfig {
868            preferred_shell: Some("   ".to_string()),
869            ..Default::default()
870        };
871
872        let resolved = resolve_shell_preference(None, &config);
873        assert_eq!(resolved, resolve_fallback_shell());
874    }
875
876    #[test]
877    fn missing_preferences_fall_back_to_default_resolver() {
878        let config = PtyConfig::default();
879        let resolved = resolve_shell_preference(None, &config);
880        assert_eq!(resolved, resolve_fallback_shell());
881    }
882
883    #[test]
884    fn zsh_fork_disabled_uses_standard_shell_resolution() -> anyhow::Result<()> {
885        let config = PtyConfig {
886            preferred_shell: Some("/bin/bash".to_string()),
887            ..Default::default()
888        };
889        let resolved = resolve_shell_preference_with_zsh_fork(None, &config)?;
890        assert_eq!(resolved, "/bin/bash");
891        Ok(())
892    }
893
894    #[test]
895    fn zsh_fork_missing_path_returns_error() {
896        let config = PtyConfig {
897            shell_zsh_fork: true,
898            zsh_path: None,
899            ..PtyConfig::default()
900        };
901        resolve_shell_preference_with_zsh_fork(Some("/bin/bash"), &config).unwrap_err();
902    }
903
904    #[cfg(unix)]
905    #[test]
906    fn zsh_fork_ignores_explicit_shell_and_uses_configured_path() -> anyhow::Result<()> {
907        let zsh = tempfile::NamedTempFile::new()?;
908        let expected = zsh.path().to_string_lossy().to_string();
909        let config = PtyConfig {
910            shell_zsh_fork: true,
911            zsh_path: Some(expected.clone()),
912            ..PtyConfig::default()
913        };
914        let resolved = resolve_shell_preference_with_zsh_fork(Some("/bin/bash"), &config)?;
915        assert_eq!(resolved, expected);
916        Ok(())
917    }
918}
919
920#[cfg(test)]
921mod token_efficiency_tests {
922    use super::*;
923
924    #[test]
925    fn test_suggests_limit_for_cat() {
926        assert_eq!(suggest_max_tokens_for_command("cat file.txt"), Some(250));
927        assert_eq!(suggest_max_tokens_for_command("cat /path/to/file.rs"), Some(250));
928        assert_eq!(suggest_max_tokens_for_command("CAT file.txt"), Some(250)); // case insensitive
929    }
930
931    #[test]
932    fn test_suggests_limit_for_bat() {
933        assert_eq!(suggest_max_tokens_for_command("bat file.rs"), Some(250));
934    }
935
936    #[test]
937    fn test_no_limit_when_already_limited() {
938        assert_eq!(suggest_max_tokens_for_command("cat file.txt | head"), None);
939        assert_eq!(suggest_max_tokens_for_command("head -n 50 file.txt"), None);
940        assert_eq!(suggest_max_tokens_for_command("tail -n 20 file.txt"), None);
941    }
942
943    #[test]
944    fn test_no_limit_for_other_commands() {
945        assert_eq!(suggest_max_tokens_for_command("ls -la"), None);
946        assert_eq!(suggest_max_tokens_for_command("grep pattern file"), None);
947        assert_eq!(suggest_max_tokens_for_command("echo hello"), None);
948    }
949}
950
951#[cfg(test)]
952mod pty_output_filter_tests {
953    use super::filter_pty_output;
954
955    #[test]
956    fn normalizes_crlf_sequences() {
957        let raw = "a\r\nb\rc\n";
958        assert_eq!(filter_pty_output(raw), "a\nb\nc\n");
959    }
960}
961
962#[cfg(test)]
963mod pty_context_tests {
964    use serde_json::json;
965
966    use super::{
967        ExecOutputPreview, PtyEphemeralCapture, attach_exec_response_context, attach_pty_continuation,
968        build_exec_response, build_exec_session_command_display,
969    };
970    use crate::tools::types::VTCodeExecSession;
971
972    #[test]
973    fn build_exec_session_command_display_unwraps_shell_c_argument() {
974        let session = VTCodeExecSession {
975            id: "run-123".to_string().into(),
976            backend: "pty".to_string(),
977            command: "zsh".to_string(),
978            args: vec!["-l".to_string(), "-c".to_string(), "cargo check".to_string()],
979            working_dir: Some(".".to_string()),
980            background: false,
981            rows: Some(24),
982            cols: Some(80),
983            child_pid: None,
984            started_at: None,
985            lifecycle_state: None,
986            exit_code: None,
987        };
988
989        assert_eq!(build_exec_session_command_display(&session), "cargo check");
990    }
991
992    #[test]
993    fn attach_exec_response_context_sets_expected_keys() {
994        let mut response = json!({ "output": "ok" });
995        let session = VTCodeExecSession {
996            id: "run-123".to_string().into(),
997            backend: "pty".to_string(),
998            command: "zsh".to_string(),
999            args: vec!["-l".to_string(), "-c".to_string(), "cargo check".to_string()],
1000            working_dir: Some(".".to_string()),
1001            background: false,
1002            rows: Some(30),
1003            cols: Some(120),
1004            child_pid: None,
1005            started_at: None,
1006            lifecycle_state: None,
1007            exit_code: None,
1008        };
1009
1010        attach_exec_response_context(&mut response, &session, "cargo check", false);
1011
1012        assert_eq!(response["session_id"], "run-123");
1013        assert_eq!(response["command"], "cargo check");
1014        assert_eq!(response["working_directory"], ".");
1015        assert_eq!(response["backend"], "pty");
1016        assert_eq!(response["rows"], 30);
1017        assert_eq!(response["cols"], 120);
1018        assert_eq!(response["is_exited"], false);
1019    }
1020
1021    #[test]
1022    fn attach_pty_continuation_compacts_next_continue_args() {
1023        let mut response = json!({ "output": "ok" });
1024        attach_pty_continuation(&mut response, "run-123");
1025
1026        assert!(response.get("follow_up_prompt").is_none());
1027        assert!(response.get("next_poll_args").is_none());
1028        assert_eq!(response["next_continue_args"], json!({ "session_id": "run-123" }));
1029        assert!(response.get("preferred_next_action").is_none());
1030    }
1031
1032    #[test]
1033    fn attach_pty_continuation_keeps_payload_compact() {
1034        let mut response = json!({ "output": "ok" });
1035        attach_pty_continuation(&mut response, "run-123");
1036
1037        assert!(response.get("follow_up_prompt").is_none());
1038        assert!(response.get("next_poll_args").is_none());
1039        assert_eq!(response["next_continue_args"], json!({ "session_id": "run-123" }));
1040    }
1041
1042    #[test]
1043    fn build_exec_response_skips_continuation_after_exit() {
1044        let session = VTCodeExecSession {
1045            id: "run-123".to_string().into(),
1046            backend: "pipe".to_string(),
1047            command: "cargo".to_string(),
1048            args: vec!["check".to_string()],
1049            working_dir: Some(".".to_string()),
1050            background: false,
1051            rows: None,
1052            cols: None,
1053            child_pid: None,
1054            started_at: None,
1055            lifecycle_state: None,
1056            exit_code: None,
1057        };
1058        let capture = PtyEphemeralCapture {
1059            output: "first\nsecond\n".to_string(),
1060            exit_code: Some(0),
1061            duration: std::time::Duration::from_millis(25),
1062        };
1063
1064        let response = build_exec_response(
1065            &session,
1066            "cargo check",
1067            &capture,
1068            ExecOutputPreview {
1069                raw_output: "first\nsecond\n".to_string(),
1070                output: "first\n[Output truncated]".to_string(),
1071                truncated: true,
1072            },
1073            None,
1074            false,
1075            None,
1076        );
1077
1078        assert_eq!(response["exit_code"], 0);
1079        assert!(response.get("next_continue_args").is_none());
1080    }
1081
1082    #[test]
1083    fn build_exec_response_steers_still_running_to_wait_action() {
1084        let session = VTCodeExecSession {
1085            id: "run-abc".to_string().into(),
1086            backend: "pipe".to_string(),
1087            command: "cargo".to_string(),
1088            args: vec!["build".to_string()],
1089            working_dir: Some(".".to_string()),
1090            background: false,
1091            rows: None,
1092            cols: None,
1093            child_pid: None,
1094            started_at: None,
1095            lifecycle_state: None,
1096            exit_code: None,
1097        };
1098        let capture = PtyEphemeralCapture {
1099            output: "   Compiling vtcode-core\n".to_string(),
1100            exit_code: None,
1101            duration: std::time::Duration::from_secs(10),
1102        };
1103
1104        let response = build_exec_response(
1105            &session,
1106            "cargo build",
1107            &capture,
1108            ExecOutputPreview {
1109                raw_output: "   Compiling vtcode-core\n".to_string(),
1110                output: "   Compiling vtcode-core\n".to_string(),
1111                truncated: false,
1112            },
1113            None,
1114            false,
1115            Some("run-abc"),
1116        );
1117
1118        // The poll-oriented continuation is still attached for incremental peeks.
1119        assert_eq!(response["next_continue_args"], json!({ "session_id": "run-abc" }));
1120        // The no-burn wait action is pre-filled and ready to reuse.
1121        assert_eq!(response["next_wait_args"]["session_id"], "run-abc");
1122        assert_eq!(response["next_wait_args"]["action"], "wait");
1123        assert_eq!(response["next_wait_args"]["wait_timeout_seconds"], 600);
1124        // The hint ranks wait ahead of polling and names the tool to call.
1125        let hint = response["next_action_hint"].as_str().expect("hint present");
1126        assert!(hint.contains("write_stdin"));
1127        assert!(hint.contains("next_wait_args"));
1128        assert!(hint.contains("no model round-trips"));
1129        assert!(hint.contains("exempt from the per-turn tool-call budget"));
1130        assert!(hint.contains("next_continue_args"));
1131        assert_eq!(response["is_exited"], false);
1132        assert_eq!(response["process_id"], "run-abc");
1133    }
1134}
1135
1136#[cfg(test)]
1137mod git_diff_tests {
1138    use super::is_git_diff_command;
1139
1140    #[test]
1141    fn detects_git_diff() {
1142        let cmd = vec!["git".to_string(), "diff".to_string()];
1143        assert!(is_git_diff_command(&cmd));
1144    }
1145
1146    #[test]
1147    fn detects_git_diff_with_flags() {
1148        let cmd = vec![
1149            "git".to_string(),
1150            "-c".to_string(),
1151            "color.ui=always".to_string(),
1152            "diff".to_string(),
1153            "--stat".to_string(),
1154        ];
1155        assert!(is_git_diff_command(&cmd));
1156    }
1157
1158    #[test]
1159    fn detects_git_diff_with_path() {
1160        let cmd = vec!["/usr/bin/git".to_string(), "diff".to_string()];
1161        assert!(is_git_diff_command(&cmd));
1162    }
1163
1164    #[test]
1165    fn ignores_other_git_commands() {
1166        let cmd = vec!["git".to_string(), "status".to_string()];
1167        assert!(!is_git_diff_command(&cmd));
1168    }
1169}
1170
1171#[cfg(test)]
1172mod unified_action_error_tests {
1173    use std::time::Duration;
1174
1175    use serde_json::json;
1176
1177    use super::{
1178        CargoTestCommandKind, ExecOutputPreview, PtyEphemeralCapture, attach_exec_recovery_guidance,
1179        attach_failure_diagnostics_metadata, build_exec_output_preview, build_exec_response, build_head_tail_preview,
1180        cargo_selector_error_diagnostics, cargo_test_failure_diagnostics, cargo_test_rerun_hint, clamp_inspect_lines,
1181        clamp_max_matches, extract_run_session_id_from_read_file_error, extract_run_session_id_from_tool_output_path,
1182        filter_lines, missing_command_session_action_error, resolve_exec_run_session_id, summarized_arg_keys,
1183    };
1184    use crate::tools::types::VTCodeExecSession;
1185
1186    #[test]
1187    fn summarized_arg_keys_reports_shape_for_non_object_payloads() {
1188        assert_eq!(summarized_arg_keys(&json!(null)), "<null>");
1189        assert_eq!(summarized_arg_keys(&json!(["a", "b"])), "<array>");
1190        assert_eq!(summarized_arg_keys(&json!("x")), "<string>");
1191    }
1192
1193    #[test]
1194    fn exec_command_missing_action_error_includes_received_keys() {
1195        let err = missing_command_session_action_error(&json!({
1196            "foo": "bar",
1197            "session_id": "123"
1198        }));
1199        let text = err.to_string();
1200        assert!(text.contains("Missing command session action"));
1201        assert!(text.contains("foo"));
1202        assert!(text.contains("session_id"));
1203    }
1204
1205    #[test]
1206    fn extracts_run_session_id_from_tool_output_path() {
1207        assert_eq!(
1208            extract_run_session_id_from_tool_output_path(".vtcode/context/tool_outputs/run-abc123.txt"),
1209            Some("run-abc123".to_string())
1210        );
1211        assert_eq!(
1212            extract_run_session_id_from_tool_output_path(".vtcode/context/tool_outputs/not-a-session.txt"),
1213            None
1214        );
1215    }
1216
1217    #[test]
1218    fn extracts_run_session_id_from_read_file_error() {
1219        let error = "Use exec_command with session_id=\"run-zz9\" instead of read_file.";
1220        assert_eq!(extract_run_session_id_from_read_file_error(error), Some("run-zz9".to_string()));
1221        assert_eq!(extract_run_session_id_from_read_file_error("no session"), None);
1222    }
1223
1224    #[test]
1225    fn resolve_exec_run_session_id_prefers_requested_session_id() {
1226        let payload = json!({ "session_id": " check_sh " });
1227        let payload = payload.as_object().expect("object");
1228
1229        assert_eq!(resolve_exec_run_session_id(payload).expect("requested session id"), "check_sh");
1230    }
1231
1232    #[test]
1233    fn resolve_exec_run_session_id_generates_default_when_missing() {
1234        let payload = json!({});
1235        let payload = payload.as_object().expect("object");
1236        let session_id = resolve_exec_run_session_id(payload).expect("generated session id");
1237
1238        assert!(session_id.starts_with("run-"));
1239    }
1240
1241    #[test]
1242    fn resolve_exec_run_session_id_rejects_invalid_values() {
1243        let payload = json!({ "session_id": "bad id" });
1244        let payload = payload.as_object().expect("object");
1245        let err = resolve_exec_run_session_id(payload).expect_err("invalid session id");
1246
1247        assert!(err.to_string().contains("Invalid session_id"));
1248    }
1249
1250    #[test]
1251    fn inspect_helpers_clamp_limits() {
1252        assert_eq!(clamp_inspect_lines(Some(0), 30), 0);
1253        assert_eq!(clamp_inspect_lines(Some(9_999), 30), 5_000);
1254        assert_eq!(clamp_max_matches(None), 200);
1255        assert_eq!(clamp_max_matches(Some(0)), 1);
1256        assert_eq!(clamp_max_matches(Some(50_000)), 10_000);
1257    }
1258
1259    #[test]
1260    fn inspect_helpers_build_head_tail_preview() {
1261        let content = "l1\nl2\nl3\nl4\nl5\nl6";
1262        let (preview, truncated) = build_head_tail_preview(content, 2, 2);
1263        assert!(truncated);
1264        assert!(preview.contains("l1"));
1265        assert!(preview.contains("l2"));
1266        assert!(preview.contains("l5"));
1267        assert!(preview.contains("l6"));
1268    }
1269
1270    #[test]
1271    fn inspect_helpers_filter_lines_literal() {
1272        let (output, matched, truncated) = filter_lines("alpha\nbeta\nalpha2", "alpha", true, 1).expect("filter");
1273        assert_eq!(matched, 2);
1274        assert!(truncated);
1275        assert!(output.contains("1: alpha"));
1276    }
1277
1278    #[test]
1279    fn exec_output_preview_truncates_on_utf8_boundaries() {
1280        let (preview, truncated) = build_exec_output_preview("a🙂b", 1);
1281
1282        assert!(truncated);
1283        // The byte window is head+tail, so the last output content survives
1284        // the cut (the part that carries build/test summaries).
1285        assert!(preview.starts_with('a'));
1286        assert!(preview.ends_with('b'));
1287        assert!(preview.contains("bytes omitted"));
1288        std::str::from_utf8(preview.as_bytes()).unwrap();
1289    }
1290
1291    #[test]
1292    fn exec_output_preview_keeps_tail_of_long_output_within_budget() {
1293        let lines: String = (0..1000).map(|idx| format!("line {idx}\n")).collect();
1294        let (preview, truncated) = build_exec_output_preview(&lines, 1000);
1295
1296        assert!(truncated);
1297        // Head shows the first line, tail shows the last — a head-only cut
1298        // lost the tail where build/test summaries live.
1299        assert!(preview.starts_with("line 0\n"));
1300        assert!(preview.trim_end().ends_with("line 999"));
1301        assert!(preview.contains("bytes omitted"));
1302        // The inline budget stays essentially intact (marker bytes aside).
1303        assert!(preview.len() <= 1000 * 4 + 64, "preview {} must stay near the 4000-byte budget", preview.len());
1304    }
1305
1306    #[test]
1307    fn exec_recovery_guidance_sets_command_not_found_metadata() {
1308        let session = VTCodeExecSession {
1309            id: "run-123".to_string().into(),
1310            backend: "pipe".to_string(),
1311            command: "zsh".to_string(),
1312            args: vec!["-c".to_string(), "pip install pymupdf".to_string()],
1313            working_dir: Some(".".to_string()),
1314            background: false,
1315            rows: None,
1316            cols: None,
1317            child_pid: None,
1318            started_at: None,
1319            lifecycle_state: None,
1320            exit_code: None,
1321        };
1322        let capture = PtyEphemeralCapture {
1323            output: String::new(),
1324            exit_code: Some(127),
1325            duration: Duration::from_millis(42),
1326        };
1327
1328        let response = build_exec_response(
1329            &session,
1330            "pip install pymupdf",
1331            &capture,
1332            ExecOutputPreview {
1333                raw_output: "bash: pip: command not found".to_string(),
1334                output: "bash: pip: command not found".to_string(),
1335                truncated: false,
1336            },
1337            None,
1338            false,
1339            None,
1340        );
1341
1342        assert_eq!(response["output"], "bash: pip: command not found");
1343        assert_eq!(response["exit_code"], 127);
1344        assert_eq!(response["session_id"], "run-123");
1345        assert_eq!(response["command"], "pip install pymupdf");
1346        assert_eq!(response["critical_note"], "Command `pip` was not found in PATH.");
1347        assert_eq!(
1348            response["next_action"],
1349            "Check the command name or install the missing binary, then rerun the command."
1350        );
1351    }
1352
1353    #[test]
1354    fn exec_recovery_guidance_ignores_non_command_not_found_exit_codes() {
1355        let mut response = json!({});
1356        attach_exec_recovery_guidance(&mut response, "cargo test", Some(1));
1357        assert!(response.get("critical_note").is_none());
1358        assert!(response.get("next_action").is_none());
1359    }
1360
1361    #[test]
1362    fn exec_recovery_guidance_redirects_apply_patch_shell_collision_to_tool() {
1363        let mut response = json!({});
1364        attach_exec_recovery_guidance(&mut response, "apply_patch", Some(127));
1365        assert_eq!(
1366            response["critical_note"],
1367            "Command `apply_patch` is not a shell binary — use the `apply_patch` tool instead."
1368        );
1369        assert!(
1370            response["next_action"]
1371                .as_str()
1372                .expect("next_action present")
1373                .contains("Call the `apply_patch` tool")
1374        );
1375
1376        let mut aliased = json!({});
1377        attach_exec_recovery_guidance(&mut aliased, "applypatch", Some(127));
1378        assert_eq!(aliased["critical_note"], response["critical_note"]);
1379
1380        let mut with_args = json!({});
1381        attach_exec_recovery_guidance(&mut with_args, "/usr/bin/apply_patch --help", Some(127));
1382        assert_eq!(with_args["critical_note"], response["critical_note"]);
1383
1384        let mut sudo_prefixed = json!({});
1385        attach_exec_recovery_guidance(&mut sudo_prefixed, "sudo apply_patch", Some(127));
1386        assert_eq!(sudo_prefixed["critical_note"], "Command `sudo` was not found in PATH.");
1387    }
1388
1389    #[test]
1390    fn cargo_selector_error_diagnostics_classifies_missing_test_target() {
1391        let output = "error: no test target named `exec_only_policy_skips_when_full_auto_is_disabled` in `vtcode-core` package\n";
1392
1393        let diagnostics = cargo_selector_error_diagnostics(
1394            CargoTestCommandKind::Nextest,
1395            "cargo nextest run --test exec_only_policy_skips_when_full_auto_is_disabled -p vtcode-core --no-capture",
1396            output,
1397        )
1398        .expect("selector diagnostics");
1399
1400        assert_eq!(diagnostics["kind"], "cargo_test_selector_error");
1401        assert_eq!(diagnostics["package"], "vtcode-core");
1402        assert_eq!(diagnostics["requested_test_target"], "exec_only_policy_skips_when_full_auto_is_disabled");
1403        assert_eq!(diagnostics["selector_error"], true);
1404        assert_eq!(
1405            diagnostics["validation_hint"],
1406            "cargo test -p vtcode-core --lib -- --list | rg 'exec_only_policy_skips_when_full_auto_is_disabled'"
1407        );
1408        assert_eq!(
1409            diagnostics["rerun_hint"],
1410            "cargo nextest run -p vtcode-core exec_only_policy_skips_when_full_auto_is_disabled"
1411        );
1412    }
1413
1414    #[test]
1415    fn cargo_test_failure_diagnostics_extracts_unit_test_failure_details() {
1416        let output = r#"────────────
1417    Nextest run ID 18fffe01-0ef9-4113-9a81-2344a7cc3c16 with nextest profile: default
1418        FAIL [   0.216s] ( 363/2669) vtcode-core core::agent::runner::tests::exec_only_policy_skips_when_full_auto_is_disabled
1419    stderr ───
1420    thread 'core::agent::runner::tests::exec_only_policy_skips_when_full_auto_is_disabled' (382951) panicked at crates/codegen/vtcode-core/src/core/agent/runner/tests.rs:692:10:
1421    task result: Invalid request: QueuedProvider has no queued responses
1422"#;
1423
1424        let diagnostics = cargo_test_failure_diagnostics("cargo nextest run -p vtcode-core", output, Some(100))
1425            .expect("failure diagnostics");
1426
1427        assert_eq!(diagnostics["kind"], "cargo_test_failure");
1428        assert_eq!(diagnostics["package"], "vtcode-core");
1429        assert_eq!(diagnostics["binary_kind"], "unit");
1430        assert_eq!(
1431            diagnostics["test_fqname"],
1432            "core::agent::runner::tests::exec_only_policy_skips_when_full_auto_is_disabled"
1433        );
1434        assert_eq!(diagnostics["panic"], "task result: Invalid request: QueuedProvider has no queued responses");
1435        assert_eq!(diagnostics["source_file"], "crates/codegen/vtcode-core/src/core/agent/runner/tests.rs");
1436        assert_eq!(diagnostics["source_line"], 692);
1437        assert_eq!(
1438            diagnostics["rerun_hint"],
1439            cargo_test_rerun_hint(
1440                CargoTestCommandKind::Nextest,
1441                "vtcode-core",
1442                "unit",
1443                "core::agent::runner::tests::exec_only_policy_skips_when_full_auto_is_disabled",
1444            )
1445        );
1446    }
1447
1448    #[test]
1449    fn build_exec_response_attaches_cargo_failure_diagnostics() {
1450        let session = VTCodeExecSession {
1451            id: "run-123".to_string().into(),
1452            backend: "pipe".to_string(),
1453            command: "cargo".to_string(),
1454            args: vec![
1455                "nextest".to_string(),
1456                "run".to_string(),
1457                "-p".to_string(),
1458                "vtcode-core".to_string(),
1459            ],
1460            working_dir: Some(".".to_string()),
1461            background: false,
1462            rows: None,
1463            cols: None,
1464            child_pid: None,
1465            started_at: None,
1466            lifecycle_state: None,
1467            exit_code: None,
1468        };
1469        let raw_output = r#"
1470        FAIL [   0.216s] ( 363/2669) vtcode-core core::agent::runner::tests::exec_only_policy_skips_when_full_auto_is_disabled
1471    thread 'core::agent::runner::tests::exec_only_policy_skips_when_full_auto_is_disabled' (382951) panicked at crates/codegen/vtcode-core/src/core/agent/runner/tests.rs:692:10:
1472    task result: Invalid request: QueuedProvider has no queued responses
1473"#;
1474        let capture = PtyEphemeralCapture {
1475            output: raw_output.to_string(),
1476            exit_code: Some(100),
1477            duration: Duration::from_millis(42),
1478        };
1479
1480        let response = build_exec_response(
1481            &session,
1482            "cargo nextest run -p vtcode-core",
1483            &capture,
1484            ExecOutputPreview {
1485                raw_output: raw_output.to_string(),
1486                output: raw_output.to_string(),
1487                truncated: false,
1488            },
1489            None,
1490            false,
1491            None,
1492        );
1493
1494        assert_eq!(
1495            response["failure_diagnostics"]["test_fqname"],
1496            "core::agent::runner::tests::exec_only_policy_skips_when_full_auto_is_disabled"
1497        );
1498        assert_eq!(response["package"], "vtcode-core");
1499        assert_eq!(response["binary_kind"], "unit");
1500        assert_eq!(response["source_file"], "crates/codegen/vtcode-core/src/core/agent/runner/tests.rs");
1501        assert_eq!(response["source_line"], 692);
1502        assert_eq!(
1503            response["rerun_hint"],
1504            "cargo nextest run -p vtcode-core core::agent::runner::tests::exec_only_policy_skips_when_full_auto_is_disabled"
1505        );
1506        assert_eq!(
1507            response["next_action"],
1508            "Rerun the failing test directly with: cargo nextest run -p vtcode-core core::agent::runner::tests::exec_only_policy_skips_when_full_auto_is_disabled"
1509        );
1510    }
1511
1512    #[test]
1513    fn attach_failure_diagnostics_metadata_promotes_selector_hints() {
1514        let mut response = json!({
1515            "success": true,
1516            "command": "cargo nextest run --test bad -p vtcode-core"
1517        });
1518        let diagnostics = json!({
1519            "kind": "cargo_test_selector_error",
1520            "package": "vtcode-core",
1521            "binary_kind": "test_target_selector",
1522            "requested_test_target": "bad",
1523            "selector_error": true,
1524            "validation_hint": "cargo test -p vtcode-core --lib -- --list | rg 'bad'",
1525            "rerun_hint": "cargo nextest run -p vtcode-core bad",
1526            "critical_note": "selector mismatch",
1527            "next_action": "validate first"
1528        });
1529
1530        attach_failure_diagnostics_metadata(&mut response, &diagnostics);
1531
1532        assert_eq!(response["package"], "vtcode-core");
1533        assert_eq!(response["binary_kind"], "test_target_selector");
1534        assert_eq!(response["selector_error"], true);
1535        assert_eq!(response["validation_hint"], "cargo test -p vtcode-core --lib -- --list | rg 'bad'");
1536        assert_eq!(response["rerun_hint"], "cargo nextest run -p vtcode-core bad");
1537        assert_eq!(response["critical_note"], "selector mismatch");
1538        assert_eq!(response["next_action"], "validate first");
1539        assert_eq!(response["failure_diagnostics"]["kind"], "cargo_test_selector_error");
1540    }
1541}
1542
1543#[cfg(test)]
1544#[path = "executors/sandbox_runtime_tests.rs"]
1545mod sandbox_runtime_tests;
1546
1547#[cfg(test)]
1548mod mcp_action_dispatch_tests {
1549    use serde_json::json;
1550
1551    use super::ToolRegistry;
1552
1553    /// `mcp_executor` must dispatch `action='connect'`/`'disconnect'` to
1554    /// `mcp_connect_server_executor`/`mcp_disconnect_server_executor` rather
1555    /// than falling through to the unknown-action branch. A bare
1556    /// `ToolRegistry::new` has no MCP client configured, so both calls fail
1557    /// at the `mcp_client()` lookup inside the delegated executor -- but the
1558    /// error text proves the dispatch reached the right function.
1559    #[tokio::test]
1560    async fn mcp_executor_dispatches_connect_and_disconnect_actions() {
1561        let temp = tempfile::tempdir().expect("tempdir");
1562        let registry = ToolRegistry::new(temp.path().to_path_buf()).await;
1563
1564        let connect_err = registry
1565            .mcp_executor(json!({"action": "connect", "name": "example"}))
1566            .await
1567            .expect_err("connect without an active mcp client should fail");
1568        let connect_text = connect_err.to_string();
1569        assert!(!connect_text.contains("unknown action"));
1570        assert!(connect_text.contains("MCP client not available"));
1571
1572        let disconnect_err = registry
1573            .mcp_executor(json!({"action": "disconnect", "name": "example"}))
1574            .await
1575            .expect_err("disconnect without an active mcp client should fail");
1576        let disconnect_text = disconnect_err.to_string();
1577        assert!(!disconnect_text.contains("unknown action"));
1578        assert!(disconnect_text.contains("MCP client not available"));
1579    }
1580
1581    #[tokio::test]
1582    async fn mcp_executor_rejects_unknown_action_with_guidance() {
1583        let temp = tempfile::tempdir().expect("tempdir");
1584        let registry = ToolRegistry::new(temp.path().to_path_buf()).await;
1585
1586        let err = registry
1587            .mcp_executor(json!({"action": "bogus"}))
1588            .await
1589            .expect_err("unknown mcp action should error");
1590        let text = err.to_string();
1591        assert!(text.contains("unknown action 'bogus'"));
1592        assert!(text.contains("connect"));
1593        assert!(text.contains("disconnect"));
1594    }
1595}