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    /// Current attempt number (1-indexed)
296    pub attempt: u32,
297}
298
299/// Build the runner script content (saved to attempt dir), plus the small
300/// helper script it execs the agent command through under a pty. Returns
301/// `(runner_script, agent_cmd_script)`.
302fn build_tmux_runner_scripts(
303    inv: &AgentInvocation,
304    agent_cmd: &str,
305    attempt_dir: &std::path::Path,
306    sandbox: Option<&[std::ffi::OsString]>,
307) -> anyhow::Result<(String, String)> {
308    let status_file = attempt_dir.join("exit.txt");
309    let stderr_file = attempt_dir.join("stderr.txt");
310    let agent_cmd_script_path = attempt_dir.join("agent_cmd.sh");
311    let sq_git_name = shell_single_quote(&inv.git_author_name);
312    let sq_git_email = shell_single_quote(&inv.git_author_email);
313    let sq_task_id = shell_single_quote(&inv.task_id);
314    let sq_output_file = shell_single_quote(&inv.output_file.display().to_string());
315    let sq_work_dir = shell_single_quote(&inv.work_dir.display().to_string());
316    let sq_status_file = shell_single_quote(&status_file.display().to_string());
317    let sq_stderr_file = shell_single_quote(&stderr_file.display().to_string());
318    let sq_agent_cmd_script = shell_single_quote(&agent_cmd_script_path.display().to_string());
319
320    // Runs the agent with stderr split off to a real file before the pty layer
321    // below merges stdout+stderr, exactly as the previous plain-pipe invocation did.
322    let agent_cmd = match sandbox {
323        Some(argv) => {
324            let prefix: Vec<String> = argv
325                .iter()
326                .map(|a| shell_single_quote(&a.to_string_lossy()))
327                .collect();
328            format!(
329                "{} /bin/bash -c {}",
330                prefix.join(" "),
331                shell_single_quote(agent_cmd)
332            )
333        }
334        None => agent_cmd.to_string(),
335    };
336    let agent_cmd_script = format!("#!/usr/bin/env bash\n{agent_cmd} 2>{sq_stderr_file}\n");
337
338    let runner_script = format!(
339        r#"#!/usr/bin/env bash
340set -euo pipefail
341
342status_file={sq_status_file}
343stderr_file={sq_stderr_file}
344trap 'status=$?; printf "%s\n" "$status" > "$status_file"' EXIT
345
346# Environment — ~/.path and ~/.private are loaded by orch at startup into the process env
347export PATH="/opt/homebrew/bin:/usr/local/bin:$PATH"
348export GIT_AUTHOR_NAME={sq_git_name}
349export GIT_COMMITTER_NAME={sq_git_name}
350export GIT_AUTHOR_EMAIL={sq_git_email}
351export GIT_COMMITTER_EMAIL={sq_git_email}
352# Env config overrides the operator's global commit.gpgsign, the signing agent
353# (1Password etc) is often locked in unattended sessions and blocks `git commit`
354export GIT_CONFIG_COUNT="1"
355export GIT_CONFIG_KEY_0="commit.gpgsign"
356export GIT_CONFIG_VALUE_0="false"
357export TASK_ID={sq_task_id}
358export OUTPUT_FILE={sq_output_file}
359unset CLAUDECODE  # allow nested claude invocations from orch
360
361cd {sq_work_dir} || {{
362    printf '%s\n' "worktree directory does not exist: {sq_work_dir}" > "$stderr_file"
363    exit 1
364}}
365
366# Run agent under a pty (via `script`) so its stdout is a tty, not a plain pipe —
367# many CLI runtimes silently switch to full block-buffering when stdout isn't a
368# tty, which can delay pane output long enough to trip silence detection even
369# while the agent is actively streaming. Tee to both output file and terminal
370# (tmux pane) for live streaming.
371set +e
372script -q /dev/null /bin/bash {sq_agent_cmd_script} | tee {sq_output_file}
373CMD_STATUS=${{PIPESTATUS[0]:-0}}
374set -e
375
376exit $CMD_STATUS
377"#,
378    );
379
380    Ok((runner_script, agent_cmd_script))
381}
382
383/// Spawn the agent in a tmux session.
384///
385/// Returns the tmux session name.
386pub async fn spawn_in_tmux(tmux: &TmuxManager, inv: &AgentInvocation) -> anyhow::Result<String> {
387    // Prepare attempt directory and prompt files (system + message).
388    let attempt_dir =
389        crate::home::task_attempt_dir_async(&inv.repo, &inv.task_id, inv.attempt).await?;
390
391    let sys_file = attempt_dir.join("prompt-sys.md");
392    let msg_file = attempt_dir.join("prompt-msg.md");
393    // Build unified permission rules and sys content
394    let mut permissions = super::agents::PermissionRules::from_config();
395    if !inv.disallowed_tools.is_empty() {
396        for tool in &inv.disallowed_tools {
397            if !permissions.disallowed_tools.contains(tool) {
398                permissions.disallowed_tools.push(tool.clone());
399            }
400        }
401    }
402    permissions.allowed_edit_paths.push(inv.work_dir.clone());
403
404    // Codex cannot start its own Seatbelt inside the OS sandbox, so the OS sandbox replaces it
405    let sandbox = if inv.sandbox {
406        permissions.sandbox = super::agents::SandboxLevel::Os;
407        Some(super::sandbox::argv(inv).await?)
408    } else {
409        None
410    };
411
412    // For Codex running in workspace-write sandbox mode, grant write access to
413    // git metadata dirs when they live outside the worktree root. We include
414    // both --git-common-dir and --git-dir because index.lock can be created
415    // under the worktree-specific git dir.
416    if inv.agent == "codex" {
417        let mut extra_dirs = BTreeSet::new();
418        for (arg, label) in [
419            ("--git-common-dir", "git common dir"),
420            ("--git-dir", "git dir"),
421        ] {
422            match resolve_git_dir_arg(&inv.work_dir, arg).await {
423                Ok(Some(dir)) if !dir.starts_with(&inv.work_dir) => {
424                    extra_dirs.insert(dir);
425                }
426                Ok(_) => {}
427                Err(e) => {
428                    tracing::debug!(
429                        work_dir = %inv.work_dir.display(),
430                        arg,
431                        error = %e,
432                        "failed to resolve {}; skipping --add-dir",
433                        label
434                    );
435                }
436            }
437        }
438        permissions.extra_writable_dirs.extend(extra_dirs);
439
440        if Shipcheck::detect(&inv.work_dir).await == Shipcheck::Available {
441            if let Err(e) = install_shipcheck_rule(&inv.work_dir).await {
442                tracing::warn!(
443                    work_dir = %inv.work_dir.display(),
444                    error = %e,
445                    "failed to install the shipcheck codex rule"
446                );
447            }
448        }
449    }
450
451    let sys_content = if !permissions.allowed_tools.is_empty() {
452        let tools_list = permissions
453            .allowed_tools
454            .iter()
455            .map(|t| format!("- {t}"))
456            .collect::<Vec<_>>()
457            .join("\n");
458        let mut vars = HashMap::new();
459        vars.insert("TOOLS_LIST".to_string(), tools_list);
460        let tools_prompt = render_prompt_template(ALLOWED_TOOLS_TEMPLATE, vars);
461        format!("{}\n\n{}", inv.system_prompt, tools_prompt)
462    } else {
463        inv.system_prompt.clone()
464    };
465
466    tokio::fs::write(&sys_file, &sys_content).await?;
467    tokio::fs::write(&msg_file, &inv.agent_message).await?;
468
469    // Build agent command using per-agent runner (used in non-PTY path below)
470    let runner = super::agents::get_runner(&inv.agent);
471
472    // Prepare environment map for tmux session (does not write GH token to disk)
473    let mut env = std::collections::HashMap::new();
474    env.insert("GIT_AUTHOR_NAME".to_string(), inv.git_author_name.clone());
475    env.insert(
476        "GIT_COMMITTER_NAME".to_string(),
477        inv.git_author_name.clone(),
478    );
479    env.insert("GIT_AUTHOR_EMAIL".to_string(), inv.git_author_email.clone());
480    env.insert(
481        "GIT_COMMITTER_EMAIL".to_string(),
482        inv.git_author_email.clone(),
483    );
484    env.insert("TASK_ID".to_string(), inv.task_id.clone());
485    env.insert(
486        "OUTPUT_FILE".to_string(),
487        inv.output_file.display().to_string(),
488    );
489
490    // Write runner script and execute it in a detached tmux session.
491    let timeout_cmd = if inv.timeout_seconds > 0 {
492        format!("timeout {}", inv.timeout_seconds)
493    } else {
494        String::new()
495    };
496    let agent_cmd = runner.build_command(
497        inv.model.as_deref(),
498        &timeout_cmd,
499        &sys_file.to_string_lossy(),
500        &msg_file.to_string_lossy(),
501        &permissions,
502    );
503
504    // Write runner script (and the agent-cmd helper script it execs under a pty)
505    // to the per-task attempt dir.
506    let script_path = attempt_dir.join("runner.sh");
507    let agent_cmd_script_path = attempt_dir.join("agent_cmd.sh");
508    let (script_content, agent_cmd_script_content) =
509        build_tmux_runner_scripts(inv, &agent_cmd, &attempt_dir, sandbox.as_deref())?;
510    tokio::fs::write(&agent_cmd_script_path, &agent_cmd_script_content).await?;
511    tokio::fs::write(&script_path, &script_content).await?;
512
513    // Make executable
514    #[cfg(unix)]
515    {
516        use std::os::unix::fs::PermissionsExt;
517        tokio::fs::set_permissions(&script_path, std::fs::Permissions::from_mode(0o755)).await?;
518        tokio::fs::set_permissions(
519            &agent_cmd_script_path,
520            std::fs::Permissions::from_mode(0o755),
521        )
522        .await?;
523    }
524
525    let command = format!("bash \"{}\"", script_path.display());
526
527    // Resolve GitHub token via the process-wide shared resolver (cached after first call)
528    let github_token = match crate::github::token::shared().get_token().await {
529        Ok(Some(token)) => {
530            tracing::debug!("Resolved GitHub token via TokenResolver for agent session");
531            Some(token)
532        }
533        Ok(None) => {
534            tracing::warn!(
535                "No GitHub token available; set GH_TOKEN, GITHUB_TOKEN, or gh.auth.token, or run gh auth login"
536            );
537            None
538        }
539        Err(e) => {
540            tracing::warn!(error = %e, "Failed to resolve GitHub token");
541            None
542        }
543    };
544
545    // Inject GH_TOKEN into env so it's passed via `tmux new-session -e` along
546    // with everything else. The `-e` flag sets variables in the *initial* pane
547    // environment, so the agent process sees it immediately on startup.
548    //
549    // IMPORTANT: Do NOT use create_session_detached + set_env + create_window
550    // to inject GH_TOKEN. That approach creates a 2-window session (window 0 =
551    // idle shell, window 1 = agent). All tmux monitoring (is_session_active,
552    // capture_pane, batch_session_active) targets the session without a window
553    // index, which defaults to the *active* window — the idle shell. This
554    // breaks completion detection (shell never exits → pane_dead always 0),
555    // output capture (reads the shell prompt, not agent output), and silence
556    // detection. See the revert of PR #2903.
557    if let Some(ref token) = github_token {
558        env.insert("GH_TOKEN".to_string(), token.clone());
559    }
560
561    let env_vec: Vec<(&str, &str)> = env.iter().map(|(k, v)| (k.as_str(), v.as_str())).collect();
562
563    let session = tmux
564        .create_session(
565            &inv.repo,
566            &inv.task_id,
567            &inv.work_dir.to_string_lossy(),
568            &command,
569            env_vec.as_slice(),
570        )
571        .await?;
572
573    tracing::info!(
574        task_id = inv.task_id,
575        agent = inv.agent,
576        session = %session,
577        "agent spawned in tmux"
578    );
579
580    Ok(session)
581}
582
583/// Build the system prompt for the agent.
584pub fn build_system_prompt(
585    _task: &crate::backends::ExternalTask,
586    context: &super::context::TaskContext,
587    route_result: Option<&crate::engine::router::RouteResult>,
588    default_branch: &str,
589    shipcheck: Shipcheck,
590) -> String {
591    let mut vars = HashMap::new();
592
593    vars.insert("DEFAULT_BRANCH".to_string(), default_branch.to_string());
594    shipcheck.insert_vars(&mut vars);
595    insert_cluster_vars(shipcheck, &mut vars);
596
597    if let Some(rr) = route_result {
598        vars.insert("ROLE".to_string(), rr.profile.role.clone());
599
600        if !rr.profile.constraints.is_empty() {
601            let constraints = rr
602                .profile
603                .constraints
604                .iter()
605                .map(|c| format!("- {c}"))
606                .collect::<Vec<_>>()
607                .join("\n");
608            vars.insert("CONSTRAINTS".to_string(), constraints);
609        }
610    }
611
612    if !context.project_instructions.is_empty() {
613        vars.insert(
614            "PROJECT_INSTRUCTIONS".to_string(),
615            context.project_instructions.clone(),
616        );
617    }
618
619    if !context.skills_docs.is_empty() {
620        vars.insert("SKILLS_DOCS".to_string(), context.skills_docs.clone());
621    }
622
623    if !context.repo_tree.is_empty() {
624        vars.insert("REPO_TREE".to_string(), context.repo_tree.clone());
625    }
626
627    render_prompt_template(AGENT_SYSTEM_TEMPLATE, vars)
628}
629
630/// Build the agent message (task prompt).
631pub fn build_agent_message(
632    task: &crate::backends::ExternalTask,
633    context: &super::context::TaskContext,
634    attempts: u32,
635) -> String {
636    let mut vars = HashMap::new();
637    vars.insert("TASK_ID".to_string(), task.id.0.clone());
638    vars.insert("TASK_TITLE".to_string(), task.title.clone());
639    vars.insert("TASK_BODY".to_string(), task.body.clone());
640
641    if !context.task_context.is_empty() {
642        vars.insert("TASK_CONTEXT".to_string(), context.task_context.clone());
643    }
644
645    if !context.parent_context.is_empty() {
646        vars.insert("PARENT_CONTEXT".to_string(), context.parent_context.clone());
647    }
648
649    if !context.issue_comments.is_empty() {
650        vars.insert("ISSUE_COMMENTS".to_string(), context.issue_comments.clone());
651    }
652
653    if !context.pr_review_context.is_empty() {
654        vars.insert(
655            "PR_REVIEW_CONTEXT".to_string(),
656            context.pr_review_context.clone(),
657        );
658    }
659
660    if attempts > 0 && !context.git_diff.is_empty() {
661        vars.insert("GIT_DIFF".to_string(), context.git_diff.clone());
662    }
663
664    if attempts > 0 {
665        vars.insert("ATTEMPT_NUMBER".to_string(), (attempts + 1).to_string());
666    }
667
668    if !context.memory.is_empty() {
669        let mut sections = Vec::new();
670        for entry in &context.memory {
671            let mut entry_vars = HashMap::new();
672            entry_vars.insert("ATTEMPT".to_string(), entry.attempt.to_string());
673            entry_vars.insert("AGENT".to_string(), entry.agent.clone());
674
675            if let Some(ref model) = entry.model {
676                entry_vars.insert("MODEL".to_string(), model.clone());
677            }
678
679            if !entry.approach.is_empty() {
680                entry_vars.insert("APPROACH".to_string(), entry.approach.clone());
681            }
682
683            if !entry.learnings.is_empty() {
684                let learnings = entry
685                    .learnings
686                    .iter()
687                    .map(|learning| format!("- {}", learning))
688                    .collect::<Vec<_>>()
689                    .join("\n");
690                entry_vars.insert("LEARNINGS".to_string(), learnings);
691            }
692
693            if let Some(ref error) = entry.error {
694                entry_vars.insert("ERROR".to_string(), error.clone());
695            }
696
697            if !entry.files_modified.is_empty() {
698                entry_vars.insert(
699                    "FILES_MODIFIED".to_string(),
700                    entry.files_modified.join(", "),
701                );
702            }
703
704            let rendered = render_prompt_template(AGENT_MEMORY_ENTRY_TEMPLATE, entry_vars);
705            sections.push(rendered.trim().to_string());
706        }
707
708        let memory_section = sections.join("\n\n");
709        vars.insert("MEMORY_SECTION".to_string(), memory_section);
710    }
711
712    render_prompt_template(AGENT_MESSAGE_TEMPLATE, vars)
713}
714
715/// Build the review prompt for the review agent.
716///
717/// This is called when a task completes and the review agent needs to
718/// review the changes before auto-merge.
719pub fn build_review_prompt(
720    task: &crate::backends::ExternalTask,
721    agent_summary: &str,
722    git_diff: &str,
723    git_log: &str,
724    default_branch: &str,
725    pr_number: u64,
726    shipcheck: Shipcheck,
727) -> String {
728    let mut vars = HashMap::new();
729    shipcheck.insert_vars(&mut vars);
730    insert_cluster_vars(shipcheck, &mut vars);
731    vars.insert("TASK_ID".to_string(), task.id.0.clone());
732    vars.insert("TASK_TITLE".to_string(), task.title.clone());
733    vars.insert("TASK_BODY".to_string(), task.body.clone());
734    vars.insert("DEFAULT_BRANCH".to_string(), default_branch.to_string());
735    vars.insert("PR_NUMBER".to_string(), pr_number.to_string());
736
737    if !agent_summary.is_empty() {
738        vars.insert("AGENT_SUMMARY".to_string(), agent_summary.to_string());
739    }
740
741    if !git_diff.is_empty() {
742        vars.insert("GIT_DIFF".to_string(), git_diff.to_string());
743    }
744
745    if !git_log.is_empty() {
746        vars.insert("GIT_LOG".to_string(), git_log.to_string());
747    }
748
749    render_prompt_template(REVIEW_PROMPT_TEMPLATE, vars)
750}
751
752/// Build the runner shell script contents for testing and inspection.
753///
754/// IMPORTANT: this must not embed secrets (GH_TOKEN) into the script.
755#[allow(dead_code)]
756pub fn build_runner_script(inv: &AgentInvocation) -> anyhow::Result<String> {
757    // Prepare attempt directory and prompt files
758    let attempt_dir = crate::home::task_attempt_dir(&inv.repo, &inv.task_id, inv.attempt)?;
759    std::fs::create_dir_all(&attempt_dir)?;
760
761    let sys_file = attempt_dir.join("prompt-sys.md");
762    let msg_file = attempt_dir.join("prompt-msg.md");
763    std::fs::write(&sys_file, &inv.system_prompt)?;
764    std::fs::write(&msg_file, &inv.agent_message)?;
765
766    build_runner_script_in_dir(inv, &attempt_dir)
767}
768
769/// Inner script builder given a pre-created attempt directory.
770/// Separated from `build_runner_script` so tests can pass a temp dir and
771/// avoid racing with the parallel binary/lib test that shares `~/.orch/state/`.
772fn build_runner_script_in_dir(
773    inv: &AgentInvocation,
774    attempt_dir: &std::path::Path,
775) -> anyhow::Result<String> {
776    let sys_file = attempt_dir.join("prompt-sys.md");
777    let msg_file = attempt_dir.join("prompt-msg.md");
778
779    // Build unified permission rules and sys content (minimal translation)
780    let mut permissions = super::agents::PermissionRules::from_config();
781    if !inv.disallowed_tools.is_empty() {
782        for tool in &inv.disallowed_tools {
783            if !permissions.disallowed_tools.contains(tool) {
784                permissions.disallowed_tools.push(tool.clone());
785            }
786        }
787    }
788    permissions.allowed_edit_paths.push(inv.work_dir.clone());
789
790    // Build agent command using per-agent runner
791    let runner = super::agents::get_runner(&inv.agent);
792    let timeout_cmd = if inv.timeout_seconds > 0 {
793        format!("timeout {}", inv.timeout_seconds)
794    } else {
795        String::new()
796    };
797    let agent_cmd = runner.build_command(
798        inv.model.as_deref(),
799        &timeout_cmd,
800        &sys_file.to_string_lossy(),
801        &msg_file.to_string_lossy(),
802        &permissions,
803    );
804
805    let status_file = attempt_dir.join("exit.txt");
806    let stderr_file = attempt_dir.join("stderr.txt");
807
808    let sq_status = shell_single_quote(&status_file.display().to_string());
809    let sq_stderr = shell_single_quote(&stderr_file.display().to_string());
810    let sq_out = shell_single_quote(&inv.output_file.display().to_string());
811    let sq_work_dir = shell_single_quote(&inv.work_dir.to_string_lossy());
812    let script = format!(
813        "#!/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",
814        agent_cmd = agent_cmd,
815    );
816
817    Ok(script)
818}
819
820/// Build the system prompt for the review agent.
821pub fn review_system_prompt() -> String {
822    render_prompt_template(REVIEW_SYSTEM_TEMPLATE, HashMap::new())
823}
824
825#[cfg(test)]
826mod tests {
827    use super::*;
828    use std::path::PathBuf;
829
830    #[test]
831    fn review_system_prompt_checks_stray_files_and_trust_boundaries() {
832        let p = review_system_prompt();
833        assert!(p.contains("**Files**"));
834        assert!(p.contains("**Trust boundaries**"));
835    }
836
837    fn test_invocation(task_id: &str) -> AgentInvocation {
838        AgentInvocation {
839            agent: "claude".to_string(),
840            model: None,
841            work_dir: PathBuf::from("/tmp"),
842            system_prompt: "test system prompt".to_string(),
843            agent_message: "test message".to_string(),
844            task_id: task_id.to_string(),
845            disallowed_tools: vec![],
846            git_author_name: "Test Bot".to_string(),
847            git_author_email: "bot@example.com".to_string(),
848            output_file: PathBuf::from("/tmp/test-output.json"),
849            timeout_seconds: 0,
850            repo: "orch-runner-test/token-check".to_string(),
851            attempt: 1,
852            sandbox: false,
853            main_project_dir: std::path::PathBuf::from("/tmp"),
854        }
855    }
856
857    #[test]
858    fn spawn_in_tmux_rejects_invalid_env() {
859        // This test verifies the function signature and basic behavior
860        // without actually spawning a tmux session.
861        // The key security guarantee: tokens are passed via tmux -e flag,
862        // not written to any file on disk.
863        let inv = test_invocation("env-test");
864        // Just verify the invocation can be created without panicking
865        assert_eq!(inv.task_id, "env-test");
866    }
867
868    #[test]
869    fn build_runner_script_persists_exit_status_on_failure() {
870        // Use a temp dir so lib and bin compilation units don't race on ~/.orch/state/.
871        let tmp = tempfile::TempDir::new().expect("temp dir");
872        let inv = test_invocation("runner-status-test");
873        let script =
874            build_runner_script_in_dir(&inv, tmp.path()).expect("runner script should build");
875
876        assert!(script
877            .contains("trap 'status=$?; printf \"%s\\n\" \"$status\" > \"$status_file\"' EXIT"));
878        assert!(script.contains("set +e"));
879    }
880
881    #[test]
882    fn build_runner_script_reports_missing_worktree() {
883        // Use a temp dir so lib and bin compilation units don't race on ~/.orch/state/.
884        let tmp = tempfile::TempDir::new().expect("temp dir");
885        let inv = test_invocation("runner-missing-worktree-test");
886        let script =
887            build_runner_script_in_dir(&inv, tmp.path()).expect("runner script should build");
888
889        assert!(script.contains("worktree directory does not exist: '/tmp'"));
890        assert!(script.contains("stderr_file='"));
891    }
892
893    #[test]
894    fn tmux_runner_script_runs_agent_under_pty_not_a_plain_pipe() {
895        // Regression test for #3554: piping the agent binary's stdout straight
896        // into `tee` leaves it non-tty, which makes many CLI runtimes switch to
897        // full block-buffering and can starve the tmux pane long enough to trip
898        // silence detection even while the agent is actively working. The agent
899        // command must run under `script` (a real pty) before hitting `tee`.
900        let tmp = tempfile::TempDir::new().expect("temp dir");
901        let inv = test_invocation("pty-wrap-test");
902        let (runner_script, agent_cmd_script) =
903            build_tmux_runner_scripts(&inv, "echo hello", tmp.path(), None)
904                .expect("runner scripts should build");
905
906        assert!(
907            runner_script.contains("script -q /dev/null /bin/bash"),
908            "agent must be exec'd under a pty via `script`, got: {runner_script}"
909        );
910        assert!(
911            runner_script.contains("| tee"),
912            "output must still be tee'd to the output file, got: {runner_script}"
913        );
914        assert!(
915            !runner_script.contains("echo hello 2>"),
916            "the raw agent command must not be piped directly into tee anymore, got: {runner_script}"
917        );
918        assert!(
919            agent_cmd_script.contains("echo hello 2>"),
920            "the agent command should run (with stderr split to a file) inside the pty-wrapped helper script, got: {agent_cmd_script}"
921        );
922    }
923
924    #[test]
925    fn tmux_runner_script_captures_agent_exit_status_via_pipestatus() {
926        let tmp = tempfile::TempDir::new().expect("temp dir");
927        let inv = test_invocation("pty-exit-status-test");
928        let (runner_script, _) = build_tmux_runner_scripts(&inv, "echo hello", tmp.path(), None)
929            .expect("runner scripts should build");
930
931        assert!(runner_script.contains("CMD_STATUS=${PIPESTATUS[0]:-0}"));
932        assert!(runner_script.contains("exit $CMD_STATUS"));
933    }
934
935    #[test]
936    fn tmux_runner_script_disables_commit_signing() {
937        // Locked signing agent must not fail `git commit` inside agent sessions
938        let tmp = tempfile::TempDir::new().expect("temp dir");
939        let inv = test_invocation("gpgsign-test");
940        let (runner_script, _) = build_tmux_runner_scripts(&inv, "echo hello", tmp.path(), None)
941            .expect("runner scripts should build");
942
943        assert!(runner_script.contains("GIT_CONFIG_KEY_0=\"commit.gpgsign\""));
944        assert!(runner_script.contains("GIT_CONFIG_VALUE_0=\"false\""));
945    }
946
947    #[test]
948    fn tmux_runner_script_writes_executable_agent_cmd_helper() {
949        let tmp = tempfile::TempDir::new().expect("temp dir");
950        let inv = test_invocation("pty-helper-path-test");
951        let (runner_script, agent_cmd_script) =
952            build_tmux_runner_scripts(&inv, "echo hello", tmp.path(), None)
953                .expect("runner scripts should build");
954
955        let agent_cmd_script_path = tmp.path().join("agent_cmd.sh");
956        assert!(
957            runner_script.contains(&agent_cmd_script_path.display().to_string()),
958            "runner script must reference the agent_cmd.sh helper path, got: {runner_script}"
959        );
960        assert!(agent_cmd_script.starts_with("#!/usr/bin/env bash\n"));
961    }
962
963    #[test]
964    fn tmux_runner_script_runs_the_agent_inside_the_sandbox() {
965        let tmp = tempfile::TempDir::new().expect("temp dir");
966        let inv = test_invocation("sandbox-test");
967        let argv: Vec<std::ffi::OsString> = vec![
968            "/usr/bin/sandbox-exec".into(),
969            "-p".into(),
970            "(version 1)".into(),
971        ];
972        let (_, agent_cmd_script) =
973            build_tmux_runner_scripts(&inv, "claude -p 'hi'", tmp.path(), Some(&argv))
974                .expect("runner scripts should build");
975        assert!(
976            agent_cmd_script.contains(
977                "'/usr/bin/sandbox-exec' '-p' '(version 1)' /bin/bash -c 'claude -p '\\''hi'\\''' 2>"
978            ),
979            "the agent must run inside the sandbox with stderr split outside it, got: {agent_cmd_script}"
980        );
981    }
982
983    #[test]
984    fn a_sandboxed_prompt_offers_no_shipcheck() {
985        assert_eq!(Shipcheck::Available.for_prompt(true), Shipcheck::Absent);
986        assert_eq!(Shipcheck::Available.for_prompt(false), Shipcheck::Available);
987        assert_eq!(
988            Shipcheck::NotInstalled.for_prompt(true),
989            Shipcheck::NotInstalled
990        );
991    }
992
993    #[test]
994    fn build_runner_script_escapes_shell_injection_in_paths() {
995        let tmp = tempfile::TempDir::new().expect("temp dir");
996        let mut inv = test_invocation("injection-test");
997        inv.work_dir = std::path::PathBuf::from("/tmp/$(whoami)/workspace");
998        inv.output_file = std::path::PathBuf::from("/tmp/evil`id`.json");
999        let script =
1000            build_runner_script_in_dir(&inv, tmp.path()).expect("runner script should build");
1001
1002        // Values must be single-quoted, neutralizing $() and backticks
1003        assert!(
1004            script.contains("'/tmp/$(whoami)/workspace'"),
1005            "work_dir with $() must be single-quoted: {script}"
1006        );
1007        assert!(
1008            script.contains("'/tmp/evil`id`.json'"),
1009            "output_file with backticks must be single-quoted: {script}"
1010        );
1011    }
1012
1013    #[test]
1014    fn review_prompt_forbids_ending_turn_on_pending_ci_status() {
1015        // Regression test for #3453: a review agent must not stop with a
1016        // prose "CI is still running" status update and leave the turn
1017        // without JSON. The prompt must explicitly route PENDING/NOT RUN CI
1018        // through the local-checks fallback and into the same-turn JSON output.
1019        let task = crate::backends::ExternalTask {
1020            id: crate::backends::ExternalId("155460".to_string()),
1021            title: "test task".to_string(),
1022            body: "test body".to_string(),
1023            state: "open".to_string(),
1024            labels: vec![],
1025            author: "tester".to_string(),
1026            created_at: "2026-01-01T00:00:00Z".to_string(),
1027            updated_at: "2026-01-01T00:00:00Z".to_string(),
1028            url: "https://example.com/1".to_string(),
1029        };
1030        let prompt = build_review_prompt(&task, "", "", "", "main", 1, Shipcheck::Absent);
1031
1032        assert!(
1033            prompt.contains("Pending CI is never a terminal review state"),
1034            "prompt must state pending CI is not terminal: {prompt}"
1035        );
1036        assert!(
1037            prompt.contains("Never end your turn with a CI-waiting status update"),
1038            "prompt must forbid ending the turn on a CI-waiting status update: {prompt}"
1039        );
1040    }
1041
1042    #[test]
1043    fn shell_single_quote_escapes_embedded_quotes() {
1044        use crate::engine::runner::agents::shell_single_quote;
1045
1046        assert_eq!(shell_single_quote("hello"), "'hello'");
1047        assert_eq!(shell_single_quote("O'Brien"), "'O'\\''Brien'");
1048        assert_eq!(shell_single_quote("$(rm -rf /)"), "'$(rm -rf /)'");
1049        assert_eq!(shell_single_quote("`whoami`"), "'`whoami`'");
1050        assert_eq!(shell_single_quote("a\"b"), "'a\"b'");
1051        assert_eq!(shell_single_quote("$HOME"), "'$HOME'");
1052    }
1053
1054    fn git_init(dir: &std::path::Path) {
1055        let out = std::process::Command::new("git")
1056            .args(["init", "-q"])
1057            .current_dir(dir)
1058            .output()
1059            .unwrap();
1060        assert!(out.status.success());
1061    }
1062
1063    #[tokio::test]
1064    async fn install_shipcheck_rule_writes_rule_and_keeps_tree_clean() {
1065        let dir = tempfile::tempdir().unwrap();
1066        git_init(dir.path());
1067
1068        install_shipcheck_rule(dir.path()).await.unwrap();
1069        install_shipcheck_rule(dir.path()).await.unwrap();
1070
1071        let rule = std::fs::read_to_string(dir.path().join(SHIPCHECK_RULE_PATH)).unwrap();
1072        assert_eq!(rule, SHIPCHECK_RULES);
1073        for cmd in ["run", "commit", "status", "logs", "doctor"] {
1074            assert!(
1075                rule.contains(&format!(r#"["shipcheck", "{cmd}"]"#)),
1076                "{cmd}"
1077            );
1078        }
1079        assert!(!rule.contains(r#"["shipcheck"]"#));
1080        for cmd in [
1081            "clean", "post", "login", "logout", "daemon", "init", "install",
1082        ] {
1083            assert!(!rule.contains(&format!(r#""{cmd}""#)), "{cmd}");
1084        }
1085
1086        let exclude = std::fs::read_to_string(dir.path().join(".git/info/exclude")).unwrap();
1087        assert_eq!(exclude.matches("orch-shipcheck.rules").count(), 1);
1088        let status = std::process::Command::new("git")
1089            .args(["status", "--porcelain", "--untracked-files=all"])
1090            .current_dir(dir.path())
1091            .output()
1092            .unwrap();
1093        assert!(status.stdout.is_empty(), "{:?}", status);
1094    }
1095
1096    #[tokio::test]
1097    async fn install_shipcheck_rule_refuses_symlinked_dirs() {
1098        for link in [".codex", ".codex/rules"] {
1099            let dir = tempfile::tempdir().unwrap();
1100            let target = tempfile::tempdir().unwrap();
1101            git_init(dir.path());
1102            std::fs::create_dir_all(dir.path().join(".codex")).unwrap();
1103            if link == ".codex" {
1104                std::fs::remove_dir(dir.path().join(".codex")).unwrap();
1105            }
1106            std::os::unix::fs::symlink(target.path(), dir.path().join(link)).unwrap();
1107
1108            assert!(install_shipcheck_rule(dir.path()).await.is_err(), "{link}");
1109            assert_eq!(
1110                std::fs::read_dir(target.path()).unwrap().count(),
1111                0,
1112                "{link}"
1113            );
1114        }
1115    }
1116
1117    #[tokio::test]
1118    async fn install_shipcheck_rule_replaces_a_symlinked_file_without_following_it() {
1119        let dir = tempfile::tempdir().unwrap();
1120        let target = tempfile::tempdir().unwrap();
1121        let outside = target.path().join("victim");
1122        std::fs::write(&outside, "keep").unwrap();
1123        git_init(dir.path());
1124        std::fs::create_dir_all(dir.path().join(".codex/rules")).unwrap();
1125        std::os::unix::fs::symlink(&outside, dir.path().join(SHIPCHECK_RULE_PATH)).unwrap();
1126
1127        install_shipcheck_rule(dir.path()).await.unwrap();
1128
1129        assert_eq!(std::fs::read_to_string(&outside).unwrap(), "keep");
1130        let meta = std::fs::symlink_metadata(dir.path().join(SHIPCHECK_RULE_PATH)).unwrap();
1131        assert!(meta.is_file());
1132    }
1133
1134    fn prompt_task() -> crate::backends::ExternalTask {
1135        crate::backends::ExternalTask {
1136            id: crate::backends::ExternalId("1".to_string()),
1137            title: "t".to_string(),
1138            body: "b".to_string(),
1139            state: "open".to_string(),
1140            labels: vec![],
1141            author: "a".to_string(),
1142            created_at: "2026-01-01T00:00:00Z".to_string(),
1143            updated_at: "2026-01-01T00:00:00Z".to_string(),
1144            url: "https://example.com/1".to_string(),
1145        }
1146    }
1147
1148    #[test]
1149    fn system_prompt_uses_shipcheck_only_when_available() {
1150        let ctx = super::super::context::TaskContext::default();
1151        let task = prompt_task();
1152        let prompt = |s| build_system_prompt(&task, &ctx, None, "main", s);
1153
1154        let available = prompt(Shipcheck::Available);
1155        assert!(available.contains("shipcheck run"));
1156        assert!(available.contains("shipcheck commit"));
1157        assert!(!available.contains(".github/workflows/"));
1158        assert!(!available.contains("not installed"));
1159
1160        let outdated = prompt(Shipcheck::Outdated);
1161        assert!(!outdated.contains("shipcheck"));
1162        assert!(outdated.contains(".github/workflows/"));
1163
1164        let missing = prompt(Shipcheck::NotInstalled);
1165        assert!(!missing.contains("shipcheck run"));
1166        assert!(missing.contains(".github/workflows/"));
1167        assert!(missing.contains("shipcheck is not installed"));
1168
1169        let absent = prompt(Shipcheck::Absent);
1170        assert!(!absent.contains("shipcheck"));
1171        assert!(absent.contains(".github/workflows/"));
1172
1173        for p in [&available, &outdated, &missing, &absent] {
1174            assert!(!p.contains("{{"), "{p}");
1175            assert!(!p.contains("install shipcheck"), "{p}");
1176        }
1177    }
1178
1179    #[test]
1180    fn review_prompt_uses_shipcheck_only_when_available() {
1181        let task = prompt_task();
1182        let prompt = |s| build_review_prompt(&task, "", "", "", "main", 1, s);
1183        assert!(prompt(Shipcheck::Available).contains("shipcheck run"));
1184        for s in [
1185            Shipcheck::Outdated,
1186            Shipcheck::NotInstalled,
1187            Shipcheck::Absent,
1188        ] {
1189            let p = prompt(s);
1190            assert!(!p.contains("shipcheck"), "{p}");
1191            assert!(p.contains(".github/workflows/"), "{p}");
1192        }
1193    }
1194
1195    #[test]
1196    fn shipcheck_classify_needs_config_and_commit() {
1197        assert_eq!(Shipcheck::classify(false, Some(true)), Shipcheck::Absent);
1198        assert_eq!(Shipcheck::classify(false, None), Shipcheck::Absent);
1199        assert_eq!(Shipcheck::classify(true, None), Shipcheck::NotInstalled);
1200        assert_eq!(Shipcheck::classify(true, Some(false)), Shipcheck::Outdated);
1201        assert_eq!(Shipcheck::classify(true, Some(true)), Shipcheck::Available);
1202    }
1203
1204    #[tokio::test]
1205    async fn supports_reads_the_usage_line() {
1206        let new_dir = tempfile::tempdir().unwrap();
1207        let new = fake_shipcheck(new_dir.path(), true, true);
1208        assert!(supports(&new, "commit").await);
1209        assert!(supports(&new, "hook").await);
1210        let old_dir = tempfile::tempdir().unwrap();
1211        let old = fake_shipcheck(old_dir.path(), false, false);
1212        assert!(!supports(&old, "commit").await);
1213        assert!(!supports(&old, "hook").await);
1214        let missing = old_dir.path().join("missing");
1215        assert!(!supports(&missing, "commit").await);
1216    }
1217
1218    // Mimics shipcheck, whose `--help` prints usage and exits 0 after any subcommand
1219    fn fake_shipcheck(dir: &std::path::Path, commit: bool, hook: bool) -> PathBuf {
1220        use std::os::unix::fs::PermissionsExt;
1221        let mut usage = "usage: shipcheck run [--sha <rev>] | status | logs".to_string();
1222        if commit {
1223            usage.push_str(" | commit -m <message>");
1224        }
1225        if hook {
1226            usage.push_str(" | hook");
1227        }
1228        usage.push_str(" | install | doctor");
1229        let bin = dir.join("shipcheck");
1230        std::fs::write(
1231            &bin,
1232            format!(
1233                "#!/bin/sh\nfor a in \"$@\"; do [ \"$a\" = --help ] && {{ echo '{usage}'; exit 0; }}; done\n[ \"$1\" = install ] && touch installed\nexit 0\n"
1234            ),
1235        )
1236        .unwrap();
1237        std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755)).unwrap();
1238        bin
1239    }
1240
1241    #[tokio::test]
1242    async fn install_shipcheck_hooks_runs_install_when_supported() {
1243        let bin_dir = tempfile::tempdir().unwrap();
1244        let work = tempfile::tempdir().unwrap();
1245        let bin = fake_shipcheck(bin_dir.path(), true, true);
1246        assert!(install_shipcheck_hooks(work.path(), Shipcheck::Available, &bin).await);
1247        assert!(work.path().join("installed").exists());
1248    }
1249
1250    #[tokio::test]
1251    async fn install_shipcheck_hooks_skips_a_shipcheck_without_hook() {
1252        let bin_dir = tempfile::tempdir().unwrap();
1253        let work = tempfile::tempdir().unwrap();
1254        let bin = fake_shipcheck(bin_dir.path(), true, false);
1255        assert!(!install_shipcheck_hooks(work.path(), Shipcheck::Available, &bin).await);
1256        assert!(!work.path().join("installed").exists());
1257    }
1258
1259    #[tokio::test]
1260    async fn install_shipcheck_hooks_skips_when_not_available() {
1261        let bin_dir = tempfile::tempdir().unwrap();
1262        let work = tempfile::tempdir().unwrap();
1263        let bin = fake_shipcheck(bin_dir.path(), true, true);
1264        for s in [
1265            Shipcheck::Outdated,
1266            Shipcheck::NotInstalled,
1267            Shipcheck::Absent,
1268        ] {
1269            assert!(!install_shipcheck_hooks(work.path(), s, &bin).await);
1270        }
1271        assert!(!work.path().join("installed").exists());
1272    }
1273
1274    #[test]
1275    fn the_progress_step_appears_only_in_cluster_mode() {
1276        let mut vars = HashMap::new();
1277        insert_cluster_vars(Shipcheck::Available, &mut vars);
1278        assert!(vars.is_empty(), "no cluster section, no cluster flags");
1279        let plain = crate::template::render_template_str(AGENT_SYSTEM_TEMPLATE, &vars).unwrap();
1280        assert!(!plain.contains("orch progress"));
1281
1282        for flag in ["CLUSTER", "CLUSTER_SHIPCHECK"] {
1283            vars.insert(flag.to_string(), "1".to_string());
1284        }
1285        let cluster = crate::template::render_template_str(AGENT_SYSTEM_TEMPLATE, &vars).unwrap();
1286        assert!(cluster.contains("orch progress"));
1287        assert!(cluster.contains("commits only through `shipcheck commit`"));
1288        assert!(!cluster.contains("It commits anything you left"));
1289    }
1290}