1use std::collections::HashMap;
4use std::env;
5use std::io::ErrorKind;
6#[cfg(unix)]
7use std::path::Path;
8use std::process::Output;
9use std::process::Stdio;
10use std::time::Duration;
11use tokio::fs;
12use tokio::fs::OpenOptions;
13use tokio::io::AsyncWriteExt;
14use tokio::process::Command;
15use tokio::sync::OnceCell;
16use tokio::time;
17
18#[derive(Clone, Copy, Debug, PartialEq, Eq)]
21pub enum Shipcheck {
22 Absent,
23 NotInstalled,
24 Outdated,
25 Available,
26}
27
28impl Shipcheck {
29 pub async fn detect(work_dir: &Path) -> Self {
30 static SUPPORTS_COMMIT: OnceCell<Option<bool>> = OnceCell::const_new();
31 let installed = SUPPORTS_COMMIT
32 .get_or_init(|| async {
33 let bin = which::which("shipcheck").ok()?;
34 Some(supports(&bin, "commit").await)
35 })
36 .await;
37 Self::classify(work_dir.join("shipcheck.toml").exists(), *installed)
38 }
39
40 fn classify(has_config: bool, supports_commit: Option<bool>) -> Self {
41 match (has_config, supports_commit) {
42 (false, _) => Shipcheck::Absent,
43 (true, None) => Shipcheck::NotInstalled,
44 (true, Some(false)) => Shipcheck::Outdated,
45 (true, Some(true)) => Shipcheck::Available,
46 }
47 }
48
49 #[must_use]
52 pub fn for_prompt(self, sandboxed: bool, hands_off: bool) -> Self {
53 if sandboxed && !hands_off && self == Shipcheck::Available {
54 return Shipcheck::Absent;
55 }
56
57 self
58 }
59
60 pub async fn in_sandbox(self, sandboxed: bool, work_dir: &Path) -> Self {
62 let hands_off = sandboxed && self == Shipcheck::Available && hands_off(work_dir).await;
63 self.for_prompt(sandboxed, hands_off)
64 }
65
66 pub(crate) fn insert_vars(self, vars: &mut HashMap<String, String>) {
67 let flags: &[&str] = match self {
68 Shipcheck::Available => &["SHIPCHECK"],
69 Shipcheck::NotInstalled => &["NO_SHIPCHECK", "SHIPCHECK_MISSING"],
70 Shipcheck::Absent | Shipcheck::Outdated => &["NO_SHIPCHECK"],
71 };
72 for flag in flags {
73 vars.insert(flag.to_string(), "1".to_string());
74 }
75 }
76}
77
78async fn run_shipcheck(bin: &Path, work_dir: &Path, args: &[&str]) -> anyhow::Result<Output> {
79 let output = Command::new(bin)
80 .args(args)
81 .current_dir(work_dir)
82 .stdin(Stdio::null())
83 .kill_on_drop(true)
84 .output();
85 Ok(time::timeout(Duration::from_secs(30), output).await??)
86}
87
88async fn hands_off(work_dir: &Path) -> bool {
90 let Ok(bin) = which::which("shipcheck") else {
91 return false;
92 };
93 run_shipcheck(&bin, work_dir, &["handoff"])
94 .await
95 .is_ok_and(|out| out.status.success())
96}
97
98pub(crate) async fn supports(bin: &Path, subcommand: &str) -> bool {
100 let Ok(out) = run_shipcheck(bin, &env::temp_dir(), &["--help"]).await else {
101 return false;
102 };
103 out.status.success()
104 && String::from_utf8_lossy(&out.stdout)
105 .split_whitespace()
106 .any(|word| word == subcommand)
107}
108
109pub async fn install_shipcheck_hooks(work_dir: &Path, shipcheck: Shipcheck, bin: &Path) -> bool {
112 if shipcheck != Shipcheck::Available {
113 return false;
114 }
115
116 if !supports(bin, "hook").await {
118 return false;
119 }
120
121 match run_shipcheck(bin, work_dir, &["install"]).await {
122 Ok(out) if out.status.success() => {}
123 Ok(out) => tracing::warn!(
124 work_dir = %work_dir.display(),
125 stderr = %String::from_utf8_lossy(&out.stderr),
126 "shipcheck install failed"
127 ),
128 Err(e) => tracing::warn!(
129 work_dir = %work_dir.display(),
130 error = %e,
131 "shipcheck install failed"
132 ),
133 }
134 true
135}
136
137const SHIPCHECK_RULE_PATH: &str = ".codex/rules/orch-shipcheck.rules";
138
139const SHIPCHECK_RULES: &str = r#"prefix_rule(pattern=["shipcheck", "run"], decision="allow")
141prefix_rule(pattern=["shipcheck", "commit"], decision="allow")
142prefix_rule(pattern=["shipcheck", "status"], decision="allow")
143prefix_rule(pattern=["shipcheck", "logs"], decision="allow")
144prefix_rule(pattern=["shipcheck", "doctor"], decision="allow")
145"#;
146
147pub(crate) async fn install_shipcheck_rule(work_dir: &Path) -> anyhow::Result<()> {
150 let mut dir = work_dir.to_path_buf();
152 for part in [".codex", "rules"] {
153 dir.push(part);
154 match fs::symlink_metadata(&dir).await {
155 Ok(meta) if meta.is_dir() => {}
156 Ok(_) => anyhow::bail!("{} is not a directory", dir.display()),
157 Err(e) if e.kind() == ErrorKind::NotFound => {
158 fs::create_dir(&dir).await?;
159 }
160 Err(e) => return Err(e.into()),
161 }
162 }
163
164 let rule = work_dir.join(SHIPCHECK_RULE_PATH);
166 match fs::remove_file(&rule).await {
167 Err(e) if e.kind() != ErrorKind::NotFound => return Err(e.into()),
168 _ => {}
169 }
170
171 let mut file = OpenOptions::new()
172 .write(true)
173 .create_new(true)
174 .open(&rule)
175 .await?;
176 AsyncWriteExt::write_all(&mut file, SHIPCHECK_RULES.as_bytes()).await?;
177
178 let output = Command::new("git")
180 .args(["rev-parse", "--git-path", "info/exclude"])
181 .current_dir(work_dir)
182 .output()
183 .await?;
184 if !output.status.success() {
185 return Ok(());
186 }
187
188 let exclude = work_dir.join(String::from_utf8_lossy(&output.stdout).trim());
189 let line = format!("/{SHIPCHECK_RULE_PATH}");
190 let current = fs::read_to_string(&exclude).await.unwrap_or_default();
191 if current.lines().any(|l| l == line) {
192 return Ok(());
193 }
194
195 if let Some(dir) = exclude.parent() {
196 fs::create_dir_all(dir).await?;
197 }
198
199 let sep = if current.is_empty() || current.ends_with('\n') {
200 ""
201 } else {
202 "\n"
203 };
204 fs::write(&exclude, format!("{current}{sep}{line}\n")).await?;
205 Ok(())
206}
207
208#[cfg(test)]
209mod tests {
210 use super::*;
211 use std::fs as std_fs;
212 use std::fs::Permissions;
213 use std::os::unix::fs as unix_fs;
214 use std::os::unix::fs::PermissionsExt;
215 use std::path::PathBuf;
216 use std::process;
217
218 fn git_init(dir: &Path) {
219 let out = process::Command::new("git")
220 .args(["init", "-q"])
221 .current_dir(dir)
222 .output()
223 .unwrap();
224 assert!(out.status.success());
225 }
226
227 #[tokio::test]
228 async fn install_shipcheck_rule_writes_rule_and_keeps_tree_clean() {
229 let dir = tempfile::tempdir().unwrap();
230 git_init(dir.path());
231
232 install_shipcheck_rule(dir.path()).await.unwrap();
233 install_shipcheck_rule(dir.path()).await.unwrap();
234
235 let rule = std_fs::read_to_string(dir.path().join(SHIPCHECK_RULE_PATH)).unwrap();
236 assert_eq!(rule, SHIPCHECK_RULES);
237 for cmd in ["run", "commit", "status", "logs", "doctor"] {
238 assert!(
239 rule.contains(&format!(r#"["shipcheck", "{cmd}"]"#)),
240 "{cmd}"
241 );
242 }
243 assert!(!rule.contains(r#"["shipcheck"]"#));
244 for cmd in [
245 "clean", "post", "login", "logout", "daemon", "init", "install",
246 ] {
247 assert!(!rule.contains(&format!(r#""{cmd}""#)), "{cmd}");
248 }
249
250 let exclude = std_fs::read_to_string(dir.path().join(".git/info/exclude")).unwrap();
251 assert_eq!(exclude.matches("orch-shipcheck.rules").count(), 1);
252 let status = process::Command::new("git")
253 .args(["status", "--porcelain", "--untracked-files=all"])
254 .current_dir(dir.path())
255 .output()
256 .unwrap();
257 assert!(status.stdout.is_empty(), "{status:?}");
258 }
259
260 #[tokio::test]
261 async fn install_shipcheck_rule_refuses_symlinked_dirs() {
262 for link in [".codex", ".codex/rules"] {
263 let dir = tempfile::tempdir().unwrap();
264 let target = tempfile::tempdir().unwrap();
265 git_init(dir.path());
266 std_fs::create_dir_all(dir.path().join(".codex")).unwrap();
267 if link == ".codex" {
268 std_fs::remove_dir(dir.path().join(".codex")).unwrap();
269 }
270 unix_fs::symlink(target.path(), dir.path().join(link)).unwrap();
271
272 assert!(install_shipcheck_rule(dir.path()).await.is_err(), "{link}");
273 assert_eq!(
274 std_fs::read_dir(target.path()).unwrap().count(),
275 0,
276 "{link}"
277 );
278 }
279 }
280
281 #[tokio::test]
282 async fn install_shipcheck_rule_replaces_a_symlinked_file_without_following_it() {
283 let dir = tempfile::tempdir().unwrap();
284 let target = tempfile::tempdir().unwrap();
285 let outside = target.path().join("victim");
286 std_fs::write(&outside, "keep").unwrap();
287 git_init(dir.path());
288 std_fs::create_dir_all(dir.path().join(".codex/rules")).unwrap();
289 unix_fs::symlink(&outside, dir.path().join(SHIPCHECK_RULE_PATH)).unwrap();
290
291 install_shipcheck_rule(dir.path()).await.unwrap();
292
293 assert_eq!(std_fs::read_to_string(&outside).unwrap(), "keep");
294 let meta = std_fs::symlink_metadata(dir.path().join(SHIPCHECK_RULE_PATH)).unwrap();
295 assert!(meta.is_file());
296 }
297
298 #[test]
299 fn shipcheck_classify_needs_config_and_commit() {
300 assert_eq!(Shipcheck::classify(false, Some(true)), Shipcheck::Absent);
301 assert_eq!(Shipcheck::classify(false, None), Shipcheck::Absent);
302 assert_eq!(Shipcheck::classify(true, None), Shipcheck::NotInstalled);
303 assert_eq!(Shipcheck::classify(true, Some(false)), Shipcheck::Outdated);
304 assert_eq!(Shipcheck::classify(true, Some(true)), Shipcheck::Available);
305 }
306
307 #[tokio::test]
308 async fn supports_reads_the_usage_line() {
309 let new_dir = tempfile::tempdir().unwrap();
310 let new = fake_shipcheck(new_dir.path(), true, true);
311 assert!(supports(&new, "commit").await);
312 assert!(supports(&new, "hook").await);
313 let old_dir = tempfile::tempdir().unwrap();
314 let old = fake_shipcheck(old_dir.path(), false, false);
315 assert!(!supports(&old, "commit").await);
316 assert!(!supports(&old, "hook").await);
317 let missing = old_dir.path().join("missing");
318 assert!(!supports(&missing, "commit").await);
319 }
320
321 fn fake_shipcheck(dir: &Path, commit: bool, hook: bool) -> PathBuf {
323 let mut usage = "usage: shipcheck run [--sha <rev>] | status | logs".to_string();
324 if commit {
325 usage.push_str(" | commit -m <message>");
326 }
327 if hook {
328 usage.push_str(" | hook");
329 }
330 usage.push_str(" | install | doctor");
331 let bin = dir.join("shipcheck");
332 std_fs::write(
333 &bin,
334 format!(
335 "#!/bin/sh\nfor a in \"$@\"; do [ \"$a\" = --help ] && {{ echo '{usage}'; exit 0; }}; done\n[ \"$1\" = install ] && touch installed\nexit 0\n"
336 ),
337 )
338 .unwrap();
339 std_fs::set_permissions(&bin, Permissions::from_mode(0o755)).unwrap();
340 bin
341 }
342
343 #[tokio::test]
344 async fn install_shipcheck_hooks_runs_install_when_supported() {
345 let bin_dir = tempfile::tempdir().unwrap();
346 let work = tempfile::tempdir().unwrap();
347 let bin = fake_shipcheck(bin_dir.path(), true, true);
348 assert!(install_shipcheck_hooks(work.path(), Shipcheck::Available, &bin).await);
349 assert!(work.path().join("installed").exists());
350 }
351
352 #[tokio::test]
353 async fn install_shipcheck_hooks_skips_a_shipcheck_without_hook() {
354 let bin_dir = tempfile::tempdir().unwrap();
355 let work = tempfile::tempdir().unwrap();
356 let bin = fake_shipcheck(bin_dir.path(), true, false);
357 assert!(!install_shipcheck_hooks(work.path(), Shipcheck::Available, &bin).await);
358 assert!(!work.path().join("installed").exists());
359 }
360
361 #[tokio::test]
362 async fn install_shipcheck_hooks_skips_when_not_available() {
363 let bin_dir = tempfile::tempdir().unwrap();
364 let work = tempfile::tempdir().unwrap();
365 let bin = fake_shipcheck(bin_dir.path(), true, true);
366 for s in [
367 Shipcheck::Outdated,
368 Shipcheck::NotInstalled,
369 Shipcheck::Absent,
370 ] {
371 assert!(!install_shipcheck_hooks(work.path(), s, &bin).await);
372 }
373 assert!(!work.path().join("installed").exists());
374 }
375}