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