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: orch loads ~/.path into its own environment at startup
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 !context.progress.is_empty() {
560        vars.insert("PROGRESS".to_string(), context.progress.clone());
561    }
562
563    if attempts > 0 && !context.git_diff.is_empty() {
564        vars.insert("GIT_DIFF".to_string(), context.git_diff.clone());
565    }
566
567    if attempts > 0 {
568        vars.insert("ATTEMPT_NUMBER".to_string(), (attempts + 1).to_string());
569    }
570
571    if !context.memory.is_empty() {
572        let mut sections = Vec::new();
573        for entry in &context.memory {
574            let mut entry_vars = HashMap::new();
575            entry_vars.insert("ATTEMPT".to_string(), entry.attempt.to_string());
576            entry_vars.insert("AGENT".to_string(), entry.agent.clone());
577
578            if let Some(ref model) = entry.model {
579                entry_vars.insert("MODEL".to_string(), model.clone());
580            }
581
582            if !entry.approach.is_empty() {
583                entry_vars.insert("APPROACH".to_string(), entry.approach.clone());
584            }
585
586            if !entry.learnings.is_empty() {
587                let learnings = entry
588                    .learnings
589                    .iter()
590                    .map(|learning| format!("- {learning}"))
591                    .collect::<Vec<_>>()
592                    .join("\n");
593                entry_vars.insert("LEARNINGS".to_string(), learnings);
594            }
595
596            if let Some(ref error) = entry.error {
597                entry_vars.insert("ERROR".to_string(), error.clone());
598            }
599
600            if !entry.files_modified.is_empty() {
601                entry_vars.insert(
602                    "FILES_MODIFIED".to_string(),
603                    entry.files_modified.join(", "),
604                );
605            }
606
607            let rendered = render_prompt_template(AGENT_MEMORY_ENTRY_TEMPLATE, &entry_vars);
608            sections.push(rendered.trim().to_string());
609        }
610
611        let memory_section = sections.join("\n\n");
612        vars.insert("MEMORY_SECTION".to_string(), memory_section);
613    }
614
615    render_prompt_template(AGENT_MESSAGE_TEMPLATE, &vars)
616}
617
618/// Build the review prompt for the review agent.
619///
620/// This is called when a task completes and the review agent needs to
621/// review the changes before auto-merge.
622pub fn build_review_prompt(
623    task: &ExternalTask,
624    agent_summary: &str,
625    git_diff: &str,
626    git_log: &str,
627    default_branch: &str,
628    pr_number: u64,
629    shipcheck: Shipcheck,
630) -> String {
631    let mut vars = HashMap::new();
632    shipcheck.insert_vars(&mut vars);
633    insert_cluster_vars(shipcheck, &mut vars);
634    vars.insert("TASK_ID".to_string(), task.id.0.clone());
635    vars.insert("TASK_TITLE".to_string(), task.title.clone());
636    vars.insert("TASK_BODY".to_string(), task.body.clone());
637    vars.insert("DEFAULT_BRANCH".to_string(), default_branch.to_string());
638    vars.insert("PR_NUMBER".to_string(), pr_number.to_string());
639
640    if !agent_summary.is_empty() {
641        vars.insert("AGENT_SUMMARY".to_string(), agent_summary.to_string());
642    }
643
644    if !git_diff.is_empty() {
645        vars.insert("GIT_DIFF".to_string(), git_diff.to_string());
646    }
647
648    if !git_log.is_empty() {
649        vars.insert("GIT_LOG".to_string(), git_log.to_string());
650    }
651
652    render_prompt_template(REVIEW_PROMPT_TEMPLATE, &vars)
653}
654
655/// Build the runner shell script contents for testing and inspection, given a pre-created
656/// attempt directory so tests can pass a temp dir.
657///
658/// IMPORTANT: this must not embed secrets (GH_TOKEN) into the script.
659#[cfg(test)]
660fn build_runner_script_in_dir(inv: &AgentInvocation, attempt_dir: &Path) -> String {
661    let sys_file = attempt_dir.join("prompt-sys.md");
662    let msg_file = attempt_dir.join("prompt-msg.md");
663
664    // Build unified permission rules and sys content (minimal translation)
665    let mut permissions = agents::PermissionRules::from_config();
666    if !inv.disallowed_tools.is_empty() {
667        for tool in &inv.disallowed_tools {
668            if !permissions.disallowed_tools.contains(tool) {
669                permissions.disallowed_tools.push(tool.clone());
670            }
671        }
672    }
673    permissions.allowed_edit_paths.push(inv.work_dir.clone());
674
675    // Build agent command using per-agent runner
676    let runner = agents::get_runner(&inv.agent);
677    let timeout_cmd = if inv.timeout_seconds > 0 {
678        format!("timeout {}", inv.timeout_seconds)
679    } else {
680        String::new()
681    };
682    let agent_cmd = runner.build_command_with_effort(
683        inv.model
684            .as_deref()
685            .map(str::trim)
686            .filter(|m| !m.is_empty()),
687        inv.reasoning_effort.as_deref(),
688        &timeout_cmd,
689        &sys_file.to_string_lossy(),
690        &msg_file.to_string_lossy(),
691        &permissions,
692    );
693
694    let status_file = attempt_dir.join("exit.txt");
695    let stderr_file = attempt_dir.join("stderr.txt");
696
697    let sq_status = shell_single_quote(&status_file.display().to_string());
698    let sq_stderr = shell_single_quote(&stderr_file.display().to_string());
699    let sq_out = shell_single_quote(&inv.output_file.display().to_string());
700    let sq_work_dir = shell_single_quote(&inv.work_dir.to_string_lossy());
701    let script = format!(
702        "#!/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",
703    );
704
705    script
706}
707
708/// Build the system prompt for the review agent.
709pub fn review_system_prompt() -> String {
710    render_prompt_template(REVIEW_SYSTEM_TEMPLATE, &HashMap::new())
711}
712
713#[cfg(test)]
714mod tests {
715    use super::*;
716    use crate::backends::ExternalId;
717    use crate::engine::agents::shell_single_quote;
718    use crate::engine::runner::sandbox;
719    use crate::engine::runner::template;
720
721    use std::path::PathBuf;
722
723    #[test]
724    fn review_system_prompt_checks_stray_files_and_trust_boundaries() {
725        let p = review_system_prompt();
726        assert!(p.contains("**Files**"));
727        assert!(p.contains("**Trust boundaries**"));
728    }
729
730    fn test_invocation(task_id: &str) -> AgentInvocation {
731        AgentInvocation {
732            agent: "claude".to_string(),
733            model: None,
734            reasoning_effort: None,
735            work_dir: PathBuf::from("/tmp"),
736            system_prompt: "test system prompt".to_string(),
737            agent_message: "test message".to_string(),
738            task_id: task_id.to_string(),
739            disallowed_tools: vec![],
740            git_author_name: "Test Bot".to_string(),
741            git_author_email: "bot@example.com".to_string(),
742            output_file: PathBuf::from("/tmp/test-output.json"),
743            timeout_seconds: 0,
744            repo: "orch-runner-test/token-check".to_string(),
745            attempt: 1,
746            sandbox: false,
747            main_project_dir: PathBuf::from("/tmp"),
748            branch: String::new(),
749        }
750    }
751
752    #[test]
753    fn spawn_in_tmux_rejects_invalid_env() {
754        // This test verifies the function signature and basic behavior
755        // without actually spawning a tmux session.
756        // The key security guarantee: tokens are passed via tmux -e flag,
757        // not written to any file on disk.
758        let inv = test_invocation("env-test");
759        // Just verify the invocation can be created without panicking
760        assert_eq!(inv.task_id, "env-test");
761    }
762
763    #[test]
764    fn build_runner_script_persists_exit_status_on_failure() {
765        // Use a temp dir so lib and bin compilation units don't race on ~/.orch/state/.
766        let tmp = tempfile::TempDir::new().expect("temp dir");
767        let inv = test_invocation("runner-status-test");
768        let script = build_runner_script_in_dir(&inv, tmp.path());
769
770        assert!(
771            script
772                .contains("trap 'status=$?; printf \"%s\\n\" \"$status\" > \"$status_file\"' EXIT")
773        );
774        assert!(script.contains("set +e"));
775    }
776
777    #[test]
778    fn build_runner_script_reports_missing_worktree() {
779        // Use a temp dir so lib and bin compilation units don't race on ~/.orch/state/.
780        let tmp = tempfile::TempDir::new().expect("temp dir");
781        let inv = test_invocation("runner-missing-worktree-test");
782        let script = build_runner_script_in_dir(&inv, tmp.path());
783
784        assert!(script.contains("worktree directory does not exist: '/tmp'"));
785        assert!(script.contains("stderr_file='"));
786    }
787
788    #[test]
789    fn tmux_runner_script_runs_agent_under_pty_not_a_plain_pipe() {
790        // Regression test for #3554: piping the agent binary's stdout straight
791        // into `tee` leaves it non-tty, which makes many CLI runtimes switch to
792        // full block-buffering and can starve the tmux pane long enough to trip
793        // silence detection even while the agent is actively working. The agent
794        // command must run under `script` (a real pty) before hitting `tee`.
795        let tmp = tempfile::TempDir::new().expect("temp dir");
796        let inv = test_invocation("pty-wrap-test");
797        let (runner_script, agent_cmd_script) =
798            build_tmux_runner_scripts(&inv, "echo hello", tmp.path(), None, &[]);
799
800        assert!(
801            runner_script.contains("script -q /dev/null /bin/bash"),
802            "agent must be exec'd under a pty via `script`, got: {runner_script}"
803        );
804        assert!(
805            runner_script.contains("| tee"),
806            "output must still be tee'd to the output file, got: {runner_script}"
807        );
808        assert!(
809            !runner_script.contains("echo hello 2>"),
810            "the raw agent command must not be piped directly into tee anymore, got: {runner_script}"
811        );
812        assert!(
813            agent_cmd_script.contains("echo hello 2>"),
814            "the agent command should run (with stderr split to a file) inside the pty-wrapped helper script, got: {agent_cmd_script}"
815        );
816    }
817
818    #[test]
819    fn tmux_runner_script_captures_agent_exit_status_via_pipestatus() {
820        let tmp = tempfile::TempDir::new().expect("temp dir");
821        let inv = test_invocation("pty-exit-status-test");
822        let (runner_script, _) =
823            build_tmux_runner_scripts(&inv, "echo hello", tmp.path(), None, &[]);
824
825        assert!(runner_script.contains("CMD_STATUS=${PIPESTATUS[0]:-0}"));
826        assert!(runner_script.contains("exit $CMD_STATUS"));
827    }
828
829    #[test]
830    fn tmux_runner_script_disables_commit_signing() {
831        // Locked signing agent must not fail `git commit` inside agent sessions
832        let tmp = tempfile::TempDir::new().expect("temp dir");
833        let inv = test_invocation("gpgsign-test");
834        let (runner_script, _) =
835            build_tmux_runner_scripts(&inv, "echo hello", tmp.path(), None, &[]);
836
837        assert!(runner_script.contains("GIT_CONFIG_KEY_0=\"commit.gpgsign\""));
838        assert!(runner_script.contains("GIT_CONFIG_VALUE_0=\"false\""));
839        assert!(runner_script.contains("GIT_CONFIG_KEY_1=\"tag.gpgsign\""));
840        // Only pushes go over HTTPS with gh's credentials, fetches keep the remote as it is
841        assert!(
842            runner_script.contains("GIT_CONFIG_KEY_2=\"url.https://github.com/.pushInsteadOf\"")
843        );
844        assert!(runner_script.contains("GIT_CONFIG_VALUE_2=\"git@github.com:\""));
845        assert!(runner_script.contains("GIT_CONFIG_VALUE_3=\"!gh auth git-credential\""));
846    }
847
848    #[test]
849    fn tmux_runner_script_writes_executable_agent_cmd_helper() {
850        let tmp = tempfile::TempDir::new().expect("temp dir");
851        let inv = test_invocation("pty-helper-path-test");
852        let (runner_script, agent_cmd_script) =
853            build_tmux_runner_scripts(&inv, "echo hello", tmp.path(), None, &[]);
854
855        let agent_cmd_script_path = tmp.path().join("agent_cmd.sh");
856        assert!(
857            runner_script.contains(&agent_cmd_script_path.display().to_string()),
858            "runner script must reference the agent_cmd.sh helper path, got: {runner_script}"
859        );
860        assert!(agent_cmd_script.starts_with("#!/usr/bin/env bash\n"));
861    }
862
863    #[test]
864    fn tmux_runner_script_runs_the_agent_inside_the_sandbox() {
865        let tmp = tempfile::TempDir::new().expect("temp dir");
866        let inv = test_invocation("sandbox-test");
867        let argv: Vec<OsString> = vec![
868            "/usr/bin/sandbox-exec".into(),
869            "-p".into(),
870            "(version 1)".into(),
871        ];
872        let (_, agent_cmd_script) =
873            build_tmux_runner_scripts(&inv, "claude -p 'hi'", tmp.path(), Some(&argv), &[]);
874        assert!(
875            agent_cmd_script.contains(
876                "env -u TMUX -u TMUX_PANE -u SSH_AUTH_SOCK TMPDIR='"
877            ) && agent_cmd_script.contains(
878                "1 '/usr/bin/sandbox-exec' '-p' '(version 1)' /bin/bash -c 'claude -p '\\''hi'\\''' 2>"
879            ),
880            "the agent must run inside the sandbox with stderr split outside it, got: {agent_cmd_script}"
881        );
882        assert!(
883            agent_cmd_script.contains(&format!(
884                "TMPDIR='{}'",
885                sandbox::run_temp_dir(tmp.path()).display()
886            )),
887            "the agent must get its own TMPDIR, got: {agent_cmd_script}"
888        );
889        assert!(
890            agent_cmd_script.contains(&format!(
891                "GH_CONFIG_DIR='{}'",
892                sandbox::gh_config_dir(&sandbox::run_temp_dir(tmp.path())).display()
893            )),
894            "gh must get a config dir it can read, got: {agent_cmd_script}"
895        );
896        assert!(agent_cmd_script.contains(" SHIPCHECK_HANDOFF=1 "));
897
898        let env = [("NPM_CONFIG_USERCONFIG", tmp.path().join("npmrc"))];
899        let (_, with_env) = build_tmux_runner_scripts(&inv, "true", tmp.path(), Some(&argv), &env);
900        assert!(with_env.contains(&format!(
901            " NPM_CONFIG_USERCONFIG='{}' ",
902            tmp.path().join("npmrc").display()
903        )));
904    }
905
906    #[test]
907    fn only_a_sandboxed_run_fetches_without_tags() {
908        let tmp = tempfile::TempDir::new().expect("temp dir");
909        let inv = test_invocation("sandbox-test");
910        let argv: Vec<OsString> = vec!["/usr/bin/sandbox-exec".into()];
911        let (sandboxed, _) = build_tmux_runner_scripts(&inv, "true", tmp.path(), Some(&argv), &[]);
912        assert!(sandboxed.contains("export GIT_CONFIG_COUNT=\"5\""));
913        assert!(sandboxed.contains("export GIT_CONFIG_VALUE_4=\"--no-tags\""));
914        let (plain, _) = build_tmux_runner_scripts(&inv, "true", tmp.path(), None, &[]);
915        assert!(!plain.contains("tagOpt"));
916        assert!(
917            !plain.contains("rm -rf"),
918            "only a sandboxed run has a temp dir to wipe"
919        );
920        assert!(sandboxed.contains(&format!(
921            "\"$status_file\"; rm -rf -- '{}'' EXIT",
922            sandbox::run_temp_dir(tmp.path()).display()
923        )));
924    }
925
926    #[test]
927    fn a_sandboxed_prompt_offers_no_shipcheck() {
928        assert_eq!(
929            Shipcheck::Available.for_prompt(true, false),
930            Shipcheck::Absent
931        );
932        assert_eq!(
933            Shipcheck::Available.for_prompt(true, true),
934            Shipcheck::Available
935        );
936        assert_eq!(
937            Shipcheck::Available.for_prompt(false, false),
938            Shipcheck::Available
939        );
940        assert_eq!(
941            Shipcheck::NotInstalled.for_prompt(true, false),
942            Shipcheck::NotInstalled
943        );
944    }
945
946    #[test]
947    fn build_runner_script_escapes_shell_injection_in_paths() {
948        let tmp = tempfile::TempDir::new().expect("temp dir");
949        let mut inv = test_invocation("injection-test");
950        inv.work_dir = PathBuf::from("/tmp/$(whoami)/workspace");
951        inv.output_file = PathBuf::from("/tmp/evil`id`.json");
952        let script = build_runner_script_in_dir(&inv, tmp.path());
953
954        // Values must be single-quoted, neutralizing $() and backticks
955        assert!(
956            script.contains("'/tmp/$(whoami)/workspace'"),
957            "work_dir with $() must be single-quoted: {script}"
958        );
959        assert!(
960            script.contains("'/tmp/evil`id`.json'"),
961            "output_file with backticks must be single-quoted: {script}"
962        );
963    }
964
965    #[test]
966    fn review_prompt_forbids_ending_turn_on_pending_ci_status() {
967        // Regression test for #3453: a review agent must not stop with a
968        // prose "CI is still running" status update and leave the turn
969        // without JSON. The prompt must explicitly route PENDING/NOT RUN CI
970        // through the local-checks fallback and into the same-turn JSON output.
971        let task = ExternalTask {
972            id: ExternalId("155460".to_string()),
973            title: "test task".to_string(),
974            body: "test body".to_string(),
975            state: "open".to_string(),
976            labels: vec![],
977            author: "tester".to_string(),
978            created_at: "2026-01-01T00:00:00Z".to_string(),
979            updated_at: "2026-01-01T00:00:00Z".to_string(),
980            url: "https://example.com/1".to_string(),
981        };
982        let prompt = build_review_prompt(&task, "", "", "", "main", 1, Shipcheck::Absent);
983
984        assert!(
985            prompt.contains("Pending CI is never a terminal review state"),
986            "prompt must state pending CI is not terminal: {prompt}"
987        );
988        assert!(
989            prompt.contains("Never end your turn with a CI-waiting status update"),
990            "prompt must forbid ending the turn on a CI-waiting status update: {prompt}"
991        );
992    }
993
994    #[test]
995    fn shell_single_quote_escapes_embedded_quotes() {
996        assert_eq!(shell_single_quote("hello"), "'hello'");
997        assert_eq!(shell_single_quote("O'Brien"), "'O'\\''Brien'");
998        assert_eq!(shell_single_quote("$(rm -rf /)"), "'$(rm -rf /)'");
999        assert_eq!(shell_single_quote("`whoami`"), "'`whoami`'");
1000        assert_eq!(shell_single_quote("a\"b"), "'a\"b'");
1001        assert_eq!(shell_single_quote("$HOME"), "'$HOME'");
1002    }
1003
1004    fn prompt_task() -> ExternalTask {
1005        ExternalTask {
1006            id: ExternalId("1".to_string()),
1007            title: "t".to_string(),
1008            body: "b".to_string(),
1009            state: "open".to_string(),
1010            labels: vec![],
1011            author: "a".to_string(),
1012            created_at: "2026-01-01T00:00:00Z".to_string(),
1013            updated_at: "2026-01-01T00:00:00Z".to_string(),
1014            url: "https://example.com/1".to_string(),
1015        }
1016    }
1017
1018    #[test]
1019    fn only_a_sandboxed_prompt_explains_the_sandbox() {
1020        let ctx = super::super::context::TaskContext::default();
1021        let task = prompt_task();
1022        let prompt = |sandboxed| {
1023            build_system_prompt(&task, &ctx, None, "main", Shipcheck::Absent, sandboxed)
1024        };
1025        assert!(prompt(true).contains("you run inside an OS sandbox"));
1026        assert!(!prompt(false).contains("OS sandbox"));
1027        assert!(!prompt(false).contains("SANDBOX"));
1028    }
1029
1030    #[test]
1031    fn system_prompt_uses_shipcheck_only_when_available() {
1032        let ctx = super::super::context::TaskContext::default();
1033        let task = prompt_task();
1034        let prompt = |s| build_system_prompt(&task, &ctx, None, "main", s, false);
1035
1036        let available = prompt(Shipcheck::Available);
1037        assert!(available.contains("shipcheck run"));
1038        assert!(available.contains("shipcheck commit"));
1039        assert!(!available.contains(".github/workflows/"));
1040        assert!(!available.contains("not installed"));
1041
1042        let outdated = prompt(Shipcheck::Outdated);
1043        assert!(!outdated.contains("shipcheck"));
1044        assert!(outdated.contains(".github/workflows/"));
1045
1046        let missing = prompt(Shipcheck::NotInstalled);
1047        assert!(!missing.contains("shipcheck run"));
1048        assert!(missing.contains(".github/workflows/"));
1049        assert!(missing.contains("shipcheck is not installed"));
1050
1051        let absent = prompt(Shipcheck::Absent);
1052        assert!(!absent.contains("shipcheck"));
1053        assert!(absent.contains(".github/workflows/"));
1054
1055        for p in [&available, &outdated, &missing, &absent] {
1056            assert!(!p.contains("{{"), "{p}");
1057            assert!(!p.contains("install shipcheck"), "{p}");
1058        }
1059    }
1060
1061    #[test]
1062    fn review_prompt_uses_shipcheck_only_when_available() {
1063        let task = prompt_task();
1064        let prompt = |s| build_review_prompt(&task, "", "", "", "main", 1, s);
1065        assert!(prompt(Shipcheck::Available).contains("shipcheck run"));
1066        for s in [
1067            Shipcheck::Outdated,
1068            Shipcheck::NotInstalled,
1069            Shipcheck::Absent,
1070        ] {
1071            let p = prompt(s);
1072            assert!(!p.contains("shipcheck"), "{p}");
1073            assert!(p.contains(".github/workflows/"), "{p}");
1074        }
1075    }
1076
1077    #[test]
1078    fn the_progress_step_appears_only_in_cluster_mode() {
1079        let mut vars = HashMap::new();
1080        insert_cluster_vars(Shipcheck::Available, &mut vars);
1081        assert!(vars.is_empty(), "no cluster section, no cluster flags");
1082        let plain = template::render_template_str(AGENT_SYSTEM_TEMPLATE, &vars).unwrap();
1083        assert!(!plain.contains("orch progress"));
1084
1085        for flag in ["CLUSTER", "CLUSTER_SHIPCHECK"] {
1086            vars.insert(flag.to_string(), "1".to_string());
1087        }
1088        let cluster = template::render_template_str(AGENT_SYSTEM_TEMPLATE, &vars).unwrap();
1089        assert!(cluster.contains("orch progress"));
1090        assert!(cluster.contains("commits only through `shipcheck commit`"));
1091        assert!(!cluster.contains("It commits anything you left"));
1092    }
1093}