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