Skip to content

Commit f995325

Browse files
authored
refactor(acp): clarify agent prompt sections (#6501)
## Why The ACP prompt puts a machine-specific Workspace prefix before static base guidance and labels the user-facing agent instruction layer as the generic System section. Because the cwd varies by launch and worktree, leading with it reduces reusable prompt-prefix stability. `[Workspace]` was added in [PR #1194](#1194) as a defensive fix after a broken `~/.sprout` → `~/.buzz` migration caused agents to scan `$HOME` and trigger macOS TCC prompts. This change retains that grounding while shrinking it to the current working directory and moving dynamic environment context after the static Base prompt. ## What - Emit the prompt in Base → Workspace → Agent Instructions order - Reduce Workspace to `Current working directory: <absolute path>` - Resolve cwd as an absolute native-platform path and preserve Windows drive/UNC paths instead of checking for a leading `/` - Emit Agent Instructions for persona and standalone agent instructions across modern and legacy ACP paths - Preserve parsing for archived observer frames that used System or the former Workspace-before-Base order, and align the persona catalog label ## Risk Assessment Medium-low — this changes prompt framing for every newly created agent session. Existing archived observer frames remain parseable, and execution still uses the same ACP working directory. Cwd resolution now fails clearly instead of substituting `/` when the process directory cannot be resolved. ## References - #1103 - #1194 Generated with Codex --------- Signed-off-by: Salman Mohammed <[email protected]>
1 parent 8c0f42e commit f995325

8 files changed

Lines changed: 247 additions & 174 deletions

File tree

‎crates/buzz-acp/src/config.rs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -411,7 +411,7 @@ pub struct CliArgs {
411411
pub no_memory: bool,
412412

413413
/// Disable the [Base] platform-context section prepended to every prompt.
414-
/// When set, agents receive only the persona [System] prompt with no Buzz orientation.
414+
/// When set, agents receive only the persona `[Agent Instructions]` prompt with no Buzz orientation.
415415
#[arg(long, env = "BUZZ_ACP_NO_BASE_PROMPT")]
416416
pub no_base_prompt: bool,
417417

@@ -480,7 +480,7 @@ pub struct CliArgs {
480480
#[arg(long, env = "BUZZ_ACP_ALLOWED_RESPOND_TO", value_delimiter = ',')]
481481
pub allowed_respond_to: Option<Vec<String>>,
482482

483-
/// Team-owned instructions layered after `[System]` and before agent memory.
483+
/// Team-owned instructions layered after `[Agent Instructions]` and before agent memory.
484484
#[arg(long, env = "BUZZ_ACP_TEAM_INSTRUCTIONS")]
485485
pub team_instructions: Option<String>,
486486

‎crates/buzz-acp/src/lib.rs‎

Lines changed: 22 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ use std::sync::Arc;
1919
use std::time::Duration;
2020

2121
use acp::{AcpClient, EnvVar, McpServer};
22-
use anyhow::Result;
22+
use anyhow::{ensure, Context, Result};
2323
use buzz_core::kind::{
2424
KIND_MEMBER_ADDED_NOTIFICATION, KIND_MEMBER_REMOVED_NOTIFICATION, KIND_STREAM_MESSAGE,
2525
KIND_STREAM_REMINDER, KIND_WORKFLOW_APPROVAL_REQUESTED,
@@ -66,6 +66,22 @@ const MODELS_TIMEOUT: Duration = Duration::from_secs(10);
6666
/// human interaction, so it must not share the short probe timeout.
6767
const AUTHENTICATE_TIMEOUT: Duration = Duration::from_secs(10 * 60);
6868

69+
/// Resolve the process working directory for ACP session metadata and prompts.
70+
///
71+
/// `std::env::current_dir()` returns an absolute path on every supported
72+
/// platform. Keep the explicit invariant check so a future source cannot
73+
/// silently introduce a relative path, and surface resolution failures instead
74+
/// of substituting a misleading Unix-specific fallback.
75+
fn current_working_directory() -> Result<String> {
76+
let cwd = std::env::current_dir().context("failed to resolve current working directory")?;
77+
ensure!(
78+
cwd.is_absolute(),
79+
"current working directory is not absolute: {}",
80+
cwd.display()
81+
);
82+
Ok(cwd.to_string_lossy().into_owned())
83+
}
84+
6985
/// Publish a kind:20001 presence update event via the WebSocket connection.
7086
///
7187
/// Ephemeral kinds (20000-29999) are rejected by the HTTP bridge, so presence
@@ -2173,6 +2189,7 @@ async fn tokio_main() -> Result<()> {
21732189
}
21742190

21752191
let base_prompt_content = config.base_prompt_content.take();
2192+
let cwd = current_working_directory()?;
21762193
let ctx = Arc::new(PromptContext {
21772194
mcp_servers: build_mcp_servers(&config),
21782195
initial_message: config.initial_message.clone(),
@@ -2191,10 +2208,7 @@ async fn tokio_main() -> Result<()> {
21912208
Some(include_str!("base_prompt.md"))
21922209
},
21932210
heartbeat_prompt: config.heartbeat_prompt.clone(),
2194-
cwd: std::env::current_dir()
2195-
.unwrap_or_else(|_| std::path::PathBuf::from("/"))
2196-
.to_string_lossy()
2197-
.to_string(),
2211+
cwd,
21982212
rest_client: relay.rest_client(),
21992213
channel_info: pool::ChannelInfoResolver::new(channel_info_map, relay.rest_client()),
22002214
context_message_limit: config.context_message_limit,
@@ -4887,10 +4901,7 @@ async fn run_models(args: ModelsArgs) -> Result<()> {
48874901
use acp::{extract_model_config_options, extract_model_state};
48884902

48894903
let agent_args = config::normalize_agent_args(&args.agent.agent_command, args.agent.agent_args);
4890-
let cwd = std::env::current_dir()
4891-
.unwrap_or_else(|_| std::path::PathBuf::from("/"))
4892-
.to_string_lossy()
4893-
.to_string();
4904+
let cwd = current_working_directory()?;
48944905

48954906
// Spawn outside the timeout so we always own the child for cleanup.
48964907
// `models` subcommand doesn't use persona packs — no extra env, no codex config.
@@ -8535,7 +8546,7 @@ mod observer_payload_trim_tests {
85358546
// to 1).
85368547
let sections = [
85378548
"[Base]\nyou are a helpful agent".to_string(),
8538-
"[System]\npersona text".to_string(),
8549+
"[Agent Instructions]\npersona text".to_string(),
85398550
"[Agent Memory — core]\nremember this".to_string(),
85408551
"[Context]\nScope: thread".to_string(),
85418552
// The triggering event body, oversized on its own.
@@ -8572,7 +8583,7 @@ mod observer_payload_trim_tests {
85728583
let texts: Vec<&str> = blocks.iter().map(|b| b["text"].as_str().unwrap()).collect();
85738584
for header in [
85748585
"[Base]",
8575-
"[System]",
8586+
"[Agent Instructions]",
85768587
"[Agent Memory — core]",
85778588
"[Context]",
85788589
"[Buzz event: @mention]",

‎crates/buzz-acp/src/pool.rs‎

Lines changed: 47 additions & 94 deletions
Original file line numberDiff line numberDiff line change
@@ -1608,64 +1608,39 @@ pub(crate) fn prepend_standing_for_legacy(
16081608
}
16091609

16101610
/// Frame the `session/new` `systemPrompt` so each present prompt carries its own
1611-
/// header, keeping the base/persona boundary recoverable downstream.
1611+
/// header, keeping the base/workspace/persona boundaries recoverable downstream.
16121612
///
1613-
/// The header framing matches the legacy per-turn path (`queue::base_section`
1614-
/// for `[Base]`, `[System]\n{...}` for the persona) so the desktop observer can
1615-
/// split the combined value into labeled sub-sections. Each prompt is wrapped
1616-
/// only when present, so a persona-only agent yields `[System]\n{persona}`
1617-
/// rather than an unlabeled blob that would be mislabeled as `[Base]`.
1618-
///
1619-
/// Prepends a `[Workspace]` section naming the agent's absolute working
1620-
/// directory. The base prompt describes the workspace layout but never its
1621-
/// absolute root, so without this anchor a model fills the gap by searching
1622-
/// `$HOME` (triggering macOS TCC prompts) or by inventing its own workspace
1623-
/// directory. The line is emitted only when a real base prompt is present and
1624-
/// `cwd` is an absolute path other than the `/` fallback — naming `/` as the
1625-
/// workspace would itself invite a `$HOME`-wide scan.
1613+
/// The static base remains first for prompt-prefix caching. When a base is
1614+
/// present, the dynamic workspace anchor follows it and precedes the user-owned
1615+
/// agent instructions. A persona-only agent still yields
1616+
/// `[Agent Instructions]\n{persona}` rather than an unlabeled blob that would
1617+
/// be mislabeled as `[Base]`.
16261618
fn framed_system_prompt(
16271619
cwd: &str,
16281620
base_prompt: Option<&str>,
16291621
system_prompt: Option<&str>,
16301622
) -> Option<String> {
1631-
let body = match (base_prompt, system_prompt) {
1623+
match (base_prompt, system_prompt) {
16321624
(Some(bp), Some(sp)) => Some(format!(
1633-
"{}\n\n[System]\n{sp}",
1634-
crate::queue::base_section(bp)
1625+
"{}\n\n{}\n\n[Agent Instructions]\n{sp}",
1626+
crate::queue::base_section(bp),
1627+
workspace_section(cwd)
1628+
)),
1629+
(Some(bp), None) => Some(format!(
1630+
"{}\n\n{}",
1631+
crate::queue::base_section(bp),
1632+
workspace_section(cwd)
16351633
)),
1636-
(Some(bp), None) => Some(crate::queue::base_section(bp)),
1637-
(None, Some(sp)) => Some(format!("[System]\n{sp}")),
1634+
(None, Some(sp)) => Some(format!("[Agent Instructions]\n{sp}")),
16381635
(None, None) => None,
1639-
}?;
1640-
// Anchor the workspace only when a base prompt is present — the workspace
1641-
// section grounds the base prompt's layout description, so it is meaningless
1642-
// for a persona-only (`[System]`-only) agent that never received that layout.
1643-
match (base_prompt, workspace_section(cwd)) {
1644-
(Some(_), Some(workspace)) => Some(format!("{workspace}\n\n{body}")),
1645-
_ => Some(body),
16461636
}
16471637
}
16481638

1649-
/// Render the `[Workspace]` grounding section, or `None` when `cwd` is unusable.
1650-
///
1651-
/// Skips relative paths and the `/` fallback (`std::env::current_dir()` resolves
1652-
/// to `/` on failure): a `/`-rooted workspace line would actively encourage the
1653-
/// `$HOME`-wide scan this section exists to prevent.
1654-
fn workspace_section(cwd: &str) -> Option<String> {
1655-
if cwd != "/" && cwd.starts_with('/') {
1656-
Some(format!(
1657-
"[Workspace]\nYour absolute working directory is `{cwd}`. All workspace \
1658-
files — `AGENTS.md`, `RESEARCH/`, `PLANS/`, `GUIDES/`, `WORK_LOGS/`, \
1659-
`OUTBOX/` — and any repositories you clone (under `{cwd}/REPOS/`) live \
1660-
here. This is where you already are, so start here rather than scanning \
1661-
`$HOME`. Any specific path the user names is fine to read."
1662-
))
1663-
} else {
1664-
None
1665-
}
1639+
fn workspace_section(cwd: &str) -> String {
1640+
format!("[Workspace]\nCurrent working directory: {cwd}")
16661641
}
16671642

1668-
/// Append the team-owned instruction section after `[System]` and before core memory.
1643+
/// Append the team-owned instruction section after `[Agent Instructions]` and before core memory.
16691644
fn with_team(prompt: Option<String>, instructions: Option<&str>) -> Option<String> {
16701645
let instructions = instructions
16711646
.map(str::trim)
@@ -1856,7 +1831,7 @@ pub async fn run_prompt_task(
18561831

18571832
//
18581833
// Core memory is delivered inside the system prompt the harness already
1859-
// builds (system role for protocol >= 2, the `[System]` user-message
1834+
// builds (system role for protocol >= 2, the `[Agent Instructions]` user-message
18601835
// section for legacy agents). To put it on the wire at `session/new` for
18611836
// modern agents, the fetch must run *before* the session is created — so
18621837
// we do it here and cache the rendered section in `state.core_sections`.
@@ -4858,7 +4833,7 @@ mod tests {
48584833
fn test_heartbeat_standing_block_is_base_only() {
48594834
// A heartbeat has no channel, so core and canvas are absent by
48604835
// construction — and it has never carried the persona. Pin that the
4861-
// shared helper does not start handing heartbeats [System].
4836+
// shared helper does not start handing heartbeats [Agent Instructions].
48624837
let composed = prepend_standing_for_legacy(1, &base_only(Some("be helpful")), "tick");
48634838
assert_eq!(composed, "[Base]\nbe helpful\n\ntick");
48644839
}
@@ -4942,7 +4917,7 @@ mod tests {
49424917
let composed = prepend_standing_for_legacy(1, &full_standing(), "do the thing");
49434918
let positions: Vec<usize> = [
49444919
"[Base]",
4945-
"[System]",
4920+
"[Agent Instructions]",
49464921
"[Team Instructions]",
49474922
"[Agent Memory — core]",
49484923
"[Huddle Instructions]",
@@ -4998,86 +4973,64 @@ mod tests {
49984973
// Also the regression guard against #2372: the session title travels
49994974
// out of band in `_meta.sessionTitle`, so this exact-bytes assertion is
50004975
// what pins the framing against a `[Session]` section reappearing here.
5001-
let framed = framed_system_prompt("/", Some("base text"), Some("persona text"))
4976+
let framed = framed_system_prompt("/workspace", Some("base text"), Some("persona text"))
50024977
.expect("both present yields Some");
5003-
assert_eq!(framed, "[Base]\nbase text\n\n[System]\npersona text");
4978+
assert_eq!(
4979+
framed,
4980+
"[Base]\nbase text\n\n[Workspace]\nCurrent working directory: /workspace\n\n[Agent Instructions]\npersona text"
4981+
);
50044982
}
50054983

50064984
#[test]
50074985
fn test_framed_system_prompt_base_only_labels_base() {
5008-
let framed = framed_system_prompt("/", Some("base text"), None).expect("base yields Some");
5009-
assert_eq!(framed, "[Base]\nbase text");
5010-
}
5011-
5012-
#[test]
5013-
fn test_framed_system_prompt_persona_only_labels_system() {
5014-
// A bare persona would be mislabeled "Base" downstream — it must carry
5015-
// its own [System] header even when no base prompt exists.
50164986
let framed =
5017-
framed_system_prompt("/", None, Some("persona text")).expect("persona yields Some");
5018-
assert_eq!(framed, "[System]\npersona text");
5019-
}
5020-
5021-
#[test]
5022-
fn test_framed_system_prompt_neither_is_none() {
5023-
assert!(framed_system_prompt("/", None, None).is_none());
5024-
}
5025-
5026-
#[test]
5027-
fn test_framed_system_prompt_absolute_cwd_prepends_workspace_before_base() {
5028-
let framed = framed_system_prompt("/Users/me/.buzz", Some("base text"), None)
5029-
.expect("base yields Some");
5030-
assert!(
5031-
framed.starts_with("[Workspace]\n"),
5032-
"workspace section must lead: {framed}"
5033-
);
5034-
assert!(framed.contains("`/Users/me/.buzz`"));
5035-
assert!(
5036-
framed.contains("\n\n[Base]\nbase text"),
5037-
"base must follow the workspace section: {framed}"
4987+
framed_system_prompt("/workspace", Some("base text"), None).expect("base yields Some");
4988+
assert_eq!(
4989+
framed,
4990+
"[Base]\nbase text\n\n[Workspace]\nCurrent working directory: /workspace"
50384991
);
50394992
}
50404993

50414994
#[test]
5042-
fn test_framed_system_prompt_persona_only_omits_workspace() {
5043-
// The workspace section grounds the base prompt's layout; a persona-only
5044-
// agent never received that layout, so no [Workspace] anchor is emitted.
5045-
let framed = framed_system_prompt("/Users/me/.buzz", None, Some("persona text"))
4995+
fn test_framed_system_prompt_persona_only_labels_agent_instructions() {
4996+
// A bare persona would be mislabeled "Base" downstream — it must carry
4997+
// its own [Agent Instructions] header even when no base prompt exists.
4998+
let framed = framed_system_prompt("/workspace", None, Some("persona text"))
50464999
.expect("persona yields Some");
5047-
assert_eq!(framed, "[System]\npersona text");
5000+
assert_eq!(framed, "[Agent Instructions]\npersona text");
50485001
}
50495002

50505003
#[test]
5051-
fn test_framed_system_prompt_root_cwd_omits_workspace() {
5052-
// The "/" fallback must never be named — it would invite a $HOME scan.
5053-
let framed = framed_system_prompt("/", Some("base text"), None).expect("base yields Some");
5054-
assert_eq!(framed, "[Base]\nbase text");
5004+
fn test_framed_system_prompt_neither_is_none() {
5005+
assert!(framed_system_prompt("/workspace", None, None).is_none());
50555006
}
50565007

50575008
#[test]
5058-
fn test_workspace_section_relative_cwd_is_none() {
5059-
assert!(workspace_section("relative/path").is_none());
5060-
assert!(workspace_section("").is_none());
5009+
fn test_workspace_section_preserves_windows_cwd() {
5010+
assert_eq!(
5011+
workspace_section(r"C:\Users\me\buzz"),
5012+
"[Workspace]\nCurrent working directory: C:\\Users\\me\\buzz"
5013+
);
50615014
}
50625015

50635016
#[test]
50645017
fn test_with_core_appends_below_framed() {
50655018
let framed = with_core(
5066-
Some("[System]\npersona".to_string()),
5019+
Some("[Agent Instructions]\npersona".to_string()),
50675020
Some("[Agent Memory — core]\nbe helpful"),
50685021
)
50695022
.expect("both present yields Some");
50705023
assert_eq!(
50715024
framed,
5072-
"[System]\npersona\n\n[Agent Memory — core]\nbe helpful"
5025+
"[Agent Instructions]\npersona\n\n[Agent Memory — core]\nbe helpful"
50735026
);
50745027
}
50755028

50765029
#[test]
50775030
fn test_with_core_framed_only_passes_through() {
5078-
let framed = with_core(Some("[System]\npersona".to_string()), None)
5031+
let framed = with_core(Some("[Agent Instructions]\npersona".to_string()), None)
50795032
.expect("framed-only yields Some");
5080-
assert_eq!(framed, "[System]\npersona");
5033+
assert_eq!(framed, "[Agent Instructions]\npersona");
50815034
}
50825035

50835036
#[test]

0 commit comments

Comments
 (0)