Skip to main content

orch/engine/runner/
agent.rs

1//! Agent command building + tmux invocation.
2//!
3//! Supports Claude, Codex, OpenCode, Grok (plus Kimi/MiniMax as Claude aliases).
4//! Runs the agent via a runner.sh script executed as the tmux session shell.
5
6use crate::engine::agents;
7use crate::engine::git::shipcheck::install_shipcheck_rule;
8pub use crate::engine::git::shipcheck::{Shipcheck, install_shipcheck_hooks};
9
10use super::sandbox;
11use crate::backends::ExternalTask;
12use crate::engine::agents::shell_single_quote;
13use crate::engine::router::RouteResult;
14use crate::engine::runner::template::render_template_str;
15use crate::github::token;
16use crate::store::cluster;
17use crate::sys::home;
18use crate::sys::tmux::TmuxManager;
19use std::collections::BTreeSet;
20use std::collections::HashMap;
21use std::env;
22use std::ffi::OsString;
23#[cfg(unix)]
24use std::fs::Permissions;
25#[cfg(unix)]
26use std::os::unix::fs::PermissionsExt;
27use std::path::Path;
28use std::path::PathBuf;
29
30use tokio::fs;
31
32const AGENT_SYSTEM_TEMPLATE: &str = include_str!("../../../prompts/agent_system.md");
33const AGENT_MESSAGE_TEMPLATE: &str = include_str!("../../../prompts/agent_message.md");
34const AGENT_MEMORY_ENTRY_TEMPLATE: &str = include_str!("../../../prompts/agent_memory_entry.md");
35const ALLOWED_TOOLS_TEMPLATE: &str = include_str!("../../../prompts/allowed_tools.md");
36const REVIEW_PROMPT_TEMPLATE: &str = include_str!("../../../prompts/review_task.md");
37const REVIEW_SYSTEM_TEMPLATE: &str = include_str!("../../../prompts/review_system.md");
38
39/// The `orch progress` step appears only when a `cluster:` section turns the cluster on.
40/// Separate flags, because the template engine does not nest `{{#if}}` blocks
41fn insert_cluster_vars(shipcheck: Shipcheck, vars: &mut HashMap<String, String>) {
42    if !cluster::enabled() {
43        return;
44    }
45
46    let commit = if shipcheck == Shipcheck::Available {
47        "CLUSTER_SHIPCHECK"
48    } else {
49        "CLUSTER_GIT"
50    };
51    for flag in ["CLUSTER", commit] {
52        vars.insert(flag.to_string(), "1".to_string());
53    }
54}
55
56fn render_prompt_template(template: &str, vars: &HashMap<String, String>) -> String {
57    match render_template_str(template, vars) {
58        Ok(rendered) => rendered,
59        Err(err) => {
60            tracing::error!(error = %err, "failed to render prompt template");
61            template.to_string()
62        }
63    }
64}
65
66/// Agent invocation configuration.
67#[derive(Debug)]
68pub struct AgentInvocation {
69    /// Agent name (claude, codex, opencode, grok, kimi, minimax)
70    pub agent: String,
71    /// Model override (e.g., "claude-sonnet-4-6", "o3", "gpt-4.1")
72    pub model: Option<String>,
73    /// Optional native CLI effort from the selected route.
74    pub reasoning_effort: Option<String>,
75    /// Working directory
76    pub work_dir: PathBuf,
77    /// System prompt content
78    pub system_prompt: String,
79    /// Agent message (task prompt)
80    pub agent_message: String,
81    /// Task ID
82    pub task_id: String,
83    /// Disallowed tools pattern
84    pub disallowed_tools: Vec<String>,
85    /// Git author name
86    pub git_author_name: String,
87    /// Git author email
88    pub git_author_email: String,
89    /// Output file path for agent response
90    pub output_file: PathBuf,
91    /// Timeout in seconds (0 = no timeout)
92    pub timeout_seconds: u64,
93    /// Repository slug (owner/repo) for per-repo state isolation
94    pub repo: String,
95    /// Whether the agent runs in the OS sandbox, from `workflow.sandbox`
96    pub sandbox: bool,
97    /// The project's main checkout, which the sandbox keeps read-only but for its `.git`
98    pub main_project_dir: PathBuf,
99    /// The task's branch, from orch's records, the one ref the sandbox lets the agent move
100    pub branch: String,
101    /// Current attempt number (1-indexed)
102    pub attempt: u32,
103}
104
105impl AgentInvocation {
106    pub fn sandbox_scope(&self) -> sandbox::Scope<'_> {
107        sandbox::Scope {
108            work_dir: &self.work_dir,
109            main_project_dir: &self.main_project_dir,
110            branch: &self.branch,
111            task_id: &self.task_id,
112        }
113    }
114}
115
116/// Build the runner script content (saved to attempt dir), plus the small
117/// helper script it execs the agent command through under a pty. Returns
118/// `(runner_script, agent_cmd_script)`.
119fn build_tmux_runner_scripts(
120    inv: &AgentInvocation,
121    agent_cmd: &str,
122    attempt_dir: &Path,
123    sandbox: Option<&[OsString]>,
124    sandbox_env: &[(&str, PathBuf)],
125) -> (String, String) {
126    let status_file = attempt_dir.join("exit.txt");
127    let stderr_file = attempt_dir.join("stderr.txt");
128    let agent_cmd_script_path = attempt_dir.join("agent_cmd.sh");
129    let sq_git_name = shell_single_quote(&inv.git_author_name);
130    let sq_git_email = shell_single_quote(&inv.git_author_email);
131    let sq_task_id = shell_single_quote(&inv.task_id);
132    let sq_output_file = shell_single_quote(&inv.output_file.display().to_string());
133    let sq_work_dir = shell_single_quote(&inv.work_dir.display().to_string());
134    let sq_status_file = shell_single_quote(&status_file.display().to_string());
135    let sq_stderr_file = shell_single_quote(&stderr_file.display().to_string());
136    let sq_agent_cmd_script = shell_single_quote(&agent_cmd_script_path.display().to_string());
137
138    // Runs the agent with stderr split off to a real file before the pty layer
139    // below merges stdout+stderr, exactly as the previous plain-pipe invocation did.
140    let agent_cmd = match sandbox {
141        Some(argv) => {
142            let prefix: Vec<String> = argv
143                .iter()
144                .map(|a| shell_single_quote(&a.to_string_lossy()))
145                .collect();
146            // The tmux and ssh-agent sockets are out of reach, and their variables go too
147            let temp = sandbox::run_temp_dir(attempt_dir);
148            let tmpdir = shell_single_quote(&temp.display().to_string());
149            // gh's own config dir holds its logins and is hidden, so gh gets an empty one and
150            // runs on GH_TOKEN
151            let gh_config =
152                shell_single_quote(&sandbox::gh_config_dir(&temp).display().to_string());
153            // shipcheck cannot start its own sandbox in here, and with this it asks its daemon
154            let extra: Vec<String> = sandbox_env
155                .iter()
156                .map(|(name, value)| {
157                    format!(
158                        " {name}={}",
159                        shell_single_quote(&value.display().to_string())
160                    )
161                })
162                .collect();
163            let vars = format!(
164                "TMPDIR={tmpdir} GH_CONFIG_DIR={gh_config} SHIPCHECK_HANDOFF=1{}",
165                extra.concat()
166            );
167
168            format!(
169                "env -u TMUX -u TMUX_PANE -u SSH_AUTH_SOCK {vars} {} /bin/bash -c {}",
170                prefix.join(" "),
171                shell_single_quote(agent_cmd)
172            )
173        }
174        None => agent_cmd.to_string(),
175    };
176    let agent_cmd_script = format!("#!/usr/bin/env bash\n{agent_cmd} 2>{sq_stderr_file}\n");
177    // The run's temp dir goes when the run ends, however it ends
178    let wipe_temp = if sandbox.is_some() {
179        format!(
180            "; rm -rf -- {}",
181            shell_single_quote(&sandbox::run_temp_dir(attempt_dir).display().to_string())
182        )
183    } else {
184        String::new()
185    };
186    // Tags are read-only in the sandbox, and a fetch that cannot write one new tag updates no ref
187    let sandbox_git_config = if sandbox.is_some() {
188        r#"export GIT_CONFIG_COUNT="5"
189export GIT_CONFIG_KEY_4="remote.origin.tagOpt"
190export GIT_CONFIG_VALUE_4="--no-tags"
191"#
192    } else {
193        ""
194    };
195
196    let runner_script = format!(
197        r#"#!/usr/bin/env bash
198set -euo pipefail
199
200status_file={sq_status_file}
201stderr_file={sq_stderr_file}
202trap 'status=$?; printf "%s\n" "$status" > "$status_file"{wipe_temp}' EXIT
203
204# Environment — ~/.path and ~/.private are loaded by orch at startup into the process env
205export PATH="/opt/homebrew/bin:/usr/local/bin:$PATH"
206export GIT_AUTHOR_NAME={sq_git_name}
207export GIT_COMMITTER_NAME={sq_git_name}
208export GIT_AUTHOR_EMAIL={sq_git_email}
209export GIT_COMMITTER_EMAIL={sq_git_email}
210# Env config overrides the operator's git config for this process only, the remotes stay as they
211# are: agents never sign, and push over HTTPS with gh's credentials, not the operator's SSH agent
212export GIT_CONFIG_COUNT="4"
213export GIT_CONFIG_KEY_0="commit.gpgsign"
214export GIT_CONFIG_VALUE_0="false"
215export GIT_CONFIG_KEY_1="tag.gpgsign"
216export GIT_CONFIG_VALUE_1="false"
217export GIT_CONFIG_KEY_2="url.https://github.com/.pushInsteadOf"
218export GIT_CONFIG_VALUE_2="git@github.com:"
219export GIT_CONFIG_KEY_3="credential.https://github.com.helper"
220export GIT_CONFIG_VALUE_3="!gh auth git-credential"
221{sandbox_git_config}export TASK_ID={sq_task_id}
222export OUTPUT_FILE={sq_output_file}
223unset CLAUDECODE  # allow nested claude invocations from orch
224
225cd {sq_work_dir} || {{
226    printf '%s\n' "worktree directory does not exist: {sq_work_dir}" > "$stderr_file"
227    exit 1
228}}
229
230# Run agent under a pty (via `script`) so its stdout is a tty, not a plain pipe —
231# many CLI runtimes silently switch to full block-buffering when stdout isn't a
232# tty, which can delay pane output long enough to trip silence detection even
233# while the agent is actively streaming. Tee to both output file and terminal
234# (tmux pane) for live streaming.
235set +e
236script -q /dev/null /bin/bash {sq_agent_cmd_script} | tee {sq_output_file}
237CMD_STATUS=${{PIPESTATUS[0]:-0}}
238set -e
239
240exit $CMD_STATUS
241"#,
242    );
243
244    (runner_script, agent_cmd_script)
245}
246
247/// Spawn the agent in a tmux session.
248///
249/// Returns the tmux session name.
250pub async fn spawn_in_tmux(tmux: &TmuxManager, inv: &AgentInvocation) -> anyhow::Result<String> {
251    // Prepare attempt directory and prompt files (system + message).
252    let attempt_dir = home::task_attempt_dir_async(&inv.repo, &inv.task_id, inv.attempt).await?;
253
254    let sys_file = attempt_dir.join("prompt-sys.md");
255    let msg_file = attempt_dir.join("prompt-msg.md");
256    // Build unified permission rules and sys content
257    let mut permissions = agents::PermissionRules::from_config();
258    if !inv.disallowed_tools.is_empty() {
259        for tool in &inv.disallowed_tools {
260            if !permissions.disallowed_tools.contains(tool) {
261                permissions.disallowed_tools.push(tool.clone());
262            }
263        }
264    }
265    permissions.allowed_edit_paths.push(inv.work_dir.clone());
266
267    // Codex cannot start its own Seatbelt inside the OS sandbox, so the OS sandbox replaces it
268    let mut sandbox_env = Vec::new();
269    let sandbox = if inv.sandbox {
270        permissions.sandbox = agents::SandboxLevel::Os;
271        let temp = sandbox::run_temp_dir(&attempt_dir);
272        fs::create_dir_all(sandbox::gh_config_dir(&temp)).await?;
273
274        // The policy makes only paths that exist read-only, so the files orch writes later in the
275        // attempt dir must exist now, or the agent could create them first
276        for name in [
277            "runner.sh",
278            "agent_cmd.sh",
279            "exit.txt",
280            "stderr.txt",
281            "prompt-sys.md",
282            "prompt-msg.md",
283            "result.json",
284        ] {
285            let path = attempt_dir.join(name);
286
287            if !path.exists() {
288                fs::write(&path, "").await?;
289            }
290        }
291
292        if !inv.output_file.exists() && inv.output_file.parent().is_some_and(Path::is_dir) {
293            fs::write(&inv.output_file, "").await?;
294        }
295
296        if let Some(home) = env::var_os("HOME") {
297            sandbox_env = sandbox::package_config(Path::new(&home), &temp);
298            sandbox_env.extend(sandbox::cache_env(Path::new(&home)));
299        }
300
301        Some(sandbox::argv(&inv.sandbox_scope(), &temp).await?)
302    } else {
303        None
304    };
305
306    // For Codex running in workspace-write sandbox mode, grant write access to
307    // git metadata dirs when they live outside the worktree root. We include
308    // both --git-common-dir and --git-dir because index.lock can be created
309    // under the worktree-specific git dir.
310    if inv.agent == "codex" {
311        let mut extra_dirs = BTreeSet::new();
312        for (arg, label) in [
313            ("--git-common-dir", "git common dir"),
314            ("--git-dir", "git dir"),
315        ] {
316            match sandbox::resolve_git_dir_arg(&inv.work_dir, arg).await {
317                Ok(Some(dir)) if !dir.starts_with(&inv.work_dir) => {
318                    extra_dirs.insert(dir);
319                }
320                Ok(_) => {}
321                Err(e) => {
322                    tracing::debug!(
323                        work_dir = %inv.work_dir.display(),
324                        arg,
325                        error = %e,
326                        "failed to resolve {}; skipping --add-dir",
327                        label
328                    );
329                }
330            }
331        }
332        permissions.extra_writable_dirs.extend(extra_dirs);
333
334        if Shipcheck::detect(&inv.work_dir).await == Shipcheck::Available
335            && let Err(e) = install_shipcheck_rule(&inv.work_dir).await
336        {
337            tracing::warn!(
338                work_dir = %inv.work_dir.display(),
339                error = %e,
340                "failed to install the shipcheck codex rule"
341            );
342        }
343    }
344
345    let sys_content = if permissions.allowed_tools.is_empty() {
346        inv.system_prompt.clone()
347    } else {
348        let tools_list = permissions
349            .allowed_tools
350            .iter()
351            .map(|t| format!("- {t}"))
352            .collect::<Vec<_>>()
353            .join("\n");
354        let mut vars = HashMap::new();
355        vars.insert("TOOLS_LIST".to_string(), tools_list);
356        let tools_prompt = render_prompt_template(ALLOWED_TOOLS_TEMPLATE, &vars);
357        format!("{}\n\n{}", inv.system_prompt, tools_prompt)
358    };
359
360    fs::write(&sys_file, &sys_content).await?;
361    fs::write(&msg_file, &inv.agent_message).await?;
362
363    // Build agent command using per-agent runner (used in non-PTY path below)
364    let runner = agents::get_runner(&inv.agent);
365
366    // Prepare environment map for tmux session (does not write GH token to disk)
367    let mut env = HashMap::new();
368    env.insert("GIT_AUTHOR_NAME".to_string(), inv.git_author_name.clone());
369    env.insert(
370        "GIT_COMMITTER_NAME".to_string(),
371        inv.git_author_name.clone(),
372    );
373    env.insert("GIT_AUTHOR_EMAIL".to_string(), inv.git_author_email.clone());
374    env.insert(
375        "GIT_COMMITTER_EMAIL".to_string(),
376        inv.git_author_email.clone(),
377    );
378    env.insert("TASK_ID".to_string(), inv.task_id.clone());
379    env.insert(
380        "OUTPUT_FILE".to_string(),
381        inv.output_file.display().to_string(),
382    );
383
384    // Write runner script and execute it in a detached tmux session.
385    let timeout_cmd = if inv.timeout_seconds > 0 {
386        format!("timeout {}", inv.timeout_seconds)
387    } else {
388        String::new()
389    };
390    let agent_cmd = runner.build_command_with_effort(
391        inv.model
392            .as_deref()
393            .map(str::trim)
394            .filter(|m| !m.is_empty()),
395        inv.reasoning_effort.as_deref(),
396        &timeout_cmd,
397        &sys_file.to_string_lossy(),
398        &msg_file.to_string_lossy(),
399        &permissions,
400    );
401
402    // Write runner script (and the agent-cmd helper script it execs under a pty)
403    // to the per-task attempt dir.
404    let script_path = attempt_dir.join("runner.sh");
405    let agent_cmd_script_path = attempt_dir.join("agent_cmd.sh");
406    let (script_content, agent_cmd_script_content) = build_tmux_runner_scripts(
407        inv,
408        &agent_cmd,
409        &attempt_dir,
410        sandbox.as_deref(),
411        &sandbox_env,
412    );
413    fs::write(&agent_cmd_script_path, &agent_cmd_script_content).await?;
414    fs::write(&script_path, &script_content).await?;
415
416    // Make executable
417    #[cfg(unix)]
418    {
419        fs::set_permissions(&script_path, Permissions::from_mode(0o755)).await?;
420        fs::set_permissions(&agent_cmd_script_path, Permissions::from_mode(0o755)).await?;
421    }
422
423    let command = format!("bash \"{}\"", script_path.display());
424
425    // Resolve GitHub token via the process-wide shared resolver (cached after first call)
426    let github_token = match token::shared().get_token().await {
427        Ok(Some(token)) => {
428            tracing::debug!("Resolved GitHub token via TokenResolver for agent session");
429            Some(token)
430        }
431        Ok(None) => {
432            tracing::warn!(
433                "No GitHub token available; set GH_TOKEN, GITHUB_TOKEN, or gh.auth.token, or run gh auth login"
434            );
435            None
436        }
437        Err(e) => {
438            tracing::warn!(error = %e, "Failed to resolve GitHub token");
439            None
440        }
441    };
442
443    // Inject GH_TOKEN into env so it's passed via `tmux new-session -e` along
444    // with everything else. The `-e` flag sets variables in the *initial* pane
445    // environment, so the agent process sees it immediately on startup.
446    //
447    // IMPORTANT: Do NOT use create_session_detached + set_env + create_window
448    // to inject GH_TOKEN. That approach creates a 2-window session (window 0 =
449    // idle shell, window 1 = agent). All tmux monitoring (is_session_active,
450    // capture_pane, batch_session_active) targets the session without a window
451    // index, which defaults to the *active* window — the idle shell. This
452    // breaks completion detection (shell never exits → pane_dead always 0),
453    // output capture (reads the shell prompt, not agent output), and silence
454    // detection. See the revert of PR #2903.
455    if let Some(ref token) = github_token {
456        env.insert("GH_TOKEN".to_string(), token.clone());
457    }
458
459    let env_vec: Vec<(&str, &str)> = env.iter().map(|(k, v)| (k.as_str(), v.as_str())).collect();
460
461    let session = tmux
462        .create_session(
463            &inv.repo,
464            &inv.task_id,
465            &inv.work_dir.to_string_lossy(),
466            &command,
467            env_vec.as_slice(),
468        )
469        .await?;
470
471    tracing::info!(
472        task_id = inv.task_id,
473        agent = inv.agent,
474        session = %session,
475        "agent spawned in tmux"
476    );
477
478    Ok(session)
479}
480
481/// Build the system prompt for the agent.
482pub fn build_system_prompt(
483    _task: &ExternalTask,
484    context: &super::context::TaskContext,
485    route_result: Option<&RouteResult>,
486    default_branch: &str,
487    shipcheck: Shipcheck,
488    sandboxed: bool,
489) -> String {
490    let mut vars = HashMap::new();
491
492    vars.insert("DEFAULT_BRANCH".to_string(), default_branch.to_string());
493    shipcheck.insert_vars(&mut vars);
494    insert_cluster_vars(shipcheck, &mut vars);
495
496    if sandboxed {
497        vars.insert("SANDBOX".to_string(), "1".to_string());
498    }
499
500    if let Some(rr) = route_result {
501        vars.insert("ROLE".to_string(), rr.profile.role.clone());
502
503        if !rr.profile.constraints.is_empty() {
504            let constraints = rr
505                .profile
506                .constraints
507                .iter()
508                .map(|c| format!("- {c}"))
509                .collect::<Vec<_>>()
510                .join("\n");
511            vars.insert("CONSTRAINTS".to_string(), constraints);
512        }
513    }
514
515    if !context.project_instructions.is_empty() {
516        vars.insert(
517            "PROJECT_INSTRUCTIONS".to_string(),
518            context.project_instructions.clone(),
519        );
520    }
521
522    if !context.repo_tree.is_empty() {
523        vars.insert("REPO_TREE".to_string(), context.repo_tree.clone());
524    }
525
526    render_prompt_template(AGENT_SYSTEM_TEMPLATE, &vars)
527}
528
529/// Build the agent message (task prompt).
530pub fn build_agent_message(
531    task: &ExternalTask,
532    context: &super::context::TaskContext,
533    attempts: u32,
534) -> String {
535    let mut vars = HashMap::new();
536    vars.insert("TASK_ID".to_string(), task.id.0.clone());
537    vars.insert("TASK_TITLE".to_string(), task.title.clone());
538    vars.insert("TASK_BODY".to_string(), task.body.clone());
539
540    if !context.task_context.is_empty() {
541        vars.insert("TASK_CONTEXT".to_string(), context.task_context.clone());
542    }
543
544    if !context.parent_context.is_empty() {
545        vars.insert("PARENT_CONTEXT".to_string(), context.parent_context.clone());
546    }
547
548    if !context.issue_comments.is_empty() {
549        vars.insert("ISSUE_COMMENTS".to_string(), context.issue_comments.clone());
550    }
551
552    if !context.pr_review_context.is_empty() {
553        vars.insert(
554            "PR_REVIEW_CONTEXT".to_string(),
555            context.pr_review_context.clone(),
556        );
557    }
558
559    if attempts > 0 && !context.git_diff.is_empty() {
560        vars.insert("GIT_DIFF".to_string(), context.git_diff.clone());
561    }
562
563    if attempts > 0 {
564        vars.insert("ATTEMPT_NUMBER".to_string(), (attempts + 1).to_string());
565    }
566
567    if !context.memory.is_empty() {
568        let mut sections = Vec::new();
569        for entry in &context.memory {
570            let mut entry_vars = HashMap::new();
571            entry_vars.insert("ATTEMPT".to_string(), entry.attempt.to_string());
572            entry_vars.insert("AGENT".to_string(), entry.agent.clone());
573
574            if let Some(ref model) = entry.model {
575                entry_vars.insert("MODEL".to_string(), model.clone());
576            }
577
578            if !entry.approach.is_empty() {
579                entry_vars.insert("APPROACH".to_string(), entry.approach.clone());
580            }
581
582            if !entry.learnings.is_empty() {
583                let learnings = entry
584                    .learnings
585                    .iter()
586                    .map(|learning| format!("- {learning}"))
587                    .collect::<Vec<_>>()
588                    .join("\n");
589                entry_vars.insert("LEARNINGS".to_string(), learnings);
590            }
591
592            if let Some(ref error) = entry.error {
593                entry_vars.insert("ERROR".to_string(), error.clone());
594            }
595
596            if !entry.files_modified.is_empty() {
597                entry_vars.insert(
598                    "FILES_MODIFIED".to_string(),
599                    entry.files_modified.join(", "),
600                );
601            }
602
603            let rendered = render_prompt_template(AGENT_MEMORY_ENTRY_TEMPLATE, &entry_vars);
604            sections.push(rendered.trim().to_string());
605        }
606
607        let memory_section = sections.join("\n\n");
608        vars.insert("MEMORY_SECTION".to_string(), memory_section);
609    }
610
611    render_prompt_template(AGENT_MESSAGE_TEMPLATE, &vars)
612}
613
614/// Build the review prompt for the review agent.
615///
616/// This is called when a task completes and the review agent needs to
617/// review the changes before auto-merge.
618pub fn build_review_prompt(
619    task: &ExternalTask,
620    agent_summary: &str,
621    git_diff: &str,
622    git_log: &str,
623    default_branch: &str,
624    pr_number: u64,
625    shipcheck: Shipcheck,
626) -> String {
627    let mut vars = HashMap::new();
628    shipcheck.insert_vars(&mut vars);
629    insert_cluster_vars(shipcheck, &mut vars);
630    vars.insert("TASK_ID".to_string(), task.id.0.clone());
631    vars.insert("TASK_TITLE".to_string(), task.title.clone());
632    vars.insert("TASK_BODY".to_string(), task.body.clone());
633    vars.insert("DEFAULT_BRANCH".to_string(), default_branch.to_string());
634    vars.insert("PR_NUMBER".to_string(), pr_number.to_string());
635
636    if !agent_summary.is_empty() {
637        vars.insert("AGENT_SUMMARY".to_string(), agent_summary.to_string());
638    }
639
640    if !git_diff.is_empty() {
641        vars.insert("GIT_DIFF".to_string(), git_diff.to_string());
642    }
643
644    if !git_log.is_empty() {
645        vars.insert("GIT_LOG".to_string(), git_log.to_string());
646    }
647
648    render_prompt_template(REVIEW_PROMPT_TEMPLATE, &vars)
649}
650
651/// Build the runner shell script contents for testing and inspection, given a pre-created
652/// attempt directory so tests can pass a temp dir.
653///
654/// IMPORTANT: this must not embed secrets (GH_TOKEN) into the script.
655#[cfg(test)]
656fn build_runner_script_in_dir(inv: &AgentInvocation, attempt_dir: &Path) -> String {
657    let sys_file = attempt_dir.join("prompt-sys.md");
658    let msg_file = attempt_dir.join("prompt-msg.md");
659
660    // Build unified permission rules and sys content (minimal translation)
661    let mut permissions = agents::PermissionRules::from_config();
662    if !inv.disallowed_tools.is_empty() {
663        for tool in &inv.disallowed_tools {
664            if !permissions.disallowed_tools.contains(tool) {
665                permissions.disallowed_tools.push(tool.clone());
666            }
667        }
668    }
669    permissions.allowed_edit_paths.push(inv.work_dir.clone());
670
671    // Build agent command using per-agent runner
672    let runner = agents::get_runner(&inv.agent);
673    let timeout_cmd = if inv.timeout_seconds > 0 {
674        format!("timeout {}", inv.timeout_seconds)
675    } else {
676        String::new()
677    };
678    let agent_cmd = runner.build_command_with_effort(
679        inv.model
680            .as_deref()
681            .map(str::trim)
682            .filter(|m| !m.is_empty()),
683        inv.reasoning_effort.as_deref(),
684        &timeout_cmd,
685        &sys_file.to_string_lossy(),
686        &msg_file.to_string_lossy(),
687        &permissions,
688    );
689
690    let status_file = attempt_dir.join("exit.txt");
691    let stderr_file = attempt_dir.join("stderr.txt");
692
693    let sq_status = shell_single_quote(&status_file.display().to_string());
694    let sq_stderr = shell_single_quote(&stderr_file.display().to_string());
695    let sq_out = shell_single_quote(&inv.output_file.display().to_string());
696    let sq_work_dir = shell_single_quote(&inv.work_dir.to_string_lossy());
697    let script = format!(
698        "#!/usr/bin/env bash\nset -euo pipefail\nstatus_file={sq_status}\nstderr_file={sq_stderr}\ntrap 'status=$?; printf \"%s\\n\" \"$status\" > \"$status_file\"' EXIT\nunset CLAUDECODE\ncd {sq_work_dir} || {{\n  printf '%s\\n' \"worktree directory does not exist: {sq_work_dir}\" > \"$stderr_file\"\n  exit 1\n}}\nset +e\nRESPONSE=$({agent_cmd} 2> \"$stderr_file\")\nCMD_STATUS=$?\nset -e\nprintf '%s' \"$RESPONSE\" > {sq_out}\nexit $CMD_STATUS\n",
699    );
700
701    script
702}
703
704/// Build the system prompt for the review agent.
705pub fn review_system_prompt() -> String {
706    render_prompt_template(REVIEW_SYSTEM_TEMPLATE, &HashMap::new())
707}
708
709#[cfg(test)]
710mod tests {
711    use super::*;
712    use crate::backends::ExternalId;
713    use crate::engine::agents::shell_single_quote;
714    use crate::engine::runner::sandbox;
715    use crate::engine::runner::template;
716
717    use std::path::PathBuf;
718
719    #[test]
720    fn review_system_prompt_checks_stray_files_and_trust_boundaries() {
721        let p = review_system_prompt();
722        assert!(p.contains("**Files**"));
723        assert!(p.contains("**Trust boundaries**"));
724    }
725
726    fn test_invocation(task_id: &str) -> AgentInvocation {
727        AgentInvocation {
728            agent: "claude".to_string(),
729            model: None,
730            reasoning_effort: None,
731            work_dir: PathBuf::from("/tmp"),
732            system_prompt: "test system prompt".to_string(),
733            agent_message: "test message".to_string(),
734            task_id: task_id.to_string(),
735            disallowed_tools: vec![],
736            git_author_name: "Test Bot".to_string(),
737            git_author_email: "bot@example.com".to_string(),
738            output_file: PathBuf::from("/tmp/test-output.json"),
739            timeout_seconds: 0,
740            repo: "orch-runner-test/token-check".to_string(),
741            attempt: 1,
742            sandbox: false,
743            main_project_dir: PathBuf::from("/tmp"),
744            branch: String::new(),
745        }
746    }
747
748    #[test]
749    fn spawn_in_tmux_rejects_invalid_env() {
750        // This test verifies the function signature and basic behavior
751        // without actually spawning a tmux session.
752        // The key security guarantee: tokens are passed via tmux -e flag,
753        // not written to any file on disk.
754        let inv = test_invocation("env-test");
755        // Just verify the invocation can be created without panicking
756        assert_eq!(inv.task_id, "env-test");
757    }
758
759    #[test]
760    fn build_runner_script_persists_exit_status_on_failure() {
761        // Use a temp dir so lib and bin compilation units don't race on ~/.orch/state/.
762        let tmp = tempfile::TempDir::new().expect("temp dir");
763        let inv = test_invocation("runner-status-test");
764        let script = build_runner_script_in_dir(&inv, tmp.path());
765
766        assert!(
767            script
768                .contains("trap 'status=$?; printf \"%s\\n\" \"$status\" > \"$status_file\"' EXIT")
769        );
770        assert!(script.contains("set +e"));
771    }
772
773    #[test]
774    fn build_runner_script_reports_missing_worktree() {
775        // Use a temp dir so lib and bin compilation units don't race on ~/.orch/state/.
776        let tmp = tempfile::TempDir::new().expect("temp dir");
777        let inv = test_invocation("runner-missing-worktree-test");
778        let script = build_runner_script_in_dir(&inv, tmp.path());
779
780        assert!(script.contains("worktree directory does not exist: '/tmp'"));
781        assert!(script.contains("stderr_file='"));
782    }
783
784    #[test]
785    fn tmux_runner_script_runs_agent_under_pty_not_a_plain_pipe() {
786        // Regression test for #3554: piping the agent binary's stdout straight
787        // into `tee` leaves it non-tty, which makes many CLI runtimes switch to
788        // full block-buffering and can starve the tmux pane long enough to trip
789        // silence detection even while the agent is actively working. The agent
790        // command must run under `script` (a real pty) before hitting `tee`.
791        let tmp = tempfile::TempDir::new().expect("temp dir");
792        let inv = test_invocation("pty-wrap-test");
793        let (runner_script, agent_cmd_script) =
794            build_tmux_runner_scripts(&inv, "echo hello", tmp.path(), None, &[]);
795
796        assert!(
797            runner_script.contains("script -q /dev/null /bin/bash"),
798            "agent must be exec'd under a pty via `script`, got: {runner_script}"
799        );
800        assert!(
801            runner_script.contains("| tee"),
802            "output must still be tee'd to the output file, got: {runner_script}"
803        );
804        assert!(
805            !runner_script.contains("echo hello 2>"),
806            "the raw agent command must not be piped directly into tee anymore, got: {runner_script}"
807        );
808        assert!(
809            agent_cmd_script.contains("echo hello 2>"),
810            "the agent command should run (with stderr split to a file) inside the pty-wrapped helper script, got: {agent_cmd_script}"
811        );
812    }
813
814    #[test]
815    fn tmux_runner_script_captures_agent_exit_status_via_pipestatus() {
816        let tmp = tempfile::TempDir::new().expect("temp dir");
817        let inv = test_invocation("pty-exit-status-test");
818        let (runner_script, _) =
819            build_tmux_runner_scripts(&inv, "echo hello", tmp.path(), None, &[]);
820
821        assert!(runner_script.contains("CMD_STATUS=${PIPESTATUS[0]:-0}"));
822        assert!(runner_script.contains("exit $CMD_STATUS"));
823    }
824
825    #[test]
826    fn tmux_runner_script_disables_commit_signing() {
827        // Locked signing agent must not fail `git commit` inside agent sessions
828        let tmp = tempfile::TempDir::new().expect("temp dir");
829        let inv = test_invocation("gpgsign-test");
830        let (runner_script, _) =
831            build_tmux_runner_scripts(&inv, "echo hello", tmp.path(), None, &[]);
832
833        assert!(runner_script.contains("GIT_CONFIG_KEY_0=\"commit.gpgsign\""));
834        assert!(runner_script.contains("GIT_CONFIG_VALUE_0=\"false\""));
835        assert!(runner_script.contains("GIT_CONFIG_KEY_1=\"tag.gpgsign\""));
836        // Only pushes go over HTTPS with gh's credentials, fetches keep the remote as it is
837        assert!(
838            runner_script.contains("GIT_CONFIG_KEY_2=\"url.https://github.com/.pushInsteadOf\"")
839        );
840        assert!(runner_script.contains("GIT_CONFIG_VALUE_2=\"git@github.com:\""));
841        assert!(runner_script.contains("GIT_CONFIG_VALUE_3=\"!gh auth git-credential\""));
842    }
843
844    #[test]
845    fn tmux_runner_script_writes_executable_agent_cmd_helper() {
846        let tmp = tempfile::TempDir::new().expect("temp dir");
847        let inv = test_invocation("pty-helper-path-test");
848        let (runner_script, agent_cmd_script) =
849            build_tmux_runner_scripts(&inv, "echo hello", tmp.path(), None, &[]);
850
851        let agent_cmd_script_path = tmp.path().join("agent_cmd.sh");
852        assert!(
853            runner_script.contains(&agent_cmd_script_path.display().to_string()),
854            "runner script must reference the agent_cmd.sh helper path, got: {runner_script}"
855        );
856        assert!(agent_cmd_script.starts_with("#!/usr/bin/env bash\n"));
857    }
858
859    #[test]
860    fn tmux_runner_script_runs_the_agent_inside_the_sandbox() {
861        let tmp = tempfile::TempDir::new().expect("temp dir");
862        let inv = test_invocation("sandbox-test");
863        let argv: Vec<OsString> = vec![
864            "/usr/bin/sandbox-exec".into(),
865            "-p".into(),
866            "(version 1)".into(),
867        ];
868        let (_, agent_cmd_script) =
869            build_tmux_runner_scripts(&inv, "claude -p 'hi'", tmp.path(), Some(&argv), &[]);
870        assert!(
871            agent_cmd_script.contains(
872                "env -u TMUX -u TMUX_PANE -u SSH_AUTH_SOCK TMPDIR='"
873            ) && agent_cmd_script.contains(
874                "1 '/usr/bin/sandbox-exec' '-p' '(version 1)' /bin/bash -c 'claude -p '\\''hi'\\''' 2>"
875            ),
876            "the agent must run inside the sandbox with stderr split outside it, got: {agent_cmd_script}"
877        );
878        assert!(
879            agent_cmd_script.contains(&format!(
880                "TMPDIR='{}'",
881                sandbox::run_temp_dir(tmp.path()).display()
882            )),
883            "the agent must get its own TMPDIR, got: {agent_cmd_script}"
884        );
885        assert!(
886            agent_cmd_script.contains(&format!(
887                "GH_CONFIG_DIR='{}'",
888                sandbox::gh_config_dir(&sandbox::run_temp_dir(tmp.path())).display()
889            )),
890            "gh must get a config dir it can read, got: {agent_cmd_script}"
891        );
892        assert!(agent_cmd_script.contains(" SHIPCHECK_HANDOFF=1 "));
893
894        let env = [("NPM_CONFIG_USERCONFIG", tmp.path().join("npmrc"))];
895        let (_, with_env) = build_tmux_runner_scripts(&inv, "true", tmp.path(), Some(&argv), &env);
896        assert!(with_env.contains(&format!(
897            " NPM_CONFIG_USERCONFIG='{}' ",
898            tmp.path().join("npmrc").display()
899        )));
900    }
901
902    #[test]
903    fn only_a_sandboxed_run_fetches_without_tags() {
904        let tmp = tempfile::TempDir::new().expect("temp dir");
905        let inv = test_invocation("sandbox-test");
906        let argv: Vec<OsString> = vec!["/usr/bin/sandbox-exec".into()];
907        let (sandboxed, _) = build_tmux_runner_scripts(&inv, "true", tmp.path(), Some(&argv), &[]);
908        assert!(sandboxed.contains("export GIT_CONFIG_COUNT=\"5\""));
909        assert!(sandboxed.contains("export GIT_CONFIG_VALUE_4=\"--no-tags\""));
910        let (plain, _) = build_tmux_runner_scripts(&inv, "true", tmp.path(), None, &[]);
911        assert!(!plain.contains("tagOpt"));
912        assert!(
913            !plain.contains("rm -rf"),
914            "only a sandboxed run has a temp dir to wipe"
915        );
916        assert!(sandboxed.contains(&format!(
917            "\"$status_file\"; rm -rf -- '{}'' EXIT",
918            sandbox::run_temp_dir(tmp.path()).display()
919        )));
920    }
921
922    #[test]
923    fn a_sandboxed_prompt_offers_no_shipcheck() {
924        assert_eq!(
925            Shipcheck::Available.for_prompt(true, false),
926            Shipcheck::Absent
927        );
928        assert_eq!(
929            Shipcheck::Available.for_prompt(true, true),
930            Shipcheck::Available
931        );
932        assert_eq!(
933            Shipcheck::Available.for_prompt(false, false),
934            Shipcheck::Available
935        );
936        assert_eq!(
937            Shipcheck::NotInstalled.for_prompt(true, false),
938            Shipcheck::NotInstalled
939        );
940    }
941
942    #[test]
943    fn build_runner_script_escapes_shell_injection_in_paths() {
944        let tmp = tempfile::TempDir::new().expect("temp dir");
945        let mut inv = test_invocation("injection-test");
946        inv.work_dir = PathBuf::from("/tmp/$(whoami)/workspace");
947        inv.output_file = PathBuf::from("/tmp/evil`id`.json");
948        let script = build_runner_script_in_dir(&inv, tmp.path());
949
950        // Values must be single-quoted, neutralizing $() and backticks
951        assert!(
952            script.contains("'/tmp/$(whoami)/workspace'"),
953            "work_dir with $() must be single-quoted: {script}"
954        );
955        assert!(
956            script.contains("'/tmp/evil`id`.json'"),
957            "output_file with backticks must be single-quoted: {script}"
958        );
959    }
960
961    #[test]
962    fn review_prompt_forbids_ending_turn_on_pending_ci_status() {
963        // Regression test for #3453: a review agent must not stop with a
964        // prose "CI is still running" status update and leave the turn
965        // without JSON. The prompt must explicitly route PENDING/NOT RUN CI
966        // through the local-checks fallback and into the same-turn JSON output.
967        let task = ExternalTask {
968            id: ExternalId("155460".to_string()),
969            title: "test task".to_string(),
970            body: "test body".to_string(),
971            state: "open".to_string(),
972            labels: vec![],
973            author: "tester".to_string(),
974            created_at: "2026-01-01T00:00:00Z".to_string(),
975            updated_at: "2026-01-01T00:00:00Z".to_string(),
976            url: "https://example.com/1".to_string(),
977        };
978        let prompt = build_review_prompt(&task, "", "", "", "main", 1, Shipcheck::Absent);
979
980        assert!(
981            prompt.contains("Pending CI is never a terminal review state"),
982            "prompt must state pending CI is not terminal: {prompt}"
983        );
984        assert!(
985            prompt.contains("Never end your turn with a CI-waiting status update"),
986            "prompt must forbid ending the turn on a CI-waiting status update: {prompt}"
987        );
988    }
989
990    #[test]
991    fn shell_single_quote_escapes_embedded_quotes() {
992        assert_eq!(shell_single_quote("hello"), "'hello'");
993        assert_eq!(shell_single_quote("O'Brien"), "'O'\\''Brien'");
994        assert_eq!(shell_single_quote("$(rm -rf /)"), "'$(rm -rf /)'");
995        assert_eq!(shell_single_quote("`whoami`"), "'`whoami`'");
996        assert_eq!(shell_single_quote("a\"b"), "'a\"b'");
997        assert_eq!(shell_single_quote("$HOME"), "'$HOME'");
998    }
999
1000    fn prompt_task() -> ExternalTask {
1001        ExternalTask {
1002            id: ExternalId("1".to_string()),
1003            title: "t".to_string(),
1004            body: "b".to_string(),
1005            state: "open".to_string(),
1006            labels: vec![],
1007            author: "a".to_string(),
1008            created_at: "2026-01-01T00:00:00Z".to_string(),
1009            updated_at: "2026-01-01T00:00:00Z".to_string(),
1010            url: "https://example.com/1".to_string(),
1011        }
1012    }
1013
1014    #[test]
1015    fn only_a_sandboxed_prompt_explains_the_sandbox() {
1016        let ctx = super::super::context::TaskContext::default();
1017        let task = prompt_task();
1018        let prompt = |sandboxed| {
1019            build_system_prompt(&task, &ctx, None, "main", Shipcheck::Absent, sandboxed)
1020        };
1021        assert!(prompt(true).contains("you run inside an OS sandbox"));
1022        assert!(!prompt(false).contains("OS sandbox"));
1023        assert!(!prompt(false).contains("SANDBOX"));
1024    }
1025
1026    #[test]
1027    fn system_prompt_uses_shipcheck_only_when_available() {
1028        let ctx = super::super::context::TaskContext::default();
1029        let task = prompt_task();
1030        let prompt = |s| build_system_prompt(&task, &ctx, None, "main", s, false);
1031
1032        let available = prompt(Shipcheck::Available);
1033        assert!(available.contains("shipcheck run"));
1034        assert!(available.contains("shipcheck commit"));
1035        assert!(!available.contains(".github/workflows/"));
1036        assert!(!available.contains("not installed"));
1037
1038        let outdated = prompt(Shipcheck::Outdated);
1039        assert!(!outdated.contains("shipcheck"));
1040        assert!(outdated.contains(".github/workflows/"));
1041
1042        let missing = prompt(Shipcheck::NotInstalled);
1043        assert!(!missing.contains("shipcheck run"));
1044        assert!(missing.contains(".github/workflows/"));
1045        assert!(missing.contains("shipcheck is not installed"));
1046
1047        let absent = prompt(Shipcheck::Absent);
1048        assert!(!absent.contains("shipcheck"));
1049        assert!(absent.contains(".github/workflows/"));
1050
1051        for p in [&available, &outdated, &missing, &absent] {
1052            assert!(!p.contains("{{"), "{p}");
1053            assert!(!p.contains("install shipcheck"), "{p}");
1054        }
1055    }
1056
1057    #[test]
1058    fn review_prompt_uses_shipcheck_only_when_available() {
1059        let task = prompt_task();
1060        let prompt = |s| build_review_prompt(&task, "", "", "", "main", 1, s);
1061        assert!(prompt(Shipcheck::Available).contains("shipcheck run"));
1062        for s in [
1063            Shipcheck::Outdated,
1064            Shipcheck::NotInstalled,
1065            Shipcheck::Absent,
1066        ] {
1067            let p = prompt(s);
1068            assert!(!p.contains("shipcheck"), "{p}");
1069            assert!(p.contains(".github/workflows/"), "{p}");
1070        }
1071    }
1072
1073    #[test]
1074    fn the_progress_step_appears_only_in_cluster_mode() {
1075        let mut vars = HashMap::new();
1076        insert_cluster_vars(Shipcheck::Available, &mut vars);
1077        assert!(vars.is_empty(), "no cluster section, no cluster flags");
1078        let plain = template::render_template_str(AGENT_SYSTEM_TEMPLATE, &vars).unwrap();
1079        assert!(!plain.contains("orch progress"));
1080
1081        for flag in ["CLUSTER", "CLUSTER_SHIPCHECK"] {
1082            vars.insert(flag.to_string(), "1".to_string());
1083        }
1084        let cluster = template::render_template_str(AGENT_SYSTEM_TEMPLATE, &vars).unwrap();
1085        assert!(cluster.contains("orch progress"));
1086        assert!(cluster.contains("commits only through `shipcheck commit`"));
1087        assert!(!cluster.contains("It commits anything you left"));
1088    }
1089}