返回 CodeWhale
worktree.rs
根目录 / crates / engine / src / tools / subagent / worktree.rs
1 //! Workspace validation and first-class git worktree isolation for sub-agents.
2
3 use std::fs;
4 use std::path::{Path, PathBuf};
5
6 use uuid::Uuid;
7
8 use crate::tools::spec::ToolError;
9 use codewhale_dependencies::{ExternalTool, Git};
10
11 use codewhale_agent_contract::role::FleetRole;
12
13 const SUBAGENT_WORKTREE_ROOT_DIR: &str = ".codewhale-worktrees";
14
15 #[derive(Debug, Clone, PartialEq, Eq)]
16 pub(super) struct SubAgentWorktreeRequest {
17 pub(super) branch: Option<String>,
18 pub(super) path: Option<PathBuf>,
19 pub(super) base_ref: Option<String>,
20 }
21
22 pub(super) fn prepare_child_workspace(
23 parent_workspace: &Path,
24 requested_cwd: Option<&Path>,
25 worktree: Option<&SubAgentWorktreeRequest>,
26 session_name: Option<&str>,
27 agent_type: &FleetRole,
28 ) -> Result<Option<PathBuf>, ToolError> {
29 let discovery_anchor = if let Some(requested_cwd) = requested_cwd {
30 validate_existing_child_cwd(parent_workspace, requested_cwd)?
31 } else {
32 canonicalize_or_self(parent_workspace)
33 };
34
35 if let Some(worktree) = worktree {
36 return create_isolated_worktree(&discovery_anchor, worktree, session_name, agent_type)
37 .map(Some);
38 }
39
40 if requested_cwd.is_some() {
41 return Ok(Some(discovery_anchor));
42 }
43
44 Ok(None)
45 }
46
47 fn canonicalize_or_self(path: &Path) -> PathBuf {
48 path.canonicalize().unwrap_or_else(|_| path.to_path_buf())
49 }
50
51 fn validate_existing_child_cwd(
52 parent_workspace: &Path,
53 requested_cwd: &Path,
54 ) -> Result<PathBuf, ToolError> {
55 let resolved = if requested_cwd.is_absolute() {
56 requested_cwd.to_path_buf()
57 } else {
58 parent_workspace.join(requested_cwd)
59 };
60 let workspace_canonical = canonicalize_or_self(parent_workspace);
61 let canonical = resolved.canonicalize().map_err(|e| {
62 ToolError::invalid_input(format!(
63 "Invalid cwd '{}': {e}. Allowed cwd: an existing directory under {} (relative paths resolve against it), or omit cwd to use it. The path may not exist yet — use worktree=true to let Codewhale create an isolated checkout.",
64 requested_cwd.display(),
65 workspace_canonical.display()
66 ))
67 })?;
68 if !canonical.starts_with(&workspace_canonical)
69 && !is_sibling_worktree_path(parent_workspace, &canonical)
70 {
71 return Err(ToolError::invalid_input(format!(
72 "cwd must be inside the parent workspace: {} is not under {}. Allowed cwd: {} or a directory beneath it (relative paths resolve against it); omit cwd to run the child there.",
73 canonical.display(),
74 workspace_canonical.display(),
75 workspace_canonical.display()
76 )));
77 }
78 Ok(canonical)
79 }
80
81 fn is_sibling_worktree_path(parent_workspace: &Path, canonical: &Path) -> bool {
82 if !canonical.is_dir() {
83 return false;
84 }
85 let Some(repo_root) = try_git_toplevel(parent_workspace) else {
86 return false;
87 };
88 let default_root = default_worktree_root(&repo_root);
89 let Some(rebased) = relative_to_root(canonical, &default_root)
90 .filter(|rest| !rest.as_os_str().is_empty())
91 .map(|rest| normalize_path_lexically(&default_root.join(rest)))
92 else {
93 return false;
94 };
95 if relative_to_root(&rebased, &default_root).is_none() {
96 return false;
97 }
98 match (git_common_dir(parent_workspace), git_common_dir(canonical)) {
99 (Some(parent_common), Some(child_common)) => parent_common == child_common,
100 _ => false,
101 }
102 }
103
104 pub(super) fn create_isolated_worktree(
105 parent_workspace: &Path,
106 request: &SubAgentWorktreeRequest,
107 session_name: Option<&str>,
108 agent_type: &FleetRole,
109 ) -> Result<PathBuf, ToolError> {
110 let repo_root = git_repo_root(parent_workspace)?;
111 let trusted = codewhale_runtime::config::is_workspace_trusted(&repo_root);
112 create_isolated_worktree_with_trust(&repo_root, request, session_name, agent_type, trusted)
113 }
114
115 fn create_isolated_worktree_with_trust(
116 repo_root: &Path,
117 request: &SubAgentWorktreeRequest,
118 session_name: Option<&str>,
119 agent_type: &FleetRole,
120 trusted: bool,
121 ) -> Result<PathBuf, ToolError> {
122 let branch = request
123 .branch
124 .clone()
125 .unwrap_or_else(|| default_worktree_branch(session_name, agent_type));
126 validate_git_branch_name(repo_root, &branch)?;
127
128 let base_ref = request
129 .base_ref
130 .as_deref()
131 .map(str::trim)
132 .filter(|value| !value.is_empty())
133 .unwrap_or("HEAD")
134 .to_string();
135 if base_ref.starts_with('-') {
136 return Err(ToolError::invalid_input(format!(
137 "Invalid worktree_base '{base_ref}': a ref cannot start with '-'"
138 )));
139 }
140 let worktree_path = resolve_worktree_path(repo_root, &branch, request.path.as_ref())?;
141 ensure_worktree_path_unlinked(repo_root, &worktree_path)?;
142 crate::install_lane_git();
143 let provisioned = codewhale_lane::provision_worktree(&codewhale_lane::WorktreeProvision {
144 repo_root: repo_root.to_path_buf(),
145 branch,
146 path: worktree_path.clone(),
147 base_ref: Some(base_ref),
148 })
149 .map_err(|err| {
150 ToolError::execution_failed(format!("Failed to create sub-agent worktree: {err:#}"))
151 })?;
152 if let Err(err) = ensure_worktree_path_unlinked(repo_root, &worktree_path) {
153 remove_unstarted_worktree(&worktree_path);
154 return Err(err);
155 }
156 match provisioned.run_setup(repo_root, trusted) {
157 Ok(Some(notice)) => {
158 tracing::info!(
159 worktree = %worktree_path.display(),
160 trusted,
161 "{notice}"
162 );
163 }
164 Ok(None) => {}
165 Err(err) => {
166 remove_unstarted_worktree(&worktree_path);
167 return Err(ToolError::execution_failed(format!(
168 "Failed to run sub-agent worktree setup: {err:#}"
169 )));
170 }
171 }
172 worktree_path.canonicalize().map_err(|err| {
173 ToolError::execution_failed(format!(
174 "Created worktree path '{}' could not be resolved: {err}",
175 worktree_path.display()
176 ))
177 })
178 }
179
180 fn ensure_worktree_path_unlinked(repo_root: &Path, worktree_path: &Path) -> Result<(), ToolError> {
181 let base = repo_root.parent().unwrap_or(repo_root);
182 if worktree_path.strip_prefix(base).is_err() {
183 return Err(ToolError::invalid_input(format!(
184 "worktree_path '{}' must stay under {}",
185 worktree_path.display(),
186 base.display()
187 )));
188 }
189 codewhale_lane::reject_linked_below(base, worktree_path)
190 .map_err(|err| ToolError::invalid_input(format!("Invalid worktree_path: {err:#}")))
191 }
192
193 /// Remove a finished worker's isolated worktree (and its merged branch) when
194 /// the worker changed nothing in it. `changed` is the delivery-evidence
195 /// inventory: `None` means git could not answer, and nothing is removed.
196 /// Removal goes through the lane implementation, which only ever deletes a
197 /// path git itself lists as a linked worktree (#5824).
198 pub(super) fn remove_unchanged_worktree(
199 worktree: &Path,
200 changed: Option<&std::collections::BTreeSet<String>>,
201 ) -> bool {
202 if !changed.is_some_and(std::collections::BTreeSet::is_empty) || !worktree.exists() {
203 return false;
204 }
205 // The delivery inventory sees tracked and untracked paths but not ignored
206 // ones, and removal is forced. A fresh worktree holds no ignored files, so
207 // any (a report, a build output) was written by the worker: keep it.
208 let pristine = Git::output(
209 &[
210 "status",
211 "--porcelain",
212 "--ignored",
213 "--untracked-files=all",
214 "-z",
215 ],
216 worktree,
217 )
218 .is_ok_and(|output| output.status.success() && output.stdout.is_empty());
219 if !pristine {
220 return false;
221 }
222 crate::install_lane_git();
223 if let Err(err) = codewhale_lane::remove_worktree_if_expired(worktree, Some(0), None) {
224 tracing::debug!(
225 "kept unchanged sub-agent worktree {}: {err:#}",
226 worktree.display()
227 );
228 }
229 !worktree.exists()
230 }
231
232 /// Remove the isolated worktree (and its new branch) of a spawn refused
233 /// before its child started. No agent ever ran in it, so everything it holds
234 /// came from the checkout itself, including what post-checkout hooks,
235 /// line-ending filters or LFS wrote there. Requiring a pristine
236 /// `git status`, as [`remove_unchanged_worktree`] does for a finished
237 /// worker, kept exactly those checkouts behind. The removal still goes
238 /// through the lane implementation, which deletes only a path git lists as a
239 /// linked worktree, and the branch only when merged.
240 pub(super) fn remove_unstarted_worktree(worktree: &Path) {
241 crate::install_lane_git();
242 let outcome = codewhale_lane::remove_worktree_if_expired(worktree, Some(0), None);
243 if outcome.is_err() || worktree.exists() {
244 tracing::warn!(
245 "could not remove the worktree of a refused sub-agent spawn {}: {}",
246 worktree.display(),
247 outcome.err().map_or_else(
248 || "git did not list it as a linked worktree".to_string(),
249 |err| format!("{err:#}")
250 )
251 );
252 }
253 }
254
255 pub(super) fn git_repo_root(workspace: &Path) -> Result<PathBuf, ToolError> {
256 const MAX_PARENT_LEVELS: usize = 4;
257 let start = canonicalize_or_self(workspace);
258 let mut paths_tried = Vec::new();
259 let mut current = Some(start.as_path());
260 let mut levels = 0usize;
261
262 while let Some(dir) = current {
263 paths_tried.push(dir.display().to_string());
264
265 if let Some(root) = try_git_toplevel(dir) {
266 return Ok(root);
267 }
268
269 // Only the anchor itself may adopt a single nested checkout (a test
270 // harness or a session workspace that wraps one repository). Ancestors
271 // are probed for containment only; unlike base they no longer adopt a
272 // lone repository found among their children, because scanning them
273 // adopts or enumerates repositories the user never pointed at — a
274 // session workspace a few levels below the home directory walked up
275 // to `$HOME` and reported the user's other projects as "multiple
276 // repositories".
277 if levels == 0
278 && let Ok(entries) = fs::read_dir(dir)
279 {
280 let mut nested_roots = Vec::new();
281 for entry in entries.flatten() {
282 if !entry
283 .file_type()
284 .is_ok_and(|ft| ft.is_dir() && !ft.is_symlink())
285 {
286 continue;
287 }
288 let child = entry.path();
289 if !path_looks_like_git_checkout(&child)
290 || child
291 .join(".git")
292 .symlink_metadata()
293 .is_ok_and(|meta| meta.file_type().is_symlink())
294 {
295 continue;
296 }
297 if child
298 .file_name()
299 .and_then(|name| name.to_str())
300 .is_some_and(|name| name.starts_with('.'))
301 {
302 continue;
303 }
304 if let Some(root) = try_git_toplevel(&child)
305 && let Ok(canonical_root) = root.canonicalize()
306 && relative_to_root(&canonical_root, dir).is_some()
307 {
308 nested_roots.push(root);
309 }
310 }
311 match nested_roots.len() {
312 0 => {}
313 1 => return Ok(nested_roots.into_iter().next().expect("single nested root")),
314 _ => {
315 let repos = nested_roots
316 .iter()
317 .map(|path| path.display().to_string())
318 .collect::<Vec<_>>()
319 .join(", ");
320 return Err(ToolError::invalid_input(format!(
321 "Multiple git repositories found under {}. Specify cwd to disambiguate: {repos}",
322 dir.display()
323 )));
324 }
325 }
326 }
327
328 levels += 1;
329 if levels > MAX_PARENT_LEVELS {
330 break;
331 }
332 current = dir.parent();
333 }
334
335 Err(ToolError::invalid_input(format!(
336 "worktree=true requires a git repository. Tried: {}",
337 paths_tried.join(", ")
338 )))
339 }
340
341 fn path_looks_like_git_checkout(path: &Path) -> bool {
342 let git_path = path.join(".git");
343 git_path.is_dir() || git_path.is_file()
344 }
345
346 fn git_rev_parse_path(args: &[&str], path: &Path) -> Option<PathBuf> {
347 let output = Git::output(args, path).ok()?;
348 if !output.status.success() {
349 return None;
350 }
351 let raw = String::from_utf8_lossy(&output.stdout).trim().to_string();
352 if raw.is_empty() {
353 None
354 } else {
355 Some(PathBuf::from(raw))
356 }
357 }
358
359 fn try_git_toplevel(path: &Path) -> Option<PathBuf> {
360 git_rev_parse_path(&["rev-parse", "--show-toplevel"], path)
361 }
362
363 fn git_common_dir(path: &Path) -> Option<PathBuf> {
364 git_rev_parse_path(
365 &["rev-parse", "--path-format=absolute", "--git-common-dir"],
366 path,
367 )
368 .and_then(|dir| dir.canonicalize().ok())
369 }
370
371 fn validate_git_branch_name(repo_root: &Path, branch: &str) -> Result<(), ToolError> {
372 let branch = branch.trim();
373 if branch.is_empty() {
374 return Err(ToolError::invalid_input(
375 "worktree_branch cannot be blank".to_string(),
376 ));
377 }
378 run_git_checked(
379 repo_root,
380 &[
381 "check-ref-format".to_string(),
382 "--branch".to_string(),
383 branch.to_string(),
384 ],
385 "validate sub-agent worktree branch",
386 )
387 .map(|_| ())
388 .map_err(|err| ToolError::invalid_input(format!("Invalid worktree_branch '{branch}': {err}")))
389 }
390
391 /// Longest seed slug a default branch carries. The default checkout path is
392 /// the branch slug, which [`sanitize_worktree_slug`] caps at 48 characters;
393 /// `codex/agent-` (12) + seed + `-` + an 8-character unique suffix must fit,
394 /// or a long agent name truncated the suffix away and every retry of that
395 /// name (or any name sharing its first 27 characters) reused one path.
396 const DEFAULT_BRANCH_SEED_MAX: usize = 27;
397
398 fn default_worktree_branch(session_name: Option<&str>, agent_type: &FleetRole) -> String {
399 let seed = session_name
400 .map(str::trim)
401 .filter(|name| !name.is_empty())
402 .unwrap_or_else(|| agent_type.as_str());
403 // The slug is ASCII, so truncating by bytes cannot split a character.
404 let mut seed = sanitize_worktree_slug(seed);
405 seed.truncate(DEFAULT_BRANCH_SEED_MAX);
406 let seed = seed.trim_end_matches(['-', '.', '_']);
407 format!(
408 "codex/agent-{}-{}",
409 if seed.is_empty() { "task" } else { seed },
410 &Uuid::new_v4().to_string()[..8]
411 )
412 }
413
414 fn resolve_worktree_path(
415 repo_root: &Path,
416 branch: &str,
417 requested_path: Option<&PathBuf>,
418 ) -> Result<PathBuf, ToolError> {
419 let default_root = default_worktree_root(repo_root);
420 let path = match requested_path {
421 // Absolute and relative requests get the same containment: a
422 // sub-agent checkout lives under the per-repo worktree root and
423 // nowhere else.
424 //
425 // The request is rebased onto `default_root` as git reported it, so a
426 // Windows caller spelling the same directory differently (`\\?\`
427 // verbatim prefix from `canonicalize`, `/` separators, drive-letter
428 // case) is compared, and checked out, in one form.
429 Some(path) => {
430 let requested = normalize_path_lexically(&default_root.join(path));
431 match relative_to_root(&requested, &default_root)
432 .map(|rest| normalize_path_lexically(&default_root.join(rest)))
433 .filter(|resolved| resolved.starts_with(&default_root))
434 {
435 Some(resolved) => resolved,
436 None => {
437 return Err(ToolError::invalid_input(format!(
438 "worktree_path '{}' must stay under {}",
439 path.display(),
440 default_root.display()
441 )));
442 }
443 }
444 }
445 None => default_root.join(branch_worktree_slug(branch)),
446 };
447 let normalized = normalize_path_lexically(&path);
448 let repo_canonical = canonicalize_or_self(repo_root);
449 if relative_to_root(&normalized, &repo_canonical).is_some() {
450 return Err(ToolError::invalid_input(format!(
451 "worktree_path must not be inside the parent checkout: {} is under {}",
452 normalized.display(),
453 repo_canonical.display()
454 )));
455 }
456 Ok(normalized)
457 }
458
459 /// The part of `candidate` below `root`, or `None` when it is not under it.
460 /// On Windows the two may spell one directory differently, so they are
461 /// compared in a simplified, case-insensitive form.
462 fn relative_to_root(candidate: &Path, root: &Path) -> Option<PathBuf> {
463 #[cfg(windows)]
464 {
465 windows_relative_to_root(&candidate.to_string_lossy(), &root.to_string_lossy())
466 .map(PathBuf::from)
467 }
468 #[cfg(not(windows))]
469 {
470 candidate.strip_prefix(root).ok().map(Path::to_path_buf)
471 }
472 }
473
474 /// String form of [`relative_to_root`] for Windows paths: `/` and `\` are one
475 /// separator, the `\\?\` and `\\?\UNC\` verbatim prefixes are dropped, and
476 /// ASCII case is ignored. The match must end on a component boundary, and a
477 /// remainder with a `..` component is refused.
478 #[cfg(any(windows, test))]
479 fn windows_relative_to_root(candidate: &str, root: &str) -> Option<String> {
480 fn simplify(path: &str) -> String {
481 let mut simple = path.replace('/', "\\");
482 if let Some(rest) = simple.strip_prefix(r"\\?\UNC\") {
483 simple = format!(r"\\{rest}");
484 } else if let Some(rest) = simple.strip_prefix(r"\\?\") {
485 simple = rest.to_string();
486 }
487 while simple.len() > 3 && simple.ends_with('\\') {
488 simple.pop();
489 }
490 simple
491 }
492 let candidate = simplify(candidate);
493 let root = simplify(root);
494 if !candidate
495 .get(..root.len())
496 .is_some_and(|head| head.eq_ignore_ascii_case(&root))
497 {
498 return None;
499 }
500 let rest = &candidate[root.len()..];
501 if !(rest.is_empty() || root.ends_with('\\') || rest.starts_with('\\')) {
502 return None;
503 }
504 let rest = rest.trim_start_matches('\\');
505 if rest.split('\\').any(|part| part == "..") {
506 return None;
507 }
508 Some(rest.to_string())
509 }
510
511 fn default_worktree_root(repo_root: &Path) -> PathBuf {
512 let repo_name = repo_root
513 .file_name()
514 .and_then(|name| name.to_str())
515 .map(sanitize_worktree_slug)
516 .filter(|name| !name.is_empty())
517 .unwrap_or_else(|| "repo".to_string());
518 let parent = repo_root.parent().unwrap_or(repo_root);
519 normalize_path_lexically(&parent.join(SUBAGENT_WORKTREE_ROOT_DIR).join(repo_name))
520 }
521
522 /// The default checkout directory for `branch`: its slug, or, when the slug
523 /// had to be cut to [`WORKTREE_SLUG_MAX`] or collapsed non-ASCII characters,
524 /// the sanitized prefix with a short hash of the whole branch name, so distinct
525 /// long or non-ASCII branches get their own checkouts instead of colliding.
526 fn branch_worktree_slug(branch: &str) -> String {
527 let slug = sanitize_worktree_slug(branch);
528 let lossy = !branch.is_ascii() || slug != sanitize_worktree_slug_within(branch, usize::MAX);
529 if !lossy {
530 return slug;
531 }
532 use sha2::{Digest, Sha256};
533 let digest = Sha256::digest(branch.as_bytes());
534 let suffix: String = digest[..4]
535 .iter()
536 .map(|byte| format!("{byte:02x}"))
537 .collect();
538 // The slug is ASCII, so cutting by bytes cannot split a character.
539 let mut prefix = slug;
540 prefix.truncate(WORKTREE_SLUG_MAX - suffix.len() - 1);
541 let prefix = prefix.trim_end_matches(['-', '.', '_']);
542 if prefix.is_empty() {
543 format!("task-{suffix}")
544 } else {
545 format!("{prefix}-{suffix}")
546 }
547 }
548
549 /// Longest sub-agent worktree path slug.
550 const WORKTREE_SLUG_MAX: usize = 48;
551
552 fn sanitize_worktree_slug(input: &str) -> String {
553 sanitize_worktree_slug_within(input, WORKTREE_SLUG_MAX)
554 }
555
556 fn sanitize_worktree_slug_within(input: &str, max: usize) -> String {
557 let mut slug = String::new();
558 for ch in input.chars() {
559 let normalized = if ch.is_ascii_alphanumeric() {
560 ch.to_ascii_lowercase()
561 } else if matches!(ch, '-' | '_' | '.') {
562 ch
563 } else {
564 '-'
565 };
566 if normalized == '-' && slug.ends_with('-') {
567 continue;
568 }
569 slug.push(normalized);
570 if slug.len() >= max {
571 break;
572 }
573 }
574 let slug = slug.trim_matches(['-', '.', '_']).to_string();
575 if slug.is_empty() {
576 "task".to_string()
577 } else {
578 slug
579 }
580 }
581
582 fn normalize_path_lexically(path: &Path) -> PathBuf {
583 let mut normalized = PathBuf::new();
584 for component in path.components() {
585 match component {
586 std::path::Component::CurDir => {}
587 std::path::Component::ParentDir => {
588 normalized.pop();
589 }
590 other => normalized.push(other.as_os_str()),
591 }
592 }
593 normalized
594 }
595
596 fn run_git_checked(workspace: &Path, args: &[String], action: &str) -> Result<String, ToolError> {
597 let arg_refs = args.iter().map(String::as_str).collect::<Vec<_>>();
598 let output = Git::output(&arg_refs, workspace).map_err(|err| {
599 ToolError::execution_failed(format!("Failed to {action}: could not run git: {err}"))
600 })?;
601 if output.status.success() {
602 return Ok(String::from_utf8_lossy(&output.stdout).to_string());
603 }
604 let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
605 let stdout = String::from_utf8_lossy(&output.stdout).trim().to_string();
606 let detail = if !stderr.is_empty() {
607 stderr
608 } else if !stdout.is_empty() {
609 stdout
610 } else {
611 format!("git exited with status {}", output.status)
612 };
613 Err(ToolError::execution_failed(format!(
614 "Failed to {action}: {detail}"
615 )))
616 }
617
618 #[cfg(test)]
619 mod tests {
620 use super::*;
621
622 /// A long agent name used to push the unique suffix past the 48-character
623 /// path slug, so a retry of the same name collided with the checkout the
624 /// previous run kept.
625 #[test]
626 fn default_worktree_paths_stay_unique_for_long_agent_names() {
627 let name = "audit-authentication-middleware-a";
628 let first = default_worktree_branch(Some(name), &FleetRole::Worker);
629 let second = default_worktree_branch(Some(name), &FleetRole::Worker);
630 let sibling = default_worktree_branch(
631 Some("audit-authentication-middleware-b"),
632 &FleetRole::Worker,
633 );
634 assert!(
635 first.starts_with("codex/agent-audit-authentication-midd"),
636 "{first}"
637 );
638 let paths = [&first, &second, &sibling].map(|branch| branch_worktree_slug(branch));
639 for (branch, path) in [&first, &second, &sibling].into_iter().zip(&paths) {
640 assert_eq!(
641 path.as_str(),
642 branch.replace('/', "-"),
643 "the default path slug keeps the whole branch, suffix included"
644 );
645 }
646 assert_ne!(paths[0], paths[1], "a retry must get its own checkout");
647 assert_ne!(
648 paths[0], paths[2],
649 "names sharing a prefix must not collide"
650 );
651 }
652
653 /// An explicit branch with no worktree_path gets its path from the branch
654 /// slug, cut at 48 characters. Two long branches sharing that prefix used
655 /// to map to one checkout, and the second spawn failed on it.
656 #[test]
657 fn long_explicit_branches_sharing_a_prefix_get_distinct_paths() {
658 let a = "feature/very-long-shared-prefix-authentication-work-a";
659 let b = "feature/very-long-shared-prefix-authentication-work-b";
660 let (path_a, path_b) = (branch_worktree_slug(a), branch_worktree_slug(b));
661 assert_ne!(path_a, path_b);
662 for path in [&path_a, &path_b] {
663 assert!(path.len() <= WORKTREE_SLUG_MAX, "{path}");
664 assert!(
665 path.starts_with("feature-very-long-shared-prefix"),
666 "{path}"
667 );
668 }
669 assert_eq!(path_a, branch_worktree_slug(a), "the path is stable");
670 assert_eq!(
671 branch_worktree_slug("feature/short"),
672 "feature-short",
673 "a branch that fits keeps its plain slug"
674 );
675 }
676
677 #[test]
678 fn non_ascii_branches_get_distinct_stable_worktree_slugs() {
679 let all_non_ascii = ["功能", "構造", "таск"].map(branch_worktree_slug);
680 assert_ne!(all_non_ascii[0], all_non_ascii[1]);
681 assert_ne!(all_non_ascii[0], all_non_ascii[2]);
682 assert_ne!(all_non_ascii[1], all_non_ascii[2]);
683 for slug in &all_non_ascii {
684 assert_ne!(slug, "task");
685 assert!(slug.is_ascii());
686 assert!(slug.len() <= WORKTREE_SLUG_MAX, "{slug}");
687 }
688
689 let same_ascii_tail_a = branch_worktree_slug("功能A");
690 let same_ascii_tail_b = branch_worktree_slug("構造A");
691 assert_ne!(same_ascii_tail_a, same_ascii_tail_b);
692 assert_ne!(same_ascii_tail_a, branch_worktree_slug("a"));
693
694 let prefixed_a = branch_worktree_slug("feature/短名");
695 let prefixed_b = branch_worktree_slug("feature/另一名");
696 assert_ne!(prefixed_a, prefixed_b);
697 assert_ne!(prefixed_a, branch_worktree_slug("feature"));
698 assert_eq!(prefixed_a, branch_worktree_slug("feature/短名"));
699 assert!(prefixed_a.starts_with("feature-"), "{prefixed_a}");
700 assert!(prefixed_a.len() <= WORKTREE_SLUG_MAX, "{prefixed_a}");
701 }
702
703 #[test]
704 fn cwd_errors_name_the_allowed_root() {
705 let workspace = tempfile::tempdir().expect("workspace");
706 let outside = tempfile::tempdir().expect("outside");
707 let root = workspace
708 .path()
709 .canonicalize()
710 .expect("canonical workspace");
711
712 let err = validate_existing_child_cwd(workspace.path(), outside.path())
713 .expect_err("outside cwd refused")
714 .to_string();
715 assert!(err.contains("Allowed cwd"), "{err}");
716 assert!(err.contains(&root.display().to_string()), "{err}");
717
718 let err = validate_existing_child_cwd(workspace.path(), Path::new("missing/dir"))
719 .expect_err("missing cwd refused")
720 .to_string();
721 assert!(err.contains("Allowed cwd"), "{err}");
722 assert!(err.contains(&root.display().to_string()), "{err}");
723
724 std::fs::create_dir(workspace.path().join("sub")).expect("sub");
725 assert_eq!(
726 validate_existing_child_cwd(workspace.path(), Path::new("sub")).expect("inside"),
727 root.join("sub")
728 );
729 }
730
731 #[test]
732 fn windows_paths_under_the_root_match_across_spellings() {
733 let root = r"C:\Users\runner\.codewhale-worktrees\repo";
734 for candidate in [
735 r"\\?\C:\Users\runner\.codewhale-worktrees\repo\inside",
736 r"c:/users/RUNNER/.codewhale-worktrees/repo/inside",
737 r"C:\Users\runner\.codewhale-worktrees\repo\inside\",
738 ] {
739 assert_eq!(
740 windows_relative_to_root(candidate, root).as_deref(),
741 Some("inside"),
742 "{candidate}"
743 );
744 }
745 assert_eq!(
746 windows_relative_to_root(r"\\?\C:\Users\runner\.codewhale-worktrees\repo", root)
747 .as_deref(),
748 Some("")
749 );
750 assert_eq!(
751 windows_relative_to_root(
752 r"\\?\UNC\server\share\wt\repo\a\b",
753 r"\\server/share/wt/repo/"
754 )
755 .as_deref(),
756 Some(r"a\b")
757 );
758 assert_eq!(
759 windows_relative_to_root(r"C:\", r"c:\").as_deref(),
760 Some("")
761 );
762 }
763
764 #[test]
765 fn windows_paths_outside_the_root_are_refused() {
766 let root = r"C:\Users\runner\.codewhale-worktrees\repo";
767 for candidate in [
768 r"C:\Users\runner\.codewhale-worktrees\repo-evil\x",
769 r"D:\Users\runner\.codewhale-worktrees\repo\x",
770 r"\\?\C:\Users\runner\.codewhale-worktrees",
771 r"C:\Users\runner\.codewhale-worktrees\repo\..\escaped",
772 r"C:\Temp\escaped",
773 ] {
774 assert_eq!(
775 windows_relative_to_root(candidate, root),
776 None,
777 "{candidate}"
778 );
779 }
780 }
781
782 fn init_test_git_repo(path: &Path) {
783 let init = std::process::Command::new("git")
784 .arg("init")
785 .current_dir(path)
786 .output()
787 .expect("git init");
788 assert!(init.status.success(), "git init failed: {init:?}");
789 let commit = std::process::Command::new("git")
790 .args([
791 "-c",
792 "user.name=codewhale Tests",
793 "-c",
794 "user.email=tests@example.com",
795 "commit",
796 "--allow-empty",
797 "-m",
798 "init",
799 ])
800 .current_dir(path)
801 .output()
802 .expect("git commit");
803 assert!(commit.status.success(), "git commit failed: {commit:?}");
804 }
805
806 #[test]
807 fn linked_sibling_worktree_and_subdirs_are_admitted_as_child_cwd() {
808 let harness = tempfile::tempdir().expect("harness");
809 let repo = harness.path().join("repo");
810 std::fs::create_dir_all(&repo).expect("repo dir");
811 init_test_git_repo(&repo);
812
813 let worktree = create_isolated_worktree(
814 &repo,
815 &SubAgentWorktreeRequest {
816 branch: Some("codex/agent-sibling-cwd".to_string()),
817 path: Some(PathBuf::from("sibling-one")),
818 base_ref: None,
819 },
820 Some("sibling-one"),
821 &FleetRole::Worker,
822 )
823 .expect("linked sibling worktree");
824
825 assert_eq!(
826 validate_existing_child_cwd(&repo, &worktree).expect("linked worktree root admitted"),
827 worktree
828 );
829
830 let relative_worktree = PathBuf::from("..")
831 .join(".codewhale-worktrees")
832 .join("repo")
833 .join("sibling-one");
834 assert_eq!(
835 validate_existing_child_cwd(&repo, &relative_worktree)
836 .expect("relative linked worktree admitted"),
837 worktree
838 );
839
840 let tracked_sub = worktree.join("tracked-sub");
841 std::fs::create_dir_all(&tracked_sub).expect("tracked sub");
842 std::fs::write(tracked_sub.join("file.txt"), "hello").expect("write tracked file");
843 let add = std::process::Command::new("git")
844 .args(["add", "tracked-sub/file.txt"])
845 .current_dir(&worktree)
846 .output()
847 .expect("git add");
848 assert!(add.status.success(), "git add failed: {add:?}");
849 let commit = std::process::Command::new("git")
850 .args([
851 "-c",
852 "user.name=codewhale Tests",
853 "-c",
854 "user.email=tests@example.com",
855 "commit",
856 "-m",
857 "add tracked file",
858 ])
859 .current_dir(&worktree)
860 .output()
861 .expect("git commit");
862 assert!(commit.status.success(), "git commit failed: {commit:?}");
863
864 assert_eq!(
865 validate_existing_child_cwd(&repo, &tracked_sub).expect("tracked subdir admitted"),
866 tracked_sub
867 );
868
869 let untracked_sub = worktree.join("untracked-sub");
870 std::fs::create_dir_all(&untracked_sub).expect("untracked sub");
871 assert_eq!(
872 validate_existing_child_cwd(&repo, &untracked_sub).expect("untracked subdir admitted"),
873 untracked_sub
874 );
875
876 let parent_sub = repo.join("parent-sub");
877 std::fs::create_dir_all(&parent_sub).expect("parent sub");
878 assert_eq!(
879 validate_existing_child_cwd(&parent_sub, &worktree)
880 .expect("repo subdir parent admits sibling worktree"),
881 worktree
882 );
883 assert_eq!(
884 prepare_child_workspace(&repo, Some(&worktree), None, None, &FleetRole::Reviewer)
885 .expect("prepare_child_workspace admits sibling worktree"),
886 Some(worktree)
887 );
888 }
889
890 #[test]
891 fn outside_directories_and_non_managed_worktrees_are_rejected_as_child_cwd() {
892 let harness = tempfile::tempdir().expect("harness");
893 let repo = harness.path().join("repo");
894 std::fs::create_dir_all(&repo).expect("repo dir");
895 init_test_git_repo(&repo);
896
897 let outside = tempfile::tempdir().expect("outside");
898 let outside_err = validate_existing_child_cwd(&repo, outside.path())
899 .expect_err("arbitrary outside directory rejected")
900 .to_string();
901 assert!(
902 outside_err.contains("cwd must be inside the parent workspace")
903 && outside_err.contains("Allowed cwd"),
904 "{outside_err}"
905 );
906
907 let unmanaged_wt = outside.path().join("unmanaged-wt");
908 let add_wt = std::process::Command::new("git")
909 .args(["worktree", "add", "-b", "codex/agent-unmanaged"])
910 .arg(&unmanaged_wt)
911 .current_dir(&repo)
912 .output()
913 .expect("git worktree add");
914 assert!(
915 add_wt.status.success(),
916 "git worktree add failed: {add_wt:?}"
917 );
918 let unmanaged_err = validate_existing_child_cwd(&repo, &unmanaged_wt)
919 .expect_err("linked worktree outside .codewhale-worktrees rejected")
920 .to_string();
921 assert!(
922 unmanaged_err.contains("cwd must be inside the parent workspace"),
923 "{unmanaged_err}"
924 );
925
926 let repo_root = try_git_toplevel(&repo).expect("repo toplevel");
927 let managed_root = default_worktree_root(&repo_root);
928 std::fs::create_dir_all(&managed_root).expect("managed root");
929 let container_err = validate_existing_child_cwd(&repo, &managed_root)
930 .expect_err("managed worktree container root itself rejected")
931 .to_string();
932 assert!(
933 container_err.contains("cwd must be inside the parent workspace"),
934 "{container_err}"
935 );
936
937 #[cfg(unix)]
938 {
939 let link = managed_root.join("escape-link");
940 std::os::unix::fs::symlink(&unmanaged_wt, &link).expect("symlink");
941 let link_err = validate_existing_child_cwd(&repo, &link)
942 .expect_err("symlink pointing outside managed root rejected")
943 .to_string();
944 assert!(
945 link_err.contains("cwd must be inside the parent workspace"),
946 "{link_err}"
947 );
948 }
949 }
950
951 #[test]
952 fn spoofed_and_plain_directories_under_worktree_root_are_rejected_as_child_cwd() {
953 let harness = tempfile::tempdir().expect("harness");
954 let repo = harness.path().join("repo");
955 std::fs::create_dir_all(&repo).expect("repo dir");
956 init_test_git_repo(&repo);
957
958 let repo_root = try_git_toplevel(&repo).expect("repo toplevel");
959 let managed_root = default_worktree_root(&repo_root);
960 let spoof = managed_root.join("spoof");
961 std::fs::create_dir_all(&spoof).expect("spoof dir");
962 init_test_git_repo(&spoof);
963
964 let spoof_err = validate_existing_child_cwd(&repo, &spoof)
965 .expect_err("foreign git repo under worktree root rejected")
966 .to_string();
967 assert!(
968 spoof_err.contains("cwd must be inside the parent workspace")
969 && spoof_err.contains("Allowed cwd"),
970 "{spoof_err}"
971 );
972
973 let plain = managed_root.join("plain");
974 std::fs::create_dir_all(&plain).expect("plain dir");
975 let plain_err = validate_existing_child_cwd(&repo, &plain)
976 .expect_err("non-git directory under worktree root rejected")
977 .to_string();
978 assert!(
979 plain_err.contains("cwd must be inside the parent workspace"),
980 "{plain_err}"
981 );
982 }
983
984 #[test]
985 fn subagent_worktree_setup_defaults_closed_and_runs_only_when_trusted() {
986 let harness = tempfile::tempdir().expect("harness");
987 let repo = harness.path().join("repo");
988 std::fs::create_dir_all(repo.join(".codewhale")).expect("manifest dir");
989 init_test_git_repo(&repo);
990 std::fs::write(
991 repo.join(".codewhale").join("worktrees.toml"),
992 "setup = [\"echo ok > setup_ran.txt\"]\n",
993 )
994 .expect("write manifest");
995
996 let untrusted_wt = create_isolated_worktree(
997 &repo,
998 &SubAgentWorktreeRequest {
999 branch: Some("codex/agent-untrusted-setup".to_string()),
1000 path: Some(PathBuf::from("untrusted-wt")),
1001 base_ref: None,
1002 },
1003 Some("untrusted-wt"),
1004 &FleetRole::Worker,
1005 )
1006 .expect("untrusted worktree creation succeeds with setup skipped");
1007 assert!(
1008 !untrusted_wt.join("setup_ran.txt").exists(),
1009 "untrusted repository must skip setup commands by default"
1010 );
1011
1012 let repo_root = git_repo_root(&repo).expect("repo root");
1013 let trusted_wt = create_isolated_worktree_with_trust(
1014 &repo_root,
1015 &SubAgentWorktreeRequest {
1016 branch: Some("codex/agent-trusted-setup".to_string()),
1017 path: Some(PathBuf::from("trusted-wt")),
1018 base_ref: None,
1019 },
1020 Some("trusted-wt"),
1021 &FleetRole::Worker,
1022 true,
1023 )
1024 .expect("trusted worktree creation runs setup");
1025 assert!(
1026 trusted_wt.join("setup_ran.txt").is_file(),
1027 "trusted repository must run setup commands"
1028 );
1029 }
1030
1031 #[test]
1032 fn subagent_worktree_cleans_up_when_trusted_setup_fails() {
1033 let harness = tempfile::tempdir().expect("harness");
1034 let repo = harness.path().join("repo");
1035 std::fs::create_dir_all(repo.join(".codewhale")).expect("manifest dir");
1036 init_test_git_repo(&repo);
1037 std::fs::write(
1038 repo.join(".codewhale").join("worktrees.toml"),
1039 "setup = [\"exit 7\"]\n",
1040 )
1041 .expect("write failing manifest");
1042
1043 let repo_root = git_repo_root(&repo).expect("repo root");
1044 let err = create_isolated_worktree_with_trust(
1045 &repo_root,
1046 &SubAgentWorktreeRequest {
1047 branch: Some("codex/agent-failing-setup".to_string()),
1048 path: Some(PathBuf::from("failing-wt")),
1049 base_ref: None,
1050 },
1051 Some("failing-wt"),
1052 &FleetRole::Worker,
1053 true,
1054 )
1055 .expect_err("failing setup must fail worktree creation");
1056 assert!(err.to_string().contains("worktree setup"), "{err}");
1057 assert!(
1058 !default_worktree_root(&repo_root)
1059 .join("failing-wt")
1060 .exists(),
1061 "failed worktree setup must clean up unstarted worktree"
1062 );
1063 }
1064 }
1065
1065 lines RUST