Skip to main content

orch/engine/runner/
agent.rs

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