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::backends::ExternalTask;
7use crate::cluster;
8use crate::engine::router::RouteResult;
9use crate::engine::runner::agents::shell_single_quote;
10use crate::github::token;
11use crate::home;
12use crate::template::render_template_str;
13use crate::tmux::TmuxManager;
14use std::collections::BTreeSet;
15use std::collections::HashMap;
16use std::env;
17use std::ffi::OsString;
18#[cfg(unix)]
19use std::fs::Permissions;
20use std::io::ErrorKind;
21#[cfg(unix)]
22use std::os::unix::fs::PermissionsExt;
23use std::path::Path;
24use std::path::PathBuf;
25use std::process::Output;
26use std::process::Stdio;
27use std::time::Duration;
28
29use tokio::fs;
30use tokio::fs::OpenOptions;
31use tokio::io::AsyncWriteExt;
32use tokio::process::Command;
33use tokio::sync::OnceCell;
34use tokio::time;
35
36const AGENT_SYSTEM_TEMPLATE: &str = include_str!("../../../prompts/agent_system.md");
37const AGENT_MESSAGE_TEMPLATE: &str = include_str!("../../../prompts/agent_message.md");
38const AGENT_MEMORY_ENTRY_TEMPLATE: &str = include_str!("../../../prompts/agent_memory_entry.md");
39const ALLOWED_TOOLS_TEMPLATE: &str = include_str!("../../../prompts/allowed_tools.md");
40const REVIEW_PROMPT_TEMPLATE: &str = include_str!("../../../prompts/review_task.md");
41const REVIEW_SYSTEM_TEMPLATE: &str = include_str!("../../../prompts/review_system.md");
42
43/// Whether the agent tests through shipcheck: the repo opts in and the shipcheck on PATH
44/// has `commit`. An older shipcheck gets the plain workflow step
45#[derive(Clone, Copy, Debug, PartialEq, Eq)]
46pub enum Shipcheck {
47    Absent,
48    NotInstalled,
49    Outdated,
50    Available,
51}
52
53impl Shipcheck {
54    pub async fn detect(work_dir: &Path) -> Self {
55        static SUPPORTS_COMMIT: OnceCell<Option<bool>> = OnceCell::const_new();
56        let installed = SUPPORTS_COMMIT
57            .get_or_init(|| async {
58                let bin = which::which("shipcheck").ok()?;
59                Some(supports(&bin, "commit").await)
60            })
61            .await;
62        Self::classify(work_dir.join("shipcheck.toml").exists(), *installed)
63    }
64
65    fn classify(has_config: bool, supports_commit: Option<bool>) -> Self {
66        match (has_config, supports_commit) {
67            (false, _) => Shipcheck::Absent,
68            (true, None) => Shipcheck::NotInstalled,
69            (true, Some(false)) => Shipcheck::Outdated,
70            (true, Some(true)) => Shipcheck::Available,
71        }
72    }
73
74    /// What the prompt offers. Inside the OS sandbox shipcheck hands its runs to its daemon, and
75    /// without that the agent runs the checks itself and the push hook runs shipcheck outside
76    #[must_use]
77    pub fn for_prompt(self, sandboxed: bool, hands_off: bool) -> Self {
78        if sandboxed && !hands_off && self == Shipcheck::Available {
79            return Shipcheck::Absent;
80        }
81
82        self
83    }
84
85    /// [`Self::for_prompt`], asking the installed shipcheck whether its daemon serves this worktree
86    pub async fn in_sandbox(self, sandboxed: bool, work_dir: &Path) -> Self {
87        let hands_off = sandboxed && self == Shipcheck::Available && hands_off(work_dir).await;
88        self.for_prompt(sandboxed, hands_off)
89    }
90
91    fn insert_vars(self, vars: &mut HashMap<String, String>) {
92        let flags: &[&str] = match self {
93            Shipcheck::Available => &["SHIPCHECK"],
94            Shipcheck::NotInstalled => &["NO_SHIPCHECK", "SHIPCHECK_MISSING"],
95            Shipcheck::Absent | Shipcheck::Outdated => &["NO_SHIPCHECK"],
96        };
97        for flag in flags {
98            vars.insert(flag.to_string(), "1".to_string());
99        }
100    }
101}
102
103/// The `orch progress` step appears only when a `cluster:` section turns the cluster on.
104/// Separate flags, because the template engine does not nest `{{#if}}` blocks
105fn insert_cluster_vars(shipcheck: Shipcheck, vars: &mut HashMap<String, String>) {
106    if !cluster::enabled() {
107        return;
108    }
109
110    let commit = if shipcheck == Shipcheck::Available {
111        "CLUSTER_SHIPCHECK"
112    } else {
113        "CLUSTER_GIT"
114    };
115    for flag in ["CLUSTER", commit] {
116        vars.insert(flag.to_string(), "1".to_string());
117    }
118}
119
120async fn run_shipcheck(bin: &Path, work_dir: &Path, args: &[&str]) -> anyhow::Result<Output> {
121    let output = Command::new(bin)
122        .args(args)
123        .current_dir(work_dir)
124        .stdin(Stdio::null())
125        .kill_on_drop(true)
126        .output();
127    Ok(time::timeout(Duration::from_secs(30), output).await??)
128}
129
130// `shipcheck handoff` exits 0 when the daemon watches the repository, and an older one has no such command
131async fn hands_off(work_dir: &Path) -> bool {
132    let Ok(bin) = which::which("shipcheck") else {
133        return false;
134    };
135    run_shipcheck(&bin, work_dir, &["handoff"])
136        .await
137        .is_ok_and(|out| out.status.success())
138}
139
140// `<sub> --help` exits 0 for any word, so read the subcommands the usage line lists
141async fn supports(bin: &Path, subcommand: &str) -> bool {
142    let Ok(out) = run_shipcheck(bin, &env::temp_dir(), &["--help"]).await else {
143        return false;
144    };
145    out.status.success()
146        && String::from_utf8_lossy(&out.stdout)
147            .split_whitespace()
148            .any(|word| word == subcommand)
149}
150
151/// Runs `shipcheck install` so every agent CLI gets shipcheck's hooks in this worktree.
152/// Returns whether install ran. It never fails the task
153pub async fn install_shipcheck_hooks(work_dir: &Path, shipcheck: Shipcheck, bin: &Path) -> bool {
154    if shipcheck != Shipcheck::Available {
155        return false;
156    }
157
158    // A shipcheck without `hook` only installs git hooks, and orch skips it
159    if !supports(bin, "hook").await {
160        return false;
161    }
162
163    match run_shipcheck(bin, work_dir, &["install"]).await {
164        Ok(out) if out.status.success() => {}
165        Ok(out) => tracing::warn!(
166            work_dir = %work_dir.display(),
167            stderr = %String::from_utf8_lossy(&out.stderr),
168            "shipcheck install failed"
169        ),
170        Err(e) => tracing::warn!(
171            work_dir = %work_dir.display(),
172            error = %e,
173            "shipcheck install failed"
174        ),
175    }
176    true
177}
178
179const SHIPCHECK_RULE_PATH: &str = ".codex/rules/orch-shipcheck.rules";
180
181// Only the commands the agent prompt uses, never clean, post, login or daemon
182const SHIPCHECK_RULES: &str = r#"prefix_rule(pattern=["shipcheck", "run"], decision="allow")
183prefix_rule(pattern=["shipcheck", "commit"], decision="allow")
184prefix_rule(pattern=["shipcheck", "status"], decision="allow")
185prefix_rule(pattern=["shipcheck", "logs"], decision="allow")
186prefix_rule(pattern=["shipcheck", "doctor"], decision="allow")
187"#;
188
189// Codex runs a command a rule allows outside its sandbox, so shipcheck reaches Docker and its
190// results dir while the agent's own commands still cannot write there
191async fn install_shipcheck_rule(work_dir: &Path) -> anyhow::Result<()> {
192    // The worktree holds repository content, so never follow a symlink it plants on the path
193    let mut dir = work_dir.to_path_buf();
194    for part in [".codex", "rules"] {
195        dir.push(part);
196        match fs::symlink_metadata(&dir).await {
197            Ok(meta) if meta.is_dir() => {}
198            Ok(_) => anyhow::bail!("{} is not a directory", dir.display()),
199            Err(e) if e.kind() == ErrorKind::NotFound => {
200                fs::create_dir(&dir).await?;
201            }
202            Err(e) => return Err(e.into()),
203        }
204    }
205
206    // remove_file drops a symlink itself, and create_new never follows one
207    let rule = work_dir.join(SHIPCHECK_RULE_PATH);
208    match fs::remove_file(&rule).await {
209        Err(e) if e.kind() != ErrorKind::NotFound => return Err(e.into()),
210        _ => {}
211    }
212
213    let mut file = OpenOptions::new()
214        .write(true)
215        .create_new(true)
216        .open(&rule)
217        .await?;
218    AsyncWriteExt::write_all(&mut file, SHIPCHECK_RULES.as_bytes()).await?;
219
220    // Keep the rule out of the agent's commits
221    let output = Command::new("git")
222        .args(["rev-parse", "--git-path", "info/exclude"])
223        .current_dir(work_dir)
224        .output()
225        .await?;
226    if !output.status.success() {
227        return Ok(());
228    }
229
230    let exclude = work_dir.join(String::from_utf8_lossy(&output.stdout).trim());
231    let line = format!("/{SHIPCHECK_RULE_PATH}");
232    let current = fs::read_to_string(&exclude).await.unwrap_or_default();
233    if current.lines().any(|l| l == line) {
234        return Ok(());
235    }
236
237    if let Some(dir) = exclude.parent() {
238        fs::create_dir_all(dir).await?;
239    }
240
241    let sep = if current.is_empty() || current.ends_with('\n') {
242        ""
243    } else {
244        "\n"
245    };
246    fs::write(&exclude, format!("{current}{sep}{line}\n")).await?;
247    Ok(())
248}
249
250/// Run `git rev-parse <arg>` from `work_dir` and canonicalize the
251/// result. Returns `Ok(None)` when git is not available or the command fails.
252pub(crate) async fn resolve_git_dir_arg(
253    work_dir: &Path,
254    arg: &str,
255) -> anyhow::Result<Option<PathBuf>> {
256    let output = Command::new("git")
257        .args(["rev-parse", arg])
258        .current_dir(work_dir)
259        .output()
260        .await?;
261
262    if !output.status.success() {
263        return Ok(None);
264    }
265
266    let raw = String::from_utf8_lossy(&output.stdout).trim().to_string();
267    if raw.is_empty() {
268        return Ok(None);
269    }
270
271    // The path may be relative to work_dir; canonicalize to absolute.
272    let candidate = if Path::new(&raw).is_absolute() {
273        PathBuf::from(&raw)
274    } else {
275        work_dir.join(&raw)
276    };
277
278    let canonical = fs::canonicalize(&candidate).await.unwrap_or(candidate);
279    Ok(Some(canonical))
280}
281
282fn render_prompt_template(template: &str, vars: &HashMap<String, String>) -> String {
283    match render_template_str(template, vars) {
284        Ok(rendered) => rendered,
285        Err(err) => {
286            tracing::error!(error = %err, "failed to render prompt template");
287            template.to_string()
288        }
289    }
290}
291
292/// Agent invocation configuration.
293#[derive(Debug)]
294pub struct AgentInvocation {
295    /// Agent name (claude, codex, opencode, grok, kimi, minimax)
296    pub agent: String,
297    /// Model override (e.g., "claude-sonnet-4-6", "o3", "gpt-4.1")
298    pub model: Option<String>,
299    /// Optional native CLI effort from the selected route.
300    pub reasoning_effort: Option<String>,
301    /// Working directory
302    pub work_dir: PathBuf,
303    /// System prompt content
304    pub system_prompt: String,
305    /// Agent message (task prompt)
306    pub agent_message: String,
307    /// Task ID
308    pub task_id: String,
309    /// Disallowed tools pattern
310    pub disallowed_tools: Vec<String>,
311    /// Git author name
312    pub git_author_name: String,
313    /// Git author email
314    pub git_author_email: String,
315    /// Output file path for agent response
316    pub output_file: PathBuf,
317    /// Timeout in seconds (0 = no timeout)
318    pub timeout_seconds: u64,
319    /// Repository slug (owner/repo) for per-repo state isolation
320    pub repo: String,
321    /// Whether the agent runs in the OS sandbox, from `workflow.sandbox`
322    pub sandbox: bool,
323    /// The project's main checkout, which the sandbox keeps read-only but for its `.git`
324    pub main_project_dir: PathBuf,
325    /// The task's branch, from orch's records, the one ref the sandbox lets the agent move
326    pub branch: String,
327    /// Current attempt number (1-indexed)
328    pub attempt: u32,
329}
330
331/// Build the runner script content (saved to attempt dir), plus the small
332/// helper script it execs the agent command through under a pty. Returns
333/// `(runner_script, agent_cmd_script)`.
334fn build_tmux_runner_scripts(
335    inv: &AgentInvocation,
336    agent_cmd: &str,
337    attempt_dir: &Path,
338    sandbox: Option<&[OsString]>,
339    sandbox_env: &[(&str, PathBuf)],
340) -> (String, String) {
341    let status_file = attempt_dir.join("exit.txt");
342    let stderr_file = attempt_dir.join("stderr.txt");
343    let agent_cmd_script_path = attempt_dir.join("agent_cmd.sh");
344    let sq_git_name = shell_single_quote(&inv.git_author_name);
345    let sq_git_email = shell_single_quote(&inv.git_author_email);
346    let sq_task_id = shell_single_quote(&inv.task_id);
347    let sq_output_file = shell_single_quote(&inv.output_file.display().to_string());
348    let sq_work_dir = shell_single_quote(&inv.work_dir.display().to_string());
349    let sq_status_file = shell_single_quote(&status_file.display().to_string());
350    let sq_stderr_file = shell_single_quote(&stderr_file.display().to_string());
351    let sq_agent_cmd_script = shell_single_quote(&agent_cmd_script_path.display().to_string());
352
353    // Runs the agent with stderr split off to a real file before the pty layer
354    // below merges stdout+stderr, exactly as the previous plain-pipe invocation did.
355    let agent_cmd = match sandbox {
356        Some(argv) => {
357            let prefix: Vec<String> = argv
358                .iter()
359                .map(|a| shell_single_quote(&a.to_string_lossy()))
360                .collect();
361            // The tmux and ssh-agent sockets are out of reach, and their variables go too
362            let temp = super::sandbox::run_temp_dir(attempt_dir);
363            let tmpdir = shell_single_quote(&temp.display().to_string());
364            // gh's own config dir holds its logins and is hidden, so gh gets an empty one and
365            // runs on GH_TOKEN
366            let gh_config =
367                shell_single_quote(&super::sandbox::gh_config_dir(&temp).display().to_string());
368            // shipcheck cannot start its own sandbox in here, and with this it asks its daemon
369            let extra: Vec<String> = sandbox_env
370                .iter()
371                .map(|(name, value)| {
372                    format!(
373                        " {name}={}",
374                        shell_single_quote(&value.display().to_string())
375                    )
376                })
377                .collect();
378            let vars = format!(
379                "TMPDIR={tmpdir} GH_CONFIG_DIR={gh_config} SHIPCHECK_HANDOFF=1{}",
380                extra.concat()
381            );
382
383            format!(
384                "env -u TMUX -u TMUX_PANE -u SSH_AUTH_SOCK {vars} {} /bin/bash -c {}",
385                prefix.join(" "),
386                shell_single_quote(agent_cmd)
387            )
388        }
389        None => agent_cmd.to_string(),
390    };
391    let agent_cmd_script = format!("#!/usr/bin/env bash\n{agent_cmd} 2>{sq_stderr_file}\n");
392    // The run's temp dir goes when the run ends, however it ends
393    let wipe_temp = if sandbox.is_some() {
394        format!(
395            "; rm -rf -- {}",
396            shell_single_quote(
397                &super::sandbox::run_temp_dir(attempt_dir)
398                    .display()
399                    .to_string()
400            )
401        )
402    } else {
403        String::new()
404    };
405    // Tags are read-only in the sandbox, and a fetch that cannot write one new tag updates no ref
406    let sandbox_git_config = if sandbox.is_some() {
407        r#"export GIT_CONFIG_COUNT="5"
408export GIT_CONFIG_KEY_4="remote.origin.tagOpt"
409export GIT_CONFIG_VALUE_4="--no-tags"
410"#
411    } else {
412        ""
413    };
414
415    let runner_script = format!(
416        r#"#!/usr/bin/env bash
417set -euo pipefail
418
419status_file={sq_status_file}
420stderr_file={sq_stderr_file}
421trap 'status=$?; printf "%s\n" "$status" > "$status_file"{wipe_temp}' EXIT
422
423# Environment — ~/.path and ~/.private are loaded by orch at startup into the process env
424export PATH="/opt/homebrew/bin:/usr/local/bin:$PATH"
425export GIT_AUTHOR_NAME={sq_git_name}
426export GIT_COMMITTER_NAME={sq_git_name}
427export GIT_AUTHOR_EMAIL={sq_git_email}
428export GIT_COMMITTER_EMAIL={sq_git_email}
429# Env config overrides the operator's git config for this process only, the remotes stay as they
430# are: agents never sign, and push over HTTPS with gh's credentials, not the operator's SSH agent
431export GIT_CONFIG_COUNT="4"
432export GIT_CONFIG_KEY_0="commit.gpgsign"
433export GIT_CONFIG_VALUE_0="false"
434export GIT_CONFIG_KEY_1="tag.gpgsign"
435export GIT_CONFIG_VALUE_1="false"
436export GIT_CONFIG_KEY_2="url.https://github.com/.pushInsteadOf"
437export GIT_CONFIG_VALUE_2="git@github.com:"
438export GIT_CONFIG_KEY_3="credential.https://github.com.helper"
439export GIT_CONFIG_VALUE_3="!gh auth git-credential"
440{sandbox_git_config}export TASK_ID={sq_task_id}
441export OUTPUT_FILE={sq_output_file}
442unset CLAUDECODE  # allow nested claude invocations from orch
443
444cd {sq_work_dir} || {{
445    printf '%s\n' "worktree directory does not exist: {sq_work_dir}" > "$stderr_file"
446    exit 1
447}}
448
449# Run agent under a pty (via `script`) so its stdout is a tty, not a plain pipe —
450# many CLI runtimes silently switch to full block-buffering when stdout isn't a
451# tty, which can delay pane output long enough to trip silence detection even
452# while the agent is actively streaming. Tee to both output file and terminal
453# (tmux pane) for live streaming.
454set +e
455script -q /dev/null /bin/bash {sq_agent_cmd_script} | tee {sq_output_file}
456CMD_STATUS=${{PIPESTATUS[0]:-0}}
457set -e
458
459exit $CMD_STATUS
460"#,
461    );
462
463    (runner_script, agent_cmd_script)
464}
465
466/// Spawn the agent in a tmux session.
467///
468/// Returns the tmux session name.
469pub async fn spawn_in_tmux(tmux: &TmuxManager, inv: &AgentInvocation) -> anyhow::Result<String> {
470    // Prepare attempt directory and prompt files (system + message).
471    let attempt_dir = home::task_attempt_dir_async(&inv.repo, &inv.task_id, inv.attempt).await?;
472
473    let sys_file = attempt_dir.join("prompt-sys.md");
474    let msg_file = attempt_dir.join("prompt-msg.md");
475    // Build unified permission rules and sys content
476    let mut permissions = super::agents::PermissionRules::from_config();
477    if !inv.disallowed_tools.is_empty() {
478        for tool in &inv.disallowed_tools {
479            if !permissions.disallowed_tools.contains(tool) {
480                permissions.disallowed_tools.push(tool.clone());
481            }
482        }
483    }
484    permissions.allowed_edit_paths.push(inv.work_dir.clone());
485
486    // Codex cannot start its own Seatbelt inside the OS sandbox, so the OS sandbox replaces it
487    let mut sandbox_env = Vec::new();
488    let sandbox = if inv.sandbox {
489        permissions.sandbox = super::agents::SandboxLevel::Os;
490        let temp = super::sandbox::run_temp_dir(&attempt_dir);
491        fs::create_dir_all(super::sandbox::gh_config_dir(&temp)).await?;
492
493        // The policy makes only paths that exist read-only, so the files orch writes later in the
494        // attempt dir must exist now, or the agent could create them first
495        for name in [
496            "runner.sh",
497            "agent_cmd.sh",
498            "exit.txt",
499            "stderr.txt",
500            "prompt-sys.md",
501            "prompt-msg.md",
502            "result.json",
503        ] {
504            let path = attempt_dir.join(name);
505
506            if !path.exists() {
507                fs::write(&path, "").await?;
508            }
509        }
510
511        if !inv.output_file.exists() && inv.output_file.parent().is_some_and(Path::is_dir) {
512            fs::write(&inv.output_file, "").await?;
513        }
514
515        if let Some(home) = env::var_os("HOME") {
516            sandbox_env = super::sandbox::package_config(Path::new(&home), &temp);
517        }
518
519        Some(super::sandbox::argv(inv, &temp).await?)
520    } else {
521        None
522    };
523
524    // For Codex running in workspace-write sandbox mode, grant write access to
525    // git metadata dirs when they live outside the worktree root. We include
526    // both --git-common-dir and --git-dir because index.lock can be created
527    // under the worktree-specific git dir.
528    if inv.agent == "codex" {
529        let mut extra_dirs = BTreeSet::new();
530        for (arg, label) in [
531            ("--git-common-dir", "git common dir"),
532            ("--git-dir", "git dir"),
533        ] {
534            match resolve_git_dir_arg(&inv.work_dir, arg).await {
535                Ok(Some(dir)) if !dir.starts_with(&inv.work_dir) => {
536                    extra_dirs.insert(dir);
537                }
538                Ok(_) => {}
539                Err(e) => {
540                    tracing::debug!(
541                        work_dir = %inv.work_dir.display(),
542                        arg,
543                        error = %e,
544                        "failed to resolve {}; skipping --add-dir",
545                        label
546                    );
547                }
548            }
549        }
550        permissions.extra_writable_dirs.extend(extra_dirs);
551
552        if Shipcheck::detect(&inv.work_dir).await == Shipcheck::Available
553            && let Err(e) = install_shipcheck_rule(&inv.work_dir).await
554        {
555            tracing::warn!(
556                work_dir = %inv.work_dir.display(),
557                error = %e,
558                "failed to install the shipcheck codex rule"
559            );
560        }
561    }
562
563    let sys_content = if permissions.allowed_tools.is_empty() {
564        inv.system_prompt.clone()
565    } else {
566        let tools_list = permissions
567            .allowed_tools
568            .iter()
569            .map(|t| format!("- {t}"))
570            .collect::<Vec<_>>()
571            .join("\n");
572        let mut vars = HashMap::new();
573        vars.insert("TOOLS_LIST".to_string(), tools_list);
574        let tools_prompt = render_prompt_template(ALLOWED_TOOLS_TEMPLATE, &vars);
575        format!("{}\n\n{}", inv.system_prompt, tools_prompt)
576    };
577
578    fs::write(&sys_file, &sys_content).await?;
579    fs::write(&msg_file, &inv.agent_message).await?;
580
581    // Build agent command using per-agent runner (used in non-PTY path below)
582    let runner = super::agents::get_runner(&inv.agent);
583
584    // Prepare environment map for tmux session (does not write GH token to disk)
585    let mut env = HashMap::new();
586    env.insert("GIT_AUTHOR_NAME".to_string(), inv.git_author_name.clone());
587    env.insert(
588        "GIT_COMMITTER_NAME".to_string(),
589        inv.git_author_name.clone(),
590    );
591    env.insert("GIT_AUTHOR_EMAIL".to_string(), inv.git_author_email.clone());
592    env.insert(
593        "GIT_COMMITTER_EMAIL".to_string(),
594        inv.git_author_email.clone(),
595    );
596    env.insert("TASK_ID".to_string(), inv.task_id.clone());
597    env.insert(
598        "OUTPUT_FILE".to_string(),
599        inv.output_file.display().to_string(),
600    );
601
602    // Write runner script and execute it in a detached tmux session.
603    let timeout_cmd = if inv.timeout_seconds > 0 {
604        format!("timeout {}", inv.timeout_seconds)
605    } else {
606        String::new()
607    };
608    let agent_cmd = runner.build_command_with_effort(
609        inv.model
610            .as_deref()
611            .map(str::trim)
612            .filter(|m| !m.is_empty()),
613        inv.reasoning_effort.as_deref(),
614        &timeout_cmd,
615        &sys_file.to_string_lossy(),
616        &msg_file.to_string_lossy(),
617        &permissions,
618    );
619
620    // Write runner script (and the agent-cmd helper script it execs under a pty)
621    // to the per-task attempt dir.
622    let script_path = attempt_dir.join("runner.sh");
623    let agent_cmd_script_path = attempt_dir.join("agent_cmd.sh");
624    let (script_content, agent_cmd_script_content) = build_tmux_runner_scripts(
625        inv,
626        &agent_cmd,
627        &attempt_dir,
628        sandbox.as_deref(),
629        &sandbox_env,
630    );
631    fs::write(&agent_cmd_script_path, &agent_cmd_script_content).await?;
632    fs::write(&script_path, &script_content).await?;
633
634    // Make executable
635    #[cfg(unix)]
636    {
637        fs::set_permissions(&script_path, Permissions::from_mode(0o755)).await?;
638        fs::set_permissions(&agent_cmd_script_path, Permissions::from_mode(0o755)).await?;
639    }
640
641    let command = format!("bash \"{}\"", script_path.display());
642
643    // Resolve GitHub token via the process-wide shared resolver (cached after first call)
644    let github_token = match token::shared().get_token().await {
645        Ok(Some(token)) => {
646            tracing::debug!("Resolved GitHub token via TokenResolver for agent session");
647            Some(token)
648        }
649        Ok(None) => {
650            tracing::warn!(
651                "No GitHub token available; set GH_TOKEN, GITHUB_TOKEN, or gh.auth.token, or run gh auth login"
652            );
653            None
654        }
655        Err(e) => {
656            tracing::warn!(error = %e, "Failed to resolve GitHub token");
657            None
658        }
659    };
660
661    // Inject GH_TOKEN into env so it's passed via `tmux new-session -e` along
662    // with everything else. The `-e` flag sets variables in the *initial* pane
663    // environment, so the agent process sees it immediately on startup.
664    //
665    // IMPORTANT: Do NOT use create_session_detached + set_env + create_window
666    // to inject GH_TOKEN. That approach creates a 2-window session (window 0 =
667    // idle shell, window 1 = agent). All tmux monitoring (is_session_active,
668    // capture_pane, batch_session_active) targets the session without a window
669    // index, which defaults to the *active* window — the idle shell. This
670    // breaks completion detection (shell never exits → pane_dead always 0),
671    // output capture (reads the shell prompt, not agent output), and silence
672    // detection. See the revert of PR #2903.
673    if let Some(ref token) = github_token {
674        env.insert("GH_TOKEN".to_string(), token.clone());
675    }
676
677    let env_vec: Vec<(&str, &str)> = env.iter().map(|(k, v)| (k.as_str(), v.as_str())).collect();
678
679    let session = tmux
680        .create_session(
681            &inv.repo,
682            &inv.task_id,
683            &inv.work_dir.to_string_lossy(),
684            &command,
685            env_vec.as_slice(),
686        )
687        .await?;
688
689    tracing::info!(
690        task_id = inv.task_id,
691        agent = inv.agent,
692        session = %session,
693        "agent spawned in tmux"
694    );
695
696    Ok(session)
697}
698
699/// Build the system prompt for the agent.
700pub fn build_system_prompt(
701    _task: &ExternalTask,
702    context: &super::context::TaskContext,
703    route_result: Option<&RouteResult>,
704    default_branch: &str,
705    shipcheck: Shipcheck,
706    sandboxed: bool,
707) -> String {
708    let mut vars = HashMap::new();
709
710    vars.insert("DEFAULT_BRANCH".to_string(), default_branch.to_string());
711    shipcheck.insert_vars(&mut vars);
712    insert_cluster_vars(shipcheck, &mut vars);
713
714    if sandboxed {
715        vars.insert("SANDBOX".to_string(), "1".to_string());
716    }
717
718    if let Some(rr) = route_result {
719        vars.insert("ROLE".to_string(), rr.profile.role.clone());
720
721        if !rr.profile.constraints.is_empty() {
722            let constraints = rr
723                .profile
724                .constraints
725                .iter()
726                .map(|c| format!("- {c}"))
727                .collect::<Vec<_>>()
728                .join("\n");
729            vars.insert("CONSTRAINTS".to_string(), constraints);
730        }
731    }
732
733    if !context.project_instructions.is_empty() {
734        vars.insert(
735            "PROJECT_INSTRUCTIONS".to_string(),
736            context.project_instructions.clone(),
737        );
738    }
739
740    if !context.repo_tree.is_empty() {
741        vars.insert("REPO_TREE".to_string(), context.repo_tree.clone());
742    }
743
744    render_prompt_template(AGENT_SYSTEM_TEMPLATE, &vars)
745}
746
747/// Build the agent message (task prompt).
748pub fn build_agent_message(
749    task: &ExternalTask,
750    context: &super::context::TaskContext,
751    attempts: u32,
752) -> String {
753    let mut vars = HashMap::new();
754    vars.insert("TASK_ID".to_string(), task.id.0.clone());
755    vars.insert("TASK_TITLE".to_string(), task.title.clone());
756    vars.insert("TASK_BODY".to_string(), task.body.clone());
757
758    if !context.task_context.is_empty() {
759        vars.insert("TASK_CONTEXT".to_string(), context.task_context.clone());
760    }
761
762    if !context.parent_context.is_empty() {
763        vars.insert("PARENT_CONTEXT".to_string(), context.parent_context.clone());
764    }
765
766    if !context.issue_comments.is_empty() {
767        vars.insert("ISSUE_COMMENTS".to_string(), context.issue_comments.clone());
768    }
769
770    if !context.pr_review_context.is_empty() {
771        vars.insert(
772            "PR_REVIEW_CONTEXT".to_string(),
773            context.pr_review_context.clone(),
774        );
775    }
776
777    if attempts > 0 && !context.git_diff.is_empty() {
778        vars.insert("GIT_DIFF".to_string(), context.git_diff.clone());
779    }
780
781    if attempts > 0 {
782        vars.insert("ATTEMPT_NUMBER".to_string(), (attempts + 1).to_string());
783    }
784
785    if !context.memory.is_empty() {
786        let mut sections = Vec::new();
787        for entry in &context.memory {
788            let mut entry_vars = HashMap::new();
789            entry_vars.insert("ATTEMPT".to_string(), entry.attempt.to_string());
790            entry_vars.insert("AGENT".to_string(), entry.agent.clone());
791
792            if let Some(ref model) = entry.model {
793                entry_vars.insert("MODEL".to_string(), model.clone());
794            }
795
796            if !entry.approach.is_empty() {
797                entry_vars.insert("APPROACH".to_string(), entry.approach.clone());
798            }
799
800            if !entry.learnings.is_empty() {
801                let learnings = entry
802                    .learnings
803                    .iter()
804                    .map(|learning| format!("- {learning}"))
805                    .collect::<Vec<_>>()
806                    .join("\n");
807                entry_vars.insert("LEARNINGS".to_string(), learnings);
808            }
809
810            if let Some(ref error) = entry.error {
811                entry_vars.insert("ERROR".to_string(), error.clone());
812            }
813
814            if !entry.files_modified.is_empty() {
815                entry_vars.insert(
816                    "FILES_MODIFIED".to_string(),
817                    entry.files_modified.join(", "),
818                );
819            }
820
821            let rendered = render_prompt_template(AGENT_MEMORY_ENTRY_TEMPLATE, &entry_vars);
822            sections.push(rendered.trim().to_string());
823        }
824
825        let memory_section = sections.join("\n\n");
826        vars.insert("MEMORY_SECTION".to_string(), memory_section);
827    }
828
829    render_prompt_template(AGENT_MESSAGE_TEMPLATE, &vars)
830}
831
832/// Build the review prompt for the review agent.
833///
834/// This is called when a task completes and the review agent needs to
835/// review the changes before auto-merge.
836pub fn build_review_prompt(
837    task: &ExternalTask,
838    agent_summary: &str,
839    git_diff: &str,
840    git_log: &str,
841    default_branch: &str,
842    pr_number: u64,
843    shipcheck: Shipcheck,
844) -> String {
845    let mut vars = HashMap::new();
846    shipcheck.insert_vars(&mut vars);
847    insert_cluster_vars(shipcheck, &mut vars);
848    vars.insert("TASK_ID".to_string(), task.id.0.clone());
849    vars.insert("TASK_TITLE".to_string(), task.title.clone());
850    vars.insert("TASK_BODY".to_string(), task.body.clone());
851    vars.insert("DEFAULT_BRANCH".to_string(), default_branch.to_string());
852    vars.insert("PR_NUMBER".to_string(), pr_number.to_string());
853
854    if !agent_summary.is_empty() {
855        vars.insert("AGENT_SUMMARY".to_string(), agent_summary.to_string());
856    }
857
858    if !git_diff.is_empty() {
859        vars.insert("GIT_DIFF".to_string(), git_diff.to_string());
860    }
861
862    if !git_log.is_empty() {
863        vars.insert("GIT_LOG".to_string(), git_log.to_string());
864    }
865
866    render_prompt_template(REVIEW_PROMPT_TEMPLATE, &vars)
867}
868
869/// Build the runner shell script contents for testing and inspection, given a pre-created
870/// attempt directory so tests can pass a temp dir.
871///
872/// IMPORTANT: this must not embed secrets (GH_TOKEN) into the script.
873#[cfg(test)]
874fn build_runner_script_in_dir(inv: &AgentInvocation, attempt_dir: &Path) -> String {
875    let sys_file = attempt_dir.join("prompt-sys.md");
876    let msg_file = attempt_dir.join("prompt-msg.md");
877
878    // Build unified permission rules and sys content (minimal translation)
879    let mut permissions = super::agents::PermissionRules::from_config();
880    if !inv.disallowed_tools.is_empty() {
881        for tool in &inv.disallowed_tools {
882            if !permissions.disallowed_tools.contains(tool) {
883                permissions.disallowed_tools.push(tool.clone());
884            }
885        }
886    }
887    permissions.allowed_edit_paths.push(inv.work_dir.clone());
888
889    // Build agent command using per-agent runner
890    let runner = super::agents::get_runner(&inv.agent);
891    let timeout_cmd = if inv.timeout_seconds > 0 {
892        format!("timeout {}", inv.timeout_seconds)
893    } else {
894        String::new()
895    };
896    let agent_cmd = runner.build_command_with_effort(
897        inv.model
898            .as_deref()
899            .map(str::trim)
900            .filter(|m| !m.is_empty()),
901        inv.reasoning_effort.as_deref(),
902        &timeout_cmd,
903        &sys_file.to_string_lossy(),
904        &msg_file.to_string_lossy(),
905        &permissions,
906    );
907
908    let status_file = attempt_dir.join("exit.txt");
909    let stderr_file = attempt_dir.join("stderr.txt");
910
911    let sq_status = shell_single_quote(&status_file.display().to_string());
912    let sq_stderr = shell_single_quote(&stderr_file.display().to_string());
913    let sq_out = shell_single_quote(&inv.output_file.display().to_string());
914    let sq_work_dir = shell_single_quote(&inv.work_dir.to_string_lossy());
915    let script = format!(
916        "#!/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",
917    );
918
919    script
920}
921
922/// Build the system prompt for the review agent.
923pub fn review_system_prompt() -> String {
924    render_prompt_template(REVIEW_SYSTEM_TEMPLATE, &HashMap::new())
925}
926
927#[cfg(test)]
928mod tests {
929    use super::*;
930    use crate::backends::ExternalId;
931    use crate::engine::runner::agents::shell_single_quote;
932    use crate::engine::runner::sandbox;
933    use crate::template;
934    use std::fs as std_fs;
935    use std::os::unix::fs as unix_fs;
936    use std::os::unix::fs::PermissionsExt;
937    use std::path::PathBuf;
938    use std::process;
939
940    #[test]
941    fn review_system_prompt_checks_stray_files_and_trust_boundaries() {
942        let p = review_system_prompt();
943        assert!(p.contains("**Files**"));
944        assert!(p.contains("**Trust boundaries**"));
945    }
946
947    fn test_invocation(task_id: &str) -> AgentInvocation {
948        AgentInvocation {
949            agent: "claude".to_string(),
950            model: None,
951            reasoning_effort: None,
952            work_dir: PathBuf::from("/tmp"),
953            system_prompt: "test system prompt".to_string(),
954            agent_message: "test message".to_string(),
955            task_id: task_id.to_string(),
956            disallowed_tools: vec![],
957            git_author_name: "Test Bot".to_string(),
958            git_author_email: "bot@example.com".to_string(),
959            output_file: PathBuf::from("/tmp/test-output.json"),
960            timeout_seconds: 0,
961            repo: "orch-runner-test/token-check".to_string(),
962            attempt: 1,
963            sandbox: false,
964            main_project_dir: PathBuf::from("/tmp"),
965            branch: String::new(),
966        }
967    }
968
969    #[test]
970    fn spawn_in_tmux_rejects_invalid_env() {
971        // This test verifies the function signature and basic behavior
972        // without actually spawning a tmux session.
973        // The key security guarantee: tokens are passed via tmux -e flag,
974        // not written to any file on disk.
975        let inv = test_invocation("env-test");
976        // Just verify the invocation can be created without panicking
977        assert_eq!(inv.task_id, "env-test");
978    }
979
980    #[test]
981    fn build_runner_script_persists_exit_status_on_failure() {
982        // Use a temp dir so lib and bin compilation units don't race on ~/.orch/state/.
983        let tmp = tempfile::TempDir::new().expect("temp dir");
984        let inv = test_invocation("runner-status-test");
985        let script = build_runner_script_in_dir(&inv, tmp.path());
986
987        assert!(
988            script
989                .contains("trap 'status=$?; printf \"%s\\n\" \"$status\" > \"$status_file\"' EXIT")
990        );
991        assert!(script.contains("set +e"));
992    }
993
994    #[test]
995    fn build_runner_script_reports_missing_worktree() {
996        // Use a temp dir so lib and bin compilation units don't race on ~/.orch/state/.
997        let tmp = tempfile::TempDir::new().expect("temp dir");
998        let inv = test_invocation("runner-missing-worktree-test");
999        let script = build_runner_script_in_dir(&inv, tmp.path());
1000
1001        assert!(script.contains("worktree directory does not exist: '/tmp'"));
1002        assert!(script.contains("stderr_file='"));
1003    }
1004
1005    #[test]
1006    fn tmux_runner_script_runs_agent_under_pty_not_a_plain_pipe() {
1007        // Regression test for #3554: piping the agent binary's stdout straight
1008        // into `tee` leaves it non-tty, which makes many CLI runtimes switch to
1009        // full block-buffering and can starve the tmux pane long enough to trip
1010        // silence detection even while the agent is actively working. The agent
1011        // command must run under `script` (a real pty) before hitting `tee`.
1012        let tmp = tempfile::TempDir::new().expect("temp dir");
1013        let inv = test_invocation("pty-wrap-test");
1014        let (runner_script, agent_cmd_script) =
1015            build_tmux_runner_scripts(&inv, "echo hello", tmp.path(), None, &[]);
1016
1017        assert!(
1018            runner_script.contains("script -q /dev/null /bin/bash"),
1019            "agent must be exec'd under a pty via `script`, got: {runner_script}"
1020        );
1021        assert!(
1022            runner_script.contains("| tee"),
1023            "output must still be tee'd to the output file, got: {runner_script}"
1024        );
1025        assert!(
1026            !runner_script.contains("echo hello 2>"),
1027            "the raw agent command must not be piped directly into tee anymore, got: {runner_script}"
1028        );
1029        assert!(
1030            agent_cmd_script.contains("echo hello 2>"),
1031            "the agent command should run (with stderr split to a file) inside the pty-wrapped helper script, got: {agent_cmd_script}"
1032        );
1033    }
1034
1035    #[test]
1036    fn tmux_runner_script_captures_agent_exit_status_via_pipestatus() {
1037        let tmp = tempfile::TempDir::new().expect("temp dir");
1038        let inv = test_invocation("pty-exit-status-test");
1039        let (runner_script, _) =
1040            build_tmux_runner_scripts(&inv, "echo hello", tmp.path(), None, &[]);
1041
1042        assert!(runner_script.contains("CMD_STATUS=${PIPESTATUS[0]:-0}"));
1043        assert!(runner_script.contains("exit $CMD_STATUS"));
1044    }
1045
1046    #[test]
1047    fn tmux_runner_script_disables_commit_signing() {
1048        // Locked signing agent must not fail `git commit` inside agent sessions
1049        let tmp = tempfile::TempDir::new().expect("temp dir");
1050        let inv = test_invocation("gpgsign-test");
1051        let (runner_script, _) =
1052            build_tmux_runner_scripts(&inv, "echo hello", tmp.path(), None, &[]);
1053
1054        assert!(runner_script.contains("GIT_CONFIG_KEY_0=\"commit.gpgsign\""));
1055        assert!(runner_script.contains("GIT_CONFIG_VALUE_0=\"false\""));
1056        assert!(runner_script.contains("GIT_CONFIG_KEY_1=\"tag.gpgsign\""));
1057        // Only pushes go over HTTPS with gh's credentials, fetches keep the remote as it is
1058        assert!(
1059            runner_script.contains("GIT_CONFIG_KEY_2=\"url.https://github.com/.pushInsteadOf\"")
1060        );
1061        assert!(runner_script.contains("GIT_CONFIG_VALUE_2=\"git@github.com:\""));
1062        assert!(runner_script.contains("GIT_CONFIG_VALUE_3=\"!gh auth git-credential\""));
1063    }
1064
1065    #[test]
1066    fn tmux_runner_script_writes_executable_agent_cmd_helper() {
1067        let tmp = tempfile::TempDir::new().expect("temp dir");
1068        let inv = test_invocation("pty-helper-path-test");
1069        let (runner_script, agent_cmd_script) =
1070            build_tmux_runner_scripts(&inv, "echo hello", tmp.path(), None, &[]);
1071
1072        let agent_cmd_script_path = tmp.path().join("agent_cmd.sh");
1073        assert!(
1074            runner_script.contains(&agent_cmd_script_path.display().to_string()),
1075            "runner script must reference the agent_cmd.sh helper path, got: {runner_script}"
1076        );
1077        assert!(agent_cmd_script.starts_with("#!/usr/bin/env bash\n"));
1078    }
1079
1080    #[test]
1081    fn tmux_runner_script_runs_the_agent_inside_the_sandbox() {
1082        let tmp = tempfile::TempDir::new().expect("temp dir");
1083        let inv = test_invocation("sandbox-test");
1084        let argv: Vec<OsString> = vec![
1085            "/usr/bin/sandbox-exec".into(),
1086            "-p".into(),
1087            "(version 1)".into(),
1088        ];
1089        let (_, agent_cmd_script) =
1090            build_tmux_runner_scripts(&inv, "claude -p 'hi'", tmp.path(), Some(&argv), &[]);
1091        assert!(
1092            agent_cmd_script.contains(
1093                "env -u TMUX -u TMUX_PANE -u SSH_AUTH_SOCK TMPDIR='"
1094            ) && agent_cmd_script.contains(
1095                "1 '/usr/bin/sandbox-exec' '-p' '(version 1)' /bin/bash -c 'claude -p '\\''hi'\\''' 2>"
1096            ),
1097            "the agent must run inside the sandbox with stderr split outside it, got: {agent_cmd_script}"
1098        );
1099        assert!(
1100            agent_cmd_script.contains(&format!(
1101                "TMPDIR='{}'",
1102                sandbox::run_temp_dir(tmp.path()).display()
1103            )),
1104            "the agent must get its own TMPDIR, got: {agent_cmd_script}"
1105        );
1106        assert!(
1107            agent_cmd_script.contains(&format!(
1108                "GH_CONFIG_DIR='{}'",
1109                sandbox::gh_config_dir(&sandbox::run_temp_dir(tmp.path())).display()
1110            )),
1111            "gh must get a config dir it can read, got: {agent_cmd_script}"
1112        );
1113        assert!(agent_cmd_script.contains(" SHIPCHECK_HANDOFF=1 "));
1114
1115        let env = [("NPM_CONFIG_USERCONFIG", tmp.path().join("npmrc"))];
1116        let (_, with_env) = build_tmux_runner_scripts(&inv, "true", tmp.path(), Some(&argv), &env);
1117        assert!(with_env.contains(&format!(
1118            " NPM_CONFIG_USERCONFIG='{}' ",
1119            tmp.path().join("npmrc").display()
1120        )));
1121    }
1122
1123    #[test]
1124    fn only_a_sandboxed_run_fetches_without_tags() {
1125        let tmp = tempfile::TempDir::new().expect("temp dir");
1126        let inv = test_invocation("sandbox-test");
1127        let argv: Vec<OsString> = vec!["/usr/bin/sandbox-exec".into()];
1128        let (sandboxed, _) = build_tmux_runner_scripts(&inv, "true", tmp.path(), Some(&argv), &[]);
1129        assert!(sandboxed.contains("export GIT_CONFIG_COUNT=\"5\""));
1130        assert!(sandboxed.contains("export GIT_CONFIG_VALUE_4=\"--no-tags\""));
1131        let (plain, _) = build_tmux_runner_scripts(&inv, "true", tmp.path(), None, &[]);
1132        assert!(!plain.contains("tagOpt"));
1133        assert!(
1134            !plain.contains("rm -rf"),
1135            "only a sandboxed run has a temp dir to wipe"
1136        );
1137        assert!(sandboxed.contains(&format!(
1138            "\"$status_file\"; rm -rf -- '{}'' EXIT",
1139            sandbox::run_temp_dir(tmp.path()).display()
1140        )));
1141    }
1142
1143    #[test]
1144    fn a_sandboxed_prompt_offers_no_shipcheck() {
1145        assert_eq!(
1146            Shipcheck::Available.for_prompt(true, false),
1147            Shipcheck::Absent
1148        );
1149        assert_eq!(
1150            Shipcheck::Available.for_prompt(true, true),
1151            Shipcheck::Available
1152        );
1153        assert_eq!(
1154            Shipcheck::Available.for_prompt(false, false),
1155            Shipcheck::Available
1156        );
1157        assert_eq!(
1158            Shipcheck::NotInstalled.for_prompt(true, false),
1159            Shipcheck::NotInstalled
1160        );
1161    }
1162
1163    #[test]
1164    fn build_runner_script_escapes_shell_injection_in_paths() {
1165        let tmp = tempfile::TempDir::new().expect("temp dir");
1166        let mut inv = test_invocation("injection-test");
1167        inv.work_dir = PathBuf::from("/tmp/$(whoami)/workspace");
1168        inv.output_file = PathBuf::from("/tmp/evil`id`.json");
1169        let script = build_runner_script_in_dir(&inv, tmp.path());
1170
1171        // Values must be single-quoted, neutralizing $() and backticks
1172        assert!(
1173            script.contains("'/tmp/$(whoami)/workspace'"),
1174            "work_dir with $() must be single-quoted: {script}"
1175        );
1176        assert!(
1177            script.contains("'/tmp/evil`id`.json'"),
1178            "output_file with backticks must be single-quoted: {script}"
1179        );
1180    }
1181
1182    #[test]
1183    fn review_prompt_forbids_ending_turn_on_pending_ci_status() {
1184        // Regression test for #3453: a review agent must not stop with a
1185        // prose "CI is still running" status update and leave the turn
1186        // without JSON. The prompt must explicitly route PENDING/NOT RUN CI
1187        // through the local-checks fallback and into the same-turn JSON output.
1188        let task = ExternalTask {
1189            id: ExternalId("155460".to_string()),
1190            title: "test task".to_string(),
1191            body: "test body".to_string(),
1192            state: "open".to_string(),
1193            labels: vec![],
1194            author: "tester".to_string(),
1195            created_at: "2026-01-01T00:00:00Z".to_string(),
1196            updated_at: "2026-01-01T00:00:00Z".to_string(),
1197            url: "https://example.com/1".to_string(),
1198        };
1199        let prompt = build_review_prompt(&task, "", "", "", "main", 1, Shipcheck::Absent);
1200
1201        assert!(
1202            prompt.contains("Pending CI is never a terminal review state"),
1203            "prompt must state pending CI is not terminal: {prompt}"
1204        );
1205        assert!(
1206            prompt.contains("Never end your turn with a CI-waiting status update"),
1207            "prompt must forbid ending the turn on a CI-waiting status update: {prompt}"
1208        );
1209    }
1210
1211    #[test]
1212    fn shell_single_quote_escapes_embedded_quotes() {
1213        assert_eq!(shell_single_quote("hello"), "'hello'");
1214        assert_eq!(shell_single_quote("O'Brien"), "'O'\\''Brien'");
1215        assert_eq!(shell_single_quote("$(rm -rf /)"), "'$(rm -rf /)'");
1216        assert_eq!(shell_single_quote("`whoami`"), "'`whoami`'");
1217        assert_eq!(shell_single_quote("a\"b"), "'a\"b'");
1218        assert_eq!(shell_single_quote("$HOME"), "'$HOME'");
1219    }
1220
1221    fn git_init(dir: &Path) {
1222        let out = process::Command::new("git")
1223            .args(["init", "-q"])
1224            .current_dir(dir)
1225            .output()
1226            .unwrap();
1227        assert!(out.status.success());
1228    }
1229
1230    #[tokio::test]
1231    async fn install_shipcheck_rule_writes_rule_and_keeps_tree_clean() {
1232        let dir = tempfile::tempdir().unwrap();
1233        git_init(dir.path());
1234
1235        install_shipcheck_rule(dir.path()).await.unwrap();
1236        install_shipcheck_rule(dir.path()).await.unwrap();
1237
1238        let rule = std_fs::read_to_string(dir.path().join(SHIPCHECK_RULE_PATH)).unwrap();
1239        assert_eq!(rule, SHIPCHECK_RULES);
1240        for cmd in ["run", "commit", "status", "logs", "doctor"] {
1241            assert!(
1242                rule.contains(&format!(r#"["shipcheck", "{cmd}"]"#)),
1243                "{cmd}"
1244            );
1245        }
1246        assert!(!rule.contains(r#"["shipcheck"]"#));
1247        for cmd in [
1248            "clean", "post", "login", "logout", "daemon", "init", "install",
1249        ] {
1250            assert!(!rule.contains(&format!(r#""{cmd}""#)), "{cmd}");
1251        }
1252
1253        let exclude = std_fs::read_to_string(dir.path().join(".git/info/exclude")).unwrap();
1254        assert_eq!(exclude.matches("orch-shipcheck.rules").count(), 1);
1255        let status = process::Command::new("git")
1256            .args(["status", "--porcelain", "--untracked-files=all"])
1257            .current_dir(dir.path())
1258            .output()
1259            .unwrap();
1260        assert!(status.stdout.is_empty(), "{status:?}");
1261    }
1262
1263    #[tokio::test]
1264    async fn install_shipcheck_rule_refuses_symlinked_dirs() {
1265        for link in [".codex", ".codex/rules"] {
1266            let dir = tempfile::tempdir().unwrap();
1267            let target = tempfile::tempdir().unwrap();
1268            git_init(dir.path());
1269            std_fs::create_dir_all(dir.path().join(".codex")).unwrap();
1270            if link == ".codex" {
1271                std_fs::remove_dir(dir.path().join(".codex")).unwrap();
1272            }
1273            unix_fs::symlink(target.path(), dir.path().join(link)).unwrap();
1274
1275            assert!(install_shipcheck_rule(dir.path()).await.is_err(), "{link}");
1276            assert_eq!(
1277                std_fs::read_dir(target.path()).unwrap().count(),
1278                0,
1279                "{link}"
1280            );
1281        }
1282    }
1283
1284    #[tokio::test]
1285    async fn install_shipcheck_rule_replaces_a_symlinked_file_without_following_it() {
1286        let dir = tempfile::tempdir().unwrap();
1287        let target = tempfile::tempdir().unwrap();
1288        let outside = target.path().join("victim");
1289        std_fs::write(&outside, "keep").unwrap();
1290        git_init(dir.path());
1291        std_fs::create_dir_all(dir.path().join(".codex/rules")).unwrap();
1292        unix_fs::symlink(&outside, dir.path().join(SHIPCHECK_RULE_PATH)).unwrap();
1293
1294        install_shipcheck_rule(dir.path()).await.unwrap();
1295
1296        assert_eq!(std_fs::read_to_string(&outside).unwrap(), "keep");
1297        let meta = std_fs::symlink_metadata(dir.path().join(SHIPCHECK_RULE_PATH)).unwrap();
1298        assert!(meta.is_file());
1299    }
1300
1301    fn prompt_task() -> ExternalTask {
1302        ExternalTask {
1303            id: ExternalId("1".to_string()),
1304            title: "t".to_string(),
1305            body: "b".to_string(),
1306            state: "open".to_string(),
1307            labels: vec![],
1308            author: "a".to_string(),
1309            created_at: "2026-01-01T00:00:00Z".to_string(),
1310            updated_at: "2026-01-01T00:00:00Z".to_string(),
1311            url: "https://example.com/1".to_string(),
1312        }
1313    }
1314
1315    #[test]
1316    fn only_a_sandboxed_prompt_explains_the_sandbox() {
1317        let ctx = super::super::context::TaskContext::default();
1318        let task = prompt_task();
1319        let prompt = |sandboxed| {
1320            build_system_prompt(&task, &ctx, None, "main", Shipcheck::Absent, sandboxed)
1321        };
1322        assert!(prompt(true).contains("you run inside an OS sandbox"));
1323        assert!(!prompt(false).contains("OS sandbox"));
1324        assert!(!prompt(false).contains("SANDBOX"));
1325    }
1326
1327    #[test]
1328    fn system_prompt_uses_shipcheck_only_when_available() {
1329        let ctx = super::super::context::TaskContext::default();
1330        let task = prompt_task();
1331        let prompt = |s| build_system_prompt(&task, &ctx, None, "main", s, false);
1332
1333        let available = prompt(Shipcheck::Available);
1334        assert!(available.contains("shipcheck run"));
1335        assert!(available.contains("shipcheck commit"));
1336        assert!(!available.contains(".github/workflows/"));
1337        assert!(!available.contains("not installed"));
1338
1339        let outdated = prompt(Shipcheck::Outdated);
1340        assert!(!outdated.contains("shipcheck"));
1341        assert!(outdated.contains(".github/workflows/"));
1342
1343        let missing = prompt(Shipcheck::NotInstalled);
1344        assert!(!missing.contains("shipcheck run"));
1345        assert!(missing.contains(".github/workflows/"));
1346        assert!(missing.contains("shipcheck is not installed"));
1347
1348        let absent = prompt(Shipcheck::Absent);
1349        assert!(!absent.contains("shipcheck"));
1350        assert!(absent.contains(".github/workflows/"));
1351
1352        for p in [&available, &outdated, &missing, &absent] {
1353            assert!(!p.contains("{{"), "{p}");
1354            assert!(!p.contains("install shipcheck"), "{p}");
1355        }
1356    }
1357
1358    #[test]
1359    fn review_prompt_uses_shipcheck_only_when_available() {
1360        let task = prompt_task();
1361        let prompt = |s| build_review_prompt(&task, "", "", "", "main", 1, s);
1362        assert!(prompt(Shipcheck::Available).contains("shipcheck run"));
1363        for s in [
1364            Shipcheck::Outdated,
1365            Shipcheck::NotInstalled,
1366            Shipcheck::Absent,
1367        ] {
1368            let p = prompt(s);
1369            assert!(!p.contains("shipcheck"), "{p}");
1370            assert!(p.contains(".github/workflows/"), "{p}");
1371        }
1372    }
1373
1374    #[test]
1375    fn shipcheck_classify_needs_config_and_commit() {
1376        assert_eq!(Shipcheck::classify(false, Some(true)), Shipcheck::Absent);
1377        assert_eq!(Shipcheck::classify(false, None), Shipcheck::Absent);
1378        assert_eq!(Shipcheck::classify(true, None), Shipcheck::NotInstalled);
1379        assert_eq!(Shipcheck::classify(true, Some(false)), Shipcheck::Outdated);
1380        assert_eq!(Shipcheck::classify(true, Some(true)), Shipcheck::Available);
1381    }
1382
1383    #[tokio::test]
1384    async fn supports_reads_the_usage_line() {
1385        let new_dir = tempfile::tempdir().unwrap();
1386        let new = fake_shipcheck(new_dir.path(), true, true);
1387        assert!(supports(&new, "commit").await);
1388        assert!(supports(&new, "hook").await);
1389        let old_dir = tempfile::tempdir().unwrap();
1390        let old = fake_shipcheck(old_dir.path(), false, false);
1391        assert!(!supports(&old, "commit").await);
1392        assert!(!supports(&old, "hook").await);
1393        let missing = old_dir.path().join("missing");
1394        assert!(!supports(&missing, "commit").await);
1395    }
1396
1397    // Mimics shipcheck, whose `--help` prints usage and exits 0 after any subcommand
1398    fn fake_shipcheck(dir: &Path, commit: bool, hook: bool) -> PathBuf {
1399        let mut usage = "usage: shipcheck run [--sha <rev>] | status | logs".to_string();
1400        if commit {
1401            usage.push_str(" | commit -m <message>");
1402        }
1403        if hook {
1404            usage.push_str(" | hook");
1405        }
1406        usage.push_str(" | install | doctor");
1407        let bin = dir.join("shipcheck");
1408        std_fs::write(
1409            &bin,
1410            format!(
1411                "#!/bin/sh\nfor a in \"$@\"; do [ \"$a\" = --help ] && {{ echo '{usage}'; exit 0; }}; done\n[ \"$1\" = install ] && touch installed\nexit 0\n"
1412            ),
1413        )
1414        .unwrap();
1415        std_fs::set_permissions(&bin, Permissions::from_mode(0o755)).unwrap();
1416        bin
1417    }
1418
1419    #[tokio::test]
1420    async fn install_shipcheck_hooks_runs_install_when_supported() {
1421        let bin_dir = tempfile::tempdir().unwrap();
1422        let work = tempfile::tempdir().unwrap();
1423        let bin = fake_shipcheck(bin_dir.path(), true, true);
1424        assert!(install_shipcheck_hooks(work.path(), Shipcheck::Available, &bin).await);
1425        assert!(work.path().join("installed").exists());
1426    }
1427
1428    #[tokio::test]
1429    async fn install_shipcheck_hooks_skips_a_shipcheck_without_hook() {
1430        let bin_dir = tempfile::tempdir().unwrap();
1431        let work = tempfile::tempdir().unwrap();
1432        let bin = fake_shipcheck(bin_dir.path(), true, false);
1433        assert!(!install_shipcheck_hooks(work.path(), Shipcheck::Available, &bin).await);
1434        assert!(!work.path().join("installed").exists());
1435    }
1436
1437    #[tokio::test]
1438    async fn install_shipcheck_hooks_skips_when_not_available() {
1439        let bin_dir = tempfile::tempdir().unwrap();
1440        let work = tempfile::tempdir().unwrap();
1441        let bin = fake_shipcheck(bin_dir.path(), true, true);
1442        for s in [
1443            Shipcheck::Outdated,
1444            Shipcheck::NotInstalled,
1445            Shipcheck::Absent,
1446        ] {
1447            assert!(!install_shipcheck_hooks(work.path(), s, &bin).await);
1448        }
1449        assert!(!work.path().join("installed").exists());
1450    }
1451
1452    #[test]
1453    fn the_progress_step_appears_only_in_cluster_mode() {
1454        let mut vars = HashMap::new();
1455        insert_cluster_vars(Shipcheck::Available, &mut vars);
1456        assert!(vars.is_empty(), "no cluster section, no cluster flags");
1457        let plain = template::render_template_str(AGENT_SYSTEM_TEMPLATE, &vars).unwrap();
1458        assert!(!plain.contains("orch progress"));
1459
1460        for flag in ["CLUSTER", "CLUSTER_SHIPCHECK"] {
1461            vars.insert(flag.to_string(), "1".to_string());
1462        }
1463        let cluster = template::render_template_str(AGENT_SYSTEM_TEMPLATE, &vars).unwrap();
1464        assert!(cluster.contains("orch progress"));
1465        assert!(cluster.contains("commits only through `shipcheck commit`"));
1466        assert!(!cluster.contains("It commits anything you left"));
1467    }
1468}