Rinomina: crate akode-*, cartelle akode-rs/ e akode-cli/, binario akode, ~/.akode, AKODE_* (A)

Riapplica la fase 5 di aKode (86e7c72e) sulla base ripulita:
- crate codex-* -> akode-*, codex-rs -> akode-rs, codex-cli -> akode-cli, binario e ausiliari akode;
- ~/.codex -> ~/.akode, CODEX_HOME -> AKODE_HOME, variabili CODEX_* -> AKODE_*, .codex/ -> .akode/ di progetto;
  nessun fallback a ~/.codex o a CODEX_*;
- testi per l'utente "Codex" -> "aKode"; testi verso il modello e istruzioni di sistema invariati;
- snapshot insta rinominati (non ancora rigenerati).
I conflitti con la base ripulita sono stati risolti riapplicando la rinomina ai file senza le
funzioni di imeAI (script di mappa dei token per file).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
andrea.difonzo
2026-11-17 12:37:52 +01:00
parent e37a0deba9
commit 7c1c6dfa8d
10306 changed files with 748026 additions and 748088 deletions

View File

@@ -0,0 +1,6 @@
load("//:defs.bzl", "codex_rust_crate")
codex_rust_crate(
name = "worktree",
crate_name = "akode_worktree",
)

View File

@@ -0,0 +1,25 @@
[package]
name = "akode-worktree"
version.workspace = true
edition.workspace = true
license.workspace = true
[lints]
workspace = true
[lib]
doctest = false
[dependencies]
anyhow = { workspace = true }
akode-git-utils = { workspace = true }
akode-protocol = { workspace = true }
dunce = { workspace = true }
serde = { workspace = true, features = ["derive"] }
serde_json = { workspace = true }
tempfile = { workspace = true }
uuid = { workspace = true, features = ["v4"] }
[dev-dependencies]
akode-utils-cargo-bin = { workspace = true }
pretty_assertions = { workspace = true }

View File

@@ -0,0 +1,228 @@
//! Runs isolated Git commands and decodes native filesystem paths.
//!
//! Commands remove inherited repository selectors and per-command Git config,
//! select the repository from the supplied working directory, and disable hooks
//! and filesystem monitoring.
//!
//! Filesystem monitoring is disabled uniformly, including Git's built-in daemon,
//! rather than probing support. These command-local overrides avoid running
//! repository-configured helpers without changing persistent Git settings.
//!
//! Working-tree operations also disable configured clean, smudge, and process filters.
use std::collections::BTreeSet;
use std::ffi::OsStr;
use std::path::Path;
use std::path::PathBuf;
use std::process::Command;
use std::process::Output;
use anyhow::Context;
use anyhow::Result;
use anyhow::bail;
use akode_git_utils::SAFE_BARE_REPOSITORY_CONFIG;
use akode_git_utils::git_config_override_env;
use akode_protocol::shell_environment::scrub_non_inheritable_env_vars;
const DISABLED_HOOKS_PATH: &str = if cfg!(windows) { "NUL" } else { "/dev/null" };
#[derive(Clone, Copy)]
pub(crate) enum GitOperation {
Metadata,
WorkingTree,
}
pub(crate) fn git_output(
cwd: &Path,
operation: GitOperation,
args: impl IntoIterator<Item = impl AsRef<OsStr>>,
) -> Result<Output> {
let mut command = base_git_command(cwd);
if matches!(operation, GitOperation::WorkingTree) {
command.envs(git_config_override_env(
configured_filters(cwd)?.into_iter().flat_map(|filter| {
[
(format!("filter.{filter}.process"), String::new()),
(format!("filter.{filter}.clean"), String::new()),
(format!("filter.{filter}.smudge"), String::new()),
(format!("filter.{filter}.required"), "false".to_owned()),
]
}),
));
}
let output = command.args(args).output().context("failed to start git")?;
ensure_git_success(&output)?;
Ok(output)
}
pub(crate) fn git_stdout<I, S>(cwd: &Path, args: I) -> Result<String>
where
I: IntoIterator<Item = S>,
S: AsRef<OsStr>,
{
let output = git_output(cwd, GitOperation::WorkingTree, args)?;
let stdout = String::from_utf8(output.stdout).context("git output is not valid UTF-8")?;
Ok(stdout.trim().to_owned())
}
pub(crate) fn git_path<I, S>(cwd: &Path, args: I) -> Result<PathBuf>
where
I: IntoIterator<Item = S>,
S: AsRef<OsStr>,
{
let output = git_output(cwd, GitOperation::Metadata, args)?;
let bytes = output.stdout.strip_suffix(b"\n").unwrap_or(&output.stdout);
#[cfg(windows)]
let bytes = bytes.strip_suffix(b"\r").unwrap_or(bytes);
git_path_from_bytes(bytes)
}
pub(crate) fn git_path_from_bytes(bytes: &[u8]) -> Result<PathBuf> {
if bytes.is_empty() {
bail!("git returned an empty path");
}
#[cfg(unix)]
{
use std::os::unix::ffi::OsStringExt;
Ok(PathBuf::from(std::ffi::OsString::from_vec(bytes.to_vec())))
}
#[cfg(not(unix))]
{
Ok(PathBuf::from(
std::str::from_utf8(bytes).context("git path is not valid UTF-8")?,
))
}
}
/// Resolves the cached repository default without fetching or inheriting Git selectors.
/// Prefer a remote HEAD (origin first), then conventional main/master refs.
pub fn default_worktree_base(cwd: &Path) -> Result<String> {
let output = git_output(
cwd,
GitOperation::Metadata,
[
"for-each-ref",
"--format=%(refname) %(symref)",
"refs/remotes",
"refs/heads",
],
)?;
// Unrelated refs may contain non-UTF-8 bytes. Decode only the chosen base,
// because CreateWorktree accepts a UTF-8 revision.
let branches = output
.stdout
.split(|byte| *byte == b'\n')
.filter_map(|line| {
let line = line.strip_suffix(b"\r").unwrap_or(line);
let separator = line.iter().position(|byte| *byte == b' ')?;
Some((&line[..separator], &line[separator + 1..]))
})
.collect::<Vec<_>>();
let base = branches
.iter()
.filter(|(name, target)| name.ends_with(b"/HEAD") && !target.is_empty())
.min_by_key(|(name, _)| (!name.starts_with(b"refs/remotes/origin/"), *name))
.map(|(_, target)| *target)
.or_else(|| {
[
b"refs/remotes/origin/main".as_slice(),
b"refs/remotes/origin/master".as_slice(),
b"refs/heads/main".as_slice(),
b"refs/heads/master".as_slice(),
]
.into_iter()
.find(|candidate| branches.iter().any(|(branch, _)| branch == candidate))
})
.context("Could not determine the project's default branch.")?;
std::str::from_utf8(base)
.context("The project's default branch is not valid UTF-8.")
.map(str::to_owned)
}
fn base_git_command(cwd: &Path) -> Command {
let mut command = Command::new("git");
// Git wrappers export repository-local state to their children. Select this
// repository from cwd, and install only our own per-command config below.
for name in [
"GIT_ALTERNATE_OBJECT_DIRECTORIES",
"GIT_CEILING_DIRECTORIES",
"GIT_CONFIG",
"GIT_CONFIG_PARAMETERS",
"GIT_CONFIG_COUNT",
"GIT_OBJECT_DIRECTORY",
"GIT_DIR",
"GIT_WORK_TREE",
"GIT_IMPLICIT_WORK_TREE",
"GIT_GRAFT_FILE",
"GIT_INDEX_FILE",
"GIT_NO_REPLACE_OBJECTS",
"GIT_REPLACE_REF_BASE",
"GIT_PREFIX",
"GIT_SHALLOW_FILE",
"GIT_COMMON_DIR",
] {
command.env_remove(name);
}
command
.current_dir(cwd)
.arg("-c")
.arg(SAFE_BARE_REPOSITORY_CONFIG)
.arg("-c")
.arg(format!("core.hooksPath={DISABLED_HOOKS_PATH}"))
.arg("-c")
.arg("core.fsmonitor=")
.arg("-c")
.arg("attr.tree=")
.arg("-c")
.arg("core.attributesFile=")
.env("GIT_LFS_SKIP_SMUDGE", "1")
.env("GIT_TERMINAL_PROMPT", "0");
scrub_non_inheritable_env_vars(&mut command);
command
}
fn configured_filters(cwd: &Path) -> Result<BTreeSet<String>> {
let output = base_git_command(cwd)
.args([
"config",
"--null",
"--name-only",
"--get-regexp",
"^filter\\.",
])
.output()
.context("failed to inspect Git filter configuration")?;
if !output.status.success() {
if output.status.code() == Some(1) {
return Ok(BTreeSet::new());
}
ensure_git_success(&output)?;
}
let mut filters = BTreeSet::new();
let names = String::from_utf8(output.stdout).context("Git filter names are not valid UTF-8")?;
for name in names.split('\0') {
if let Some((driver, attribute)) = name
.strip_prefix("filter.")
.and_then(|name| name.rsplit_once('.'))
&& !driver.is_empty()
&& matches!(attribute, "clean" | "smudge" | "process" | "required")
{
filters.insert(driver.to_owned());
}
}
Ok(filters)
}
fn ensure_git_success(output: &Output) -> Result<()> {
if output.status.success() {
return Ok(());
}
let stderr = String::from_utf8_lossy(&output.stderr);
bail!("git command failed: {}", stderr.trim())
}
#[cfg(test)]
#[path = "git_tests.rs"]
mod tests;

View File

@@ -0,0 +1,195 @@
//! Tests Git output handling and isolation from configured hooks and filters.
use std::fs;
use std::path::Path;
use std::process::Command;
#[cfg(unix)]
use anyhow::Context;
use anyhow::Result;
use pretty_assertions::assert_eq;
use tempfile::TempDir;
use super::GitOperation;
use super::configured_filters;
use super::git_output;
use super::git_stdout;
fn setup_git(cwd: &Path, args: &[&str]) -> Result<()> {
let output = Command::new("git").current_dir(cwd).args(args).output()?;
if !output.status.success() {
anyhow::bail!(
"git setup failed: {}",
String::from_utf8_lossy(&output.stderr).trim()
);
}
Ok(())
}
fn repository() -> Result<(TempDir, std::path::PathBuf)> {
let directory = tempfile::tempdir()?;
let root = directory.path().join("repository");
fs::create_dir(&root)?;
setup_git(&root, &["init", "-b", "main"])?;
setup_git(&root, &["config", "user.name", "Codex Test"])?;
setup_git(&root, &["config", "user.email", "codex@example.invalid"])?;
fs::write(root.join("tracked.txt"), "tracked\n")?;
setup_git(&root, &["add", "tracked.txt"])?;
setup_git(&root, &["commit", "--no-gpg-sign", "-m", "initial"])?;
Ok((directory, root))
}
#[test]
fn git_stdout_returns_trimmed_output() -> Result<()> {
let (_directory, root) = repository()?;
assert_eq!(git_stdout(&root, ["branch", "--show-current"])?, "main");
Ok(())
}
#[test]
fn git_output_reports_nonzero_exit_status() -> Result<()> {
let (_directory, root) = repository()?;
let error = git_output(
&root,
GitOperation::WorkingTree,
["rev-parse", "--verify", "missing-ref"],
)
.expect_err("unknown revision should fail");
assert!(error.to_string().contains("git command failed"));
Ok(())
}
#[test]
fn discovers_filter_drivers_with_dotted_names() -> Result<()> {
let (_directory, root) = repository()?;
setup_git(
&root,
&["config", "filter.some.nested.driver.smudge", "cat"],
)?;
setup_git(&root, &["config", "filter.simple.required", "true"])?;
setup_git(&root, &["config", "filter.x=y.process", "cat"])?;
let filters = configured_filters(&root)?;
assert!(filters.contains("some.nested.driver"));
assert!(filters.contains("simple"));
assert!(filters.contains("x=y"));
Ok(())
}
#[cfg(unix)]
#[test]
fn checkout_does_not_execute_configured_hooks_fsmonitor_or_filters() -> Result<()> {
let (directory, root) = repository()?;
fs::write(root.join(".gitattributes"), "*.txt filter=x=y -text\n")?;
setup_git(&root, &["add", ".gitattributes"])?;
setup_git(&root, &["commit", "--no-gpg-sign", "-m", "attributes"])?;
let hooks = directory.path().join("hooks");
fs::create_dir(&hooks)?;
let hook_marker = directory.path().join("hook-executed");
let hook = hooks.join("post-checkout");
write_marker_script(&hook, &hook_marker)?;
let fsmonitor_marker = directory.path().join("fsmonitor-executed");
let fsmonitor = directory.path().join("fsmonitor");
write_marker_script(&fsmonitor, &fsmonitor_marker)?;
let filter_marker = directory.path().join("filter-executed");
let filter = directory.path().join("filter");
write_marker_script(&filter, &filter_marker)?;
setup_git(
&root,
&[
"config",
"core.hooksPath",
hooks.to_str().context("hooks path")?,
],
)?;
setup_git(
&root,
&[
"config",
"core.fsmonitor",
fsmonitor.to_str().context("fsmonitor path")?,
],
)?;
for attribute in ["clean", "smudge", "process"] {
setup_git(
&root,
&[
"config",
&format!("filter.x=y.{attribute}"),
filter.to_str().context("filter path")?,
],
)?;
}
setup_git(&root, &["config", "filter.x=y.required", "true"])?;
let checkout = directory.path().join("checkout");
git_output(
&root,
GitOperation::WorkingTree,
[
"worktree",
"add",
"--detach",
checkout.to_str().context("checkout path")?,
"HEAD",
],
)?;
git_output(
&checkout,
GitOperation::WorkingTree,
["status", "--porcelain"],
)?;
assert!(!hook_marker.exists(), "repository hook was executed");
assert!(!fsmonitor_marker.exists(), "fsmonitor helper was executed");
assert!(!filter_marker.exists(), "attribute filter was executed");
assert_eq!(
fs::read_to_string(checkout.join("tracked.txt"))?,
"tracked\n"
);
Ok(())
}
#[cfg(unix)]
fn write_marker_script(path: &Path, marker: &Path) -> Result<()> {
let marker = marker.to_str().context("marker path is not valid UTF-8")?;
akode_utils_cargo_bin::write_executable(
path,
&format!("#!/bin/sh\nprintf executed > '{marker}'\ncat\n"),
)?;
Ok(())
}
#[cfg(unix)]
#[test]
fn default_base_ignores_unrelated_non_utf8_refs() -> Result<()> {
let (_directory, root) = repository()?;
let head = git_stdout(&root, ["rev-parse", "HEAD"])?;
// Packed refs work even on filesystems that cannot store non-UTF-8 filenames.
fs::write(
root.join(".git/packed-refs"),
[head.as_bytes(), b" refs/heads/unrelated-\xff\n"].concat(),
)?;
assert_eq!(super::default_worktree_base(&root)?, "refs/heads/main");
setup_git(
&root,
&["update-ref", "refs/remotes/origin/release/stable", "HEAD"],
)?;
setup_git(
&root,
&[
"symbolic-ref",
"refs/remotes/origin/HEAD",
"refs/remotes/origin/release/stable",
],
)?;
assert_eq!(
super::default_worktree_base(&root)?,
"refs/remotes/origin/release/stable"
);
Ok(())
}

View File

@@ -0,0 +1,410 @@
mod git;
mod metadata;
mod paths;
mod settings;
use crate::git::GitOperation;
use crate::git::git_output;
use crate::git::git_path;
use crate::git::git_path_from_bytes;
use crate::git::git_stdout;
use crate::paths::allocate_worktree_root;
use crate::paths::remove_empty_bucket;
use anyhow::Context;
use anyhow::Result;
use anyhow::bail;
use serde::Serialize;
use std::ffi::OsStr;
use std::fs;
use std::path::Component;
use std::path::Path;
use std::path::PathBuf;
pub use git::default_worktree_base;
pub use settings::DEFAULT_WORKTREE_KEEP_COUNT;
pub use settings::WorktreeSettings;
/// A Desktop-compatible checkout and the cwd that should be used to start its thread.
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ManagedWorktree {
pub root: PathBuf,
pub cwd: PathBuf,
pub source_root: PathBuf,
pub source_cwd: PathBuf,
pub head_sha: String,
/// A UTF-8 branch label, when available; absence does not imply detached HEAD.
pub branch: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CreateWorktree {
pub source_cwd: PathBuf,
pub base: Option<String>,
}
/// Creates and identifies worktrees using the existing Codex Desktop contract.
#[derive(Clone, Debug)]
pub struct WorktreeManager {
settings: WorktreeSettings,
}
impl WorktreeManager {
pub fn new(mut settings: WorktreeSettings) -> Self {
settings.root = dunce::simplified(&settings.root).to_path_buf();
Self { settings }
}
pub fn settings(&self) -> &WorktreeSettings {
&self.settings
}
pub fn create(&self, request: &CreateWorktree) -> Result<ManagedWorktree> {
if !self.settings.root.is_absolute() {
bail!("managed worktree root must be an absolute path");
}
let source_cwd = dunce::canonicalize(&request.source_cwd)
.with_context(|| format!("cannot resolve {}", request.source_cwd.display()))?;
let source_root = repository_root(&source_cwd)?;
let relative_cwd = source_cwd
.strip_prefix(&source_root)
.context("working directory is outside the repository root")?;
let repository_name = source_root
.file_name()
.context("repository root has no directory name")?;
let revision = format!("{}^{{commit}}", request.base.as_deref().unwrap_or("HEAD"));
let head_sha = git_stdout(
&source_root,
[
"rev-parse",
"--verify",
"--end-of-options",
revision.as_str(),
],
)?;
let root = allocate_worktree_root(&self.settings.root, repository_name)?;
let result = git_output(
&source_root,
GitOperation::WorkingTree,
[
OsStr::new("worktree"),
OsStr::new("add"),
OsStr::new("--detach"),
OsStr::new("--no-checkout"),
root.as_os_str(),
OsStr::new(&head_sha),
],
);
if let Err(error) = result {
remove_empty_bucket(&root);
return Err(error).context("cannot create managed worktree");
}
// Write only the destination's config, without changing shared settings or
// enabling worktreeConfig for the source repository.
let result = git_path(
&root,
[
"rev-parse",
"--path-format=absolute",
"--git-path",
"config.worktree",
],
)
.and_then(|config| {
git_output(
&root,
GitOperation::Metadata,
[
OsStr::new("config"),
OsStr::new("--file"),
config.as_os_str(),
OsStr::new("core.worktree"),
root.as_os_str(),
],
)?;
// Discover destination-only filters before materializing files, and pin
// the working tree even when per-worktree configuration is disabled.
git_output(
&root,
GitOperation::WorkingTree,
[
"--work-tree=.",
"reset",
"--hard",
"--no-recurse-submodules",
head_sha.as_str(),
],
)
});
if let Err(error) = result {
remove_worktree(&source_root, &root)
.context("cannot roll back an incomplete managed worktree")?;
return Err(error).context("cannot populate managed worktree");
}
let cwd = root.join(relative_cwd);
if !is_safe_worktree_cwd(&root, &cwd) {
remove_worktree(&source_root, &root)
.context("cannot roll back a worktree missing its working directory")?;
bail!(
"requested base does not contain a safe working directory {}",
relative_cwd.display()
);
}
Ok(ManagedWorktree {
cwd,
root,
source_root,
source_cwd,
head_sha,
branch: None,
})
}
pub fn list(&self, source_cwd: &Path) -> Result<Vec<ManagedWorktree>> {
let source_cwd = dunce::canonicalize(source_cwd)
.with_context(|| format!("cannot resolve {}", source_cwd.display()))?;
let source_root = repository_root(&source_cwd)?;
let relative_cwd = source_cwd
.strip_prefix(&source_root)
.context("working directory is outside the repository root")?;
let managed_root =
dunce::canonicalize(&self.settings.root).unwrap_or_else(|_| self.settings.root.clone());
let source_common_dir = resolve_git_path(&source_root, "--git-common-dir")?;
let output = git_output(
&source_cwd,
GitOperation::Metadata,
["worktree", "list", "--porcelain", "-z"],
)?;
let fields = output
.stdout
.split(|byte| *byte == b'\0')
.collect::<Vec<_>>();
let mut worktrees = Vec::new();
for entry in fields.split(|field| field.is_empty()) {
let mut root = None;
let mut head_sha = None;
let mut branch = None;
for field in entry {
if let Some(path) = field.strip_prefix(b"worktree ") {
root = Some(git_path_from_bytes(path)?);
} else if let Some(head) = field.strip_prefix(b"HEAD ") {
head_sha = Some(
std::str::from_utf8(head)
.context("worktree HEAD is not valid UTF-8")?
.to_owned(),
);
} else if let Some(name) = field.strip_prefix(b"branch ") {
branch = Some(name.strip_prefix(b"refs/heads/").unwrap_or(name));
}
}
let Some(root) = root else {
continue;
};
let Some(bucket) = root.parent() else {
continue;
};
// Keep aliases from changing which registration supplies the metadata.
if ![root.as_path(), bucket].into_iter().all(|path| {
fs::symlink_metadata(path).is_ok_and(|metadata| metadata.file_type().is_dir())
}) {
continue;
}
let canonical_root = dunce::canonicalize(&root).unwrap_or_else(|_| root.clone());
let linked_git_file = fs::symlink_metadata(canonical_root.join(".git"))
.is_ok_and(|metadata| metadata.file_type().is_file());
if !has_managed_layout(&managed_root, &canonical_root) || !linked_git_file {
continue;
}
if linked_worktree_common_dir(&canonical_root).ok().as_ref() != Some(&source_common_dir)
{
continue;
}
// A different linked checkout can occupy a stale registration's path.
// Require its administration directory to point back to this checkout.
let Ok(git_dir) = resolve_git_path(&canonical_root, "--git-dir") else {
continue;
};
let Ok(backlink) = fs::read(git_dir.join("gitdir")) else {
continue;
};
let backlink = backlink.strip_suffix(b"\n").unwrap_or(&backlink);
#[cfg(windows)]
let backlink = backlink.strip_suffix(b"\r").unwrap_or(backlink);
let Ok(backlink) = git_path_from_bytes(backlink) else {
continue;
};
let Ok(backlink) = dunce::canonicalize(git_dir.join(backlink)) else {
continue;
};
let Ok(git_file) = dunce::canonicalize(canonical_root.join(".git")) else {
continue;
};
if backlink != git_file {
continue;
}
let cwd = root.join(relative_cwd);
if !is_safe_worktree_cwd(&canonical_root, &cwd) {
continue;
}
let head_sha = head_sha
.with_context(|| format!("managed worktree {} has no HEAD", root.display()))?;
worktrees.push(ManagedWorktree {
cwd,
root,
source_root: source_root.clone(),
source_cwd: source_cwd.clone(),
head_sha,
branch: branch.and_then(|name| std::str::from_utf8(name).ok().map(str::to_owned)),
});
}
worktrees.sort_by(|left, right| left.root.cmp(&right.root));
Ok(worktrees)
}
pub fn bind_thread(&self, checkout: &Path, thread_id: &str) -> Result<()> {
let checkout = self.managed_checkout(checkout)?;
metadata::bind_thread(&checkout, thread_id)
}
pub fn owner(&self, checkout: &Path) -> Result<Option<String>> {
let checkout = self.managed_checkout(checkout)?;
metadata::owner(&checkout)
}
/// Remove a currently registered checkout from this repository, refusing local changes.
pub fn remove(&self, source_cwd: &Path, root: &Path) -> Result<()> {
let checkout = self
.list(source_cwd)?
.into_iter()
.find(|checkout| checkout.root == root)
.with_context(|| {
format!(
"{} is not a managed worktree in this repository",
root.display()
)
})?;
let source_cwd = dunce::canonicalize(source_cwd).with_context(|| {
format!("cannot resolve current directory {}", source_cwd.display())
})?;
let checkout_root = dunce::canonicalize(&checkout.root)
.with_context(|| format!("cannot resolve worktree {}", checkout.root.display()))?;
if source_cwd.starts_with(&checkout_root) {
bail!("switch to another checkout before deleting the current worktree");
}
let ignored = git_output(
&checkout.root,
GitOperation::WorkingTree,
[
OsStr::new("ls-files"),
OsStr::new("--others"),
OsStr::new("--ignored"),
OsStr::new("--exclude-standard"),
OsStr::new("-z"),
],
)?;
if !ignored.stdout.is_empty() {
bail!("worktree contains ignored local files; remove them before deleting it");
}
git_output(
&checkout.source_root,
GitOperation::WorkingTree,
[
OsStr::new("worktree"),
OsStr::new("remove"),
root.as_os_str(),
],
)?;
remove_empty_bucket(root);
Ok(())
}
fn managed_checkout(&self, checkout: &Path) -> Result<PathBuf> {
let managed_root = dunce::canonicalize(&self.settings.root).with_context(|| {
format!(
"cannot resolve managed worktree root {}",
self.settings.root.display()
)
})?;
let checkout = dunce::canonicalize(checkout)
.with_context(|| format!("cannot resolve worktree {}", checkout.display()))?;
if !has_managed_layout(&managed_root, &checkout) {
bail!("{} is not a managed worktree", checkout.display());
}
linked_worktree_common_dir(&checkout)?;
Ok(checkout)
}
}
fn remove_worktree(source_root: &Path, root: &Path) -> Result<()> {
let result = git_output(
source_root,
GitOperation::WorkingTree,
[
OsStr::new("worktree"),
OsStr::new("remove"),
OsStr::new("--force"),
root.as_os_str(),
],
);
remove_empty_bucket(root);
result.map(|_| ())
}
fn is_safe_worktree_cwd(root: &Path, cwd: &Path) -> bool {
let Ok(root) = dunce::canonicalize(root) else {
return false;
};
dunce::canonicalize(cwd).is_ok_and(|resolved| resolved.is_dir() && resolved.starts_with(&root))
}
fn linked_worktree_common_dir(checkout: &Path) -> Result<PathBuf> {
if checkout != repository_root(checkout)? {
bail!("{} is not a worktree root", checkout.display());
}
let git_dir = resolve_git_path(checkout, "--git-dir")?;
let common_dir = resolve_git_path(checkout, "--git-common-dir")?;
if git_dir == common_dir {
bail!("{} is not a linked worktree", checkout.display());
}
Ok(common_dir)
}
fn has_managed_layout(root: &Path, checkout: &Path) -> bool {
let Ok(relative) = checkout.strip_prefix(root) else {
return false;
};
let mut components = relative.components();
let Some(Component::Normal(bucket)) = components.next() else {
return false;
};
let Some(bucket) = bucket.to_str() else {
return false;
};
bucket.len() == 4
&& bucket.bytes().all(|byte| byte.is_ascii_hexdigit())
&& matches!(components.next(), Some(Component::Normal(_)))
&& components.next().is_none()
}
fn resolve_git_path(checkout: &Path, argument: &str) -> Result<PathBuf> {
let path = checkout.join(git_path(checkout, ["rev-parse", argument])?);
dunce::canonicalize(&path)
.with_context(|| format!("cannot resolve Git path {}", path.display()))
}
fn repository_root(cwd: &Path) -> Result<PathBuf> {
let path = git_path(cwd, ["rev-parse", "--show-toplevel"])?;
dunce::canonicalize(&path)
.with_context(|| format!("cannot resolve repository root {}", path.display()))
}

View File

@@ -0,0 +1,91 @@
//! Reads and binds Desktop-compatible thread ownership for managed worktrees.
//!
//! Stores a versioned `codex-thread.json` record in each worktree's Git metadata.
//! Binding publishes the record atomically without replacing another owner;
//! binding the same thread again leaves the existing record unchanged.
use crate::git::git_path;
use anyhow::Context;
use anyhow::Result;
use anyhow::bail;
use serde::Deserialize;
use serde::Serialize;
use std::fs;
use std::io::Write;
use std::path::Path;
use std::path::PathBuf;
use tempfile::NamedTempFile;
const OWNER_FILENAME: &str = "codex-thread.json";
const OWNER_VERSION: u8 = 1;
#[derive(Debug, Deserialize, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct OwnerRecord {
version: u8,
owner_thread_id: String,
}
pub(crate) fn owner(checkout: &Path) -> Result<Option<String>> {
let path = metadata_path(checkout)?;
let contents = match fs::read(&path) {
Ok(contents) => contents,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
Err(error) => {
return Err(error)
.with_context(|| format!("cannot read worktree owner at {}", path.display()));
}
};
let record: OwnerRecord = serde_json::from_slice(&contents)
.with_context(|| format!("invalid worktree owner at {}", path.display()))?;
if record.version != OWNER_VERSION || record.owner_thread_id.is_empty() {
bail!("invalid worktree owner at {}", path.display());
}
Ok(Some(record.owner_thread_id))
}
pub(crate) fn bind_thread(checkout: &Path, thread_id: &str) -> Result<()> {
if thread_id.is_empty() {
bail!("worktree owner thread ID cannot be empty");
}
if let Some(existing) = owner(checkout)? {
if existing == thread_id {
return Ok(());
}
bail!("worktree already belongs to thread {existing}");
}
let path = metadata_path(checkout)?;
let directory = path.parent().context("worktree metadata has no parent")?;
let mut temporary = NamedTempFile::new_in(directory)
.with_context(|| format!("cannot create worktree metadata in {}", directory.display()))?;
serde_json::to_writer(
&mut temporary,
&OwnerRecord {
version: OWNER_VERSION,
owner_thread_id: thread_id.to_owned(),
},
)?;
temporary.flush()?;
match temporary.persist_noclobber(&path) {
Ok(_) => Ok(()),
Err(error) if error.error.kind() == std::io::ErrorKind::AlreadyExists => {
if owner(checkout)?.as_deref() == Some(thread_id) {
Ok(())
} else {
bail!("worktree was concurrently assigned to another thread")
}
}
Err(error) => Err(error.error)
.with_context(|| format!("cannot write worktree owner at {}", path.display())),
}
}
fn metadata_path(checkout: &Path) -> Result<PathBuf> {
let path = git_path(checkout, ["rev-parse", "--git-path", OWNER_FILENAME])?;
Ok(checkout.join(path))
}

View File

@@ -0,0 +1,46 @@
//! Allocates Desktop-compatible worktree buckets and removes empty buckets.
use anyhow::Context;
use anyhow::Result;
use anyhow::bail;
use std::ffi::OsStr;
use std::fs;
use std::io;
use std::path::Path;
use std::path::PathBuf;
use uuid::Uuid;
pub(crate) fn allocate_worktree_root(root: &Path, repository_name: &OsStr) -> Result<PathBuf> {
fs::create_dir_all(root)
.with_context(|| format!("cannot create worktree root {}", root.display()))?;
#[cfg(target_os = "macos")]
{
let marker = root.join(".metadata_never_index");
fs::write(&marker, b"").with_context(|| {
format!("cannot disable Spotlight indexing at {}", marker.display())
})?;
}
for _ in 0..=u16::MAX {
let identifier = Uuid::new_v4().simple().to_string();
let bucket = root.join(&identifier[..4]);
match fs::create_dir(&bucket) {
Ok(()) => return Ok(bucket.join(repository_name)),
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {}
Err(error) => {
return Err(error).with_context(|| {
format!("cannot create worktree bucket {}", bucket.display())
});
}
}
}
bail!("all managed worktree identifiers are in use")
}
pub(crate) fn remove_empty_bucket(checkout: &Path) {
if let Some(bucket) = checkout.parent() {
let _ = fs::remove_dir(bucket);
}
}

View File

@@ -0,0 +1,92 @@
//! Resolves managed-worktree settings shared with Desktop.
//! CLI allocation uses the same root without enabling automatic cleanup.
use anyhow::Context;
use anyhow::Result;
use anyhow::bail;
use serde_json::Value;
use std::collections::HashMap;
use std::path::Path;
use std::path::PathBuf;
const WORKTREE_ROOT: &str = "git-worktree-root";
const AUTO_CLEANUP: &str = "worktree-auto-cleanup-enabled";
const KEEP_COUNT: &str = "worktree-keep-count";
pub const DEFAULT_WORKTREE_KEEP_COUNT: usize = 15;
/// Effective host-local settings for managed worktrees.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct WorktreeSettings {
pub root: PathBuf,
pub auto_cleanup_enabled: bool,
pub keep_count: usize,
}
impl WorktreeSettings {
/// Shares Desktop's allocation root while leaving CLI cleanup disabled.
pub fn for_cli(codex_home: &Path, desktop: Option<&HashMap<String, Value>>) -> Result<Self> {
let desktop = desktop
.and_then(|settings| settings.get(WORKTREE_ROOT))
.map(|root| HashMap::from([(WORKTREE_ROOT.to_owned(), root.clone())]));
Ok(Self {
auto_cleanup_enabled: false,
..Self::from_desktop_config(codex_home, desktop.as_ref())?
})
}
/// Resolves existing `[desktop]` values without introducing another config format.
pub fn from_desktop_config(
codex_home: &Path,
desktop: Option<&HashMap<String, Value>>,
) -> Result<Self> {
let root = match desktop.and_then(|settings| settings.get(WORKTREE_ROOT)) {
None | Some(Value::Null) => codex_home.join("worktrees"),
Some(value) => {
let configured = value
.as_str()
.context("desktop.git-worktree-root must be a string")?
.trim();
if configured.is_empty() {
codex_home.join("worktrees")
} else {
let path = PathBuf::from(configured);
if !path.is_absolute() {
bail!("desktop.git-worktree-root must be an absolute path");
}
path
}
}
};
let auto_cleanup_enabled = desktop
.and_then(|settings| settings.get(AUTO_CLEANUP))
.map(|value| {
value
.as_bool()
.context("desktop.worktree-auto-cleanup-enabled must be a boolean")
})
.transpose()?
.unwrap_or(true);
let keep_count = desktop
.and_then(|settings| settings.get(KEEP_COUNT))
.map(|value| {
let count = value
.as_u64()
.context("desktop.worktree-keep-count must be a positive integer")?;
if count == 0 {
bail!("desktop.worktree-keep-count must be a positive integer");
}
usize::try_from(count).context("desktop.worktree-keep-count is too large")
})
.transpose()?
.unwrap_or(DEFAULT_WORKTREE_KEEP_COUNT);
Ok(Self {
root: dunce::simplified(&root).to_path_buf(),
auto_cleanup_enabled,
keep_count,
})
}
}

View File

@@ -0,0 +1,76 @@
#![allow(clippy::expect_used)]
use akode_worktree::WorktreeSettings;
use pretty_assertions::assert_eq;
use serde_json::Value;
use serde_json::json;
use std::collections::HashMap;
fn desktop_config(entries: [(&str, Value); 3]) -> HashMap<String, Value> {
entries
.into_iter()
.map(|(key, value)| (key.to_owned(), value))
.collect()
}
#[test]
fn default_settings_match_desktop_worktree_defaults() {
let codex_home = tempfile::tempdir().expect("create Codex home");
let settings = WorktreeSettings::from_desktop_config(codex_home.path(), /*desktop*/ None)
.expect("load default worktree settings");
assert_eq!(
settings,
WorktreeSettings {
root: codex_home.path().join("worktrees"),
auto_cleanup_enabled: true,
keep_count: 15,
}
);
}
#[test]
fn desktop_settings_use_existing_root_and_retention_keys() {
let codex_home = tempfile::tempdir().expect("create Codex home");
let custom_root = codex_home.path().join("custom-managed-worktrees");
let desktop = desktop_config([
(
"git-worktree-root",
json!(custom_root.to_string_lossy().into_owned()),
),
("worktree-auto-cleanup-enabled", json!(false)),
("worktree-keep-count", json!(4)),
]);
let settings = WorktreeSettings::from_desktop_config(codex_home.path(), Some(&desktop))
.expect("load existing Desktop worktree settings");
assert_eq!(
settings,
WorktreeSettings {
root: custom_root,
auto_cleanup_enabled: false,
keep_count: 4,
}
);
}
#[test]
fn desktop_settings_reject_invalid_root_and_retention_values() {
let codex_home = tempfile::tempdir().expect("create Codex home");
let invalid_configs = [
HashMap::from([("git-worktree-root".to_owned(), json!("relative/worktrees"))]),
HashMap::from([("worktree-auto-cleanup-enabled".to_owned(), json!("yes"))]),
HashMap::from([("worktree-keep-count".to_owned(), json!(0))]),
HashMap::from([("worktree-keep-count".to_owned(), json!(-1))]),
HashMap::from([("worktree-keep-count".to_owned(), json!(1.5))]),
];
for desktop in invalid_configs {
assert!(
WorktreeSettings::from_desktop_config(codex_home.path(), Some(&desktop)).is_err(),
"invalid Desktop worktree settings were accepted: {desktop:?}",
);
}
}

View File

@@ -0,0 +1,980 @@
#![allow(clippy::expect_used)]
use akode_worktree::CreateWorktree;
use akode_worktree::ManagedWorktree;
use akode_worktree::WorktreeManager;
use akode_worktree::WorktreeSettings;
use akode_worktree::default_worktree_base;
use pretty_assertions::assert_eq;
use serde_json::Value;
use serde_json::json;
use std::collections::HashMap;
use std::fs;
use std::path::Path;
use std::path::PathBuf;
use std::process::Command;
use tempfile::TempDir;
struct RepositoryFixture {
_temp_dir: TempDir,
codex_home: PathBuf,
repository: PathBuf,
}
impl RepositoryFixture {
fn new() -> Self {
let temp_dir = tempfile::tempdir().expect("create temporary test directory");
let temp_root = dunce::canonicalize(temp_dir.path()).expect("canonicalize temporary root");
let codex_home = temp_root.join("akode-home");
let repository = temp_root.join("project");
fs::create_dir_all(&codex_home).expect("create Codex home");
initialize_repository(&repository);
Self {
_temp_dir: temp_dir,
codex_home,
repository,
}
}
fn manager(&self) -> WorktreeManager {
let settings =
WorktreeSettings::from_desktop_config(&self.codex_home, /*desktop*/ None)
.expect("load default worktree settings");
WorktreeManager::new(settings)
}
}
fn initialize_repository(repository: &Path) {
fs::create_dir_all(repository.join("nested/component"))
.expect("create temporary repository directories");
run_git(repository, &["init", "--quiet"]);
fs::write(
repository.join("README.md"),
"initial repository contents\n",
)
.expect("write tracked repository file");
fs::write(
repository.join("nested/component/tracked.txt"),
"nested tracked file\n",
)
.expect("write nested tracked repository file");
run_git(repository, &["add", "."]);
commit(repository, "initial commit");
}
fn commit(repository: &Path, message: &str) {
run_git(
repository,
&["commit", "--quiet", "--no-gpg-sign", "-m", message],
);
}
fn create_worktree(
manager: &WorktreeManager,
source_cwd: &Path,
base: Option<&str>,
) -> anyhow::Result<ManagedWorktree> {
manager.create(&CreateWorktree {
source_cwd: source_cwd.to_path_buf(),
base: base.map(str::to_owned),
})
}
#[test]
fn removing_managed_worktree_refuses_dirty_or_unrelated_checkouts() {
let fixture = RepositoryFixture::new();
let manager = fixture.manager();
let checkout = create_worktree(&manager, &fixture.repository, /*base*/ None)
.expect("create managed checkout");
let other = RepositoryFixture::new();
assert!(manager.remove(&other.repository, &checkout.root).is_err());
assert!(
manager
.remove(&fixture.repository, &fixture.repository)
.is_err()
);
let aliased_current = checkout
.root
.join("..")
.join(checkout.root.file_name().expect("managed checkout name"));
assert!(
manager
.remove(&aliased_current, &checkout.root)
.expect_err("cannot remove current checkout via alias")
.to_string()
.contains("current worktree")
);
assert!(checkout.root.exists());
fs::write(checkout.root.join("unsaved.txt"), "local work\n").expect("write untracked file");
assert!(manager.remove(&fixture.repository, &checkout.root).is_err());
assert!(checkout.root.join("unsaved.txt").exists());
fs::remove_file(checkout.root.join("unsaved.txt")).expect("remove untracked file");
fs::write(fixture.repository.join(".git/info/exclude"), ".env\n")
.expect("ignore local settings file");
fs::write(checkout.root.join(".env"), "local settings\n").expect("write ignored file");
assert!(
manager
.remove(&fixture.repository, &checkout.root)
.expect_err("refuse ignored local files")
.to_string()
.contains("ignored local files")
);
assert!(checkout.root.join(".env").exists());
fs::remove_file(checkout.root.join(".env")).expect("remove ignored file");
manager
.remove(&fixture.repository, &checkout.root)
.expect("remove clean checkout");
assert!(!checkout.root.exists());
assert!(
manager
.list(&fixture.repository)
.expect("list remaining")
.is_empty()
);
}
fn git_output(repository: &Path, args: &[&str]) -> std::process::Output {
Command::new("git")
.current_dir(repository)
.args([
"-c",
"user.name=Codex Worktree Test",
"-c",
"user.email=codex-worktree-test@example.invalid",
"-c",
"commit.gpgSign=false",
"-c",
"tag.gpgSign=false",
])
.args(args)
.output()
.unwrap_or_else(|error| panic!("run git {args:?} in {repository:?}: {error}"))
}
fn run_git(repository: &Path, args: &[&str]) -> String {
let output = git_output(repository, args);
assert!(
output.status.success(),
"git {args:?} failed in {repository:?}: {}",
String::from_utf8_lossy(&output.stderr),
);
String::from_utf8(output.stdout)
.expect("git output is UTF-8")
.trim()
.to_owned()
}
#[test]
fn cli_creation_shares_default_and_custom_desktop_pools_without_enabling_cleanup() {
let fixture = RepositoryFixture::new();
for root in [None, Some(fixture.codex_home.join("custom-desktop"))] {
let desktop =
root.map(|root| HashMap::from([("git-worktree-root".to_owned(), json!(root))]));
let desktop_settings =
WorktreeSettings::from_desktop_config(&fixture.codex_home, desktop.as_ref())
.expect("resolve desktop settings");
let mut cli_desktop = desktop.unwrap_or_default();
cli_desktop.insert("worktree-auto-cleanup-enabled".to_owned(), json!("unused"));
cli_desktop.insert("worktree-keep-count".to_owned(), json!(0));
let manager = WorktreeManager::new(
WorktreeSettings::for_cli(&fixture.codex_home, Some(&cli_desktop))
.expect("resolve CLI settings"),
);
let worktree = create_worktree(&manager, &fixture.repository, /*base*/ None)
.expect("create CLI worktree");
assert!(worktree.root.starts_with(&desktop_settings.root));
assert_eq!(
manager.settings(),
&WorktreeSettings {
auto_cleanup_enabled: false,
..desktop_settings.clone()
}
);
assert_eq!(
WorktreeManager::new(desktop_settings)
.list(&fixture.repository)
.expect("list desktop worktrees"),
vec![worktree],
);
}
}
#[test]
fn thread_binding_rejects_primary_and_unmanaged_worktrees() {
let fixture = RepositoryFixture::new();
let manager = fixture.manager();
fs::create_dir_all(&manager.settings().root).expect("create managed root");
assert!(
manager
.bind_thread(&fixture.repository, "not-a-managed-thread")
.is_err(),
);
assert!(
!fixture.repository.join(".git/codex-thread.json").exists(),
"primary checkout ownership metadata must not be modified",
);
let unmanaged = manager.settings().root.join("scratch").join("project");
fs::create_dir_all(unmanaged.parent().expect("unmanaged parent"))
.expect("create unmanaged parent");
run_git(
&fixture.repository,
&[
"worktree",
"add",
"--detach",
unmanaged.to_str().expect("UTF-8 unmanaged worktree"),
"HEAD",
],
);
assert!(manager.bind_thread(&unmanaged, "unmanaged").is_err());
assert!(manager.owner(&unmanaged).is_err());
}
#[test]
fn thread_binding_writes_the_exact_desktop_owner_schema_into_git_metadata() {
let fixture = RepositoryFixture::new();
let manager = fixture.manager();
let checkout = manager.settings().root.join("a1b2/project");
fs::create_dir_all(checkout.parent().expect("checkout parent")).expect("create bucket");
run_git(
&fixture.repository,
&[
"worktree",
"add",
"--detach",
checkout.to_str().expect("UTF-8 checkout"),
"HEAD",
],
);
let thread_id = "019f1234-5678-7000-8000-000000000001";
assert_eq!(manager.owner(&checkout).expect("read initial owner"), None);
manager
.bind_thread(&checkout, thread_id)
.expect("bind managed worktree to thread");
assert_eq!(
manager.owner(&checkout).expect("read bound owner"),
Some(thread_id.to_owned()),
);
let metadata_path = checkout.join(run_git(
&checkout,
&["rev-parse", "--git-path", "codex-thread.json"],
));
let metadata: Value = serde_json::from_slice(
&fs::read(&metadata_path).expect("read Desktop-compatible worktree owner metadata"),
)
.expect("parse Desktop-compatible worktree owner metadata");
assert_eq!(
metadata,
json!({
"version": 1,
"ownerThreadId": thread_id,
}),
);
}
#[test]
fn creation_uses_desktop_hash_bucket_layout_and_detached_head() {
let fixture = RepositoryFixture::new();
let manager = fixture.manager();
let source_head = run_git(&fixture.repository, &["rev-parse", "HEAD"]);
let worktree = create_worktree(&manager, &fixture.repository, /*base*/ None)
.expect("create managed worktree");
assert_eq!(
manager
.settings()
.root
.join(".metadata_never_index")
.is_file(),
cfg!(target_os = "macos"),
);
assert_eq!(
worktree.root.parent().and_then(Path::parent),
Some(fixture.codex_home.join("worktrees").as_path())
);
assert_eq!(
worktree.root.file_name(),
fixture.repository.file_name(),
"Desktop expects the repository name underneath the hash bucket",
);
let bucket = worktree
.root
.parent()
.and_then(Path::file_name)
.and_then(|name| name.to_str())
.expect("worktree has a UTF-8 hash-bucket directory");
assert_eq!(bucket.len(), 4);
assert!(bucket.bytes().all(|byte| byte.is_ascii_hexdigit()));
assert_eq!(worktree.cwd, worktree.root);
assert_eq!(worktree.source_root, fixture.repository);
assert_eq!(worktree.source_cwd, worktree.source_root);
assert_eq!(worktree.head_sha, source_head);
assert_eq!(worktree.branch, None);
assert_eq!(run_git(&worktree.root, &["rev-parse", "HEAD"]), source_head);
assert!(
!git_output(&worktree.root, &["symbolic-ref", "--quiet", "HEAD"])
.status
.success(),
"Desktop-managed worktrees start with a detached HEAD",
);
}
#[test]
fn creation_preserves_the_source_working_directory_relative_to_the_repository() {
let fixture = RepositoryFixture::new();
let manager = fixture.manager();
fs::create_dir_all(&manager.settings().root).expect("precreate managed worktree root");
let source_cwd = fixture.repository.join("nested/component");
let worktree = create_worktree(&manager, &source_cwd, /*base*/ None)
.expect("create worktree from nested source directory");
assert_eq!(worktree.source_root, fixture.repository);
assert_eq!(worktree.source_cwd, source_cwd);
assert_eq!(worktree.cwd, worktree.root.join("nested/component"));
assert!(worktree.cwd.join("tracked.txt").is_file());
assert_eq!(
manager
.settings()
.root
.join(".metadata_never_index")
.is_file(),
cfg!(target_os = "macos"),
);
}
#[test]
fn creation_respects_an_explicit_starting_commit() {
let fixture = RepositoryFixture::new();
let manager = fixture.manager();
let initial_commit = run_git(&fixture.repository, &["rev-parse", "HEAD"]);
fs::write(fixture.repository.join("second.txt"), "second commit\n")
.expect("write another tracked repository file");
run_git(&fixture.repository, &["add", "second.txt"]);
commit(&fixture.repository, "second commit");
let worktree = create_worktree(&manager, &fixture.repository, Some(&initial_commit))
.expect("create worktree from explicit commit");
assert_eq!(worktree.head_sha, initial_commit);
assert_eq!(
run_git(&worktree.root, &["rev-parse", "HEAD"]),
initial_commit
);
assert!(!worktree.root.join("second.txt").exists());
}
#[test]
fn creation_peels_annotated_tags_to_the_checked_out_commit() {
let fixture = RepositoryFixture::new();
let manager = fixture.manager();
let commit = run_git(&fixture.repository, &["rev-parse", "HEAD"]);
run_git(
&fixture.repository,
&["tag", "-a", "release", "-m", "annotated release"],
);
let worktree = create_worktree(&manager, &fixture.repository, Some("release"))
.expect("create worktree from annotated tag");
assert_eq!(worktree.head_sha, commit);
assert_eq!(run_git(&worktree.root, &["rev-parse", "HEAD"]), commit);
}
#[cfg(unix)]
#[test]
fn creation_rejects_a_working_directory_that_escapes_through_a_base_symlink() {
let fixture = RepositoryFixture::new();
let manager = fixture.manager();
let original = run_git(&fixture.repository, &["rev-parse", "HEAD"]);
let outside = fixture.codex_home.join("outside-worktree");
fs::create_dir_all(&outside).expect("create outside directory");
let linked_directory = fixture.repository.join("nested/component");
fs::remove_dir_all(&linked_directory).expect("remove existing tracked directory");
std::os::unix::fs::symlink(&outside, &linked_directory)
.expect("replace tracked directory with an escaping symlink");
run_git(&fixture.repository, &["add", "-A"]);
commit(
&fixture.repository,
"introduce escaping working-directory symlink",
);
let unsafe_revision = run_git(&fixture.repository, &["rev-parse", "HEAD"]);
run_git(&fixture.repository, &["reset", "--hard", &original]);
let registered_before = run_git(&fixture.repository, &["worktree", "list", "--porcelain"]);
assert!(
create_worktree(&manager, &linked_directory, Some(&unsafe_revision)).is_err(),
"an escaping destination symlink must never become the thread cwd",
);
assert_eq!(
run_git(&fixture.repository, &["worktree", "list", "--porcelain"]),
registered_before
);
}
#[test]
fn creation_ignores_inherited_git_environment() {
const CHILD_ROOT: &str = "AKODE_WORKTREE_ENV_TEST_ROOT";
if let Some(root) = std::env::var_os(CHILD_ROOT) {
let root = PathBuf::from(root);
let source = root.join("project");
let source_cwd = source.join("nested/component");
let settings =
WorktreeSettings::from_desktop_config(&root.join("akode-home"), /*desktop*/ None)
.expect("fixture operation succeeds");
let base = default_worktree_base(&source_cwd).expect("resolve source default");
assert_eq!(base, "refs/remotes/origin/source-default");
let worktree = create_worktree(&WorktreeManager::new(settings), &source_cwd, Some(&base))
.expect("fixture operation succeeds");
assert_eq!(worktree.source_root, source);
assert_eq!(worktree.source_cwd, source_cwd);
assert_eq!(
worktree.head_sha,
std::env::var("AKODE_WORKTREE_ENV_TEST_HEAD").expect("fixture operation succeeds")
);
return;
}
let fixture = RepositoryFixture::new();
let other = fixture.codex_home.join("other-repository");
initialize_repository(&other);
fs::write(other.join("other.txt"), "different repository").expect("fixture operation succeeds");
run_git(&other, &["add", "."]);
commit(&other, "different repository");
fs::write(
fixture.repository.join(".gitattributes"),
"*.txt filter=review\n",
)
.expect("fixture operation succeeds");
run_git(&fixture.repository, &["add", "."]);
commit(&fixture.repository, "checkout filter attributes");
for (repository, branch) in [
(&fixture.repository, "source-default"),
(&other, "other-default"),
] {
let target = format!("refs/remotes/origin/{branch}");
run_git(repository, &["update-ref", &target, "HEAD"]);
run_git(
repository,
&["symbolic-ref", "refs/remotes/origin/HEAD", &target],
);
}
let mut child = Command::new(std::env::current_exe().expect("current test executable"));
child
.args(["--exact", "creation_ignores_inherited_git_environment", "--nocapture"])
.env(CHILD_ROOT, fixture.repository.parent().expect("fixture parent"))
.env("AKODE_WORKTREE_ENV_TEST_HEAD", run_git(&fixture.repository, &["rev-parse", "HEAD"]))
.env("GIT_DIR", other.join(".git"))
.env("GIT_COMMON_DIR", other.join(".git"))
.env("GIT_CEILING_DIRECTORIES", &fixture.repository)
.env("GIT_WORK_TREE", &fixture.repository)
.env("GIT_CONFIG_COUNT", "1")
.env("GIT_CONFIG_KEY_0", "filter.review.required")
.env("GIT_CONFIG_VALUE_0", "true")
.env("GIT_CONFIG_PARAMETERS", "'filter.review.process=codex-worktree-nonexistent-filter' 'filter.review.required=true'");
let output = child.output().expect("fixture operation succeeds");
assert!(
output.status.success(),
"child failed: {}\n{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr),
);
}
#[test]
fn creation_disables_filters_from_destination_conditional_config() {
let fixture = RepositoryFixture::new();
fs::write(
fixture.repository.join(".gitattributes"),
"*.txt filter=late text eol=lf\n",
)
.expect("write checkout attributes");
run_git(&fixture.repository, &["add", "."]);
commit(&fixture.repository, "checkout attributes");
let config = fixture.codex_home.join("destination.gitconfig");
fs::write(
&config,
"[filter \"late\"]\nsmudge = codex-worktree-nonexistent-filter\nrequired = true\n",
)
.expect("write conditional filter config");
let git_dir = fixture.repository.join(".git/worktrees");
let condition = format!(
"includeIf.gitdir:{}/.path",
git_dir.to_string_lossy().replace('\\', "/")
);
run_git(
&fixture.repository,
&["config", &condition, config.to_str().expect("UTF-8 config")],
);
let worktree = create_worktree(&fixture.manager(), &fixture.repository, /*base*/ None)
.expect("checkout must not invoke the destination-only filter");
assert_eq!(
fs::read_to_string(worktree.root.join("nested/component/tracked.txt"))
.expect("read checked out file"),
"nested tracked file\n",
);
}
#[test]
fn creation_preserves_dirty_source_with_shared_git_config() {
let fixture = RepositoryFixture::new();
initialize_repository(&fixture.repository.join("submodule"));
run_git(
&fixture.repository,
&["submodule", "add", "./submodule", "submodule"],
);
commit(&fixture.repository, "add initialized submodule");
for (key, value) in [
(
"core.worktree",
fixture.repository.to_str().expect("UTF-8 repository"),
),
("extensions.worktreeConfig", "true"),
("core.autocrlf", "false"),
("submodule.recurse", "true"),
] {
run_git(&fixture.repository, &["config", key, value]);
}
let config_path = fixture.repository.join(".git/config");
let source_config = fs::read(&config_path).expect("read shared Git config");
let path = "nested/component/tracked.txt";
let original = fs::read(fixture.repository.join(path)).expect("read committed file");
let dirty = b"uncommitted source contents";
fs::write(fixture.repository.join(path), dirty).expect("dirty the source checkout");
let worktree = create_worktree(&fixture.manager(), &fixture.repository, /*base*/ None)
.expect("create without resetting the source checkout");
assert_eq!(
(
fs::read(fixture.repository.join(path)).expect("read dirty source file"),
fs::read(worktree.root.join(path)).expect("read new checkout file"),
fs::read(config_path).expect("reread shared Git config"),
),
(dirty.to_vec(), original, source_config),
);
assert_eq!(
(
PathBuf::from(run_git(&worktree.cwd, &["rev-parse", "--show-toplevel"])),
run_git(&worktree.cwd, &["status", "--porcelain"]),
),
(worktree.root, String::new()),
);
}
#[test]
fn creation_rolls_back_when_the_base_lacks_the_source_subdirectory() {
let fixture = RepositoryFixture::new();
let manager = fixture.manager();
let older_commit = run_git(&fixture.repository, &["rev-parse", "HEAD"]);
let source_cwd = fixture.repository.join("introduced/later");
fs::create_dir_all(&source_cwd).expect("create newly introduced source directory");
fs::write(source_cwd.join("tracked.txt"), "new directory\n")
.expect("write newly introduced tracked file");
run_git(&fixture.repository, &["add", "."]);
commit(&fixture.repository, "introduce source directory");
let registered_before = run_git(&fixture.repository, &["worktree", "list", "--porcelain"]);
assert!(
create_worktree(&manager, &source_cwd, Some(&older_commit)).is_err(),
"a destination cwd missing from the requested base must fail",
);
assert_eq!(
run_git(&fixture.repository, &["worktree", "list", "--porcelain"]),
registered_before
);
assert_eq!(
fs::read_dir(&manager.settings().root)
.expect("read managed root")
.filter(|entry| {
entry
.as_ref()
.expect("read managed root entry")
.file_type()
.expect("read managed root entry type")
.is_dir()
})
.count(),
0,
"failed creation must remove its own empty bucket",
);
}
#[test]
fn creation_rejects_relative_roots_before_resolving_the_source() {
let directory = TempDir::new().expect("create temporary directory");
let source = directory.path().join("missing-source");
let settings = WorktreeSettings::from_desktop_config(
Path::new("relative-codex-home"),
/*desktop*/ None,
)
.expect("load settings with a relative default root");
let error = create_worktree(&WorktreeManager::new(settings), &source, /*base*/ None)
.expect_err("relative roots must fail before source discovery");
assert_eq!(
error.to_string(),
"managed worktree root must be an absolute path",
);
}
#[test]
fn creation_fails_for_a_directory_outside_a_git_repository() {
let fixture = RepositoryFixture::new();
let manager = fixture.manager();
let non_repository = fixture.codex_home.join("not-a-repository");
fs::create_dir_all(&non_repository).expect("create non-repository directory");
assert!(
create_worktree(&manager, &non_repository, /*base*/ None).is_err(),
"managed worktree creation requires a Git repository",
);
}
#[test]
fn listing_rejects_a_primary_checkout_even_when_its_path_matches_the_layout() {
let fixture = RepositoryFixture::new();
let manager = fixture.manager();
let primary = manager.settings().root.join("a1b2").join("ordinary");
initialize_repository(&primary);
assert!(
manager
.list(&primary)
.expect("list managed worktrees for primary checkout")
.is_empty(),
"a primary checkout under a matching path is not a managed linked worktree",
);
let git_dir = fixture.codex_home.join("separate-git-dir");
run_git(
&primary,
&[
"init",
"--separate-git-dir",
git_dir.to_str().expect("UTF-8 fixture path"),
],
);
assert!(primary.join(".git").is_file());
assert!(
manager
.list(&primary)
.expect("fixture operation succeeds")
.is_empty()
);
}
#[test]
fn listing_skips_worktrees_without_a_safe_source_working_directory() {
let fixture = RepositoryFixture::new();
let manager = fixture.manager();
let source_cwd = fixture.repository.join("nested/component");
let valid =
create_worktree(&manager, &source_cwd, /*base*/ None).expect("fixture operation succeeds");
let missing =
create_worktree(&manager, &source_cwd, /*base*/ None).expect("fixture operation succeeds");
let file =
create_worktree(&manager, &source_cwd, /*base*/ None).expect("fixture operation succeeds");
fs::remove_dir_all(&missing.cwd).expect("fixture operation succeeds");
fs::remove_dir_all(&file.cwd).expect("fixture operation succeeds");
fs::write(&file.cwd, "not a directory").expect("fixture operation succeeds");
#[cfg(unix)]
{
let escaping = create_worktree(&manager, &source_cwd, /*base*/ None)
.expect("fixture operation succeeds");
fs::remove_dir_all(&escaping.cwd).expect("fixture operation succeeds");
std::os::unix::fs::symlink(&source_cwd, &escaping.cwd).expect("fixture operation succeeds");
}
assert_eq!(
manager
.list(&source_cwd)
.expect("fixture operation succeeds"),
vec![valid]
);
}
#[test]
fn listing_rejects_a_stale_registration_reused_by_another_repository() {
let fixture = RepositoryFixture::new();
let manager = fixture.manager();
let stale = create_worktree(&manager, &fixture.repository, /*base*/ None)
.expect("fixture operation succeeds");
fs::remove_dir_all(&stale.root).expect("fixture operation succeeds");
let other = fixture.codex_home.join("other-repository");
initialize_repository(&other);
run_git(
&other,
&[
"worktree",
"add",
"--detach",
stale.root.to_str().expect("UTF-8 fixture path"),
"HEAD",
],
);
assert!(
manager
.list(&fixture.repository)
.expect("fixture operation succeeds")
.is_empty()
);
assert_eq!(
manager
.list(&other)
.expect("fixture operation succeeds")
.len(),
1
);
}
#[test]
fn listing_rejects_a_stale_registration_reused_by_the_same_repository() {
let fixture = RepositoryFixture::new();
let manager = fixture.manager();
let original = run_git(&fixture.repository, &["rev-parse", "HEAD"]);
fs::write(fixture.repository.join("second.txt"), "second commit\n")
.expect("write second revision");
run_git(&fixture.repository, &["add", "second.txt"]);
commit(&fixture.repository, "second commit");
let current = run_git(&fixture.repository, &["rev-parse", "HEAD"]);
let stale = manager.settings().root.join("a1b2/project");
let moved = manager.settings().root.join("c3d4/project");
// Use ordinary Git checkouts: manager.create pins core.worktree to its path.
for (path, revision) in [(&stale, &original), (&moved, &current)] {
fs::create_dir_all(path.parent().expect("worktree bucket"))
.expect("create worktree bucket");
run_git(
&fixture.repository,
&[
"worktree",
"add",
"--detach",
path.to_str().expect("UTF-8 fixture path"),
revision,
],
);
}
let valid = create_worktree(&manager, &fixture.repository, /*base*/ None)
.expect("create unaffected worktree");
fs::remove_dir_all(&stale).expect("remove stale checkout");
fs::rename(&moved, &stale).expect("reuse stale path without repairing registration");
assert_eq!(
manager.list(&fixture.repository).expect("list worktrees"),
vec![valid],
);
}
#[cfg(unix)]
#[test]
fn listing_rejects_checkout_and_bucket_aliases_but_allows_a_root_alias() {
let fixture = RepositoryFixture::new();
let manager = fixture.manager();
let stale = create_worktree(&manager, &fixture.repository, /*base*/ None)
.expect("create stale checkout");
fs::write(fixture.repository.join("second.txt"), "second commit\n")
.expect("write second revision");
run_git(&fixture.repository, &["add", "second.txt"]);
commit(&fixture.repository, "second commit");
let valid = create_worktree(&manager, &fixture.repository, /*base*/ None)
.expect("create valid checkout");
let expected = vec![valid.clone()];
fs::remove_dir_all(&stale.root).expect("remove stale checkout");
std::os::unix::fs::symlink(&valid.root, &stale.root).expect("alias stale checkout");
assert_eq!(
manager.list(&fixture.repository).expect("list worktrees"),
expected,
);
fs::remove_file(&stale.root).expect("remove checkout alias");
let stale_bucket = stale.root.parent().expect("stale worktree bucket");
fs::remove_dir(stale_bucket).expect("remove stale bucket");
std::os::unix::fs::symlink(
valid.root.parent().expect("valid worktree bucket"),
stale_bucket,
)
.expect("alias stale bucket");
assert_eq!(
manager.list(&fixture.repository).expect("list worktrees"),
expected,
);
let aliased_root = fixture.codex_home.join("aliased-worktrees");
std::os::unix::fs::symlink(&manager.settings().root, &aliased_root)
.expect("alias managed root");
let aliased_manager = WorktreeManager::new(WorktreeSettings {
root: aliased_root,
..manager.settings().clone()
});
assert_eq!(
aliased_manager
.list(&fixture.repository)
.expect("list worktrees through managed-root alias"),
expected,
);
}
#[cfg(unix)]
#[test]
fn listing_preserves_inventory_when_a_branch_name_is_not_utf8() {
use std::os::unix::ffi::OsStrExt;
let fixture = RepositoryFixture::new();
let manager = fixture.manager();
let worktree = create_worktree(&manager, &fixture.repository, /*base*/ None)
.expect("fixture operation succeeds");
let branch = b"refs/heads/non-utf8-\xff";
// Packed refs can represent these names even on filesystems that reject
// non-UTF-8 filenames, including APFS.
let mut packed_ref = format!("{} ", worktree.head_sha).into_bytes();
packed_ref.extend_from_slice(branch);
packed_ref.push(b'\n');
fs::write(fixture.repository.join(".git/packed-refs"), packed_ref)
.expect("fixture operation succeeds");
let output = Command::new("git")
.current_dir(&worktree.root)
.args(["symbolic-ref", "HEAD"])
.arg(std::ffi::OsStr::from_bytes(branch))
.output()
.expect("fixture operation succeeds");
assert!(output.status.success());
assert_eq!(
manager
.list(&fixture.repository)
.expect("fixture operation succeeds"),
vec![worktree]
);
// The primary checkout is not managed, but its metadata is parsed too.
fs::write(
fixture.repository.join(".git/HEAD"),
[b"ref: ".as_slice(), branch, b"\n"].concat(),
)
.expect("fixture operation succeeds");
assert_eq!(
manager
.list(&fixture.repository)
.expect("fixture operation succeeds")
.len(),
1
);
}
#[test]
fn listing_only_includes_managed_worktrees_for_the_requested_repository() {
let fixture = RepositoryFixture::new();
let manager = fixture.manager();
let first = create_worktree(&manager, &fixture.repository, /*base*/ None)
.expect("create first worktree");
let second = create_worktree(&manager, &fixture.repository, /*base*/ None)
.expect("create second worktree");
let other_repository = fixture.codex_home.join("other-project");
initialize_repository(&other_repository);
let unrelated = create_worktree(&manager, &other_repository, /*base*/ None)
.expect("create unrelated repository worktree");
let listed = manager
.list(&fixture.repository)
.expect("list managed worktrees for source repository");
let listed_roots: Vec<&Path> = listed.iter().map(|entry| entry.root.as_path()).collect();
assert_eq!(listed_roots.len(), 2);
assert!(listed_roots.contains(&first.root.as_path()));
assert!(listed_roots.contains(&second.root.as_path()));
assert!(!listed_roots.contains(&unrelated.root.as_path()));
let unrelated_list = manager
.list(&other_repository)
.expect("list managed worktrees for the other repository");
assert_eq!(unrelated_list.len(), 1);
assert_eq!(unrelated_list[0].root, unrelated.root);
}
#[test]
fn listing_ignores_worktrees_outside_the_desktop_bucket_layout() {
let fixture = RepositoryFixture::new();
let manager = fixture.manager();
let root = manager.settings().root.join("scratch").join("project");
fs::create_dir_all(root.parent().expect("scratch worktree parent"))
.expect("create scratch worktree parent");
run_git(
&fixture.repository,
&[
"worktree",
"add",
"--detach",
root.to_str().expect("UTF-8 scratch worktree"),
"HEAD",
],
);
assert!(
manager
.list(&fixture.repository)
.expect("list managed worktrees")
.is_empty(),
"non-Desktop worktrees must never enter the managed inventory",
);
}
#[cfg(unix)]
#[test]
fn creation_listing_and_thread_binding_preserve_native_repository_paths() {
use std::ffi::OsString;
#[cfg(not(target_os = "macos"))]
use std::os::unix::ffi::OsStringExt;
let fixture = RepositoryFixture::new();
let manager = fixture.manager();
for name in [
OsString::from("project with trailing space "),
OsString::from("project-東京"),
// APFS only supports creating filenames with valid UTF-8.
#[cfg(not(target_os = "macos"))]
OsString::from_vec(b"project-\xff".to_vec()),
] {
let repository = fixture.codex_home.join(&name);
initialize_repository(&repository);
let worktree = create_worktree(&manager, &repository, /*base*/ None)
.expect("create managed worktree with a native repository path");
assert_eq!(worktree.source_root, repository);
assert_eq!(worktree.root.file_name(), Some(name.as_os_str()));
let listed = manager
.list(&repository)
.expect("list managed worktrees with a native repository path");
assert_eq!(listed.len(), 1);
assert_eq!(listed[0].root, worktree.root);
manager
.bind_thread(&worktree.root, "native-path-thread")
.expect("bind managed worktree with a native repository path");
assert_eq!(
manager
.owner(&worktree.root)
.expect("read owner with a native repository path"),
Some("native-path-thread".to_owned()),
);
}
}