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