Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
Load global AGENTS.md into native agent system prompt (#56757)
Richard Feldman29ca37fdcc99
diff --git a/crates/agent/src/agent.rs b/crates/agent/src/agent.rsindex 779add105b3..e9cdfdb935f 100644--- a/crates/agent/src/agent.rs+++ b/crates/agent/src/agent.rs@@ -10,6 +10,7 @@ mod thread;mod thread_store;mod tool_permissions;mod tools;+mod user_agents_md;use context_server::ContextServerId;pub use db::*;@@ -22,6 +23,7 @@ pub use thread::*;pub use thread_store::*;pub use tool_permissions::*;pub use tools::*;+pub use user_agents_md::{UserAgentsMd, UserAgentsMdState, init as init_user_agents_md};use acp_thread::{AcpThread, AgentModelSelector, AgentSessionInfo, AgentSessionList, AgentSessionListRequest,diff --git a/crates/agent/src/templates.rs b/crates/agent/src/templates.rsindex 1eb9f9937a3..b369b07b81f 100644--- a/crates/agent/src/templates.rs+++ b/crates/agent/src/templates.rs@@ -40,6 +40,9 @@ pub struct SystemPromptTemplate<'a> {pub available_tools: Vec<SharedString>,pub model_name: Option<String>,pub date: String,+ /// Contents of the user-global `~/.config/zed/AGENTS.md` file (or the+ /// platform equivalent), if present and non-empty.+ pub user_agents_md: Option<SharedString>,}impl Template for SystemPromptTemplate<'_> {@@ -83,6 +86,7 @@ mod tests {available_tools: vec!["echo".into(), "update_plan".into()],model_name: Some("test-model".to_string()),date: "2026-01-01".to_string(),+ user_agents_md: None,};let templates = Templates::new();let rendered = template.render(&templates).unwrap();@@ -92,4 +96,57 @@ mod tests {assert!(rendered.contains("## Planning"));assert!(rendered.contains("test-model"));}++ #[test]+ fn test_system_prompt_renders_user_agents_md_before_project_rules() {+ use prompt_store::{ProjectContext, RulesFileContext, WorktreeContext};+ use util::rel_path::RelPath;++ let worktrees = vec![WorktreeContext {+ root_name: "my-project".to_string(),+ abs_path: std::path::Path::new("/tmp/my-project").into(),+ rules_file: Some(RulesFileContext {+ path_in_worktree: RelPath::unix("AGENTS.md").unwrap().into(),+ text: "project-specific guidance".to_string(),+ project_entry_id: 1,+ }),+ }];+ let project = ProjectContext::new(worktrees, Vec::new());+ let template = SystemPromptTemplate {+ project: &project,+ available_tools: vec!["echo".into()],+ model_name: Some("test-model".to_string()),+ date: "2026-01-01".to_string(),+ user_agents_md: Some("always be concise".into()),+ };+ let templates = Templates::new();+ let rendered = template.render(&templates).unwrap();++ assert!(rendered.contains("### Personal `AGENTS.md`"));+ assert!(rendered.contains("always be concise"));+ assert!(rendered.contains("### Project Rules"));+ assert!(rendered.contains("project-specific guidance"));++ let personal_idx = rendered.find("### Personal `AGENTS.md`").unwrap();+ let project_idx = rendered.find("### Project Rules").unwrap();+ assert!(+ personal_idx < project_idx,+ "personal AGENTS.md should render before project rules so project rules can override it"+ );+ }++ #[test]+ fn test_system_prompt_omits_user_agents_md_section_when_absent() {+ let project = prompt_store::ProjectContext::default();+ let template = SystemPromptTemplate {+ project: &project,+ available_tools: vec!["echo".into()],+ model_name: Some("test-model".to_string()),+ date: "2026-01-01".to_string(),+ user_agents_md: None,+ };+ let templates = Templates::new();+ let rendered = template.render(&templates).unwrap();+ assert!(!rendered.contains("### Personal `AGENTS.md`"));+ }}diff --git a/crates/agent/src/templates/system_prompt.hbs b/crates/agent/src/templates/system_prompt.hbsindex 204e4e5dea5..c7128d9cb6b 100644--- a/crates/agent/src/templates/system_prompt.hbs+++ b/crates/agent/src/templates/system_prompt.hbs@@ -212,12 +212,26 @@ To use a Skill:4. If the Skill references additional files, use `read_file` to access them. Paths inside a Skill resolve relative to that Skill's directory (the parent of its `SKILL.md`).{{/if}}-{{#if (or has_rules has_user_rules)}}+{{#if (or user_agents_md has_rules has_user_rules)}}## User's Custom InstructionsThe following additional instructions are provided by the user and should be followed to the best of your ability{{#if (gt (len available_tools) 0)}} without interfering with the tool use guidelines{{/if}}.+{{#if user_agents_md}}+### Personal `AGENTS.md`++These instructions apply to every project this user opens. Project-specific rules below may override them.++``````+{{{user_agents_md}}}+``````++{{/if}}{{#if has_rules}}+### Project Rules++These instructions are scoped to the current project. They take precedence over the personal `AGENTS.md` above when they conflict.+There are project rules that apply to these root directories:{{#each worktrees}}{{#if rules_file}}diff --git a/crates/agent/src/thread.rs b/crates/agent/src/thread.rsindex 1891112cdd4..c004305779a 100644--- a/crates/agent/src/thread.rs+++ b/crates/agent/src/thread.rs@@ -4,7 +4,7 @@ use crate::{FindPathTool, FindReferencesTool, GetCodeActionsTool, GoToDefinitionTool, GrepTool,ListDirectoryTool, MovePathTool, ProjectSnapshot, ReadFileTool, RenameTool, SpawnAgentTool,SystemPromptTemplate, Template, Templates, TerminalTool, ToolPermissionDecision,- UpdatePlanTool, WebSearchTool, WriteFileTool, decide_permission_from_settings,+ UpdatePlanTool, UserAgentsMd, WebSearchTool, WriteFileTool, decide_permission_from_settings,};use acp_thread::{MentionUri, UserMessageId};use action_log::ActionLog;@@ -3063,11 +3063,13 @@ impl Thread {self.messages.len());+ let user_agents_md = UserAgentsMd::global(cx).and_then(|s| s.content().cloned());let system_prompt = SystemPromptTemplate {project: self.project_context.read(cx),available_tools,model_name: self.model.as_ref().map(|m| m.name().0.to_string()),date: Local::now().format("%Y-%m-%d").to_string(),+ user_agents_md,}.render(&self.templates).context("failed to build system prompt")diff --git a/crates/agent/src/tools/evals/edit_file.rs b/crates/agent/src/tools/evals/edit_file.rsindex c26cfd9b0b7..08bf869d14b 100644--- a/crates/agent/src/tools/evals/edit_file.rs+++ b/crates/agent/src/tools/evals/edit_file.rs@@ -371,6 +371,7 @@ impl EditToolTest {available_tools: tool_names,model_name: None,date: chrono::Local::now().format("%Y-%m-%d").to_string(),+ user_agents_md: None,};let templates = Templates::new();template.render(&templates)?diff --git a/crates/agent/src/tools/evals/terminal_tool.rs b/crates/agent/src/tools/evals/terminal_tool.rsindex 9391f328d68..c06ce08db44 100644--- a/crates/agent/src/tools/evals/terminal_tool.rs+++ b/crates/agent/src/tools/evals/terminal_tool.rs@@ -230,6 +230,7 @@ impl TerminalToolTest {available_tools: tool_names,model_name: None,date: chrono::Local::now().format("%Y-%m-%d").to_string(),+ user_agents_md: None,};template.render(&Templates::new())?};diff --git a/crates/agent/src/tools/evals/write_file.rs b/crates/agent/src/tools/evals/write_file.rsindex d03457ffec9..b8f3de78587 100644--- a/crates/agent/src/tools/evals/write_file.rs+++ b/crates/agent/src/tools/evals/write_file.rs@@ -201,6 +201,7 @@ impl WriteToolTest {available_tools: tool_names,model_name: None,date: chrono::Local::now().format("%Y-%m-%d").to_string(),+ user_agents_md: None,};let templates = Templates::new();template.render(&templates)?diff --git a/crates/agent/src/user_agents_md.rs b/crates/agent/src/user_agents_md.rsnew file mode 100644index 00000000000..f078b0e2c8e--- /dev/null+++ b/crates/agent/src/user_agents_md.rs@@ -0,0 +1,264 @@+//! User-global `AGENTS.md` support.+//!+//! Loads `~/.config/zed/AGENTS.md` (or the platform equivalent) into an+//! in-memory global, watches the file for changes, and surfaces read errors+//! through a caller-supplied notifier (so the host application can present+//! them with the same UI it uses for settings/keymap errors).+//!+//! Empty or whitespace-only files are treated as "no user `AGENTS.md`".+//! Read errors are also treated as "no user `AGENTS.md`" for the purpose of+//! the system prompt, but the error itself is exposed via+//! [`UserAgentsMdState::Error`] and forwarded to the notifier.+//!+//! The file is read in full, mirroring how project rules / repo `AGENTS.md`+//! files are loaded by the native agent today.++use std::sync::Arc;++use fs::Fs;+use futures::StreamExt as _;+use gpui::{App, BorrowAppContext, Global, SharedString, Task};+use settings::watch_config_file;++/// In-memory state of the user-global `AGENTS.md` file.+#[derive(Debug, Default, Clone)]+pub enum UserAgentsMdState {+ /// The file is missing, empty, or whitespace-only.+ #[default]+ Empty,+ /// The file was loaded successfully; carries its trimmed contents.+ Loaded(SharedString),+ /// The file exists but could not be read; carries the error message.+ Error(SharedString),+}++impl UserAgentsMdState {+ /// The trimmed `AGENTS.md` content, if the file was loaded successfully.+ pub fn content(&self) -> Option<&SharedString> {+ match self {+ Self::Loaded(content) => Some(content),+ Self::Empty | Self::Error(_) => None,+ }+ }++ /// The most recent read error, if the file exists but could not be read.+ pub fn error(&self) -> Option<&SharedString> {+ match self {+ Self::Error(message) => Some(message),+ Self::Empty | Self::Loaded(_) => None,+ }+ }+}++/// Global wrapper that owns the current [`UserAgentsMdState`] plus the watcher+/// task responsible for keeping it up to date.+///+/// Holding the [`Task`] in a `_watcher` field (matching the+/// `_settings_files_watcher` pattern in `SettingsStore`) ties the watcher's+/// lifetime to the data it produces: replacing or removing the global cancels+/// the watcher.+pub struct UserAgentsMd {+ state: UserAgentsMdState,+ _watcher: Task<()>,+}++impl Global for UserAgentsMd {}++impl UserAgentsMd {+ pub fn global(cx: &App) -> Option<&Self> {+ cx.try_global::<UserAgentsMd>()+ }++ pub fn state(&self) -> &UserAgentsMdState {+ &self.state+ }++ /// Convenience accessor for the trimmed `AGENTS.md` content.+ pub fn content(&self) -> Option<&SharedString> {+ self.state.content()+ }++ /// Convenience accessor for the most recent read error.+ pub fn error(&self) -> Option<&SharedString> {+ self.state.error()+ }+}++/// Initialize the user-global `AGENTS.md` watcher.+///+/// Starts a background task that watches [`paths::agents_file`] for changes+/// and updates the [`UserAgentsMd`] global accordingly. The `on_change`+/// callback is invoked on the foreground thread whenever a new read completes,+/// so callers can show or dismiss notifications matching the+/// settings/keymap-error UI.+///+/// Calling this more than once replaces the previous global, which drops the+/// previous watcher task and cancels it.+pub fn init(+ fs: Arc<dyn Fs>,+ cx: &mut App,+ on_change: impl Fn(&UserAgentsMdState, &mut App) + 'static,+) {+ let watcher = spawn_watcher(fs, cx, on_change);+ cx.set_global(UserAgentsMd {+ state: UserAgentsMdState::default(),+ _watcher: watcher,+ });+}++fn spawn_watcher(+ fs: Arc<dyn Fs>,+ cx: &mut App,+ on_change: impl Fn(&UserAgentsMdState, &mut App) + 'static,+) -> Task<()> {+ let path = paths::agents_file().clone();+ let (mut rx, watcher_task) = watch_config_file(cx.background_executor(), fs.clone(), path);++ cx.spawn(async move |cx| {+ // Keep the file watcher task alive for as long as this task runs.+ let _watcher_task = watcher_task;++ // `watch_config_file` swallows file-open errors (it emits an empty+ // string when the file is missing or unreadable), so we probe the+ // path on each event to tell "missing / empty" apart from "exists but+ // failed to read". This mirrors how `settings.json` is watched, with+ // the extra probe being the only addition: settings.json doesn't need+ // to surface read errors because invalid JSON is reported separately,+ // but for AGENTS.md a raw read error is the only signal we get.+ while let Some(raw) = rx.next().await {+ let trimmed = raw.trim();+ let new_state = if !trimmed.is_empty() {+ UserAgentsMdState::Loaded(SharedString::from(trimmed.to_string()))+ } else if let Some(error) = probe_read_error(fs.as_ref(), paths::agents_file()).await {+ UserAgentsMdState::Error(error)+ } else {+ UserAgentsMdState::Empty+ };++ cx.update(|cx| {+ cx.update_global::<UserAgentsMd, _>(|md, _| {+ md.state = new_state.clone();+ });+ on_change(&new_state, cx);+ });+ }+ })+}++async fn probe_read_error(fs: &dyn Fs, path: &std::path::Path) -> Option<SharedString> {+ match fs.load(path).await {+ Ok(_) => None,+ Err(err) => {+ if let Some(io_err) = err.downcast_ref::<std::io::Error>()+ && io_err.kind() == std::io::ErrorKind::NotFound+ {+ return None;+ }+ Some(SharedString::from(format!("{err:#}")))+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use fs::FakeFs;+ use gpui::TestAppContext;+ use std::cell::RefCell;+ use std::rc::Rc;++ async fn init_test(+ cx: &mut TestAppContext,+ ) -> (Arc<FakeFs>, Rc<RefCell<Vec<UserAgentsMdState>>>) {+ cx.executor().allow_parking();+ let fs = FakeFs::new(cx.executor());+ // FakeFs requires the parent directory to exist before insert_file.+ let config_dir = paths::agents_file()+ .parent()+ .expect("AGENTS.md path should have a parent")+ .to_path_buf();+ fs.create_dir(&config_dir).await.unwrap();++ let history: Rc<RefCell<Vec<UserAgentsMdState>>> = Rc::new(RefCell::new(vec![]));+ let history_clone = history.clone();+ cx.update(|cx| {+ init(fs.clone(), cx, move |state, _cx| {+ history_clone.borrow_mut().push(state.clone());+ });+ });+ (fs, history)+ }++ #[gpui::test]+ async fn loads_initial_content(cx: &mut TestAppContext) {+ let path = paths::agents_file();+ let (fs, history) = init_test(cx).await;+ fs.insert_file(path, b"be concise".to_vec()).await;++ cx.run_until_parked();+ cx.update(|cx| {+ assert_eq!(+ UserAgentsMd::global(cx)+ .and_then(|md| md.content().cloned())+ .as_deref(),+ Some("be concise"),+ );+ assert!(+ UserAgentsMd::global(cx)+ .and_then(|md| md.error().cloned())+ .is_none()+ );+ });+ assert!(matches!(+ history.borrow().last(),+ Some(UserAgentsMdState::Loaded(_))+ ));+ }++ #[gpui::test]+ async fn empty_file_is_ignored(cx: &mut TestAppContext) {+ let path = paths::agents_file();+ let (fs, history) = init_test(cx).await;+ fs.insert_file(path, b" \n \t".to_vec()).await;++ cx.run_until_parked();+ cx.update(|cx| {+ assert!(+ UserAgentsMd::global(cx)+ .and_then(|md| md.content().cloned())+ .is_none()+ );+ });+ assert!(matches!(+ history.borrow().last(),+ Some(UserAgentsMdState::Empty)+ ));+ }++ #[gpui::test]+ async fn reacts_to_file_changes(cx: &mut TestAppContext) {+ let path = paths::agents_file();+ let (fs, _history) = init_test(cx).await;+ fs.insert_file(path, b"first".to_vec()).await;+ cx.run_until_parked();+ cx.update(|cx| {+ assert_eq!(+ UserAgentsMd::global(cx)+ .and_then(|md| md.content().cloned())+ .as_deref(),+ Some("first"),+ );+ });++ fs.insert_file(path, b"second".to_vec()).await;+ cx.run_until_parked();+ cx.update(|cx| {+ assert_eq!(+ UserAgentsMd::global(cx)+ .and_then(|md| md.content().cloned())+ .as_deref(),+ Some("second"),+ );+ });+ }+}diff --git a/crates/paths/src/paths.rs b/crates/paths/src/paths.rsindex 800ac414be1..dbdbd01ac16 100644--- a/crates/paths/src/paths.rs+++ b/crates/paths/src/paths.rs@@ -316,6 +316,15 @@ pub fn debug_scenarios_file() -> &'static PathBuf {DEBUG_SCENARIOS_FILE.get_or_init(|| config_dir().join("debug.json"))}+/// Returns the path to the user-global `AGENTS.md` file.+///+/// This file holds personal agent instructions that apply to every project the+/// user opens, and is loaded into the native Zed agent's system prompt.+pub fn agents_file() -> &'static PathBuf {+ static AGENTS_FILE: OnceLock<PathBuf> = OnceLock::new();+ AGENTS_FILE.get_or_init(|| config_dir().join("AGENTS.md"))+}+/// Returns the path to the extensions directory.////// This is where installed extensions are stored.diff --git a/crates/zed/src/main.rs b/crates/zed/src/main.rsindex 7adbbc9bb82..affe1521a68 100644--- a/crates/zed/src/main.rs+++ b/crates/zed/src/main.rs@@ -719,6 +719,7 @@ fn main() {false,cx,);+ zed::watch_user_agents_md(app_state.fs.clone(), cx);repl::init(app_state.fs.clone(), cx);recent_projects::init(cx);diff --git a/crates/zed/src/zed.rs b/crates/zed/src/zed.rsindex 8e5c04654a5..fedf9d8cf24 100644--- a/crates/zed/src/zed.rs+++ b/crates/zed/src/zed.rs@@ -15,6 +15,7 @@ pub mod visual_tests;#[cfg(target_os = "windows")]pub(crate) mod windows_only_instance;+use agent::{UserAgentsMdState, init_user_agents_md};use agent_ui::AgentDiffToolbar;use anyhow::Context as _;pub use app_menus::*;@@ -1875,6 +1876,32 @@ fn init_cursor_hide_mode(cx: &mut App) {cx.observe_global::<SettingsStore>(apply).detach();}+/// Starts watching `~/.config/zed/AGENTS.md` (or the platform equivalent) and+/// surfaces any read errors using the same notification UI as settings errors.+///+/// The file itself is loaded into [`agent::UserAgentsMd`] for inclusion in the+/// native agent's system prompt.+pub fn watch_user_agents_md(fs: Arc<dyn fs::Fs>, cx: &mut App) {+ struct UserAgentsMdParseError;+ let notification_id = NotificationId::unique::<UserAgentsMdParseError>();++ init_user_agents_md(fs, cx, move |state, cx| match state {+ UserAgentsMdState::Loaded(_) | UserAgentsMdState::Empty => {+ dismiss_app_notification(¬ification_id, cx);+ }+ UserAgentsMdState::Error(message) => {+ let path = paths::agents_file().display().to_string();+ log::error!("Failed to load user AGENTS.md from {path}: {message}");+ let body = format!("Failed to load {path}\n{message}");+ let notification_id = notification_id.clone();+ show_app_notification(notification_id, cx, move |cx| {+ let body = body.clone();+ cx.new(|cx| MessageNotification::new(body, cx))+ });+ }+ });+}+pub fn watch_settings_files(fs: Arc<dyn fs::Fs>, cx: &mut App) {MigrationNotification::set_global(cx.new(|_| MigrationNotification), cx);