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        }
299
300        Some(sandbox::argv(&inv.sandbox_scope(), &temp).await?)
301    } else {
302        None
303    };
304
305    // For Codex running in workspace-write sandbox mode, grant write access to
306    // git metadata dirs when they live outside the worktree root. We include
307    // both --git-common-dir and --git-dir because index.lock can be created
308    // under the worktree-specific git dir.
309    if inv.agent == "codex" {
310        let mut extra_dirs = BTreeSet::new();
311        for (arg, label) in [
312            ("--git-common-dir", "git common dir"),
313            ("--git-dir", "git dir"),
314        ] {
315            match sandbox::resolve_git_dir_arg(&inv.work_dir, arg).await {
316                Ok(Some(dir)) if !dir.starts_with(&inv.work_dir) => {
317                    extra_dirs.insert(dir);
318                }
319                Ok(_) => {}
320                Err(e) => {
321                    tracing::debug!(
322                        work_dir = %inv.work_dir.display(),
323                        arg,
324                        error = %e,
325                        "failed to resolve {}; skipping --add-dir",
326                        label
327                    );
328                }
329            }
330        }
331        permissions.extra_writable_dirs.extend(extra_dirs);
332
333        if Shipcheck::detect(&inv.work_dir).await == Shipcheck::Available
334            && let Err(e) = install_shipcheck_rule(&inv.work_dir).await
335        {
336            tracing::warn!(
337                work_dir = %inv.work_dir.display(),
338                error = %e,
339                "failed to install the shipcheck codex rule"
340            );
341        }
342    }
343
344    let sys_content = if permissions.allowed_tools.is_empty() {
345        inv.system_prompt.clone()
346    } else {
347        let tools_list = permissions
348            .allowed_tools
349            .iter()
350            .map(|t| format!("- {t}"))
351            .collect::<Vec<_>>()
352            .join("\n");
353        let mut vars = HashMap::new();
354        vars.insert("TOOLS_LIST".to_string(), tools_list);
355        let tools_prompt = render_prompt_template(ALLOWED_TOOLS_TEMPLATE, &vars);
356        format!("{}\n\n{}", inv.system_prompt, tools_prompt)
357    };
358
359    fs::write(&sys_file, &sys_content).await?;
360    fs::write(&msg_file, &inv.agent_message).await?;
361
362    // Build agent command using per-agent runner (used in non-PTY path below)
363    let runner = agents::get_runner(&inv.agent);
364
365    // Prepare environment map for tmux session (does not write GH token to disk)
366    let mut env = HashMap::new();
367    env.insert("GIT_AUTHOR_NAME".to_string(), inv.git_author_name.clone());
368    env.insert(
369        "GIT_COMMITTER_NAME".to_string(),
370        inv.git_author_name.clone(),
371    );
372    env.insert("GIT_AUTHOR_EMAIL".to_string(), inv.git_author_email.clone());
373    env.insert(
374        "GIT_COMMITTER_EMAIL".to_string(),
375        inv.git_author_email.clone(),
376    );
377    env.insert("TASK_ID".to_string(), inv.task_id.clone());
378    env.insert(
379        "OUTPUT_FILE".to_string(),
380        inv.output_file.display().to_string(),
381    );
382
383    // Write runner script and execute it in a detached tmux session.
384    let timeout_cmd = if inv.timeout_seconds > 0 {
385        format!("timeout {}", inv.timeout_seconds)
386    } else {
387        String::new()
388    };
389    let agent_cmd = runner.build_command_with_effort(
390        inv.model
391            .as_deref()
392            .map(str::trim)
393            .filter(|m| !m.is_empty()),
394        inv.reasoning_effort.as_deref(),
395        &timeout_cmd,
396        &sys_file.to_string_lossy(),
397        &msg_file.to_string_lossy(),
398        &permissions,
399    );
400
401    // Write runner script (and the agent-cmd helper script it execs under a pty)
402    // to the per-task attempt dir.
403    let script_path = attempt_dir.join("runner.sh");
404    let agent_cmd_script_path = attempt_dir.join("agent_cmd.sh");
405    let (script_content, agent_cmd_script_content) = build_tmux_runner_scripts(
406        inv,
407        &agent_cmd,
408        &attempt_dir,
409        sandbox.as_deref(),
410        &sandbox_env,
411    );
412    fs::write(&agent_cmd_script_path, &agent_cmd_script_content).await?;
413    fs::write(&script_path, &script_content).await?;
414
415    // Make executable
416    #[cfg(unix)]
417    {
418        fs::set_permissions(&script_path, Permissions::from_mode(0o755)).await?;
419        fs::set_permissions(&agent_cmd_script_path, Permissions::from_mode(0o755)).await?;
420    }
421
422    let command = format!("bash \"{}\"", script_path.display());
423
424    // Resolve GitHub token via the process-wide shared resolver (cached after first call)
425    let github_token = match token::shared().get_token().await {
426        Ok(Some(token)) => {
427            tracing::debug!("Resolved GitHub token via TokenResolver for agent session");
428            Some(token)
429        }
430        Ok(None) => {
431            tracing::warn!(
432                "No GitHub token available; set GH_TOKEN, GITHUB_TOKEN, or gh.auth.token, or run gh auth login"
433            );
434            None
435        }
436        Err(e) => {
437            tracing::warn!(error = %e, "Failed to resolve GitHub token");
438            None
439        }
440    };
441
442    // Inject GH_TOKEN into env so it's passed via `tmux new-session -e` along
443    // with everything else. The `-e` flag sets variables in the *initial* pane
444    // environment, so the agent process sees it immediately on startup.
445    //
446    // IMPORTANT: Do NOT use create_session_detached + set_env + create_window
447    // to inject GH_TOKEN. That approach creates a 2-window session (window 0 =
448    // idle shell, window 1 = agent). All tmux monitoring (is_session_active,
449    // capture_pane, batch_session_active) targets the session without a window
450    // index, which defaults to the *active* window — the idle shell. This
451    // breaks completion detection (shell never exits → pane_dead always 0),
452    // output capture (reads the shell prompt, not agent output), and silence
453    // detection. See the revert of PR #2903.
454    if let Some(ref token) = github_token {
455        env.insert("GH_TOKEN".to_string(), token.clone());
456    }
457
458    let env_vec: Vec<(&str, &str)> = env.iter().map(|(k, v)| (k.as_str(), v.as_str())).collect();
459
460    let session = tmux
461        .create_session(
462            &inv.repo,
463            &inv.task_id,
464            &inv.work_dir.to_string_lossy(),
465            &command,
466            env_vec.as_slice(),
467        )
468        .await?;
469
470    tracing::info!(
471        task_id = inv.task_id,
472        agent = inv.agent,
473        session = %session,
474        "agent spawned in tmux"
475    );
476
477    Ok(session)
478}
479
480/// Build the system prompt for the agent.
481pub fn build_system_prompt(
482    _task: &ExternalTask,
483    context: &super::context::TaskContext,
484    route_result: Option<&RouteResult>,
485    default_branch: &str,
486    shipcheck: Shipcheck,
487    sandboxed: bool,
488) -> String {
489    let mut vars = HashMap::new();
490
491    vars.insert("DEFAULT_BRANCH".to_string(), default_branch.to_string());
492    shipcheck.insert_vars(&mut vars);
493    insert_cluster_vars(shipcheck, &mut vars);
494
495    if sandboxed {
496        vars.insert("SANDBOX".to_string(), "1".to_string());
497    }
498
499    if let Some(rr) = route_result {
500        vars.insert("ROLE".to_string(), rr.profile.role.clone());
501
502        if !rr.profile.constraints.is_empty() {
503            let constraints = rr
504                .profile
505                .constraints
506                .iter()
507                .map(|c| format!("- {c}"))
508                .collect::<Vec<_>>()
509                .join("\n");
510            vars.insert("CONSTRAINTS".to_string(), constraints);
511        }
512    }
513
514    if !context.project_instructions.is_empty() {
515        vars.insert(
516            "PROJECT_INSTRUCTIONS".to_string(),
517            context.project_instructions.clone(),
518        );
519    }
520
521    if !context.repo_tree.is_empty() {
522        vars.insert("REPO_TREE".to_string(), context.repo_tree.clone());
523    }
524
525    render_prompt_template(AGENT_SYSTEM_TEMPLATE, &vars)
526}
527
528/// Build the agent message (task prompt).
529pub fn build_agent_message(
530    task: &ExternalTask,
531    context: &super::context::TaskContext,
532    attempts: u32,
533) -> String {
534    let mut vars = HashMap::new();
535    vars.insert("TASK_ID".to_string(), task.id.0.clone());
536    vars.insert("TASK_TITLE".to_string(), task.title.clone());
537    vars.insert("TASK_BODY".to_string(), task.body.clone());
538
539    if !context.task_context.is_empty() {
540        vars.insert("TASK_CONTEXT".to_string(), context.task_context.clone());
541    }
542
543    if !context.parent_context.is_empty() {
544        vars.insert("PARENT_CONTEXT".to_string(), context.parent_context.clone());
545    }
546
547    if !context.issue_comments.is_empty() {
548        vars.insert("ISSUE_COMMENTS".to_string(), context.issue_comments.clone());
549    }
550
551    if !context.pr_review_context.is_empty() {
552        vars.insert(
553            "PR_REVIEW_CONTEXT".to_string(),
554            context.pr_review_context.clone(),
555        );
556    }
557
558    if attempts > 0 && !context.git_diff.is_empty() {
559        vars.insert("GIT_DIFF".to_string(), context.git_diff.clone());
560    }
561
562    if attempts > 0 {
563        vars.insert("ATTEMPT_NUMBER".to_string(), (attempts + 1).to_string());
564    }
565
566    if !context.memory.is_empty() {
567        let mut sections = Vec::new();
568        for entry in &context.memory {
569            let mut entry_vars = HashMap::new();
570            entry_vars.insert("ATTEMPT".to_string(), entry.attempt.to_string());
571            entry_vars.insert("AGENT".to_string(), entry.agent.clone());
572
573            if let Some(ref model) = entry.model {
574                entry_vars.insert("MODEL".to_string(), model.clone());
575            }
576
577            if !entry.approach.is_empty() {
578                entry_vars.insert("APPROACH".to_string(), entry.approach.clone());
579            }
580
581            if !entry.learnings.is_empty() {
582                let learnings = entry
583                    .learnings
584                    .iter()
585                    .map(|learning| format!("- {learning}"))
586                    .collect::<Vec<_>>()
587                    .join("\n");
588                entry_vars.insert("LEARNINGS".to_string(), learnings);
589            }
590
591            if let Some(ref error) = entry.error {
592                entry_vars.insert("ERROR".to_string(), error.clone());
593            }
594
595            if !entry.files_modified.is_empty() {
596                entry_vars.insert(
597                    "FILES_MODIFIED".to_string(),
598                    entry.files_modified.join(", "),
599                );
600            }
601
602            let rendered = render_prompt_template(AGENT_MEMORY_ENTRY_TEMPLATE, &entry_vars);
603            sections.push(rendered.trim().to_string());
604        }
605
606        let memory_section = sections.join("\n\n");
607        vars.insert("MEMORY_SECTION".to_string(), memory_section);
608    }
609
610    render_prompt_template(AGENT_MESSAGE_TEMPLATE, &vars)
611}
612
613/// Build the review prompt for the review agent.
614///
615/// This is called when a task completes and the review agent needs to
616/// review the changes before auto-merge.
617pub fn build_review_prompt(
618    task: &ExternalTask,
619    agent_summary: &str,
620    git_diff: &str,
621    git_log: &str,
622    default_branch: &str,
623    pr_number: u64,
624    shipcheck: Shipcheck,
625) -> String {
626    let mut vars = HashMap::new();
627    shipcheck.insert_vars(&mut vars);
628    insert_cluster_vars(shipcheck, &mut vars);
629    vars.insert("TASK_ID".to_string(), task.id.0.clone());
630    vars.insert("TASK_TITLE".to_string(), task.title.clone());
631    vars.insert("TASK_BODY".to_string(), task.body.clone());
632    vars.insert("DEFAULT_BRANCH".to_string(), default_branch.to_string());
633    vars.insert("PR_NUMBER".to_string(), pr_number.to_string());
634
635    if !agent_summary.is_empty() {
636        vars.insert("AGENT_SUMMARY".to_string(), agent_summary.to_string());
637    }
638
639    if !git_diff.is_empty() {
640        vars.insert("GIT_DIFF".to_string(), git_diff.to_string());
641    }
642
643    if !git_log.is_empty() {
644        vars.insert("GIT_LOG".to_string(), git_log.to_string());
645    }
646
647    render_prompt_template(REVIEW_PROMPT_TEMPLATE, &vars)
648}
649
650/// Build the runner shell script contents for testing and inspection, given a pre-created
651/// attempt directory so tests can pass a temp dir.
652///
653/// IMPORTANT: this must not embed secrets (GH_TOKEN) into the script.
654#[cfg(test)]
655fn build_runner_script_in_dir(inv: &AgentInvocation, attempt_dir: &Path) -> String {
656    let sys_file = attempt_dir.join("prompt-sys.md");
657    let msg_file = attempt_dir.join("prompt-msg.md");
658
659    // Build unified permission rules and sys content (minimal translation)
660    let mut permissions = agents::PermissionRules::from_config();
661    if !inv.disallowed_tools.is_empty() {
662        for tool in &inv.disallowed_tools {
663            if !permissions.disallowed_tools.contains(tool) {
664                permissions.disallowed_tools.push(tool.clone());
665            }
666        }
667    }
668    permissions.allowed_edit_paths.push(inv.work_dir.clone());
669
670    // Build agent command using per-agent runner
671    let runner = agents::get_runner(&inv.agent);
672    let timeout_cmd = if inv.timeout_seconds > 0 {
673        format!("timeout {}", inv.timeout_seconds)
674    } else {
675        String::new()
676    };
677    let agent_cmd = runner.build_command_with_effort(
678        inv.model
679            .as_deref()
680            .map(str::trim)
681            .filter(|m| !m.is_empty()),
682        inv.reasoning_effort.as_deref(),
683        &timeout_cmd,
684        &sys_file.to_string_lossy(),
685        &msg_file.to_string_lossy(),
686        &permissions,
687    );
688
689    let status_file = attempt_dir.join("exit.txt");
690    let stderr_file = attempt_dir.join("stderr.txt");
691
692    let sq_status = shell_single_quote(&status_file.display().to_string());
693    let sq_stderr = shell_single_quote(&stderr_file.display().to_string());
694    let sq_out = shell_single_quote(&inv.output_file.display().to_string());
695    let sq_work_dir = shell_single_quote(&inv.work_dir.to_string_lossy());
696    let script = format!(
697        "#!/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",
698    );
699
700    script
701}
702
703/// Build the system prompt for the review agent.
704pub fn review_system_prompt() -> String {
705    render_prompt_template(REVIEW_SYSTEM_TEMPLATE, &HashMap::new())
706}
707
708#[cfg(test)]
709mod tests {
710    use super::*;
711    use crate::backends::ExternalId;
712    use crate::engine::agents::shell_single_quote;
713    use crate::engine::runner::sandbox;
714    use crate::engine::runner::template;
715
716    use std::path::PathBuf;
717
718    #[test]
719    fn review_system_prompt_checks_stray_files_and_trust_boundaries() {
720        let p = review_system_prompt();
721        assert!(p.contains("**Files**"));
722        assert!(p.contains("**Trust boundaries**"));
723    }
724
725    fn test_invocation(task_id: &str) -> AgentInvocation {
726        AgentInvocation {
727            agent: "claude".to_string(),
728            model: None,
729            reasoning_effort: None,
730            work_dir: PathBuf::from("/tmp"),
731            system_prompt: "test system prompt".to_string(),
732            agent_message: "test message".to_string(),
733            task_id: task_id.to_string(),
734            disallowed_tools: vec![],
735            git_author_name: "Test Bot".to_string(),
736            git_author_email: "bot@example.com".to_string(),
737            output_file: PathBuf::from("/tmp/test-output.json"),
738            timeout_seconds: 0,
739            repo: "orch-runner-test/token-check".to_string(),
740            attempt: 1,
741            sandbox: false,
742            main_project_dir: PathBuf::from("/tmp"),
743            branch: String::new(),
744        }
745    }
746
747    #[test]
748    fn spawn_in_tmux_rejects_invalid_env() {
749        // This test verifies the function signature and basic behavior
750        // without actually spawning a tmux session.
751        // The key security guarantee: tokens are passed via tmux -e flag,
752        // not written to any file on disk.
753        let inv = test_invocation("env-test");
754        // Just verify the invocation can be created without panicking
755        assert_eq!(inv.task_id, "env-test");
756    }
757
758    #[test]
759    fn build_runner_script_persists_exit_status_on_failure() {
760        // Use a temp dir so lib and bin compilation units don't race on ~/.orch/state/.
761        let tmp = tempfile::TempDir::new().expect("temp dir");
762        let inv = test_invocation("runner-status-test");
763        let script = build_runner_script_in_dir(&inv, tmp.path());
764
765        assert!(
766            script
767                .contains("trap 'status=$?; printf \"%s\\n\" \"$status\" > \"$status_file\"' EXIT")
768        );
769        assert!(script.contains("set +e"));
770    }
771
772    #[test]
773    fn build_runner_script_reports_missing_worktree() {
774        // Use a temp dir so lib and bin compilation units don't race on ~/.orch/state/.
775        let tmp = tempfile::TempDir::new().expect("temp dir");
776        let inv = test_invocation("runner-missing-worktree-test");
777        let script = build_runner_script_in_dir(&inv, tmp.path());
778
779        assert!(script.contains("worktree directory does not exist: '/tmp'"));
780        assert!(script.contains("stderr_file='"));
781    }
782
783    #[test]
784    fn tmux_runner_script_runs_agent_under_pty_not_a_plain_pipe() {
785        // Regression test for #3554: piping the agent binary's stdout straight
786        // into `tee` leaves it non-tty, which makes many CLI runtimes switch to
787        // full block-buffering and can starve the tmux pane long enough to trip
788        // silence detection even while the agent is actively working. The agent
789        // command must run under `script` (a real pty) before hitting `tee`.
790        let tmp = tempfile::TempDir::new().expect("temp dir");
791        let inv = test_invocation("pty-wrap-test");
792        let (runner_script, agent_cmd_script) =
793            build_tmux_runner_scripts(&inv, "echo hello", tmp.path(), None, &[]);
794
795        assert!(
796            runner_script.contains("script -q /dev/null /bin/bash"),
797            "agent must be exec'd under a pty via `script`, got: {runner_script}"
798        );
799        assert!(
800            runner_script.contains("| tee"),
801            "output must still be tee'd to the output file, got: {runner_script}"
802        );
803        assert!(
804            !runner_script.contains("echo hello 2>"),
805            "the raw agent command must not be piped directly into tee anymore, got: {runner_script}"
806        );
807        assert!(
808            agent_cmd_script.contains("echo hello 2>"),
809            "the agent command should run (with stderr split to a file) inside the pty-wrapped helper script, got: {agent_cmd_script}"
810        );
811    }
812
813    #[test]
814    fn tmux_runner_script_captures_agent_exit_status_via_pipestatus() {
815        let tmp = tempfile::TempDir::new().expect("temp dir");
816        let inv = test_invocation("pty-exit-status-test");
817        let (runner_script, _) =
818            build_tmux_runner_scripts(&inv, "echo hello", tmp.path(), None, &[]);
819
820        assert!(runner_script.contains("CMD_STATUS=${PIPESTATUS[0]:-0}"));
821        assert!(runner_script.contains("exit $CMD_STATUS"));
822    }
823
824    #[test]
825    fn tmux_runner_script_disables_commit_signing() {
826        // Locked signing agent must not fail `git commit` inside agent sessions
827        let tmp = tempfile::TempDir::new().expect("temp dir");
828        let inv = test_invocation("gpgsign-test");
829        let (runner_script, _) =
830            build_tmux_runner_scripts(&inv, "echo hello", tmp.path(), None, &[]);
831
832        assert!(runner_script.contains("GIT_CONFIG_KEY_0=\"commit.gpgsign\""));
833        assert!(runner_script.contains("GIT_CONFIG_VALUE_0=\"false\""));
834        assert!(runner_script.contains("GIT_CONFIG_KEY_1=\"tag.gpgsign\""));
835        // Only pushes go over HTTPS with gh's credentials, fetches keep the remote as it is
836        assert!(
837            runner_script.contains("GIT_CONFIG_KEY_2=\"url.https://github.com/.pushInsteadOf\"")
838        );
839        assert!(runner_script.contains("GIT_CONFIG_VALUE_2=\"git@github.com:\""));
840        assert!(runner_script.contains("GIT_CONFIG_VALUE_3=\"!gh auth git-credential\""));
841    }
842
843    #[test]
844    fn tmux_runner_script_writes_executable_agent_cmd_helper() {
845        let tmp = tempfile::TempDir::new().expect("temp dir");
846        let inv = test_invocation("pty-helper-path-test");
847        let (runner_script, agent_cmd_script) =
848            build_tmux_runner_scripts(&inv, "echo hello", tmp.path(), None, &[]);
849
850        let agent_cmd_script_path = tmp.path().join("agent_cmd.sh");
851        assert!(
852            runner_script.contains(&agent_cmd_script_path.display().to_string()),
853            "runner script must reference the agent_cmd.sh helper path, got: {runner_script}"
854        );
855        assert!(agent_cmd_script.starts_with("#!/usr/bin/env bash\n"));
856    }
857
858    #[test]
859    fn tmux_runner_script_runs_the_agent_inside_the_sandbox() {
860        let tmp = tempfile::TempDir::new().expect("temp dir");
861        let inv = test_invocation("sandbox-test");
862        let argv: Vec<OsString> = vec![
863            "/usr/bin/sandbox-exec".into(),
864            "-p".into(),
865            "(version 1)".into(),
866        ];
867        let (_, agent_cmd_script) =
868            build_tmux_runner_scripts(&inv, "claude -p 'hi'", tmp.path(), Some(&argv), &[]);
869        assert!(
870            agent_cmd_script.contains(
871                "env -u TMUX -u TMUX_PANE -u SSH_AUTH_SOCK TMPDIR='"
872            ) && agent_cmd_script.contains(
873                "1 '/usr/bin/sandbox-exec' '-p' '(version 1)' /bin/bash -c 'claude -p '\\''hi'\\''' 2>"
874            ),
875            "the agent must run inside the sandbox with stderr split outside it, got: {agent_cmd_script}"
876        );
877        assert!(
878            agent_cmd_script.contains(&format!(
879                "TMPDIR='{}'",
880                sandbox::run_temp_dir(tmp.path()).display()
881            )),
882            "the agent must get its own TMPDIR, got: {agent_cmd_script}"
883        );
884        assert!(
885            agent_cmd_script.contains(&format!(
886                "GH_CONFIG_DIR='{}'",
887                sandbox::gh_config_dir(&sandbox::run_temp_dir(tmp.path())).display()
888            )),
889            "gh must get a config dir it can read, got: {agent_cmd_script}"
890        );
891        assert!(agent_cmd_script.contains(" SHIPCHECK_HANDOFF=1 "));
892
893        let env = [("NPM_CONFIG_USERCONFIG", tmp.path().join("npmrc"))];
894        let (_, with_env) = build_tmux_runner_scripts(&inv, "true", tmp.path(), Some(&argv), &env);
895        assert!(with_env.contains(&format!(
896            " NPM_CONFIG_USERCONFIG='{}' ",
897            tmp.path().join("npmrc").display()
898        )));
899    }
900
901    #[test]
902    fn only_a_sandboxed_run_fetches_without_tags() {
903        let tmp = tempfile::TempDir::new().expect("temp dir");
904        let inv = test_invocation("sandbox-test");
905        let argv: Vec<OsString> = vec!["/usr/bin/sandbox-exec".into()];
906        let (sandboxed, _) = build_tmux_runner_scripts(&inv, "true", tmp.path(), Some(&argv), &[]);
907        assert!(sandboxed.contains("export GIT_CONFIG_COUNT=\"5\""));
908        assert!(sandboxed.contains("export GIT_CONFIG_VALUE_4=\"--no-tags\""));
909        let (plain, _) = build_tmux_runner_scripts(&inv, "true", tmp.path(), None, &[]);
910        assert!(!plain.contains("tagOpt"));
911        assert!(
912            !plain.contains("rm -rf"),
913            "only a sandboxed run has a temp dir to wipe"
914        );
915        assert!(sandboxed.contains(&format!(
916            "\"$status_file\"; rm -rf -- '{}'' EXIT",
917            sandbox::run_temp_dir(tmp.path()).display()
918        )));
919    }
920
921    #[test]
922    fn a_sandboxed_prompt_offers_no_shipcheck() {
923        assert_eq!(
924            Shipcheck::Available.for_prompt(true, false),
925            Shipcheck::Absent
926        );
927        assert_eq!(
928            Shipcheck::Available.for_prompt(true, true),
929            Shipcheck::Available
930        );
931        assert_eq!(
932            Shipcheck::Available.for_prompt(false, false),
933            Shipcheck::Available
934        );
935        assert_eq!(
936            Shipcheck::NotInstalled.for_prompt(true, false),
937            Shipcheck::NotInstalled
938        );
939    }
940
941    #[test]
942    fn build_runner_script_escapes_shell_injection_in_paths() {
943        let tmp = tempfile::TempDir::new().expect("temp dir");
944        let mut inv = test_invocation("injection-test");
945        inv.work_dir = PathBuf::from("/tmp/$(whoami)/workspace");
946        inv.output_file = PathBuf::from("/tmp/evil`id`.json");
947        let script = build_runner_script_in_dir(&inv, tmp.path());
948
949        // Values must be single-quoted, neutralizing $() and backticks
950        assert!(
951            script.contains("'/tmp/$(whoami)/workspace'"),
952            "work_dir with $() must be single-quoted: {script}"
953        );
954        assert!(
955            script.contains("'/tmp/evil`id`.json'"),
956            "output_file with backticks must be single-quoted: {script}"
957        );
958    }
959
960    #[test]
961    fn review_prompt_forbids_ending_turn_on_pending_ci_status() {
962        // Regression test for #3453: a review agent must not stop with a
963        // prose "CI is still running" status update and leave the turn
964        // without JSON. The prompt must explicitly route PENDING/NOT RUN CI
965        // through the local-checks fallback and into the same-turn JSON output.
966        let task = ExternalTask {
967            id: ExternalId("155460".to_string()),
968            title: "test task".to_string(),
969            body: "test body".to_string(),
970            state: "open".to_string(),
971            labels: vec![],
972            author: "tester".to_string(),
973            created_at: "2026-01-01T00:00:00Z".to_string(),
974            updated_at: "2026-01-01T00:00:00Z".to_string(),
975            url: "https://example.com/1".to_string(),
976        };
977        let prompt = build_review_prompt(&task, "", "", "", "main", 1, Shipcheck::Absent);
978
979        assert!(
980            prompt.contains("Pending CI is never a terminal review state"),
981            "prompt must state pending CI is not terminal: {prompt}"
982        );
983        assert!(
984            prompt.contains("Never end your turn with a CI-waiting status update"),
985            "prompt must forbid ending the turn on a CI-waiting status update: {prompt}"
986        );
987    }
988
989    #[test]
990    fn shell_single_quote_escapes_embedded_quotes() {
991        assert_eq!(shell_single_quote("hello"), "'hello'");
992        assert_eq!(shell_single_quote("O'Brien"), "'O'\\''Brien'");
993        assert_eq!(shell_single_quote("$(rm -rf /)"), "'$(rm -rf /)'");
994        assert_eq!(shell_single_quote("`whoami`"), "'`whoami`'");
995        assert_eq!(shell_single_quote("a\"b"), "'a\"b'");
996        assert_eq!(shell_single_quote("$HOME"), "'$HOME'");
997    }
998
999    fn prompt_task() -> ExternalTask {
1000        ExternalTask {
1001            id: ExternalId("1".to_string()),
1002            title: "t".to_string(),
1003            body: "b".to_string(),
1004            state: "open".to_string(),
1005            labels: vec![],
1006            author: "a".to_string(),
1007            created_at: "2026-01-01T00:00:00Z".to_string(),
1008            updated_at: "2026-01-01T00:00:00Z".to_string(),
1009            url: "https://example.com/1".to_string(),
1010        }
1011    }
1012
1013    #[test]
1014    fn only_a_sandboxed_prompt_explains_the_sandbox() {
1015        let ctx = super::super::context::TaskContext::default();
1016        let task = prompt_task();
1017        let prompt = |sandboxed| {
1018            build_system_prompt(&task, &ctx, None, "main", Shipcheck::Absent, sandboxed)
1019        };
1020        assert!(prompt(true).contains("you run inside an OS sandbox"));
1021        assert!(!prompt(false).contains("OS sandbox"));
1022        assert!(!prompt(false).contains("SANDBOX"));
1023    }
1024
1025    #[test]
1026    fn system_prompt_uses_shipcheck_only_when_available() {
1027        let ctx = super::super::context::TaskContext::default();
1028        let task = prompt_task();
1029        let prompt = |s| build_system_prompt(&task, &ctx, None, "main", s, false);
1030
1031        let available = prompt(Shipcheck::Available);
1032        assert!(available.contains("shipcheck run"));
1033        assert!(available.contains("shipcheck commit"));
1034        assert!(!available.contains(".github/workflows/"));
1035        assert!(!available.contains("not installed"));
1036
1037        let outdated = prompt(Shipcheck::Outdated);
1038        assert!(!outdated.contains("shipcheck"));
1039        assert!(outdated.contains(".github/workflows/"));
1040
1041        let missing = prompt(Shipcheck::NotInstalled);
1042        assert!(!missing.contains("shipcheck run"));
1043        assert!(missing.contains(".github/workflows/"));
1044        assert!(missing.contains("shipcheck is not installed"));
1045
1046        let absent = prompt(Shipcheck::Absent);
1047        assert!(!absent.contains("shipcheck"));
1048        assert!(absent.contains(".github/workflows/"));
1049
1050        for p in [&available, &outdated, &missing, &absent] {
1051            assert!(!p.contains("{{"), "{p}");
1052            assert!(!p.contains("install shipcheck"), "{p}");
1053        }
1054    }
1055
1056    #[test]
1057    fn review_prompt_uses_shipcheck_only_when_available() {
1058        let task = prompt_task();
1059        let prompt = |s| build_review_prompt(&task, "", "", "", "main", 1, s);
1060        assert!(prompt(Shipcheck::Available).contains("shipcheck run"));
1061        for s in [
1062            Shipcheck::Outdated,
1063            Shipcheck::NotInstalled,
1064            Shipcheck::Absent,
1065        ] {
1066            let p = prompt(s);
1067            assert!(!p.contains("shipcheck"), "{p}");
1068            assert!(p.contains(".github/workflows/"), "{p}");
1069        }
1070    }
1071
1072    #[test]
1073    fn the_progress_step_appears_only_in_cluster_mode() {
1074        let mut vars = HashMap::new();
1075        insert_cluster_vars(Shipcheck::Available, &mut vars);
1076        assert!(vars.is_empty(), "no cluster section, no cluster flags");
1077        let plain = template::render_template_str(AGENT_SYSTEM_TEMPLATE, &vars).unwrap();
1078        assert!(!plain.contains("orch progress"));
1079
1080        for flag in ["CLUSTER", "CLUSTER_SHIPCHECK"] {
1081            vars.insert(flag.to_string(), "1".to_string());
1082        }
1083        let cluster = template::render_template_str(AGENT_SYSTEM_TEMPLATE, &vars).unwrap();
1084        assert!(cluster.contains("orch progress"));
1085        assert!(cluster.contains("commits only through `shipcheck commit`"));
1086        assert!(!cluster.contains("It commits anything you left"));
1087    }
1088}