showing agents.md at start

This commit is contained in:
pap
2025-08-07 00:20:56 +01:00
parent f25b2e8e2c
commit 72f54926ad
3 changed files with 221 additions and 7 deletions
+1 -1
View File
@@ -38,7 +38,7 @@ mod models;
mod openai_model_info;
mod openai_tools;
pub mod plan_tool;
mod project_doc;
pub mod project_doc;
pub mod protocol;
mod rollout;
pub(crate) mod safety;
+138
View File
@@ -13,6 +13,7 @@
use crate::config::Config;
use std::path::Path;
use std::path::PathBuf;
use tokio::io::AsyncReadExt;
use tracing::error;
@@ -90,6 +91,143 @@ async fn find_project_doc(config: &Config) -> std::io::Result<Option<String>> {
Ok(None)
}
/// Lightweight description of where user and project instruction files were
/// sourced from. Paths are absolute and only present when a corresponding file
/// exists and is non-empty.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InstructionsInfo {
pub user_instructions_path: Option<PathBuf>,
pub project_instructions_path: Option<PathBuf>,
}
/// Asynchronously collect the paths of the user instructions (from
/// `CODEX_HOME/AGENTS.md`) and the project instructions (nearest `AGENTS.md`
/// discovered by [`find_project_doc`]'s search algorithm).
///
/// - If `project_doc_max_bytes == 0` we consider project docs disabled and the
/// path will be `None` even if a file exists.
/// - Empty files are treated as "not set".
pub async fn collect_instructions_info(config: &Config) -> InstructionsInfo {
let user_instructions_path = {
let mut p = config.codex_home.clone();
p.push("AGENTS.md");
match tokio::fs::read_to_string(&p).await {
Ok(s) if !s.trim().is_empty() => Some(p),
_ => None,
}
};
let project_instructions_path = if config.project_doc_max_bytes == 0 {
None
} else {
find_project_doc_path_async(config).await
};
InstructionsInfo {
user_instructions_path,
project_instructions_path,
}
}
/// Internal helper that mirrors the search performed by [`find_project_doc`] but
/// returns the discovered file path instead of the contents.
async fn find_project_doc_path_async(config: &Config) -> Option<PathBuf> {
// Attempt in cwd first.
if let Some(p) = find_first_candidate_path_async(&config.cwd, CANDIDATE_FILENAMES).await {
return Some(p);
}
// Walk up towards git root, then stop.
let mut dir = match config.cwd.canonicalize() {
Ok(c) => c,
Err(_) => config.cwd.clone(),
};
while let Some(parent) = dir.parent() {
let git_marker = dir.join(".git");
let git_exists = match tokio::fs::metadata(&git_marker).await {
Ok(_) => true,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => false,
Err(_) => false,
};
if git_exists {
return find_first_candidate_path_async(&dir, CANDIDATE_FILENAMES).await;
}
dir = parent.to_path_buf();
}
None
}
async fn find_first_candidate_path_async(dir: &Path, names: &[&str]) -> Option<PathBuf> {
for name in names {
let candidate = dir.join(name);
match tokio::fs::read_to_string(&candidate).await {
Ok(s) if !s.trim().is_empty() => return Some(candidate),
_ => continue,
}
}
None
}
/// Synchronous variant for UI code that isn't async-aware. Mirrors
/// [`collect_instructions_info`] using blocking filesystem APIs.
pub fn collect_instructions_info_sync(config: &Config) -> InstructionsInfo {
let user_instructions_path = {
let mut p = config.codex_home.clone();
p.push("AGENTS.md");
match std::fs::read_to_string(&p) {
Ok(s) if !s.trim().is_empty() => Some(p),
_ => None,
}
};
let project_instructions_path = if config.project_doc_max_bytes == 0 {
None
} else {
find_project_doc_path_sync(config)
};
InstructionsInfo {
user_instructions_path,
project_instructions_path,
}
}
fn find_project_doc_path_sync(config: &Config) -> Option<PathBuf> {
// Try cwd first
if let Some(p) = find_first_candidate_path_sync(&config.cwd, CANDIDATE_FILENAMES) {
return Some(p);
}
let mut dir = config
.cwd
.canonicalize()
.unwrap_or_else(|_| config.cwd.clone());
while let Some(parent) = dir.parent() {
let git_marker = dir.join(".git");
let git_exists = match std::fs::metadata(&git_marker) {
Ok(_) => true,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => false,
Err(_) => false,
};
if git_exists {
return find_first_candidate_path_sync(&dir, CANDIDATE_FILENAMES);
}
dir = parent.to_path_buf();
}
None
}
fn find_first_candidate_path_sync(dir: &Path, names: &[&str]) -> Option<PathBuf> {
for name in names {
let candidate = dir.join(name);
match std::fs::read_to_string(&candidate) {
Ok(s) if !s.trim().is_empty() => return Some(candidate),
_ => continue,
}
}
None
}
/// Attempt to load the first candidate file found in `dir`. Returns the file
/// contents (truncated if it exceeds `max_bytes`) when successful.
async fn load_first_candidate(
+82 -6
View File
@@ -11,6 +11,7 @@ use codex_core::config::Config;
use codex_core::plan_tool::PlanItemArg;
use codex_core::plan_tool::StepStatus;
use codex_core::plan_tool::UpdatePlanArgs;
use codex_core::project_doc::collect_instructions_info_sync;
use codex_core::protocol::FileChange;
use codex_core::protocol::McpInvocation;
use codex_core::protocol::SessionConfiguredEvent;
@@ -179,7 +180,7 @@ impl HistoryCell {
None => config.cwd.display().to_string(),
};
let lines: Vec<Line<'static>> = vec![
let mut lines: Vec<Line<'static>> = vec![
Line::from(vec![
Span::raw(">_ ").dim(),
Span::styled(
@@ -191,12 +192,67 @@ impl HistoryCell {
Line::from("".dim()),
Line::from(" Try one of the following commands to get started:".dim()),
Line::from("".dim()),
Line::from(format!(" 1. /init - {}", SlashCommand::Init.description()).dim()),
Line::from(format!(" 2. /status - {}", SlashCommand::Status.description()).dim()),
Line::from(format!(" 3. /compact - {}", SlashCommand::Compact.description()).dim()),
Line::from(format!(" 4. /new - {}", SlashCommand::New.description()).dim()),
Line::from("".dim()),
];
// If user/project instructions are configured, show their paths and
// replace the '/init' hint; otherwise keep the original '/init'.
let info = collect_instructions_info_sync(config);
let render_path = |p: &std::path::PathBuf| -> String {
match relativize_to_home(p) {
Some(rel) if !rel.as_os_str().is_empty() => format!("~/{}", rel.display()),
_ => p.display().to_string(),
}
};
let mut command_number = 1;
if info.user_instructions_path.is_some() || info.project_instructions_path.is_some() {
let mut parts: Vec<String> = Vec::new();
if let Some(p) = info.user_instructions_path.as_ref() {
parts.push(format!("user instructions ({})", render_path(p)));
}
if let Some(p) = info.project_instructions_path.as_ref() {
parts.push(format!("project instructions ({})", render_path(p)));
}
let using_line = format!(" Using {}", parts.join(" and "));
lines.push(Line::from(using_line).dim());
} else {
lines.push(
Line::from(format!(
" {}. /init - {}",
command_number,
SlashCommand::Init.description()
))
.dim(),
);
command_number += 1;
}
// Always keep the remaining suggestions.
lines.push(
Line::from(format!(
" {}. /status - {}",
command_number,
SlashCommand::Status.description()
))
.dim(),
);
command_number += 1;
lines.push(
Line::from(format!(
" {}. /compact - {}",
command_number,
SlashCommand::Compact.description()
))
.dim(),
);
command_number += 1;
lines.push(
Line::from(format!(
" {}. /new - {}",
command_number,
SlashCommand::New.description()
))
.dim(),
);
lines.push(Line::from("".dim()));
HistoryCell::WelcomeMessage {
view: TextBlock::new(lines),
}
@@ -454,6 +510,26 @@ impl HistoryCell {
let mut lines: Vec<Line<'static>> = Vec::new();
lines.push(Line::from("/status".magenta()));
// If instructions are configured, show the source paths at the top.
let info = collect_instructions_info_sync(config);
if info.user_instructions_path.is_some() || info.project_instructions_path.is_some() {
let render_path = |p: &std::path::PathBuf| -> String {
match relativize_to_home(p) {
Some(rel) if !rel.as_os_str().is_empty() => format!("~/{}", rel.display()),
_ => p.display().to_string(),
}
};
let mut parts: Vec<String> = Vec::new();
if let Some(p) = info.user_instructions_path.as_ref() {
parts.push(format!("user instructions ({})", render_path(p)));
}
if let Some(p) = info.project_instructions_path.as_ref() {
parts.push(format!("project instructions ({})", render_path(p)));
}
lines.push(Line::from(format!("Using {}", parts.join(" and "))));
lines.push(Line::from(""));
}
// Config
for (key, value) in create_config_summary_entries(config) {
lines.push(Line::from(vec![format!("{key}: ").bold(), value.into()]));