Base: codex-main originale (prima del fork aKode)

This commit is contained in:
Andrea
2026-11-09 10:37:42 +01:00
commit 7874033c81
10166 changed files with 2728937 additions and 0 deletions

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 codex_git_utils::SAFE_BARE_REPOSITORY_CONFIG;
use codex_git_utils::git_config_override_env;
use codex_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")?;
codex_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,
})
}
}