From 72f54926ad96331b02105fe1777aa44646f59180 Mon Sep 17 00:00:00 2001 From: pap Date: Thu, 7 Aug 2025 00:20:56 +0100 Subject: [PATCH] showing agents.md at start --- codex-rs/core/src/lib.rs | 2 +- codex-rs/core/src/project_doc.rs | 138 +++++++++++++++++++++++++++++++ codex-rs/tui/src/history_cell.rs | 88 ++++++++++++++++++-- 3 files changed, 221 insertions(+), 7 deletions(-) diff --git a/codex-rs/core/src/lib.rs b/codex-rs/core/src/lib.rs index c728bd3125..620044bf33 100644 --- a/codex-rs/core/src/lib.rs +++ b/codex-rs/core/src/lib.rs @@ -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; diff --git a/codex-rs/core/src/project_doc.rs b/codex-rs/core/src/project_doc.rs index 9f46159d1d..37c954ac16 100644 --- a/codex-rs/core/src/project_doc.rs +++ b/codex-rs/core/src/project_doc.rs @@ -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> { 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, + pub project_instructions_path: Option, +} + +/// 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 { + // 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 { + 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 { + // 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 { + 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( diff --git a/codex-rs/tui/src/history_cell.rs b/codex-rs/tui/src/history_cell.rs index c577ce17a0..aab29fa7c7 100644 --- a/codex-rs/tui/src/history_cell.rs +++ b/codex-rs/tui/src/history_cell.rs @@ -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> = vec![ + let mut lines: Vec> = 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 = 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> = 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 = 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()]));