返回 CodeWhale
worktree.rs
根目录 / crates / lane / src / worktree.rs
1 //! Worktree provisioning owned by Runtime (not Fleet) — #4176 / #4016.
2
3 use std::fs;
4 use std::io::Read;
5 use std::path::{Path, PathBuf};
6 use std::process::Command;
7 use std::sync::OnceLock;
8 use std::time::{SystemTime, UNIX_EPOCH};
9
10 use anyhow::{Context, Result, bail};
11 use chrono::DateTime;
12
13 pub type GitCommandFn = fn(&Path) -> Result<Command>;
14
15 static GIT_COMMAND: OnceLock<GitCommandFn> = OnceLock::new();
16
17 pub fn set_git_command(constructor: GitCommandFn) {
18 let _ = GIT_COMMAND.set(constructor);
19 }
20
21 fn git_command(dir: &Path) -> Result<Command> {
22 #[cfg(test)]
23 let constructor = GIT_COMMAND.get_or_init(|| tests::plain_git_command);
24 #[cfg(not(test))]
25 let constructor = GIT_COMMAND
26 .get()
27 .context("no git command was configured for lane worktrees")?;
28 constructor(dir)
29 }
30
31 /// Spec for an isolated worktree + branch for a lane.
32 #[derive(Debug, Clone)]
33 pub struct WorktreeProvision {
34 /// Git repository root (must contain `.git`).
35 pub repo_root: PathBuf,
36 /// Branch to create (from `base_ref`).
37 pub branch: String,
38 /// Directory for the new worktree (created by `git worktree add`).
39 pub path: PathBuf,
40 /// Base ref to branch from (default `HEAD`).
41 pub base_ref: Option<String>,
42 }
43
44 #[derive(Debug, Clone)]
45 pub struct ProvisionedWorktree {
46 pub path: PathBuf,
47 pub branch: String,
48 }
49
50 const MAX_WORKTREE_MANIFEST_BYTES: u64 = 64 * 1024;
51 const MAX_WORKTREE_SETUP_COMMANDS: usize = 64;
52 const MAX_SETUP_OUTPUT_SNIPPET_CHARS: usize = 240;
53
54 #[derive(Debug, Default, PartialEq, Eq)]
55 struct WorktreeSetupManifest {
56 setup: Vec<String>,
57 setup_unix: Vec<String>,
58 setup_windows: Vec<String>,
59 }
60
61 impl WorktreeSetupManifest {
62 fn commands_for_platform(&self, is_windows: bool) -> Vec<String> {
63 let mut out = self.setup.clone();
64 if is_windows {
65 out.extend(self.setup_windows.iter().cloned());
66 } else {
67 out.extend(self.setup_unix.iter().cloned());
68 }
69 out
70 }
71 }
72
73 impl WorktreeProvision {
74 pub fn run_setup(
75 repo_root: &Path,
76 worktree_path: &Path,
77 trusted: bool,
78 ) -> Result<Option<String>> {
79 run_worktree_setup(repo_root, worktree_path, trusted)
80 }
81 }
82
83 impl ProvisionedWorktree {
84 pub fn run_setup(&self, repo_root: &Path, trusted: bool) -> Result<Option<String>> {
85 run_worktree_setup(repo_root, &self.path, trusted)
86 }
87 }
88
89 fn run_worktree_setup(
90 repo_root: &Path,
91 worktree_path: &Path,
92 trusted: bool,
93 ) -> Result<Option<String>> {
94 let manifest_path = repo_root.join(".codewhale").join("worktrees.toml");
95 reject_linked_below(repo_root, &manifest_path)?;
96 let metadata = match fs::symlink_metadata(&manifest_path) {
97 Ok(meta) => meta,
98 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
99 Err(error) => {
100 return Err(error).with_context(|| format!("inspect {}", manifest_path.display()));
101 }
102 };
103 if metadata.file_type().is_symlink() {
104 bail!(
105 "refusing to read linked worktree manifest {}",
106 manifest_path.display()
107 );
108 }
109 if !metadata.is_file() {
110 bail!(
111 "worktree manifest is not a regular file: {}",
112 manifest_path.display()
113 );
114 }
115 if metadata.len() > MAX_WORKTREE_MANIFEST_BYTES {
116 bail!(
117 ".codewhale/worktrees.toml exceeds maximum size of {MAX_WORKTREE_MANIFEST_BYTES} bytes"
118 );
119 }
120 if !trusted {
121 return Ok(Some(
122 "Skipped .codewhale/worktrees.toml setup: repository is untrusted".to_string(),
123 ));
124 }
125 let file = fs::File::open(&manifest_path)
126 .with_context(|| format!("open {}", manifest_path.display()))?;
127 let mut bytes = Vec::new();
128 file.take(MAX_WORKTREE_MANIFEST_BYTES + 1)
129 .read_to_end(&mut bytes)
130 .with_context(|| format!("read {}", manifest_path.display()))?;
131 if bytes.len() as u64 > MAX_WORKTREE_MANIFEST_BYTES {
132 bail!(
133 ".codewhale/worktrees.toml exceeds maximum size of {MAX_WORKTREE_MANIFEST_BYTES} bytes"
134 );
135 }
136 let raw = String::from_utf8(bytes).context("parse .codewhale/worktrees.toml as UTF-8")?;
137 let manifest = parse_worktree_manifest(&raw)?;
138 let commands = manifest.commands_for_platform(cfg!(windows));
139 if commands.is_empty() {
140 return Ok(None);
141 }
142 let mut last_output = String::new();
143 for cmd in &commands {
144 let snippet = execute_setup_command(repo_root, worktree_path, cmd)?;
145 if !snippet.is_empty() {
146 last_output = snippet;
147 }
148 }
149 if last_output.is_empty() {
150 Ok(Some(format!(
151 "Ran {} setup command(s) from .codewhale/worktrees.toml",
152 commands.len()
153 )))
154 } else {
155 Ok(Some(format!(
156 "Ran {} setup command(s) from .codewhale/worktrees.toml ({last_output})",
157 commands.len()
158 )))
159 }
160 }
161
162 fn execute_setup_command(repo_root: &Path, worktree_path: &Path, cmd: &str) -> Result<String> {
163 #[cfg(windows)]
164 let mut command = {
165 let mut c = Command::new("cmd");
166 c.args(["/C", cmd]);
167 c
168 };
169 #[cfg(not(windows))]
170 let mut command = {
171 let mut c = Command::new("sh");
172 c.args(["-c", cmd]);
173 c
174 };
175 let output = command
176 .current_dir(worktree_path)
177 .env("CODEWHALE_REPO_ROOT", repo_root)
178 .env("CODEWHALE_WORKTREE_PATH", worktree_path)
179 .output()
180 .with_context(|| format!("run worktree setup command `{cmd}`"))?;
181 let stdout = String::from_utf8_lossy(&output.stdout);
182 let stderr = String::from_utf8_lossy(&output.stderr);
183 if !output.status.success() {
184 let detail = compact_output_snippet(&stderr)
185 .or_else(|| compact_output_snippet(&stdout))
186 .unwrap_or_default();
187 bail!(
188 "worktree setup command `{cmd}` failed ({}){}{}",
189 output.status,
190 if detail.is_empty() { "" } else { ": " },
191 detail
192 );
193 }
194 Ok(compact_output_snippet(&stdout)
195 .or_else(|| compact_output_snippet(&stderr))
196 .unwrap_or_default())
197 }
198
199 fn compact_output_snippet(raw: &str) -> Option<String> {
200 let line = raw
201 .lines()
202 .rev()
203 .map(str::trim)
204 .find(|line| !line.is_empty())?;
205 let mut out = String::new();
206 for ch in line.chars() {
207 if ch.is_control() {
208 continue;
209 }
210 if out.chars().count() >= MAX_SETUP_OUTPUT_SNIPPET_CHARS {
211 out.push_str("...");
212 break;
213 }
214 out.push(ch);
215 }
216 if out.is_empty() { None } else { Some(out) }
217 }
218
219 fn parse_worktree_manifest(raw: &str) -> Result<WorktreeSetupManifest> {
220 let input = raw.strip_prefix('\u{feff}').unwrap_or(raw);
221 let bytes = input.as_bytes();
222 let mut pos = 0usize;
223 let mut manifest = WorktreeSetupManifest::default();
224 let mut seen_setup = false;
225 let mut seen_unix = false;
226 let mut seen_windows = false;
227 let mut total_commands = 0usize;
228
229 loop {
230 skip_ws_and_comments(bytes, &mut pos);
231 if pos >= bytes.len() {
232 break;
233 }
234 let key_start = pos;
235 while pos < bytes.len()
236 && (bytes[pos].is_ascii_alphanumeric() || bytes[pos] == b'_' || bytes[pos] == b'-')
237 {
238 pos += 1;
239 }
240 if pos == key_start {
241 bail!("invalid syntax in .codewhale/worktrees.toml near byte {pos}");
242 }
243 let key = &input[key_start..pos];
244 skip_inline_ws(bytes, &mut pos);
245 if pos >= bytes.len() || bytes[pos] != b'=' {
246 bail!("expected '=' after key '{key}' in .codewhale/worktrees.toml");
247 }
248 pos += 1;
249 skip_inline_ws(bytes, &mut pos);
250 let list = parse_toml_string_array(input, &mut pos, key)?;
251 total_commands = total_commands.saturating_add(list.len());
252 if total_commands > MAX_WORKTREE_SETUP_COMMANDS {
253 bail!(
254 ".codewhale/worktrees.toml exceeds maximum of {MAX_WORKTREE_SETUP_COMMANDS} commands"
255 );
256 }
257 match key {
258 "setup" => {
259 if seen_setup {
260 bail!("duplicate key 'setup' in .codewhale/worktrees.toml");
261 }
262 seen_setup = true;
263 manifest.setup = list;
264 }
265 "setup_unix" => {
266 if seen_unix {
267 bail!("duplicate key 'setup_unix' in .codewhale/worktrees.toml");
268 }
269 seen_unix = true;
270 manifest.setup_unix = list;
271 }
272 "setup_windows" => {
273 if seen_windows {
274 bail!("duplicate key 'setup_windows' in .codewhale/worktrees.toml");
275 }
276 seen_windows = true;
277 manifest.setup_windows = list;
278 }
279 other => {
280 bail!("unknown key '{other}' in .codewhale/worktrees.toml");
281 }
282 }
283 skip_inline_ws(bytes, &mut pos);
284 if pos < bytes.len() && bytes[pos] == b'#' {
285 while pos < bytes.len() && bytes[pos] != b'\n' {
286 pos += 1;
287 }
288 }
289 if pos < bytes.len() {
290 if bytes[pos] == b'\r' {
291 pos += 1;
292 }
293 if pos < bytes.len() && bytes[pos] == b'\n' {
294 pos += 1;
295 } else if pos < bytes.len() {
296 bail!("unexpected trailing token after '{key}' in .codewhale/worktrees.toml");
297 }
298 }
299 }
300
301 Ok(manifest)
302 }
303
304 fn skip_inline_ws(bytes: &[u8], pos: &mut usize) {
305 while *pos < bytes.len() && matches!(bytes[*pos], b' ' | b'\t') {
306 *pos += 1;
307 }
308 }
309
310 fn skip_ws_and_comments(bytes: &[u8], pos: &mut usize) {
311 loop {
312 while *pos < bytes.len() && matches!(bytes[*pos], b' ' | b'\t' | b'\r' | b'\n') {
313 *pos += 1;
314 }
315 if *pos < bytes.len() && bytes[*pos] == b'#' {
316 while *pos < bytes.len() && bytes[*pos] != b'\n' {
317 *pos += 1;
318 }
319 } else {
320 break;
321 }
322 }
323 }
324
325 fn parse_toml_string_array(input: &str, pos: &mut usize, key: &str) -> Result<Vec<String>> {
326 let bytes = input.as_bytes();
327 if *pos >= bytes.len() || bytes[*pos] != b'[' {
328 bail!("expected array for '{key}' in .codewhale/worktrees.toml");
329 }
330 *pos += 1;
331 let mut items = Vec::new();
332 loop {
333 skip_ws_and_comments(bytes, pos);
334 if *pos >= bytes.len() {
335 bail!("unterminated array for '{key}' in .codewhale/worktrees.toml");
336 }
337 if bytes[*pos] == b']' {
338 *pos += 1;
339 break;
340 }
341 let item = match bytes[*pos] {
342 b'"' => parse_toml_basic_string(input, pos, key)?,
343 b'\'' => parse_toml_literal_string(input, pos, key)?,
344 _ => bail!("expected string element in '{key}' array in .codewhale/worktrees.toml"),
345 };
346 if item.trim().is_empty() || item.contains('\0') {
347 bail!("invalid empty or NUL command in '{key}' in .codewhale/worktrees.toml");
348 }
349 items.push(item);
350 if items.len() > MAX_WORKTREE_SETUP_COMMANDS {
351 bail!(
352 ".codewhale/worktrees.toml exceeds maximum of {MAX_WORKTREE_SETUP_COMMANDS} commands"
353 );
354 }
355 skip_ws_and_comments(bytes, pos);
356 if *pos >= bytes.len() {
357 bail!("unterminated array for '{key}' in .codewhale/worktrees.toml");
358 }
359 if bytes[*pos] == b',' {
360 *pos += 1;
361 } else if bytes[*pos] == b']' {
362 *pos += 1;
363 break;
364 } else {
365 bail!("expected ',' or ']' in '{key}' array in .codewhale/worktrees.toml");
366 }
367 }
368 Ok(items)
369 }
370
371 fn parse_toml_basic_string(input: &str, pos: &mut usize, key: &str) -> Result<String> {
372 let bytes = input.as_bytes();
373 *pos += 1;
374 let mut out = String::new();
375 while *pos < bytes.len() {
376 let ch = input[*pos..].chars().next().context("unexpected EOF")?;
377 *pos += ch.len_utf8();
378 match ch {
379 '"' => return Ok(out),
380 '\n' | '\r' => {
381 bail!("unterminated string in '{key}' in .codewhale/worktrees.toml");
382 }
383 '\\' => {
384 let esc = input[*pos..]
385 .chars()
386 .next()
387 .with_context(|| format!("unterminated escape in '{key}'"))?;
388 *pos += esc.len_utf8();
389 match esc {
390 '\\' => out.push('\\'),
391 '"' => out.push('"'),
392 'n' => out.push('\n'),
393 'r' => out.push('\r'),
394 't' => out.push('\t'),
395 other => {
396 bail!(
397 "unsupported escape '\\{other}' in '{key}' in .codewhale/worktrees.toml"
398 )
399 }
400 }
401 }
402 c if c.is_control() && c != '\t' => {
403 bail!("invalid control character in '{key}' in .codewhale/worktrees.toml");
404 }
405 c => out.push(c),
406 }
407 }
408 bail!("unterminated string in '{key}' in .codewhale/worktrees.toml")
409 }
410
411 fn parse_toml_literal_string(input: &str, pos: &mut usize, key: &str) -> Result<String> {
412 let bytes = input.as_bytes();
413 *pos += 1;
414 let start = *pos;
415 while *pos < bytes.len() {
416 let ch = input[*pos..].chars().next().context("unexpected EOF")?;
417 if ch == '\'' {
418 let value = input[start..*pos].to_string();
419 *pos += 1;
420 return Ok(value);
421 }
422 if ch == '\n' || ch == '\r' || (ch.is_control() && ch != '\t') {
423 bail!("invalid character in literal string in '{key}' in .codewhale/worktrees.toml");
424 }
425 *pos += ch.len_utf8();
426 }
427 bail!("unterminated literal string in '{key}' in .codewhale/worktrees.toml")
428 }
429
430 /// Refuse `path` when an existing component between `root` and `path` is a
431 /// link. A path outside `root` (an explicit `--worktree-path`) is the caller's
432 /// own choice and is not checked.
433 pub fn reject_linked_below(root: &Path, path: &Path) -> Result<()> {
434 let Ok(relative) = path.strip_prefix(root) else {
435 return Ok(());
436 };
437 let mut current = root.to_path_buf();
438 for component in relative.components() {
439 current.push(component);
440 match fs::symlink_metadata(&current) {
441 Ok(metadata) if metadata.file_type().is_symlink() => {
442 bail!(
443 "refusing to create a worktree through the link {}",
444 current.display()
445 );
446 }
447 Ok(_) => {}
448 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
449 Err(error) => {
450 return Err(error).with_context(|| format!("inspect {}", current.display()));
451 }
452 }
453 }
454 Ok(())
455 }
456
457 /// Create a git worktree + branch for a lane.
458 pub fn provision_worktree(spec: &WorktreeProvision) -> Result<ProvisionedWorktree> {
459 if spec.branch.trim().is_empty() {
460 bail!("worktree branch must not be empty");
461 }
462 if !spec.repo_root.exists() {
463 bail!("repo root does not exist: {}", spec.repo_root.display());
464 }
465 let base = spec.base_ref.as_deref().unwrap_or("HEAD");
466 // A leading '-' would be parsed as a `git worktree add` option.
467 if spec.branch.starts_with('-') || base.starts_with('-') {
468 bail!("worktree branch and base ref must not start with '-'");
469 }
470 if let Some(parent) = spec.path.parent() {
471 // The default location is `<repo>/.codewhale/lanes/<id>`: a link on
472 // the way down from the repository would send the checkout elsewhere.
473 reject_linked_below(&spec.repo_root, parent)?;
474 fs::create_dir_all(parent)
475 .with_context(|| format!("create worktree parent {}", parent.display()))?;
476 }
477 // Capture git output instead of inheriting the caller's terminal. Runtime
478 // callers include the raw-mode TUI launch screen, where even one inherited
479 // progress/error line corrupts the alternate-screen buffer.
480 let output = git_command(&spec.repo_root)?
481 .args([
482 "worktree",
483 "add",
484 "-b",
485 &spec.branch,
486 "--",
487 &spec.path.to_string_lossy(),
488 base,
489 ])
490 .output()
491 .context("git worktree add")?;
492 if !output.status.success() {
493 let detail = String::from_utf8_lossy(&output.stderr).trim().to_string();
494 bail!(
495 "git worktree add failed for branch {} at {}{}{}",
496 spec.branch,
497 spec.path.display(),
498 if detail.is_empty() { "" } else { ": " },
499 detail
500 );
501 }
502 Ok(ProvisionedWorktree {
503 path: spec.path.clone(),
504 branch: spec.branch.clone(),
505 })
506 }
507
508 /// Remove a worktree when TTL has expired (or immediately when TTL is 0).
509 ///
510 /// `stopped_at` is RFC3339. When `ttl_secs` is `None`, no cleanup is performed.
511 ///
512 /// Removal only ever touches a path that git identifies as a managed worktree
513 /// of its own repository (#5824); anything else — a stale or malformed record
514 /// pointing at an unrelated directory — is left untouched.
515 pub fn remove_worktree_if_expired(
516 worktree_path: &Path,
517 ttl_secs: Option<u64>,
518 stopped_at: Option<&str>,
519 ) -> Result<()> {
520 let Some(ttl) = ttl_secs else {
521 return Ok(());
522 };
523 if !worktree_path.exists() {
524 return Ok(());
525 }
526 if ttl > 0 {
527 let Some(stopped) = stopped_at else {
528 return Ok(());
529 };
530 let stopped_ts = DateTime::parse_from_rfc3339(stopped)
531 .with_context(|| format!("parse stopped_at {stopped}"))?
532 .timestamp() as u64;
533 let now = SystemTime::now()
534 .duration_since(UNIX_EPOCH)
535 .map(|d| d.as_secs())
536 .unwrap_or(0);
537 if now.saturating_sub(stopped_ts) < ttl {
538 return Ok(());
539 }
540 }
541
542 // Ask the worktree what it is before deleting it: once the directory is
543 // gone, neither its branch nor its repository is recoverable from the path.
544 let Some(details) = worktree_details(worktree_path) else {
545 return Ok(());
546 };
547 // #5824: a stale or malformed record must not turn TTL cleanup into an
548 // unbounded recursive delete. Removal proceeds only for a path that git
549 // itself identifies as a managed worktree of `details.repo_root`.
550 if !is_managed_worktree(worktree_path, &details) {
551 tracing::debug!(
552 "skipped TTL cleanup of {}: git does not identify it as a managed worktree",
553 worktree_path.display()
554 );
555 return Ok(());
556 }
557
558 // Best-effort: git worktree remove --force, then rm -rf.
559 let removed = git_command(&details.repo_root)
560 .and_then(|mut command| {
561 Ok(command
562 .args([
563 "worktree",
564 "remove",
565 "--force",
566 &worktree_path.to_string_lossy(),
567 ])
568 .status()?)
569 })
570 .is_ok_and(|status| status.success());
571 if !removed && worktree_path.exists() && is_managed_worktree(worktree_path, &details) {
572 // Re-verified immediately before the fallback: the directory may have
573 // been swapped for an unrelated one between identification and removal.
574 fs::remove_dir_all(worktree_path)
575 .with_context(|| format!("remove worktree {}", worktree_path.display()))?;
576 }
577 if !removed {
578 // The directory is gone but git still has it registered, and
579 // `git worktree add` refuses a path it already knows about.
580 if let Ok(mut command) = git_command(&details.repo_root) {
581 let _ = command.args(["worktree", "prune"]).status();
582 }
583 }
584 if let Some(branch) = details.branch.as_deref() {
585 delete_lane_branch(&details.repo_root, branch);
586 }
587 Ok(())
588 }
589
590 /// What a lane worktree is: which repository owns it, which branch it has
591 /// checked out (`None` when detached), and every worktree that repository
592 /// lists.
593 struct WorktreeDetails {
594 repo_root: PathBuf,
595 branch: Option<String>,
596 /// The worktrees the owning repository lists; a candidate path must
597 /// resolve to one of these before cleanup may delete anything (#5824).
598 worktrees: Vec<PathBuf>,
599 }
600
601 fn worktree_details(worktree_path: &Path) -> Option<WorktreeDetails> {
602 let listing = git_command(worktree_path)
603 .ok()?
604 .args(["worktree", "list", "--porcelain"])
605 .output()
606 .ok()
607 .filter(|output| output.status.success())?;
608 let listing = String::from_utf8_lossy(&listing.stdout);
609 let worktrees: Vec<PathBuf> = listing
610 .lines()
611 .filter_map(|line| line.strip_prefix("worktree "))
612 .map(PathBuf::from)
613 .collect();
614 // The main worktree is listed first, so its path is the repository root.
615 let repo_root = worktrees.first().cloned()?;
616
617 let branch = git_command(worktree_path)
618 .ok()
619 .and_then(|mut command| {
620 command
621 .args(["symbolic-ref", "--quiet", "--short", "HEAD"])
622 .output()
623 .ok()
624 })
625 .filter(|output| output.status.success())
626 .map(|output| String::from_utf8_lossy(&output.stdout).trim().to_string())
627 .filter(|branch| !branch.is_empty());
628
629 Some(WorktreeDetails {
630 repo_root,
631 branch,
632 worktrees,
633 })
634 }
635
636 /// Whether git identifies `worktree_path` itself as a managed worktree of the
637 /// repository in `details` (#5824). Two checks, both required:
638 ///
639 /// - the candidate resolves to a worktree the owning repository lists, and
640 /// - the worktree is a *linked* one: its `.git` file names the registration
641 /// the owning repository keeps beneath `<repo>/.git/worktrees/`.
642 ///
643 /// Repository roots (whose `.git` is a directory with no registration) and
644 /// plain subdirectories of a repo (which are not listed as worktrees) fail
645 /// here and are never candidates for recursive deletion. Paths are
646 /// canonicalized on both sides so symlinks (macOS `/tmp` -> `/private/tmp`)
647 /// and relative records cannot smuggle a different directory past the check.
648 fn is_managed_worktree(worktree_path: &Path, details: &WorktreeDetails) -> bool {
649 let Ok(candidate) = fs::canonicalize(worktree_path) else {
650 return false;
651 };
652 let listed = details
653 .worktrees
654 .iter()
655 .any(|path| fs::canonicalize(path).is_ok_and(|resolved| resolved == candidate));
656 if !listed {
657 return false;
658 }
659 let Ok(repo_root) = fs::canonicalize(&details.repo_root) else {
660 return false;
661 };
662 let registrations = repo_root.join(".git").join("worktrees");
663 let registration = fs::read_to_string(worktree_path.join(".git"))
664 .ok()
665 .and_then(|dot_git| {
666 dot_git
667 .lines()
668 .find_map(|line| line.strip_prefix("gitdir: "))
669 .map(str::trim)
670 .filter(|gitdir| !gitdir.is_empty())
671 .map(PathBuf::from)
672 });
673 let Some(registration) = registration else {
674 return false;
675 };
676 let registration = if registration.is_absolute() {
677 registration
678 } else {
679 worktree_path.join(registration)
680 };
681 fs::canonicalize(registration).is_ok_and(|resolved| resolved.starts_with(registrations))
682 }
683
684 /// Delete the branch a removed lane worktree was on.
685 ///
686 /// Lane branch names are derived from the user's launch name (`codex/{slug}`),
687 /// not from a UUID, so leaving the branch behind makes reusing that name fail
688 /// with "branch already exists" — a worktree directory that no longer exists
689 /// still blocking a legitimate lane.
690 ///
691 /// This uses `branch -d`, not `-D`: a lane branch with nothing on it beyond
692 /// its base is merged and deletes cleanly, which is the case that was broken.
693 /// A branch carrying unmerged commits is someone's work, and a TTL timer is
694 /// not a mandate to throw it away — that one is kept, and the name stays taken
695 /// until a human decides otherwise.
696 fn delete_lane_branch(repo_root: &Path, branch: &str) {
697 let output = git_command(repo_root)
698 .and_then(|mut command| Ok(command.args(["branch", "-d", branch]).output()?));
699 match output {
700 Ok(output) if output.status.success() => {}
701 Ok(output) => {
702 tracing::debug!(
703 "kept lane branch {branch} after worktree cleanup: {}",
704 String::from_utf8_lossy(&output.stderr).trim()
705 );
706 }
707 Err(err) => {
708 tracing::debug!("could not delete lane branch {branch}: {err}");
709 }
710 }
711 }
712
713 #[cfg(test)]
714 pub(crate) mod tests {
715 use super::*;
716 use std::process::Command;
717 use tempfile::tempdir;
718
719 pub(super) fn plain_git_command(dir: &Path) -> Result<Command> {
720 let mut command = Command::new("git");
721 command.current_dir(dir);
722 Ok(command)
723 }
724
725 pub(crate) fn init_repo(root: &Path) {
726 assert!(
727 Command::new("git")
728 .args(["init", "-b", "main"])
729 .current_dir(root)
730 .status()
731 .unwrap()
732 .success()
733 );
734 assert!(
735 Command::new("git")
736 .args(["config", "user.email", "lane@test"])
737 .current_dir(root)
738 .status()
739 .unwrap()
740 .success()
741 );
742 assert!(
743 Command::new("git")
744 .args(["config", "user.name", "lane"])
745 .current_dir(root)
746 .status()
747 .unwrap()
748 .success()
749 );
750 fs::write(root.join("README"), "lane").unwrap();
751 assert!(
752 Command::new("git")
753 .args(["add", "README"])
754 .current_dir(root)
755 .status()
756 .unwrap()
757 .success()
758 );
759 assert!(
760 Command::new("git")
761 .args(["commit", "-m", "init"])
762 .current_dir(root)
763 .status()
764 .unwrap()
765 .success()
766 );
767 }
768
769 #[test]
770 fn provision_and_ttl_zero_cleanup() {
771 let dir = tempdir().unwrap();
772 let repo = dir.path().join("repo");
773 fs::create_dir_all(&repo).unwrap();
774 init_repo(&repo);
775 let wt_path = dir.path().join("wt-lane");
776 let provisioned = provision_worktree(&WorktreeProvision {
777 repo_root: repo,
778 branch: "codex/lane-test".into(),
779 path: wt_path.clone(),
780 base_ref: Some("main".into()),
781 })
782 .unwrap();
783 assert!(provisioned.path.is_dir());
784 assert!(wt_path.join("README").is_file());
785
786 remove_worktree_if_expired(&wt_path, Some(0), Some("2020-01-01T00:00:00Z")).unwrap();
787 assert!(
788 !wt_path.exists(),
789 "TTL 0 should remove worktree immediately"
790 );
791 }
792
793 #[cfg(unix)]
794 #[test]
795 fn provision_refuses_a_linked_lanes_directory_under_the_repo() {
796 let dir = tempdir().unwrap();
797 let repo = dir.path().join("repo");
798 fs::create_dir_all(repo.join(".codewhale")).unwrap();
799 init_repo(&repo);
800 let outside = dir.path().join("outside");
801 fs::create_dir_all(&outside).unwrap();
802 std::os::unix::fs::symlink(&outside, repo.join(".codewhale").join("lanes")).unwrap();
803
804 let error = provision_worktree(&WorktreeProvision {
805 repo_root: repo.clone(),
806 branch: "codex/lane-linked".into(),
807 path: repo.join(".codewhale").join("lanes").join("lane-1"),
808 base_ref: Some("main".into()),
809 })
810 .expect_err("a linked lanes directory must be refused");
811 assert!(format!("{error:#}").contains("link"), "{error:#}");
812 assert_eq!(fs::read_dir(&outside).unwrap().count(), 0);
813 }
814
815 #[test]
816 fn provision_refuses_option_shaped_base_ref() {
817 let dir = tempdir().unwrap();
818 let repo = dir.path().join("repo");
819 fs::create_dir_all(&repo).unwrap();
820 init_repo(&repo);
821 let wt_path = dir.path().join("nested").join("wt-lane");
822 let err = provision_worktree(&WorktreeProvision {
823 repo_root: repo.clone(),
824 branch: "codex/lane-opt".into(),
825 path: wt_path.clone(),
826 base_ref: Some("--lock".into()),
827 })
828 .expect_err("option-shaped base ref must be refused");
829 assert!(
830 err.to_string().contains("must not start with '-'"),
831 "{err:#}"
832 );
833 assert!(!wt_path.exists());
834 assert!(!dir.path().join("nested").exists(), "nothing created");
835 assert!(!branch_exists(&repo, "codex/lane-opt"));
836 let list = Command::new("git")
837 .current_dir(&repo)
838 .args(["worktree", "list", "--porcelain"])
839 .output()
840 .unwrap();
841 assert!(!String::from_utf8_lossy(&list.stdout).contains("locked"));
842 }
843
844 #[test]
845 fn provision_accepts_a_path_that_looks_like_an_option() {
846 let dir = tempdir().unwrap();
847 let repo = dir.path().join("repo");
848 fs::create_dir_all(&repo).unwrap();
849 init_repo(&repo);
850 // With `--` before the positionals, git reads this as a path.
851 let provisioned = provision_worktree(&WorktreeProvision {
852 repo_root: repo.clone(),
853 branch: "codex/lane-dash-path".into(),
854 path: PathBuf::from("--detach"),
855 base_ref: Some("main".into()),
856 })
857 .unwrap();
858 assert!(repo.join("--detach").join("README").is_file());
859 assert!(branch_exists(&repo, "codex/lane-dash-path"));
860 drop(provisioned);
861 }
862
863 fn branch_exists(repo: &Path, branch: &str) -> bool {
864 Command::new("git")
865 .current_dir(repo)
866 .args(["rev-parse", "--verify", "--quiet", branch])
867 .status()
868 .unwrap()
869 .success()
870 }
871
872 #[test]
873 fn expired_cleanup_deletes_the_branch_so_the_lane_name_is_reusable() {
874 // #4731: cleanup removed the worktree directory but left the branch.
875 // Lane branches are named from the user's launch name, so reusing that
876 // name then failed with "branch already exists" — pointing at a
877 // worktree that no longer existed.
878 let dir = tempdir().unwrap();
879 let repo = dir.path().join("repo");
880 fs::create_dir_all(&repo).unwrap();
881 init_repo(&repo);
882
883 let wt_path = dir.path().join("wt-lane");
884 let spec = WorktreeProvision {
885 repo_root: repo.clone(),
886 branch: "codex/reused-name".into(),
887 path: wt_path.clone(),
888 base_ref: Some("main".into()),
889 };
890 provision_worktree(&spec).unwrap();
891 assert!(branch_exists(&repo, "codex/reused-name"));
892
893 remove_worktree_if_expired(&wt_path, Some(0), Some("2020-01-01T00:00:00Z")).unwrap();
894 assert!(!wt_path.exists());
895 assert!(
896 !branch_exists(&repo, "codex/reused-name"),
897 "an unused lane branch must not outlive its worktree"
898 );
899
900 // The whole point: the same launch name provisions again.
901 provision_worktree(&spec).expect("re-provisioning the same lane name must succeed");
902 assert!(wt_path.join("README").is_file());
903 }
904
905 #[test]
906 fn expired_cleanup_keeps_a_branch_with_unmerged_work() {
907 // A TTL timer is not a mandate to discard commits. The worktree goes;
908 // the branch carrying work stays, and the name stays taken until a
909 // human decides otherwise.
910 let dir = tempdir().unwrap();
911 let repo = dir.path().join("repo");
912 fs::create_dir_all(&repo).unwrap();
913 init_repo(&repo);
914
915 let wt_path = dir.path().join("wt-lane");
916 provision_worktree(&WorktreeProvision {
917 repo_root: repo.clone(),
918 branch: "codex/has-work".into(),
919 path: wt_path.clone(),
920 base_ref: Some("main".into()),
921 })
922 .unwrap();
923
924 fs::write(wt_path.join("work.txt"), "unmerged").unwrap();
925 for args in [
926 vec!["add", "work.txt"],
927 vec!["commit", "-m", "lane work worth keeping"],
928 ] {
929 assert!(
930 Command::new("git")
931 .args(&args)
932 .current_dir(&wt_path)
933 .status()
934 .unwrap()
935 .success()
936 );
937 }
938
939 remove_worktree_if_expired(&wt_path, Some(0), Some("2020-01-01T00:00:00Z")).unwrap();
940 assert!(!wt_path.exists(), "the worktree directory is disposable");
941 assert!(
942 branch_exists(&repo, "codex/has-work"),
943 "a branch with unmerged commits must survive worktree cleanup"
944 );
945 }
946
947 #[test]
948 fn ttl_cleanup_never_deletes_a_plain_directory() {
949 // #5824: a stale or malformed record pointing at an unrelated
950 // directory must not turn TTL cleanup into an unbounded recursive
951 // delete just because the TTL is zero.
952 let dir = tempdir().unwrap();
953 let precious = dir.path().join("not-a-worktree");
954 fs::create_dir_all(precious.join("nested")).unwrap();
955 fs::write(precious.join("nested/keep.txt"), "keep").unwrap();
956
957 remove_worktree_if_expired(&precious, Some(0), Some("2020-01-01T00:00:00Z")).unwrap();
958 assert!(
959 precious.exists(),
960 "git cannot identify this path as a managed worktree, so cleanup must do nothing"
961 );
962 assert_eq!(
963 fs::read_to_string(precious.join("nested/keep.txt")).unwrap(),
964 "keep"
965 );
966 }
967
968 #[test]
969 fn ttl_cleanup_never_deletes_inside_an_unrelated_repository() {
970 // Git commands succeed from within a subdirectory of some unrelated
971 // repo, but that repo does not list the subdirectory as a worktree.
972 let dir = tempdir().unwrap();
973 let repo = dir.path().join("repo");
974 fs::create_dir_all(&repo).unwrap();
975 init_repo(&repo);
976 let precious = repo.join("src");
977 fs::create_dir_all(&precious).unwrap();
978 fs::write(precious.join("keep.txt"), "keep").unwrap();
979
980 remove_worktree_if_expired(&precious, Some(0), Some("2020-01-01T00:00:00Z")).unwrap();
981 assert!(
982 precious.exists(),
983 "a subdirectory of an unrelated repo is not a managed worktree"
984 );
985 assert!(precious.join("keep.txt").exists());
986 }
987
988 #[test]
989 fn ttl_cleanup_never_deletes_a_repository_root() {
990 // The main worktree of a repo is not a linked lane worktree: its
991 // `.git` is a directory with no registration beneath
992 // `.git/worktrees/`. A record pointing there must not wipe a repo.
993 let dir = tempdir().unwrap();
994 let repo = dir.path().join("repo");
995 fs::create_dir_all(&repo).unwrap();
996 init_repo(&repo);
997
998 remove_worktree_if_expired(&repo, Some(0), Some("2020-01-01T00:00:00Z")).unwrap();
999 assert!(
1000 repo.exists(),
1001 "a repository root must never be recursively deleted by TTL cleanup"
1002 );
1003 assert!(repo.join(".git").exists());
1004 }
1005
1006 #[test]
1007 fn ttl_cleanup_leaves_a_path_swapped_after_provisioning_intact() {
1008 // The record was written when the path was a managed worktree; by the
1009 // time cleanup runs, the directory has been replaced by an unrelated
1010 // one. Deletion must see the path as it is now, not as the record
1011 // claims it was.
1012 let dir = tempdir().unwrap();
1013 let repo = dir.path().join("repo");
1014 fs::create_dir_all(&repo).unwrap();
1015 init_repo(&repo);
1016 let wt_path = dir.path().join("wt-lane");
1017 provision_worktree(&WorktreeProvision {
1018 repo_root: repo,
1019 branch: "codex/swapped".into(),
1020 path: wt_path.clone(),
1021 base_ref: Some("main".into()),
1022 })
1023 .unwrap();
1024
1025 fs::remove_dir_all(&wt_path).unwrap();
1026 fs::create_dir_all(&wt_path).unwrap();
1027 fs::write(wt_path.join("keep.txt"), "keep").unwrap();
1028
1029 remove_worktree_if_expired(&wt_path, Some(0), Some("2020-01-01T00:00:00Z")).unwrap();
1030 assert!(
1031 wt_path.exists(),
1032 "the replacement directory is not the identified worktree and must survive"
1033 );
1034 assert!(wt_path.join("keep.txt").exists());
1035 }
1036
1037 #[test]
1038 fn managed_identity_holds_for_a_real_worktree_and_fails_after_a_swap() {
1039 // The gate that guards the window between identification and removal:
1040 // it must accept the worktree git provisioned and refuse the same
1041 // path once its contents no longer resolve to that worktree.
1042 let dir = tempdir().unwrap();
1043 let repo = dir.path().join("repo");
1044 fs::create_dir_all(&repo).unwrap();
1045 init_repo(&repo);
1046 let wt_path = dir.path().join("wt-lane");
1047 provision_worktree(&WorktreeProvision {
1048 repo_root: repo.clone(),
1049 branch: "codex/identity".into(),
1050 path: wt_path.clone(),
1051 base_ref: Some("main".into()),
1052 })
1053 .unwrap();
1054
1055 let details = worktree_details(&wt_path).expect("a provisioned worktree identifies itself");
1056 assert!(is_managed_worktree(&wt_path, &details));
1057
1058 fs::remove_dir_all(&wt_path).unwrap();
1059 fs::create_dir_all(&wt_path).unwrap();
1060 fs::write(wt_path.join("keep.txt"), "keep").unwrap();
1061 assert!(
1062 !is_managed_worktree(&wt_path, &details),
1063 "a swapped directory no longer resolves to the identified worktree"
1064 );
1065 }
1066
1067 #[test]
1068 fn manifest_parses_strict_setup_and_platform_lists() {
1069 let raw = r#"
1070 # worktree setup
1071 setup = [
1072 "echo common",
1073 'echo literal',
1074 ]
1075 setup_unix = ["echo unix-only"]
1076 setup_windows = ["echo win-only"]
1077 "#;
1078 let parsed = parse_worktree_manifest(raw).expect("valid manifest");
1079 assert_eq!(
1080 parsed.commands_for_platform(false),
1081 vec!["echo common", "echo literal", "echo unix-only"]
1082 );
1083 assert_eq!(
1084 parsed.commands_for_platform(true),
1085 vec!["echo common", "echo literal", "echo win-only"]
1086 );
1087 }
1088
1089 #[test]
1090 fn manifest_rejects_unknown_duplicate_and_malformed_entries() {
1091 assert!(parse_worktree_manifest("unknown = [\"echo x\"]").is_err());
1092 assert!(parse_worktree_manifest("setup = \"echo x\"").is_err());
1093 assert!(parse_worktree_manifest("setup = [\"a\"]\nsetup = [\"b\"]").is_err());
1094 assert!(parse_worktree_manifest("setup = [\"\"]").is_err());
1095 assert!(parse_worktree_manifest("[section]\nsetup = [\"a\"]").is_err());
1096 }
1097
1098 #[test]
1099 fn setup_skips_untrusted_repo_and_runs_only_when_trusted() {
1100 let dir = tempdir().unwrap();
1101 let repo = dir.path().join("repo");
1102 fs::create_dir_all(repo.join(".codewhale")).unwrap();
1103 init_repo(&repo);
1104 fs::write(
1105 repo.join(".codewhale").join("worktrees.toml"),
1106 "setup = [\"echo setup-ok > setup_marker.txt && echo ready\"]\n",
1107 )
1108 .unwrap();
1109
1110 let wt_path = dir.path().join("wt-setup");
1111 let provisioned = provision_worktree(&WorktreeProvision {
1112 repo_root: repo.clone(),
1113 branch: "codex/lane-setup".into(),
1114 path: wt_path.clone(),
1115 base_ref: Some("main".into()),
1116 })
1117 .unwrap();
1118
1119 let untrusted = provisioned.run_setup(&repo, false).unwrap();
1120 assert!(
1121 untrusted
1122 .as_deref()
1123 .is_some_and(|msg| msg.contains("untrusted")),
1124 "{untrusted:?}"
1125 );
1126 assert!(
1127 !wt_path.join("setup_marker.txt").exists(),
1128 "untrusted repository must never execute setup commands"
1129 );
1130
1131 let trusted = provisioned.run_setup(&repo, true).unwrap();
1132 assert!(
1133 trusted
1134 .as_deref()
1135 .is_some_and(|msg| msg.contains("Ran 1 setup command") && msg.contains("ready")),
1136 "{trusted:?}"
1137 );
1138 assert!(wt_path.join("setup_marker.txt").is_file());
1139 }
1140
1141 #[test]
1142 fn setup_rejects_oversized_manifest() {
1143 let dir = tempdir().unwrap();
1144 let repo = dir.path().join("repo");
1145 fs::create_dir_all(repo.join(".codewhale")).unwrap();
1146 init_repo(&repo);
1147 let oversized = format!(
1148 "setup = [\"{}\"]\n",
1149 "a".repeat((MAX_WORKTREE_MANIFEST_BYTES as usize) + 64)
1150 );
1151 fs::write(repo.join(".codewhale").join("worktrees.toml"), oversized).unwrap();
1152
1153 let err = WorktreeProvision::run_setup(&repo, &repo, true)
1154 .expect_err("oversized manifest must be rejected");
1155 assert!(err.to_string().contains("maximum size"), "{err:#}");
1156 }
1157
1158 #[cfg(unix)]
1159 #[test]
1160 fn setup_rejects_symlinked_manifest() {
1161 let dir = tempdir().unwrap();
1162 let repo = dir.path().join("repo");
1163 fs::create_dir_all(repo.join(".codewhale")).unwrap();
1164 init_repo(&repo);
1165 let outside = dir.path().join("outside.toml");
1166 fs::write(&outside, "setup = [\"echo nope\"]\n").unwrap();
1167 std::os::unix::fs::symlink(&outside, repo.join(".codewhale").join("worktrees.toml"))
1168 .unwrap();
1169
1170 let err = WorktreeProvision::run_setup(&repo, &repo, true)
1171 .expect_err("symlinked manifest must be rejected");
1172 assert!(err.to_string().contains("link"), "{err:#}");
1173 }
1174 }
1175
1175 lines RUST