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