Skip to content

Commit 6db9051

Browse files
wpfleger96npub1mn7jgtj4w2pd0g0zeuhxsa6jy6p0rewxz4kujt98my82ahfmp72sxjexk7
andauthored
feat(acp): surface error-class outcomes to the activity feed only, never the channel (#1010)
Signed-off-by: Will Pfleger <[email protected]> Co-authored-by: npub1mn7jgtj4w2pd0g0zeuhxsa6jy6p0rewxz4kujt98my82ahfmp72sxjexk7 <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@sprout-oss.stage.blox.sqprod.co>
1 parent 563f684 commit 6db9051

2 files changed

Lines changed: 165 additions & 144 deletions

File tree

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

Lines changed: 165 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1776,7 +1776,6 @@ async fn tokio_main() -> Result<()> {
17761776
&respawn_tx,
17771777
&mut respawn_tasks,
17781778
observer.clone(),
1779-
&relay,
17801779
) == LoopAction::Exit
17811780
{
17821781
break;
@@ -2071,23 +2070,13 @@ fn handle_prompt_result(
20712070
respawn_tx: &mpsc::Sender<RespawnResult>,
20722071
respawn_tasks: &mut tokio::task::JoinSet<()>,
20732072
observer: Option<observer::ObserverHandle>,
2074-
relay: &HarnessRelay,
20752073
) -> LoopAction {
20762074
let before = pool.task_map().len();
20772075
let agent_index = result.agent.index;
20782076
pool.task_map_mut()
20792077
.retain(|_, meta| meta.agent_index != agent_index);
20802078
debug_assert_eq!(before, pool.task_map().len() + 1);
20812079

2082-
// Extract thread root from the batch before it's consumed by requeue.
2083-
// Used by death notices to thread the message into the original conversation.
2084-
let thread_root: Option<String> = result
2085-
.batch
2086-
.as_ref()
2087-
.and_then(|b| b.events.first())
2088-
.map(|e| queue::parse_thread_tags(&e.event))
2089-
.and_then(|tags| tags.root_event_id);
2090-
20912080
// Requeue BEFORE mark_complete: requeue() sets retry_after with a future
20922081
// deadline, and mark_complete() checks for it to decide whether to preserve
20932082
// retry_counts. If mark_complete runs first, retry_counts is cleared and
@@ -2176,11 +2165,6 @@ fn handle_prompt_result(
21762165
};
21772166
emit_turn_error(death_message);
21782167

2179-
// Post a visible death notice to the channel so humans know why
2180-
// the agent went silent.
2181-
if let Some(ch) = channel_id {
2182-
relay.publish_death_notice(ch, death_message, thread_root.as_deref());
2183-
}
21842168
let index = result.agent.index;
21852169
let slot_history = &mut crash_history[index];
21862170
if !spawn_respawn_task(
@@ -2238,15 +2222,6 @@ fn handle_prompt_result(
22382222
);
22392223
emit_turn_error(&e.to_string());
22402224

2241-
// Post a visible death notice for transport errors too.
2242-
if let Some(ch) = channel_id {
2243-
relay.publish_death_notice(
2244-
ch,
2245-
"Agent connection lost (transport error)",
2246-
thread_root.as_deref(),
2247-
);
2248-
}
2249-
22502225
let index = result.agent.index;
22512226
let slot_history = &mut crash_history[index];
22522227
if !spawn_respawn_task(
@@ -3146,3 +3121,168 @@ mod build_mcp_servers_tests {
31463121
);
31473122
}
31483123
}
3124+
3125+
#[cfg(test)]
3126+
mod error_outcome_emission_tests {
3127+
//! Pins the policy that error-class outcomes surface to the activity feed
3128+
//! and never to the channel:
3129+
//!
3130+
//! - Channel silence is enforced *structurally* — `handle_prompt_result`
3131+
//! takes no relay handle, so it has no way to post a channel message. A
3132+
//! future re-introduction of channel notices would have to add the relay
3133+
//! parameter back, which these tests' construction would then refuse to
3134+
//! compile against.
3135+
//! - Feed coverage is the regression-prone half and is asserted at runtime:
3136+
//! each error outcome must emit exactly one `turn_error` observer event.
3137+
//! If any branch drops its `emit_turn_error` call, the matching test goes
3138+
//! red.
3139+
3140+
use super::*;
3141+
use crate::acp::{AcpClient, AcpError};
3142+
use crate::observer::ObserverHandle;
3143+
use crate::pool::{AgentPool, OwnedAgent, PromptOutcome, PromptResult, PromptSource};
3144+
use std::collections::HashSet;
3145+
3146+
fn test_config() -> Config {
3147+
Config {
3148+
keys: nostr::Keys::generate(),
3149+
relay_url: "ws://localhost:3000".into(),
3150+
// `true` exits cleanly, so the async respawn fails fast and
3151+
// harmlessly off the JoinSet — irrelevant to the synchronous
3152+
// feed emission under test.
3153+
agent_command: "true".into(),
3154+
agent_args: vec![],
3155+
mcp_command: "test-mcp-server".into(),
3156+
idle_timeout_secs: config::DEFAULT_IDLE_TIMEOUT_SECS,
3157+
max_turn_duration_secs: 3600,
3158+
agents: 1,
3159+
heartbeat_interval_secs: 0,
3160+
heartbeat_prompt: None,
3161+
system_prompt: None,
3162+
initial_message: None,
3163+
subscribe_mode: config::SubscribeMode::All,
3164+
dedup_mode: config::DedupMode::Queue,
3165+
multiple_event_handling: config::MultipleEventHandling::Queue,
3166+
ignore_self: true,
3167+
kinds_override: None,
3168+
channels_override: None,
3169+
no_mention_filter: false,
3170+
config_path: std::path::PathBuf::from("./buzz-acp.toml"),
3171+
context_message_limit: 12,
3172+
max_turns_per_session: 0,
3173+
presence_enabled: true,
3174+
typing_enabled: true,
3175+
memory_enabled: false,
3176+
model: None,
3177+
permission_mode: config::PermissionMode::BypassPermissions,
3178+
respond_to: config::RespondTo::Anyone,
3179+
respond_to_allowlist: HashSet::new(),
3180+
persona_env_vars: vec![],
3181+
relay_observer: false,
3182+
agent_owner: None,
3183+
no_base_prompt: false,
3184+
base_prompt_content: None,
3185+
}
3186+
}
3187+
3188+
/// Spawn a real but inert agent subprocess (`cat`) so the error paths have
3189+
/// an `OwnedAgent` to move into respawn or return to the pool. The error
3190+
/// branches never talk to the subprocess.
3191+
async fn dummy_agent(index: usize) -> OwnedAgent {
3192+
OwnedAgent {
3193+
index,
3194+
acp: AcpClient::spawn("cat", &[], &[])
3195+
.await
3196+
.expect("spawn cat as inert agent"),
3197+
state: Default::default(),
3198+
model_capabilities: None,
3199+
desired_model: None,
3200+
// Error branches under test never read this; 1 is the legacy
3201+
// non-systemPrompt path, the simplest valid value.
3202+
protocol_version: 1,
3203+
}
3204+
}
3205+
3206+
/// Drive one error outcome through `handle_prompt_result` and return how
3207+
/// many `turn_error` events it emitted to the observer feed.
3208+
async fn turn_errors_emitted_for(outcome: PromptOutcome) -> usize {
3209+
let agent = dummy_agent(0).await;
3210+
let mut pool = AgentPool::from_slots(vec![None]);
3211+
3212+
// `handle_prompt_result` asserts it removes exactly one in-flight task
3213+
// for the completing agent (the slot was checked out, not idle). Mirror
3214+
// the real dispatch path by registering a TaskMeta keyed on a genuine
3215+
// `task::Id` — only obtainable from inside a spawned task.
3216+
let task_id = pool.join_set.spawn(async {}).id();
3217+
pool.task_map_mut().insert(
3218+
task_id,
3219+
crate::pool::TaskMeta {
3220+
agent_index: 0,
3221+
channel_id: None,
3222+
recoverable_batch: None,
3223+
control_tx: None,
3224+
},
3225+
);
3226+
3227+
let mut queue = EventQueue::new(config::DedupMode::Queue);
3228+
let config = test_config();
3229+
let mut heartbeat_in_flight = false;
3230+
let removed_channels = HashSet::new();
3231+
let mut crash_history = vec![SlotCircuit {
3232+
crash_times: Vec::new(),
3233+
open_until: None,
3234+
respawn_in_flight: false,
3235+
}];
3236+
let (respawn_tx, _respawn_rx) = mpsc::channel(8);
3237+
let mut respawn_tasks = tokio::task::JoinSet::new();
3238+
let observer = ObserverHandle::in_process();
3239+
3240+
let result = PromptResult {
3241+
agent,
3242+
source: PromptSource::Channel(Uuid::new_v4()),
3243+
outcome,
3244+
batch: None,
3245+
};
3246+
3247+
handle_prompt_result(
3248+
&mut pool,
3249+
&mut queue,
3250+
&config,
3251+
result,
3252+
&mut heartbeat_in_flight,
3253+
&removed_channels,
3254+
&mut crash_history,
3255+
&respawn_tx,
3256+
&mut respawn_tasks,
3257+
Some(observer.clone()),
3258+
);
3259+
3260+
observer
3261+
.snapshot()
3262+
.iter()
3263+
.filter(|e| e.kind == "turn_error")
3264+
.count()
3265+
}
3266+
3267+
#[tokio::test]
3268+
async fn agent_exited_emits_exactly_one_feed_event() {
3269+
assert_eq!(turn_errors_emitted_for(PromptOutcome::AgentExited).await, 1);
3270+
}
3271+
3272+
#[tokio::test]
3273+
async fn timeout_emits_exactly_one_feed_event() {
3274+
assert_eq!(turn_errors_emitted_for(PromptOutcome::Timeout).await, 1);
3275+
}
3276+
3277+
#[tokio::test]
3278+
async fn transport_error_emits_exactly_one_feed_event() {
3279+
let io = AcpError::Io(std::io::Error::other("pipe broke"));
3280+
assert_eq!(turn_errors_emitted_for(PromptOutcome::Error(io)).await, 1);
3281+
}
3282+
3283+
#[tokio::test]
3284+
async fn application_error_emits_exactly_one_feed_event() {
3285+
let app = AcpError::IdleTimeout(std::time::Duration::from_secs(1));
3286+
assert_eq!(turn_errors_emitted_for(PromptOutcome::Error(app)).await, 1);
3287+
}
3288+
}

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

Lines changed: 0 additions & 119 deletions
Original file line numberDiff line numberDiff line change
@@ -327,9 +327,6 @@ pub enum RelayError {
327327

328328
#[error("Unexpected message: {0}")]
329329
UnexpectedMessage(String),
330-
331-
#[error("Event build error: {0}")]
332-
EventBuild(String),
333330
}
334331

335332
impl From<nostr::event::builder::Error> for RelayError {
@@ -778,44 +775,6 @@ impl HarnessRelay {
778775
Ok(event)
779776
}
780777

781-
/// Build a channel message (kind:9) for death notices — posted when the
782-
/// agent session ends due to timeout or unexpected exit.
783-
/// If `thread_root` is provided, the message is threaded as a reply.
784-
pub fn build_death_notice(
785-
&self,
786-
channel_id: Uuid,
787-
message: &str,
788-
thread_root: Option<&str>,
789-
) -> Result<Event, RelayError> {
790-
use buzz_core::kind::KIND_STREAM_MESSAGE;
791-
792-
let h_tag = Tag::parse(["h", &channel_id.to_string()])
793-
.map_err(|e| RelayError::EventBuild(e.to_string()))?;
794-
let mut tags = vec![h_tag];
795-
if let Some(root_id) = thread_root {
796-
let e_tag = Tag::parse(["e", root_id, "", "root"])
797-
.map_err(|e| RelayError::EventBuild(e.to_string()))?;
798-
tags.push(e_tag);
799-
}
800-
let event = EventBuilder::new(Kind::Custom(KIND_STREAM_MESSAGE as u16), message)
801-
.tags(tags)
802-
.sign_with_keys(&self.keys)?;
803-
Ok(event)
804-
}
805-
806-
/// Build and publish a death notice, logging any failure rather than
807-
/// propagating it. Used by both the timeout and transport-error paths.
808-
pub fn publish_death_notice(&self, channel_id: Uuid, message: &str, thread_root: Option<&str>) {
809-
match self.build_death_notice(channel_id, message, thread_root) {
810-
Ok(event) => {
811-
if let Err(e) = self.try_publish_event(event) {
812-
warn!("failed to publish death notice: {e}");
813-
}
814-
}
815-
Err(e) => warn!("failed to build death notice: {e}"),
816-
}
817-
}
818-
819778
/// Set the startup watermark timestamp (Finding #22).
820779
///
821780
/// Call this once after `connect()` with the Unix timestamp captured just
@@ -3519,82 +3478,4 @@ mod tests {
35193478
"after backpressure removal, replay must be accepted"
35203479
);
35213480
}
3522-
3523-
// ── Death-notice builder (PR #935 fix: reply→root marker) ─────────────────
3524-
3525-
/// Construct a minimal HarnessRelay for unit-testing `build_death_notice`.
3526-
/// Only `keys` is exercised; other fields are dummies.
3527-
fn make_test_relay() -> HarnessRelay {
3528-
let (cmd_tx, _cmd_rx) = mpsc::channel(1);
3529-
let (_event_tx, event_rx) = mpsc::channel(1);
3530-
HarnessRelay {
3531-
event_rx,
3532-
observer_control_rx: None,
3533-
cmd_tx,
3534-
http: reqwest::Client::new(),
3535-
relay_url: "ws://localhost:3000".into(),
3536-
keys: nostr::Keys::generate(),
3537-
auth_tag: None,
3538-
bg_handle: None,
3539-
}
3540-
}
3541-
3542-
#[test]
3543-
fn death_notice_has_root_marker_not_reply() {
3544-
let relay = make_test_relay();
3545-
let channel_id = Uuid::new_v4();
3546-
let root_id = "abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890";
3547-
let event = relay
3548-
.build_death_notice(channel_id, "agent timed out", Some(root_id))
3549-
.expect("build_death_notice should succeed");
3550-
3551-
// The NIP-10 e-tag must use "root" marker (not "reply").
3552-
let e_tags: Vec<_> = event
3553-
.tags
3554-
.iter()
3555-
.filter(|t| t.as_slice().first().map(|s| s.as_str()) == Some("e"))
3556-
.collect();
3557-
assert_eq!(e_tags.len(), 1, "expected exactly one e-tag");
3558-
let e_tag = e_tags[0].as_slice();
3559-
assert_eq!(e_tag[1], root_id, "e-tag should reference the root event");
3560-
assert_eq!(e_tag[2], "", "relay hint should be empty");
3561-
assert_eq!(e_tag[3], "root", "marker must be 'root', not 'reply'");
3562-
}
3563-
3564-
#[test]
3565-
fn death_notice_has_channel_h_tag() {
3566-
let relay = make_test_relay();
3567-
let channel_id = Uuid::new_v4();
3568-
let event = relay
3569-
.build_death_notice(channel_id, "agent crashed", None)
3570-
.expect("build_death_notice should succeed");
3571-
3572-
let h_tags: Vec<_> = event
3573-
.tags
3574-
.iter()
3575-
.filter(|t| t.as_slice().first().map(|s| s.as_str()) == Some("h"))
3576-
.collect();
3577-
assert_eq!(h_tags.len(), 1, "expected exactly one h-tag");
3578-
assert_eq!(
3579-
h_tags[0].as_slice()[1],
3580-
channel_id.to_string(),
3581-
"h-tag should contain the channel UUID"
3582-
);
3583-
}
3584-
3585-
#[test]
3586-
fn death_notice_without_thread_root_has_no_e_tag() {
3587-
let relay = make_test_relay();
3588-
let channel_id = Uuid::new_v4();
3589-
let event = relay
3590-
.build_death_notice(channel_id, "agent exited", None)
3591-
.expect("build_death_notice should succeed");
3592-
3593-
let e_tags: Vec<_> = event
3594-
.tags
3595-
.iter()
3596-
.filter(|t| t.as_slice().first().map(|s| s.as_str()) == Some("e"))
3597-
.collect();
3598-
assert!(e_tags.is_empty(), "no e-tag when thread_root is None");
3599-
}
36003481
}

0 commit comments

Comments
 (0)