From ed3dce97bc93095921360296e645fd4a900613a0 Mon Sep 17 00:00:00 2001 From: Jonathan Mohrbacher Date: Sun, 22 Nov 2026 00:32:34 -0500 Subject: [PATCH] [NO-JIRA] Deliver subdirectory hints in tool responses instead of the system prompt (R20) v1.60.2 folds subdirectory hints into the system prompt, rebuilt each turn from the agent-visible tool requests. The prompt changes whenever a new directory is touched, or when compaction drops the call that found one, and each change invalidates the provider's prompt cache from the system prompt on. Hints now go once into the last successful tool result of the batch that needs them, as an assistant-only text block in the 1.54 format (lead-in plus a marker), so sessions migrated from 1.54 do not get them twice. Delivery is a pure function of the stored conversation, with no in-memory state to requeue: directories come from agent-visible tool requests, as upstream's did, and a hint counts as delivered while its hint block is in an agent-visible tool result (a marker quoted elsewhere does not count). After compaction a hint returns with the first call into its directory; truncation (honk /undo) removes the block with the calls that found the directory. X-Shepherd-Wake: johnnymo87/goose#29 --- .github/workflows/patched-test.yml | 9 +- crates/goose/src/agents/state_machine/mod.rs | 3 +- .../state_machine/ops_platform_extensions.rs | 15 +- .../agents/state_machine/ops_toolcalling.rs | 36 +- .../state_machine/subdirectory_hints.rs | 355 ++++++++++++++++++ .../tests/prompt_skill_lifecycle.rs | 22 +- 6 files changed, 414 insertions(+), 26 deletions(-) create mode 100644 crates/goose/src/agents/state_machine/subdirectory_hints.rs diff --git a/.github/workflows/patched-test.yml b/.github/workflows/patched-test.yml index 099c7aa94b46..73f6fa4bcb20 100644 --- a/.github/workflows/patched-test.yml +++ b/.github/workflows/patched-test.yml @@ -190,7 +190,14 @@ jobs: "context_mgmt::rolling::tests::rolling_settings_write_null" \ "context_mgmt::rolling::tests::rolling_state_default_absent" \ "context_mgmt::rolling::tests::rolling_state_invalid_defaults" \ - "context_mgmt::rolling::tests::rolling_state_roundtrip" + "context_mgmt::rolling::tests::rolling_state_roundtrip" \ + "agents::state_machine::subdirectory_hints::tests::hints_are_appended_to_the_tool_response_for_the_agent_only" \ + "agents::state_machine::subdirectory_hints::tests::hints_already_in_the_conversation_are_not_delivered_again" \ + "agents::state_machine::subdirectory_hints::tests::hints_hidden_from_the_agent_return_with_the_next_call_into_the_directory" \ + "agents::state_machine::subdirectory_hints::tests::a_quoted_marker_does_not_count_as_delivered" \ + "agents::state_machine::subdirectory_hints::tests::failed_tool_responses_do_not_carry_hints" \ + "agents::state_machine::subdirectory_hints::tests::hints_go_to_the_last_successful_response_in_directory_order" \ + "agents::state_machine::tests::prompt_skill_lifecycle::prompt_and_skill_lifecycle" run_exact_tests --release -p goose --features "$F" --test self_compact -- \ "test_happy_path_self_compact" \ diff --git a/crates/goose/src/agents/state_machine/mod.rs b/crates/goose/src/agents/state_machine/mod.rs index 375bcfbe6031..8e5c7a7e93d9 100644 --- a/crates/goose/src/agents/state_machine/mod.rs +++ b/crates/goose/src/agents/state_machine/mod.rs @@ -1,4 +1,4 @@ -// Modified by Jonathan Mohrbacher, 2026: export retry and compaction failure checks for turn errors; self-compaction operation; rolling memory operation. +// Modified by Jonathan Mohrbacher, 2026: export retry and compaction failure checks for turn errors; self-compaction operation; rolling memory operation; subdirectory_hints module. //! Runs an ordered, re-entrant pipeline over persisted conversation state. //! //! Callers persist incoming messages, construct `Step`s from their own operations, @@ -29,6 +29,7 @@ mod ops_tool_pair_compaction; mod ops_toolcalling; mod proactive_compaction; mod session; +mod subdirectory_hints; pub(crate) use session::run as run_goose; mod tool_approval; mod tool_confirmation; diff --git a/crates/goose/src/agents/state_machine/ops_platform_extensions.rs b/crates/goose/src/agents/state_machine/ops_platform_extensions.rs index 4215f2fde14e..aef4b9d37aa9 100644 --- a/crates/goose/src/agents/state_machine/ops_platform_extensions.rs +++ b/crates/goose/src/agents/state_machine/ops_platform_extensions.rs @@ -1,3 +1,4 @@ +// Modified by Jonathan Mohrbacher, 2026: platform tool responses carry subdirectory hints. use std::sync::{Arc, Mutex}; use anyhow::Result; @@ -121,11 +122,19 @@ impl Operation for PlatformExtensionOperation { if calls.is_empty() { return not_applicable(); } - let mut session = session.clone(); + let mut call_session = session.clone(); if let Some(directory) = tools.working_dir() { - session.working_dir = directory.to_path_buf(); + call_session.working_dir = directory.to_path_buf(); } - self.execution.run(calls, &session, emit).await + self.execution + .run( + calls, + &call_session, + conversation, + &session.working_dir, + emit, + ) + .await } async fn finalize_cancellation( diff --git a/crates/goose/src/agents/state_machine/ops_toolcalling.rs b/crates/goose/src/agents/state_machine/ops_toolcalling.rs index 37473e14f251..5e8073219c4e 100644 --- a/crates/goose/src/agents/state_machine/ops_toolcalling.rs +++ b/crates/goose/src/agents/state_machine/ops_toolcalling.rs @@ -1,3 +1,4 @@ +// Modified by Jonathan Mohrbacher, 2026: subdirectory hints are delivered in tool responses, not the system prompt. //! Exposes extension capabilities and executes requests that belong to them. use std::collections::{HashMap, HashSet}; @@ -15,6 +16,7 @@ use crate::agents::extension::ExtensionInfo; use crate::agents::extension_manager::CallRequest; use crate::agents::reply_parts::is_tool_visible_to_model; use crate::agents::state_machine::ops_llm::{ADVERTISED_TOOLS_NOTE, LLM_OPERATION_NAME}; +use crate::agents::state_machine::subdirectory_hints::deliver_subdirectory_hints; use crate::agents::state_machine::{ applied, messages_since_kickoff, not_applicable, yielded_with, Command, ConversationEffect, Emitter, GooseEffect, Operation, OperationResult, @@ -27,7 +29,6 @@ use crate::conversation::message::{ ActionRequiredData, Message, MessageContent, ProviderMetadata, ToolRequest, }; use crate::conversation::Conversation; -use crate::hints::load_hints::SubdirectoryHintTracker; use crate::session::Session; pub(super) const EXPIRED_APPROVAL_RESPONSE: &str = @@ -698,23 +699,9 @@ impl Operation for ToolExecutionOperation { async fn prompt_parts( &self, session: &Session, - conversation: &Conversation, + _conversation: &Conversation, ) -> Result> { - let mut hints = SubdirectoryHintTracker::new(); - for message in conversation - .messages() - .iter() - .filter(|message| message.is_agent_visible()) - { - for content in &message.content { - if let MessageContent::ToolRequest(request) = content { - if let Ok(tool_call) = &request.tool_call { - hints.record_tool_arguments(&tool_call.arguments, &session.working_dir); - } - } - } - } - let mut prompt_parts = hints.load_new_hints(&session.working_dir); + let mut prompt_parts = Vec::new(); let tools = ToolSnapshot::for_session(&self.tools, &self.services, &session.id).await?; #[cfg(feature = "code-mode")] @@ -847,7 +834,15 @@ impl Operation for ToolExecutionOperation { }; calls.push((request, result)); } - self.execution.run(calls, &call_session, emit).await + self.execution + .run( + calls, + &call_session, + conversation, + &session.working_dir, + emit, + ) + .await } } @@ -882,6 +877,8 @@ impl ToolExecution { &self, calls: Vec<(ToolRequest, ToolCallResult)>, session: &Session, + conversation: &Conversation, + hint_working_dir: &Path, emit: &Emitter, ) -> Result> { let mut tool_streams = Vec::new(); @@ -929,7 +926,8 @@ impl ToolExecution { } let (actions, response) = self.take_batch(); - let response = response.ok_or_else(|| anyhow!("tool batch produced no responses"))?; + let mut response = response.ok_or_else(|| anyhow!("tool batch produced no responses"))?; + deliver_subdirectory_hints(&mut response, conversation, hint_working_dir); emit.emit(AgentEvent::Message(response.user_visible_content())); applied(actions.into_iter().chain([response]).map(GooseEffect::from)) } diff --git a/crates/goose/src/agents/state_machine/subdirectory_hints.rs b/crates/goose/src/agents/state_machine/subdirectory_hints.rs new file mode 100644 index 000000000000..cacad6addbf5 --- /dev/null +++ b/crates/goose/src/agents/state_machine/subdirectory_hints.rs @@ -0,0 +1,355 @@ +// Modified by Jonathan Mohrbacher, 2026: subdirectory hints are delivered in the conversation, not the system prompt. +//! Delivers subdirectory hints once, inside the tool response that first touched the +//! directory, instead of folding them into the system prompt. +//! +//! A system prompt that changes whenever a new directory is touched invalidates the +//! provider's prompt cache from the system prompt onward. Delivered hints stay in the +//! conversation, so the prefix never changes for them. +//! +//! Delivery is a pure function of the stored conversation, never of in-memory state. +//! Directories come from agent-visible tool requests, as upstream's system-prompt hints +//! did, and a hint counts as delivered while its block is in an agent-visible tool +//! result. Compaction hides both, so a hint returns with the first call into its +//! directory afterwards, and volume stays bounded by the visible window. Truncation +//! (honk /undo) deletes the block with the calls that found the directory. + +use std::path::Path; + +use rmcp::model::{Annotations, ContentBlock, Role, TextContent}; + +use crate::conversation::message::{Message, MessageContent}; +use crate::conversation::Conversation; +use crate::hints::get_context_filenames; +use crate::hints::load_hints::SubdirectoryHintTracker; + +const HINT_KEY_PREFIX: &str = "subdir_hints:"; +const LEAD_IN: &str = "Repository instructions "; + +fn marker_open(dir: &str) -> String { + format!("") +} + +fn format_hint(dir: &str, content: &str) -> String { + let lead_in = get_context_filenames() + .into_iter() + .find(|name| Path::new(dir).join(name).is_file()) + .map(|name| format!("{LEAD_IN}from {dir}/{name}, which apply to files under {dir}:")) + .unwrap_or_else(|| format!("{LEAD_IN}that apply to files under {dir}:")); + format!( + "{lead_in}\n{}\n{}\n", + marker_open(dir), + content.trim() + ) +} + +fn is_hint_block(text: &TextContent) -> bool { + text.text.starts_with(LEAD_IN) + && text + .annotations + .as_ref() + .and_then(|annotations| annotations.audience.as_deref()) + == Some(&[Role::Assistant][..]) +} + +/// Only hint blocks count, so a marker quoted elsewhere (a compaction summary, a +/// transcript grep) does not suppress delivery. +fn message_delivers(message: &Message, marker: &str) -> bool { + message.content.iter().any(|content| match content { + MessageContent::ToolResponse(response) => { + response.tool_result.as_ref().is_ok_and(|result| { + result.content.iter().any(|block| match block { + ContentBlock::Text(text) => is_hint_block(text) && text.text.contains(marker), + _ => false, + }) + }) + } + _ => false, + }) +} + +fn delivered(conversation: &Conversation, dir: &str) -> bool { + let marker = marker_open(dir); + conversation + .messages() + .iter() + .filter(|message| message.is_agent_visible()) + .any(|message| message_delivers(message, &marker)) +} + +fn undelivered_hints(conversation: &Conversation, working_dir: &Path) -> Vec<(String, String)> { + let mut tracker = SubdirectoryHintTracker::new(); + for message in conversation + .messages() + .iter() + .filter(|message| message.is_agent_visible()) + { + for content in &message.content { + if let MessageContent::ToolRequest(request) = content { + if let Ok(tool_call) = &request.tool_call { + tracker.record_tool_arguments(&tool_call.arguments, working_dir); + } + } + } + } + let mut hints: Vec<(String, String)> = tracker + .load_new_hints(working_dir) + .into_iter() + .filter_map(|(key, content)| { + let dir = key + .strip_prefix(HINT_KEY_PREFIX) + .unwrap_or(&key) + .to_string(); + (!delivered(conversation, &dir)).then_some((dir, content)) + }) + .collect(); + hints.sort_by(|a, b| a.0.cmp(&b.0)); + hints +} + +/// Appends the hints of directories touched by stored tool requests whose marker is not +/// in an agent-visible message to the last successful tool result in `response`. With no +/// successful result nothing is appended, and a later batch delivers them. +pub(super) fn deliver_subdirectory_hints( + response: &mut Message, + conversation: &Conversation, + working_dir: &Path, +) { + let Some(result) = response + .content + .iter_mut() + .rev() + .filter_map(|content| match content { + MessageContent::ToolResponse(response) => response.tool_result.as_mut().ok(), + _ => None, + }) + .find(|result| result.is_error != Some(true)) + else { + return; + }; + let hints = undelivered_hints(conversation, working_dir); + if hints.is_empty() { + return; + } + let text = hints + .iter() + .map(|(dir, content)| format_hint(dir, content)) + .collect::>() + .join("\n\n"); + result + .content + .push(ContentBlock::Text(TextContent::new(text).with_annotations( + Annotations::default().with_audience(vec![Role::Assistant]), + ))); +} + +#[cfg(test)] +mod tests { + use super::*; + use rmcp::model::{CallToolRequestParams, CallToolResult}; + use std::fs; + use tempfile::TempDir; + + struct Repo { + _temp: TempDir, + root: std::path::PathBuf, + sub: String, + } + + fn repo() -> Repo { + let temp = TempDir::new().unwrap(); + let root = temp.path().canonicalize().unwrap(); + let sub = root.join("sub"); + fs::create_dir_all(&sub).unwrap(); + fs::write(sub.join("AGENTS.md"), "sub hint content").unwrap(); + let sub = sub.display().to_string(); + Repo { + _temp: temp, + root, + sub, + } + } + + fn read_request(id: &str, path: &str) -> Message { + let arguments = serde_json::json!({ "path": path }) + .as_object() + .cloned() + .unwrap(); + Message::assistant().with_tool_request( + id, + Ok(CallToolRequestParams::new("read").with_arguments(arguments)), + ) + } + + fn tool_response(id: &str, ok: bool) -> Message { + let result = if ok { + CallToolResult::success(vec![ContentBlock::text("file body")]) + } else { + CallToolResult::error(vec![ContentBlock::text("failed")]) + }; + Message::user().with_tool_response(id, Ok(result)) + } + + fn result_texts(message: &Message) -> Vec { + message + .content + .iter() + .filter_map(|content| match content { + MessageContent::ToolResponse(response) => response.tool_result.as_ref().ok(), + _ => None, + }) + .flat_map(|result| result.content.iter()) + .filter_map(|block| match block { + ContentBlock::Text(text) => Some(text.text.clone()), + _ => None, + }) + .collect() + } + + #[test] + fn hints_are_appended_to_the_tool_response_for_the_agent_only() { + let repo = repo(); + let conversation = Conversation::new_unvalidated([read_request("t1", "sub/file.rs")]); + let mut response = tool_response("t1", true); + + deliver_subdirectory_hints(&mut response, &conversation, &repo.root); + + let texts = result_texts(&response); + assert_eq!(texts.len(), 2, "{texts:?}"); + assert!(texts[1].starts_with(&format!( + "Repository instructions from {}/AGENTS.md, which apply to files under {}:", + repo.sub, repo.sub + ))); + assert!(texts[1].contains(&marker_open(&repo.sub))); + assert!(texts[1].contains("sub hint content")); + assert!(texts[1].ends_with("")); + assert_eq!( + result_texts(&response.user_visible_content()), + ["file body"] + ); + } + + #[test] + fn hints_already_in_the_conversation_are_not_delivered_again() { + let repo = repo(); + let mut earlier = tool_response("t1", true); + deliver_subdirectory_hints( + &mut earlier, + &Conversation::new_unvalidated([read_request("t1", "sub/a.rs")]), + &repo.root, + ); + let conversation = Conversation::new_unvalidated([ + read_request("t1", "sub/a.rs"), + earlier, + read_request("t2", "sub/b.rs"), + ]); + let mut response = tool_response("t2", true); + + deliver_subdirectory_hints(&mut response, &conversation, &repo.root); + + assert_eq!(result_texts(&response), ["file body"]); + } + + #[test] + fn hints_hidden_from_the_agent_return_with_the_next_call_into_the_directory() { + let repo = repo(); + let mut earlier = tool_response("t1", true); + deliver_subdirectory_hints( + &mut earlier, + &Conversation::new_unvalidated([read_request("t1", "sub/a.rs")]), + &repo.root, + ); + let hidden = [ + read_request("t1", "sub/a.rs").with_visibility(true, false), + earlier.with_visibility(true, false), + ]; + + let mut elsewhere = tool_response("t2", true); + let conversation = Conversation::new_unvalidated( + hidden + .iter() + .cloned() + .chain([read_request("t2", "README.md")]), + ); + deliver_subdirectory_hints(&mut elsewhere, &conversation, &repo.root); + assert_eq!(result_texts(&elsewhere), ["file body"]); + + let mut back = tool_response("t3", true); + let conversation = Conversation::new_unvalidated( + hidden + .iter() + .cloned() + .chain([read_request("t3", "sub/b.rs")]), + ); + deliver_subdirectory_hints(&mut back, &conversation, &repo.root); + let texts = result_texts(&back); + assert_eq!(texts.len(), 2, "{texts:?}"); + assert!(texts[1].contains(&marker_open(&repo.sub))); + } + + #[test] + fn a_quoted_marker_does_not_count_as_delivered() { + let repo = repo(); + let quoted = Message::user().with_tool_response( + "t0", + Ok(CallToolResult::success(vec![ContentBlock::text(format!( + "grep hit: {}", + marker_open(&repo.sub) + ))])), + ); + let conversation = Conversation::new_unvalidated([ + Message::assistant().with_text(marker_open(&repo.sub)), + quoted, + read_request("t1", "sub/file.rs"), + ]); + let mut response = tool_response("t1", true); + + deliver_subdirectory_hints(&mut response, &conversation, &repo.root); + + assert_eq!(result_texts(&response).len(), 2); + } + + #[test] + fn failed_tool_responses_do_not_carry_hints() { + let repo = repo(); + let conversation = Conversation::new_unvalidated([read_request("t1", "sub/file.rs")]); + let mut response = tool_response("t1", false); + + deliver_subdirectory_hints(&mut response, &conversation, &repo.root); + + assert_eq!(result_texts(&response), ["failed"]); + } + + #[test] + fn hints_go_to_the_last_successful_response_in_directory_order() { + let repo = repo(); + let other = repo.root.join("other"); + fs::create_dir_all(&other).unwrap(); + fs::write(other.join("AGENTS.md"), "other hint content").unwrap(); + let conversation = Conversation::new_unvalidated([ + read_request("t1", "sub/file.rs"), + read_request("t2", "other/file.rs"), + ]); + let mut response = Message::user() + .with_tool_response( + "t1", + Ok(CallToolResult::success(vec![ContentBlock::text("one")])), + ) + .with_tool_response( + "t2", + Ok(CallToolResult::error(vec![ContentBlock::text("two")])), + ); + + deliver_subdirectory_hints(&mut response, &conversation, &repo.root); + + let texts = result_texts(&response); + assert_eq!(texts.len(), 3, "{texts:?}"); + assert_eq!(texts[0], "one"); + assert_eq!(texts[2], "two"); + let hints = &texts[1]; + let other_at = hints + .find(&marker_open(&other.display().to_string())) + .unwrap(); + let sub_at = hints.find(&marker_open(&repo.sub)).unwrap(); + assert!(other_at < sub_at, "{hints}"); + } +} diff --git a/crates/goose/src/agents/state_machine/tests/prompt_skill_lifecycle.rs b/crates/goose/src/agents/state_machine/tests/prompt_skill_lifecycle.rs index ce346cd8ce4b..0b0ff8152f17 100644 --- a/crates/goose/src/agents/state_machine/tests/prompt_skill_lifecycle.rs +++ b/crates/goose/src/agents/state_machine/tests/prompt_skill_lifecycle.rs @@ -1,3 +1,4 @@ +// Modified by Jonathan Mohrbacher, 2026: subdirectory hints arrive in the conversation once, not in the system prompt. use anyhow::Result; use serde_json::json; @@ -27,8 +28,25 @@ async fn prompt_and_skill_lifecycle() -> Result<()> { api.on("result: 1").reply("nested work complete"); pipeline.run(["work in nested"]).await?; let calls = api.calls(); - assert!(!calls[calls.len() - 2].system_contains("NESTED_PROJECT_INSTRUCTION")); - assert!(calls[calls.len() - 1].system_contains("NESTED_PROJECT_INSTRUCTION")); + assert!(!calls[calls.len() - 2].input_contains("NESTED_PROJECT_INSTRUCTION")); + let after_tool = &calls[calls.len() - 1]; + assert!(!after_tool.system_contains("NESTED_PROJECT_INSTRUCTION")); + assert_eq!( + after_tool.input_occurrences("NESTED_PROJECT_INSTRUCTION"), + 1 + ); + assert!(after_tool.input_contains("