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,6 @@
load("//:defs.bzl", "codex_rust_crate")
codex_rust_crate(
name = "codex-home",
crate_name = "codex_home",
)

View File

@@ -0,0 +1,22 @@
[package]
edition.workspace = true
license.workspace = true
name = "codex-home"
version.workspace = true
[lib]
doctest = false
[lints]
workspace = true
[dependencies]
codex-extension-api = { workspace = true }
codex-utils-absolute-path = { workspace = true }
tokio = { workspace = true, features = ["fs"] }
tracing = { workspace = true }
[dev-dependencies]
pretty_assertions = { workspace = true }
tempfile = { workspace = true }
tokio = { workspace = true, features = ["macros", "rt"] }

View File

@@ -0,0 +1,113 @@
use std::collections::HashSet;
use std::io;
use std::sync::Arc;
use std::sync::Mutex;
use codex_extension_api::Instructions;
use codex_extension_api::LoadInstructionsFuture;
use codex_extension_api::LoadedUserInstructions;
use codex_extension_api::UserInstructionsProvider;
use codex_utils_absolute_path::AbsolutePathBuf;
const DEFAULT_AGENTS_MD_FILENAME: &str = "AGENTS.md";
const LOCAL_AGENTS_MD_FILENAME: &str = "AGENTS.override.md";
/// Loads user instructions from a Codex home directory.
#[derive(Clone, Debug)]
pub struct CodexHomeUserInstructionsProvider {
codex_home: AbsolutePathBuf,
// Cached instructions and warning history are shared across provider clones.
state: Arc<Mutex<InstructionsState>>,
}
#[derive(Debug, Default)]
struct InstructionsState {
// Failed refreshes retain the last good value; confirmed absence still clears it.
last_successful_instructions: Option<Instructions>,
// Report ongoing failures once, then again if they return after recovery.
active_warnings: HashSet<String>,
}
impl CodexHomeUserInstructionsProvider {
/// Creates a provider rooted at the supplied absolute Codex home directory.
pub fn new(codex_home: AbsolutePathBuf) -> Self {
Self {
codex_home,
state: Arc::new(Mutex::new(InstructionsState::default())),
}
}
#[tracing::instrument(name = "instructions.load", skip_all, fields(provider = "global"))]
async fn load_from_codex_home(&self) -> LoadedUserInstructions {
let mut warnings = Vec::new();
for candidate in [LOCAL_AGENTS_MD_FILENAME, DEFAULT_AGENTS_MD_FILENAME] {
let path = self.codex_home.join(candidate);
match tokio::fs::metadata(path.as_path()).await {
Ok(metadata) if !metadata.is_file() => continue,
Ok(_) => {}
Err(err) if err.kind() == io::ErrorKind::NotFound => continue,
Err(err) => {
warnings.push(format!(
"Failed to read global AGENTS.md instructions from `{}`: {err}",
path.display()
));
continue;
}
}
let data = match tokio::fs::read(path.as_path()).await {
Ok(data) => data,
Err(err) if err.kind() == io::ErrorKind::NotFound => continue,
Err(err) => {
warnings.push(format!(
"Failed to read global AGENTS.md instructions from `{}`: {err}",
path.display()
));
continue;
}
};
let contents = String::from_utf8_lossy(&data);
let trimmed = contents.trim();
if !trimmed.is_empty() {
return LoadedUserInstructions {
instructions: Some(Instructions {
text: trimmed.to_string(),
source: Some(path),
}),
warnings,
};
}
}
LoadedUserInstructions {
instructions: None,
warnings,
}
}
}
impl UserInstructionsProvider for CodexHomeUserInstructionsProvider {
fn load_user_instructions(&self) -> LoadInstructionsFuture<'_> {
Box::pin(async move {
let mut loaded = self.load_from_codex_home().await;
let mut state = self
.state
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if loaded.instructions.is_some() || loaded.warnings.is_empty() {
state
.last_successful_instructions
.clone_from(&loaded.instructions);
} else {
loaded.instructions = state.last_successful_instructions.clone();
}
let previous_warnings = std::mem::take(&mut state.active_warnings);
loaded.warnings.retain(|warning| {
state.active_warnings.insert(warning.clone())
&& !previous_warnings.contains(warning)
});
loaded
})
}
}
#[cfg(test)]
mod tests;

View File

@@ -0,0 +1,209 @@
use std::fs;
use std::path::Path;
use codex_extension_api::Instructions;
use codex_extension_api::LoadedUserInstructions;
use codex_extension_api::UserInstructionsProvider;
use codex_utils_absolute_path::AbsolutePathBuf;
use pretty_assertions::assert_eq;
use tempfile::TempDir;
use super::CodexHomeUserInstructionsProvider;
use super::DEFAULT_AGENTS_MD_FILENAME;
use super::LOCAL_AGENTS_MD_FILENAME;
fn provider(home: &TempDir) -> CodexHomeUserInstructionsProvider {
CodexHomeUserInstructionsProvider::new(
AbsolutePathBuf::try_from(home.path().to_path_buf()).expect("absolute temp dir"),
)
}
fn expected(
home: &TempDir,
filename: &str,
text: &str,
warnings: Vec<String>,
) -> LoadedUserInstructions {
LoadedUserInstructions {
instructions: Some(Instructions {
text: text.to_string(),
source: Some(
AbsolutePathBuf::try_from(home.path().join(filename))
.expect("absolute source path"),
),
}),
warnings,
}
}
#[cfg(unix)]
fn create_symlink_loop(path: &Path) {
std::os::unix::fs::symlink(
path.file_name().expect("override path should have a name"),
path,
)
.expect("create symlink loop");
}
#[cfg(windows)]
fn create_symlink_loop(path: &Path) {
std::os::windows::fs::symlink_file(
path.file_name().expect("override path should have a name"),
path,
)
.expect("create symlink loop");
}
#[tokio::test]
async fn missing_files_return_no_instructions() {
let home = TempDir::new().expect("temp dir");
assert_eq!(
provider(&home).load_user_instructions().await,
LoadedUserInstructions::default()
);
}
#[tokio::test]
async fn override_takes_precedence_over_default() {
let home = TempDir::new().expect("temp dir");
fs::write(home.path().join(DEFAULT_AGENTS_MD_FILENAME), "default").expect("write default");
fs::write(home.path().join(LOCAL_AGENTS_MD_FILENAME), "override").expect("write override");
assert_eq!(
provider(&home).load_user_instructions().await,
expected(&home, LOCAL_AGENTS_MD_FILENAME, "override", Vec::new())
);
}
#[tokio::test]
async fn empty_override_falls_back_to_trimmed_default() {
let home = TempDir::new().expect("temp dir");
fs::write(home.path().join(LOCAL_AGENTS_MD_FILENAME), " \n\t").expect("write override");
fs::write(
home.path().join(DEFAULT_AGENTS_MD_FILENAME),
"\n default instructions \n",
)
.expect("write default");
assert_eq!(
provider(&home).load_user_instructions().await,
expected(
&home,
DEFAULT_AGENTS_MD_FILENAME,
"default instructions",
Vec::new()
)
);
}
#[tokio::test]
async fn directory_override_falls_back_to_default() {
let home = TempDir::new().expect("temp dir");
fs::create_dir(home.path().join(LOCAL_AGENTS_MD_FILENAME)).expect("create override directory");
fs::write(home.path().join(DEFAULT_AGENTS_MD_FILENAME), "default").expect("write default");
assert_eq!(
provider(&home).load_user_instructions().await,
expected(&home, DEFAULT_AGENTS_MD_FILENAME, "default", Vec::new())
);
}
#[tokio::test]
async fn recoverable_override_read_error_warns_and_falls_back_to_default() {
let home = TempDir::new().expect("temp dir");
let provider = provider(&home);
let override_path = home.path().join(LOCAL_AGENTS_MD_FILENAME);
create_symlink_loop(&override_path);
fs::write(home.path().join(DEFAULT_AGENTS_MD_FILENAME), "default").expect("write default");
let read_error = fs::read(&override_path).expect_err("symlink loop should not be readable");
let warning = format!(
"Failed to read global AGENTS.md instructions from `{}`: {read_error}",
override_path.display()
);
assert_eq!(
provider.load_user_instructions().await,
expected(
&home,
DEFAULT_AGENTS_MD_FILENAME,
"default",
vec![warning.clone()]
)
);
assert_eq!(
provider.clone().load_user_instructions().await,
expected(&home, DEFAULT_AGENTS_MD_FILENAME, "default", Vec::new())
);
fs::remove_file(&override_path).expect("remove broken symlink");
assert_eq!(
provider.load_user_instructions().await,
expected(&home, DEFAULT_AGENTS_MD_FILENAME, "default", Vec::new())
);
create_symlink_loop(&override_path);
assert_eq!(
provider.load_user_instructions().await,
expected(&home, DEFAULT_AGENTS_MD_FILENAME, "default", vec![warning])
);
}
#[tokio::test]
async fn failed_refresh_retains_last_success_until_recovery_or_removal() {
let home = TempDir::new().expect("temp dir");
let provider = provider(&home);
let path = home.path().join(DEFAULT_AGENTS_MD_FILENAME);
fs::write(&path, "initial").expect("write initial instructions");
let initial = provider.load_user_instructions().await;
fs::remove_file(&path).expect("remove initial file");
create_symlink_loop(&path);
let failed = provider.load_user_instructions().await;
assert_eq!(failed.instructions, initial.instructions);
assert_eq!(failed.warnings.len(), 1);
assert_eq!(provider.load_user_instructions().await, initial);
fs::remove_file(&path).expect("remove broken symlink");
fs::write(&path, "recovered").expect("restore instructions");
assert_eq!(
provider.load_user_instructions().await,
expected(&home, DEFAULT_AGENTS_MD_FILENAME, "recovered", Vec::new()),
);
fs::write(&path, " \n").expect("clear instructions");
assert_eq!(
provider.load_user_instructions().await,
LoadedUserInstructions::default(),
);
fs::remove_file(&path).expect("remove cleared instructions");
create_symlink_loop(&path);
let failed_after_clear = provider.load_user_instructions().await;
assert_eq!(failed_after_clear.instructions, None);
assert_eq!(failed_after_clear.warnings.len(), 1);
fs::remove_file(&path).expect("remove broken symlink");
assert_eq!(
provider.load_user_instructions().await,
LoadedUserInstructions::default(),
);
}
#[tokio::test]
async fn invalid_utf8_is_lossy() {
let home = TempDir::new().expect("temp dir");
let path = home.path().join(DEFAULT_AGENTS_MD_FILENAME);
let mut invalid_utf8 = b"global".to_vec();
invalid_utf8.push(0xff);
invalid_utf8.extend_from_slice(b" doc");
fs::write(&path, &invalid_utf8).expect("write invalid utf-8");
let outcome = provider(&home).load_user_instructions().await;
assert_eq!(
outcome,
expected(
&home,
DEFAULT_AGENTS_MD_FILENAME,
"global\u{fffd} doc",
Vec::new()
)
);
}

View File

@@ -0,0 +1,3 @@
mod instructions;
pub use instructions::CodexHomeUserInstructionsProvider;