From 83058d172ae327e15ea33316e58d93b76d2452c9 Mon Sep 17 00:00:00 2001 From: QuicksilverSlick Date: Sun, 15 Nov 2026 15:18:35 -0600 Subject: [PATCH 1/2] fix(acp): allowlisted people may DM the agent, and refusals reach the sender On 13 Nov Chris, on Chris Orchestrator's allowlist, DMed it and got nothing: - The DM branch of the author gate checked only owner-or-sibling and never read the allowlist (upstream #2591). In allowlist mode an allowlisted author now passes in a DM. The check stays on the author, so a stranger in the same DM gets nothing, and `anyone` stays owner-only in DMs. This diverges from upstream on purpose: keep our arm on the next sync. - The "not set up to take requests" reply failed with HTTP 400 and the relay's reason was thrown away. A non-retriable status now logs and returns the first 200 characters of the body. - The one-notice memo was used up by that failed post, so his next two DMs met silence. The notice now posts, waits 11 s (the relay's membership cache) and tries once more. The memo keeps a (channel, author) claim only once the relay accepted the notice; a failed one releases it so the next message tries again, logs an error and gives the owner a Critical Bench card plus a text (D1). - A mention refused on catch-up (sent while the agent was down) now gets the notice too: it is ledgered when refused, so it never replays twice. Non-mentions still get none. post_notice now returns whether the relay accepted it; the other four callers ignore it. Two older tests that pinned the upstream DM rule are updated: the listener-boundary test now expects an allowlisted DM author through both listeners, and the discovery fail-closed test proves DM hardening with `anyone` + a stranger. Chris's three 13 Nov DMs will not replay (the ledger marked them done); he must send again once this is live. Factory-Task: partner-fixes-15nov/1-chris-dm Claude-Account: russelledeming@gmail.com Co-Authored-By: Claude Opus 5.5 --- crates/buzz-acp/src/factory.rs | 61 +++++ crates/buzz-acp/src/lib.rs | 367 +++++++++++++++++++++++++++--- crates/buzz-acp/src/pool.rs | 17 +- crates/buzz-acp/src/relay.rs | 18 +- crates/buzz-acp/src/setup_mode.rs | 3 +- 5 files changed, 420 insertions(+), 46 deletions(-) diff --git a/crates/buzz-acp/src/factory.rs b/crates/buzz-acp/src/factory.rs index 0e7bc7ce3b9..5eb4f181e01 100644 --- a/crates/buzz-acp/src/factory.rs +++ b/crates/buzz-acp/src/factory.rs @@ -1395,6 +1395,36 @@ impl Factory { ); } + /// A refusal the sender was never told about: the "not set up to take + /// requests" notice could not be posted, even on its retry. `event_id` is + /// the refused message's hex id. + pub(crate) fn refusal_unseen(&mut self, channel_id: uuid::Uuid, event_id: &str) { + let who = card_name(self.who(), &self.reporting.short); + let body = format!( + "{who} isn't set up to take requests from this person, and its reply saying so could \ + not be posted, so they are waiting on an answer that won't come. If they should \ + have access, add them in the agent's access settings and ask them to send it \ + again. Otherwise let them know." + ); + let id = format!( + "{}-refused-{}", + self.reporting.short, + event_id.get(..12).unwrap_or(event_id) + ); + let link = format!("buzz://message?channel={channel_id}&id={event_id}"); + let title = format!("{who} turned away a message without telling the sender"); + self.alert_critical(&format!( + "{title}. They are waiting on an answer that won't come." + )); + self.card( + &id, + &title, + &body, + "Nothing happens by itself: the sender is not told.", + serde_json::json!([{"label": "Open message", "url": link}]), + ); + } + /// Drop a Critical, needs-you card in the Bench inbox (spec 7.1) in the /// Bench's drop format, once per id per incident. Written beside its name /// and renamed into place, so the Bench never reads half a file. @@ -2687,4 +2717,35 @@ mod tests { let mut f = Factory::new(None, "claude-agent-acp"); f.dropped(channel, &event, "boom"); } + + #[test] + fn refusal_unseen_card_links_the_message_and_never_shows_unsafe_text() { + let bench = tempfile::tempdir().unwrap(); + let mut f = Factory::new(None, "claude-agent-acp"); + f.reporting = reporting("Chris Orchestrator"); + f.reporting.bench = Some(bench.path().to_path_buf()); + let channel = uuid::Uuid::parse_str("335dd4e1-0000-4000-8000-000000000001").unwrap(); + let event = "ef".repeat(32); + f.refusal_unseen(channel, &event); + let card = read_card(bench.path(), "ade9d0e2-refused-efefefefefef").expect("card"); + assert_eq!( + card["title"], + "Chris Orchestrator turned away a message without telling the sender" + ); + assert_eq!(card["severity"], "critical"); + assert_eq!( + card["links"][0]["url"], + format!("buzz://message?channel={channel}&id={event}") + ); + assert_eq!( + card["plain"]["ifYouWait"], + "Nothing happens by itself: the sender is not told." + ); + let body = card["body"].as_str().unwrap(); + assert!(card_safe(body), "{body}"); + // D1 (15 Nov 2026): the owner is texted as well as carded. + let texts = f.take_alerts(); + assert_eq!(texts.len(), 1, "{texts:?}"); + assert!(texts[0].contains("turned away a message"), "{texts:?}"); + } } diff --git a/crates/buzz-acp/src/lib.rs b/crates/buzz-acp/src/lib.rs index fc1dc0b68bc..fd6f564ab7d 100644 --- a/crates/buzz-acp/src/lib.rs +++ b/crates/buzz-acp/src/lib.rs @@ -615,6 +615,11 @@ mod inbound_author_gate { if is_dm { return match respond_to { RespondTo::Nobody => Some(false), + // Owner decision 15 Nov 2026: people on the allowlist may DM the agent. The check is + // still on the author, so a stranger in the same DM gets nothing. `anyone` stays + // owner-only in DMs (upstream #2591: an agent can be asked to open a DM with anyone). + // Deliberate divergence from upstream: keep this arm on the next upstream sync. + RespondTo::Allowlist if allowlist.contains(author) => Some(true), _ => owner_or_sibling(author, owner_cache, rest_client).await, }; } @@ -3470,8 +3475,10 @@ async fn run_harness( // reply per refused event lets a noisy author turn the agent into a // flooder. Bounded because this process is long-lived and the key space is // attacker-controlled — on overflow we clear and allow one more notice per - // pair rather than growing without limit. - let mut gate_notified: HashSet<(Uuid, String)> = HashSet::new(); + // pair rather than growing without limit. A pair is claimed while its + // notice posts and kept only once the relay accepted it: a notice that + // never landed told nobody, so it must not use up their one notice. + let gate_notified: Arc>> = Arc::default(); // Independent of pool readiness: a never-mentioned lazy agent must still // self-terminate. The watch interval is capped so small configured bounds @@ -4265,6 +4272,7 @@ async fn run_harness( let inbound_channel_id = buzz_event.channel_id; let inbound_kind = buzz_event.event.kind.as_u16(); let inbound_author = buzz_event.event.pubkey.to_hex(); + let inbound_event_id = buzz_event.event.id.to_hex(); let inbound_thread_tags = queue::notice_thread_tags( &buzz_event.event, queue::parse_thread_tags(&buzz_event.event), @@ -4283,6 +4291,7 @@ async fn run_harness( ) .await; let refusal = authorized.as_ref().err().copied(); + let ledgered = inbound_mention.is_some(); // Refused under the policy it was sent under: a // later respond-to change restarts the agent and // must not reopen it. A failed lookup retries. @@ -4298,10 +4307,13 @@ async fn run_harness( // into a flooder. A failed lookup is not a // refusal, so it gets no notice: "not set up to // take requests from you" would be false. - if gate_notice_due(refusal, inbound_backlog) + let memo_key = (inbound_channel_id, inbound_author); + if gate_notice_due(refusal, inbound_backlog, ledgered) && remember_gate_notice( - &mut gate_notified, - (inbound_channel_id, inbound_author), + &mut gate_notified + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner), + memo_key.clone(), ) { let is_dm = @@ -4315,15 +4327,28 @@ async fn run_harness( }; let content = author_gate_notice_text(is_dm); let rest = ctx.rest_client.clone(); + let factory = config.factory.clone(); + let memo = Arc::clone(&gate_notified); tokio::spawn(async move { - pool::post_notice( + // The relay's membership cache can refuse a post into a DM + // opened moments ago, for up to 10 s. + let waits = [Duration::ZERO, Duration::from_secs(11)]; + let posted = post_refusal_notice( &rest, inbound_channel_id, &inbound_thread_tags, &content, &mentions, + &waits, ) .await; + settle_refusal_notice( + posted, + &memo, + &memo_key, + &factory, + &inbound_event_id, + ); }); } continue; @@ -5990,11 +6015,54 @@ fn remember_gate_notice(seen: &mut HashSet<(Uuid, String)>, key: (Uuid, String)) true } +/// Post a refusal notice, retrying after each wait; true once the relay accepts it. +async fn post_refusal_notice( + rest: &relay::RestClient, + channel_id: Uuid, + thread_tags: &ThreadTags, + content: &str, + mentions: &[String], + waits: &[Duration], +) -> bool { + for wait in waits { + tokio::time::sleep(*wait).await; + if pool::post_notice(rest, channel_id, thread_tags, content, mentions).await { + return true; + } + } + false +} + +/// After a refusal notice's last try. The memo means "told", so a claim stays +/// only once the notice landed. Otherwise it is released, so the sender's next +/// message tries again, and the owner gets a card and a text (D1, 15 Nov 2026). +fn settle_refusal_notice( + posted: bool, + memo: &std::sync::Mutex>, + key: &(Uuid, String), + factory: &factory::FactoryHandle, + event_id: &str, +) { + if posted { + return; + } + memo.lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .remove(key); + tracing::error!( + channel_id = %key.0, + event_id, + "refusal notice could not be posted — the sender was not told; raising to the owner" + ); + factory.lock().refusal_unseen(key.0, event_id); +} + /// Whether a gate refusal earns the "not set up to take requests" notice. -/// Never for backlog: a refused mention is replayed on every restart inside -/// the catch-up window, and the notice memo does not survive one. -fn gate_notice_due(refusal: Option, backlog: bool) -> bool { - !backlog && refusal == Some(GateRefusal::Policy) +/// A refused mention is marked done in the catch-up ledger (`note_refused`), so one replayed here was +/// never answered: notify it. A non-mention has no ledger entry and would repeat every restart: skip it. +/// Worst case: one repeat notice if the agent dies within REFUSED_SAVE_DELAY (10 s). +fn gate_notice_due(refusal: Option, backlog: bool, ledgered: bool) -> bool { + refusal == Some(GateRefusal::Policy) && (!backlog || ledgered) } /// What someone outside the author gate is told. @@ -9147,9 +9215,9 @@ mod author_gate_tests { } /// Both production boundaries must retain DM classification when composing - /// trusted workflow attribution with configured author policy. External - /// allowlist entries and `Anyone` stay denied in a DM; owner and sibling - /// principals remain allowed; `Nobody` remains absolute. + /// trusted workflow attribution with configured author policy. `Anyone` + /// stays denied in a DM; allowlisted people (owner decision 15 Nov 2026), + /// owner and sibling principals are allowed; `Nobody` remains absolute. #[tokio::test] async fn production_listener_boundaries_enforce_dm_author_policy() { for listener in [ListenerBoundary::Normal, ListenerBoundary::Setup] { @@ -9157,7 +9225,7 @@ mod author_gate_tests { let relay_hex = relay_keys.public_key().to_hex(); let external = nostr::Keys::generate().public_key().to_hex(); let external_allowlist = HashSet::from([external.clone()]); - let denied_external = listener_boundary_scenario(ListenerBoundaryScenario { + let allowed_external = listener_boundary_scenario(ListenerBoundaryScenario { listener, relay_keys: &relay_keys, workflow_owner: &external, @@ -9173,8 +9241,8 @@ mod author_gate_tests { }) .await; assert!( - !denied_external.1, - "{} listener must deny an external allowlist entry in a DM", + allowed_external.1, + "{} listener must allow an allowlisted person in a DM", listener.name() ); @@ -10073,7 +10141,7 @@ mod author_gate_tests { .err(); assert_eq!(refusal, Some(expected)); assert_eq!( - gate_notice_due(refusal, false), + gate_notice_due(refusal, false, true), expected == GateRefusal::Policy, "{expected:?}" ); @@ -10082,13 +10150,23 @@ mod author_gate_tests { server.abort(); } + /// A message sent while the agent was down is refused on catch-up. A + /// mention is ledgered when refused, so it never replays twice: tell them. + /// A non-mention has no ledger entry and would re-notice every restart. #[test] - fn backlog_refusal_posts_no_notice() { - assert!(gate_notice_due(Some(GateRefusal::Policy), false)); - assert!( - !gate_notice_due(Some(GateRefusal::Policy), true), - "a refused mention replays on every restart; it must not re-notice each time" - ); + fn backlog_refusal_notices_only_a_ledgered_mention() { + let policy = Some(GateRefusal::Policy); + let unverified = Some(GateRefusal::Unverified); + for (refusal, backlog, ledgered, due, case) in [ + (policy, false, false, true, "live + Policy"), + (policy, true, true, true, "backlog + Policy + ledgered"), + (policy, true, false, false, "backlog + Policy, unledgered"), + (unverified, false, true, false, "Unverified, live"), + (unverified, true, true, false, "Unverified, backlog"), + (None, false, true, false, "no refusal"), + ] { + assert_eq!(gate_notice_due(refusal, backlog, ledgered), due, "{case}"); + } } #[test] @@ -10194,28 +10272,99 @@ mod author_gate_tests { // ── DM hardening ────────────────────────────────────────────────────── // // In a DM, clients auto-p-tag every participant, and an agent can be - // asked to open a DM with a third party. The gate must therefore ignore - // the allowlist and `anyone` mode inside DMs: only owner + verified - // siblings fire turns. + // asked to open a DM with a third party. The gate therefore checks the + // author, never the DM's membership: owner, verified siblings and (in + // allowlist mode, owner decision 15 Nov 2026) allowlisted people fire + // turns. `anyone` stays owner-only in DMs. Upstream #2591 rejects the + // allowlist here too; this fork diverges on purpose. + + #[tokio::test] + async fn test_dm_admits_allowlisted_person_under_allowlist() { + let cache = cache_with_sibling(); + let allowlist = HashSet::from([EXTERNAL.to_string()]); + assert!( + inbound_author_gate::test_author_allowed( + &RespondTo::Allowlist, + &allowlist, + EXTERNAL, + true, + &cache, + &dummy_rest_client() + ) + .await, + "an allowlisted person must be able to DM an allowlist-mode agent" + ); + } #[tokio::test] - async fn test_dm_rejects_allowlisted_external_pubkey() { + async fn test_dm_rejects_stranger_under_allowlist() { let cache = cache_with_sibling(); let allowlist = HashSet::from([EXTERNAL.to_string()]); assert!( !inbound_author_gate::test_author_allowed( &RespondTo::Allowlist, &allowlist, + STRANGER, + true, + &cache, + &dummy_rest_client() + ) + .await, + "the check is on the author: a stranger in the same DM gets nothing" + ); + } + + #[tokio::test] + async fn test_dm_ignores_the_list_outside_allowlist_mode() { + let cache = cache_with_sibling(); + let allowlist = HashSet::from([EXTERNAL.to_string()]); + assert!( + !inbound_author_gate::test_author_allowed( + &RespondTo::OwnerOnly, + &allowlist, EXTERNAL, true, &cache, &dummy_rest_client() ) .await, - "an allowlisted external pubkey must NOT fire a turn inside a DM" + "a leftover list must not open an owner-only agent's DMs" ); } + /// The 13 Nov incident: Chris, on Chris Orchestrator's allowlist, DMed it + /// and was dropped by the DM branch. Replayed through the listener gate. + #[tokio::test] + async fn test_dm_from_allowlisted_person_passes_the_listener_gate() { + let agent = nostr::Keys::generate().public_key().to_hex(); + let chris = nostr::Keys::generate(); + let rest = dummy_rest_client(); + let gate = InboundAuthorGate::connect(&rest, &agent, "test").await; + let cache = OwnerCache::new(Some(nostr::Keys::generate().public_key().to_hex())); + let event = nostr::EventBuilder::new( + nostr::Kind::Custom(KIND_STREAM_MESSAGE as u16), + "can you look at this?", + ) + .tags([nostr::Tag::parse(["p", agent.as_str()]).expect("p tag")]) + .sign_with_keys(&chris) + .unwrap(); + let allowlist = HashSet::from([chris.public_key().to_hex()]); + let decision = gate + .evaluate_for_test( + &event, + &RespondTo::Allowlist, + &allowlist, + true, + &cache, + &rest, + ) + .await; + assert!(decision.allowed, "an allowlisted DM must start a turn"); + // The list answers before any relay lookup: an unreachable relay is no excuse. + assert!(!decision.unverified); + assert_eq!(cache.proven_verdict(&chris.public_key().to_hex()), None); + } + #[tokio::test] async fn test_dm_rejects_stranger_under_anyone() { let cache = cache_with_sibling(); @@ -10318,6 +10467,158 @@ mod author_gate_tests { (rest, server) } + // ── refusal notice transport ────────────────────────────────────────── + // + // 13 Nov: the refusal reply to Chris's first DM failed with HTTP 400 and + // the harness threw the relay's reason away; his next two DMs got nothing. + + const NOT_A_MEMBER: (&str, &str) = ( + "400 Bad Request", + r#"{"error":"restricted: not a channel member"}"#, + ); + const ACCEPTED: (&str, &str) = ("200 OK", r#"{"accepted":true}"#); + + /// A relay that answers each request with the next of `replies` (the last + /// one repeats), counting requests. Reads the whole request first, so the + /// close never resets a client still sending its body. + async fn scripted_relay( + replies: Vec<(&'static str, &'static str)>, + ) -> ( + relay::RestClient, + Arc, + tokio::task::JoinHandle<()>, + ) { + use std::sync::atomic::{AtomicUsize, Ordering}; + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + + let listener = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("bind scripted relay"); + let base_url = format!("http://{}", listener.local_addr().unwrap()); + let requests = Arc::new(AtomicUsize::new(0)); + let served = requests.clone(); + let server = tokio::spawn(async move { + while let Ok((mut socket, _)) = listener.accept().await { + let mut request = Vec::new(); + let mut chunk = [0u8; 4096]; + loop { + let n = socket.read(&mut chunk).await.unwrap_or(0); + request.extend_from_slice(&chunk[..n]); + let text = String::from_utf8_lossy(&request).to_ascii_lowercase(); + let complete = text.find("\r\n\r\n").is_some_and(|end| { + let body_len = text[..end] + .lines() + .find_map(|l| l.strip_prefix("content-length:")) + .and_then(|v| v.trim().parse::().ok()) + .unwrap_or(0); + request.len() >= end + 4 + body_len + }); + if n == 0 || complete { + break; + } + } + let i = served.fetch_add(1, Ordering::SeqCst); + let (status, body) = replies[i.min(replies.len() - 1)]; + let response = format!( + "HTTP/1.1 {status}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + ); + let _ = socket.write_all(response.as_bytes()).await; + } + }); + let rest = relay::RestClient { + http: reqwest::Client::new(), + base_url, + keys: nostr::Keys::generate(), + auth_tag_json: None, + }; + (rest, requests, server) + } + + #[tokio::test] + async fn refused_post_names_the_relay_rule() { + let (rest, _, server) = scripted_relay(vec![NOT_A_MEMBER]).await; + let event = nostr::EventBuilder::new(nostr::Kind::Custom(9), "hello") + .sign_with_keys(&rest.keys) + .unwrap(); + let err = rest + .submit_event(&event) + .await + .expect_err("a 400 is refused") + .to_string(); + server.abort(); + assert!(err.contains("restricted: not a channel member"), "{err}"); + } + + #[tokio::test] + async fn refusal_notice_retries_until_the_relay_accepts_it() { + use std::sync::atomic::Ordering; + let waits = [Duration::ZERO, Duration::ZERO]; + let post = |rest: relay::RestClient| async move { + post_refusal_notice( + &rest, + Uuid::new_v4(), + &ThreadTags::default(), + "not set up", + &[], + &waits, + ) + .await + }; + + let (rest, posts, server) = scripted_relay(vec![NOT_A_MEMBER, ACCEPTED]).await; + assert!( + post(rest).await, + "the retry lands once the relay accepts it" + ); + assert_eq!(posts.load(Ordering::SeqCst), 2); + server.abort(); + + let (rest, posts, server) = scripted_relay(vec![NOT_A_MEMBER]).await; + assert!(!post(rest).await, "a notice that never lands is reported"); + assert_eq!( + posts.load(Ordering::SeqCst), + 2, + "one post per wait, no more" + ); + server.abort(); + } + + /// 13 Nov: the failed reply used up Chris's one notice, so his next two + /// DMs met silence. A notice that never landed keeps no claim, and the + /// owner hears about it instead. + #[test] + fn refusal_memo_keeps_a_claim_only_once_the_notice_landed() { + let bench = tempfile::tempdir().unwrap(); + let mut factory = factory::Factory::new(None, "claude-agent-acp"); + factory.reporting.short = "ade9d0e2".to_string(); + factory.reporting.bench = Some(bench.path().to_path_buf()); + let factory = factory::FactoryHandle::new(factory); + let memo = std::sync::Mutex::new(HashSet::new()); + let key = (Uuid::from_u128(1), "chris".to_string()); + let card = bench + .path() + .join("inbox") + .join(factory::CARD_WRITER) + .join("ade9d0e2-refused-abababababab.json"); + + assert!(remember_gate_notice(&mut memo.lock().unwrap(), key.clone())); + settle_refusal_notice(true, &memo, &key, &factory, &"ab".repeat(32)); + assert!(memo.lock().unwrap().contains(&key), "told: stays told"); + assert!(!card.exists(), "a landed notice needs no card"); + assert!(factory.lock().take_alerts().is_empty()); + + memo.lock().unwrap().clear(); + assert!(remember_gate_notice(&mut memo.lock().unwrap(), key.clone())); + settle_refusal_notice(false, &memo, &key, &factory, &"ab".repeat(32)); + assert!( + remember_gate_notice(&mut memo.lock().unwrap(), key.clone()), + "never told: their next message must try again" + ); + assert!(card.exists(), "the owner gets a card"); + assert_eq!(factory.lock().take_alerts().len(), 1, "and a text"); + } + #[tokio::test] async fn test_sibling_indeterminate_relay_failure_is_not_cached() { let owner = nostr::Keys::generate().public_key().to_hex(); @@ -10778,21 +11079,21 @@ mod author_gate_tests { let discovered = relay::merge_discovered_channels(vec![id], &serde_json::json!([])); let channel_info = resolver(discovered); let owner_cache = cache_with_sibling(); - let allowlist = HashSet::from([EXTERNAL.to_string()]); let is_dm = is_dm_channel(id, &channel_info).await; assert!(is_dm, "unknown startup metadata must fail closed as DM"); + // `anyone` admits a stranger in a channel but not in a DM. assert!( !inbound_author_gate::test_author_allowed( - &RespondTo::Allowlist, - &allowlist, - EXTERNAL, + &RespondTo::Anyone, + &HashSet::new(), + STRANGER, is_dm, &owner_cache, &dummy_rest_client(), ) .await, - "an external author must not pass when startup discovery omitted metadata" + "a stranger must not pass when startup discovery omitted metadata" ); } diff --git a/crates/buzz-acp/src/pool.rs b/crates/buzz-acp/src/pool.rs index f7b39bd4aab..e3d23a3fd76 100644 --- a/crates/buzz-acp/src/pool.rs +++ b/crates/buzz-acp/src/pool.rs @@ -5856,22 +5856,29 @@ pub(crate) fn permission_refusal_notice_text(tools: &[String]) -> String { /// /// Best-effort by design: the caller must not be blocked waiting on the relay, /// and a notice that cannot be delivered must not take the turn down with it. +/// Returns whether the relay accepted it. pub(crate) async fn post_notice( rest: &crate::relay::RestClient, channel_id: Uuid, thread_tags: &ThreadTags, content: &str, mentions: &[String], -) { +) -> bool { let Some(event) = build_failure_notice_event(&rest.keys, channel_id, thread_tags, content, mentions) else { - return; + return false; }; match tokio::time::timeout(Duration::from_secs(5), rest.submit_event(&event)).await { - Ok(Ok(_)) => {} - Ok(Err(e)) => tracing::warn!(channel = %channel_id, "notice failed: {e}"), - Err(_) => tracing::warn!(channel = %channel_id, "notice timed out"), + Ok(Ok(_)) => true, + Ok(Err(e)) => { + tracing::warn!(channel = %channel_id, "notice failed: {e}"); + false + } + Err(_) => { + tracing::warn!(channel = %channel_id, "notice timed out"); + false + } } } diff --git a/crates/buzz-acp/src/relay.rs b/crates/buzz-acp/src/relay.rs index cdb4c09150e..a3a599acfc8 100644 --- a/crates/buzz-acp/src/relay.rs +++ b/crates/buzz-acp/src/relay.rs @@ -475,14 +475,18 @@ impl RestClient { // Surface non-retriable statuses (401/403/500/…): callers // often swallow the Err, and a silent auth failure here has // previously masqueraded as "the agent just went quiet". - tracing::warn!( - "{method} {path} returned non-retriable HTTP {}", - resp.status() - ); + // The body names the relay rule, e.g. "restricted: not a channel member". + let status = resp.status(); + let why: String = resp + .text() + .await + .unwrap_or_default() + .chars() + .take(200) + .collect(); + tracing::warn!("{method} {path} returned non-retriable HTTP {status}: {why}"); return Err(RelayError::Http(format!( - "{method} {} returned HTTP {}", - path, - resp.status() + "{method} {path} returned HTTP {status}: {why}" ))); } Err(e) if e.is_timeout() || e.is_connect() => { diff --git a/crates/buzz-acp/src/setup_mode.rs b/crates/buzz-acp/src/setup_mode.rs index 0671a24c4c8..a7b096e82c1 100644 --- a/crates/buzz-acp/src/setup_mode.rs +++ b/crates/buzz-acp/src/setup_mode.rs @@ -430,7 +430,8 @@ pub(crate) async fn run_setup_listener(config: Config, payload: SetupPayload) -> // Apply the same author gate as normal mode so the nudge only goes // to authors the real agent would have answered. Same DM hardening: - // in DMs only owner/siblings get a nudge (fail-closed on unknown type). + // in DMs only owner/siblings, plus allowlisted people under + // `allowlist`, get a nudge (fail-closed on unknown type). let Ok(authorized_event) = authorize_setup_listener_event( &mut author_gate_ctx, buzz_event, From afdafdcc865bf0dc49ebf3739a2f83d5912a0c86 Mon Sep 17 00:00:00 2001 From: QuicksilverSlick Date: Sun, 15 Nov 2026 15:39:08 -0600 Subject: [PATCH 2/2] fix(acp): a failing refusal notice costs one card and one text per sender Review fixes for the allowlisted-DM slice: - A pair's first failed notice releases its claim once, so the sender's next message tries again, and tells the owner once. Any later failure keeps the claim: a relay that keeps refusing costs no more posts, cards or texts. The card id is keyed on (channel, sender), not the event. - The owner's text goes out from the notice task itself. The beat that sends queued texts runs only while the pool is up, and a refusal arrives while it sleeps. - The text uses alert_aside, not alert_critical: a refusal is not an incident, so it must not mute the next real Critical's text or owe an all-clear nobody expects. - The card's advice no longer assumes allowlist mode: "change who can send it instructions". Factory-Task: partner-fixes-15nov/1-chris-dm Claude-Account: russelledeming@gmail.com Co-Authored-By: Claude Opus 5.5 --- crates/buzz-acp/src/factory.rs | 30 ++++++--- crates/buzz-acp/src/lib.rs | 119 +++++++++++++++++++++------------ 2 files changed, 98 insertions(+), 51 deletions(-) diff --git a/crates/buzz-acp/src/factory.rs b/crates/buzz-acp/src/factory.rs index 5eb4f181e01..83b6ea991a1 100644 --- a/crates/buzz-acp/src/factory.rs +++ b/crates/buzz-acp/src/factory.rs @@ -1396,24 +1396,28 @@ impl Factory { } /// A refusal the sender was never told about: the "not set up to take - /// requests" notice could not be posted, even on its retry. `event_id` is - /// the refused message's hex id. - pub(crate) fn refusal_unseen(&mut self, channel_id: uuid::Uuid, event_id: &str) { + /// requests" notice could not be posted, even on its retry. `author` is + /// the sender's hex key and `event_id` the refused message's hex id. The + /// caller raises this once per (channel, sender), so the card is keyed on + /// that pair. + pub(crate) fn refusal_unseen(&mut self, channel_id: uuid::Uuid, author: &str, event_id: &str) { let who = card_name(self.who(), &self.reporting.short); let body = format!( "{who} isn't set up to take requests from this person, and its reply saying so could \ not be posted, so they are waiting on an answer that won't come. If they should \ - have access, add them in the agent's access settings and ask them to send it \ - again. Otherwise let them know." + have access, change who can send it instructions and ask them to send it again. \ + Otherwise let them know." ); let id = format!( - "{}-refused-{}", + "{}-refused-{channel_id}-{}", self.reporting.short, - event_id.get(..12).unwrap_or(event_id) + author.get(..12).unwrap_or(author) ); let link = format!("buzz://message?channel={channel_id}&id={event_id}"); let title = format!("{who} turned away a message without telling the sender"); - self.alert_critical(&format!( + // Not an incident: the agent is working. `alert_critical` would mute the + // next real Critical's text and owe an all-clear nobody expects. + self.alert_aside(&format!( "{title}. They are waiting on an answer that won't come." )); self.card( @@ -2726,8 +2730,12 @@ mod tests { f.reporting.bench = Some(bench.path().to_path_buf()); let channel = uuid::Uuid::parse_str("335dd4e1-0000-4000-8000-000000000001").unwrap(); let event = "ef".repeat(32); - f.refusal_unseen(channel, &event); - let card = read_card(bench.path(), "ade9d0e2-refused-efefefefefef").expect("card"); + f.refusal_unseen(channel, &"cd".repeat(32), &event); + let card = read_card( + bench.path(), + &format!("ade9d0e2-refused-{channel}-cdcdcdcdcdcd"), + ) + .expect("card, keyed on the (channel, sender) pair"); assert_eq!( card["title"], "Chris Orchestrator turned away a message without telling the sender" @@ -2747,5 +2755,7 @@ mod tests { let texts = f.take_alerts(); assert_eq!(texts.len(), 1, "{texts:?}"); assert!(texts[0].contains("turned away a message"), "{texts:?}"); + // Not an incident: no all-clear is owed and the next Critical still texts. + assert!(f.alerted.is_none()); } } diff --git a/crates/buzz-acp/src/lib.rs b/crates/buzz-acp/src/lib.rs index fd6f564ab7d..c40d294772a 100644 --- a/crates/buzz-acp/src/lib.rs +++ b/crates/buzz-acp/src/lib.rs @@ -3476,9 +3476,9 @@ async fn run_harness( // flooder. Bounded because this process is long-lived and the key space is // attacker-controlled — on overflow we clear and allow one more notice per // pair rather than growing without limit. A pair is claimed while its - // notice posts and kept only once the relay accepted it: a notice that - // never landed told nobody, so it must not use up their one notice. - let gate_notified: Arc>> = Arc::default(); + // notice posts and kept once the relay accepted it; a first failure + // releases it once (`settle_refusal_notice`). + let gate_notified: Arc> = Arc::default(); // Independent of pool readiness: a never-mentioned lazy agent must still // self-terminate. The watch interval is capped so small configured bounds @@ -4312,7 +4312,8 @@ async fn run_harness( && remember_gate_notice( &mut gate_notified .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner), + .unwrap_or_else(std::sync::PoisonError::into_inner) + .told, memo_key.clone(), ) { @@ -4328,6 +4329,8 @@ async fn run_harness( let content = author_gate_notice_text(is_dm); let rest = ctx.rest_client.clone(); let factory = config.factory.clone(); + let alert_cmd = config.factory_alert_cmd.clone(); + let sms_to = config.factory_alert_sms_to.clone(); let memo = Arc::clone(&gate_notified); tokio::spawn(async move { // The relay's membership cache can refuse a post into a DM @@ -4342,13 +4345,19 @@ async fn run_harness( &waits, ) .await; - settle_refusal_notice( + let texts = settle_refusal_notice( posted, &memo, &memo_key, &factory, &inbound_event_id, ); + if !texts.is_empty() { + deliver_factory_state( + None, None, texts, rest, alert_cmd, sms_to, + ) + .await; + } }); } continue; @@ -6033,28 +6042,55 @@ async fn post_refusal_notice( false } -/// After a refusal notice's last try. The memo means "told", so a claim stays -/// only once the notice landed. Otherwise it is released, so the sender's next -/// message tries again, and the owner gets a card and a text (D1, 15 Nov 2026). +/// The refusal-notice memo, keyed by (channel, author). +#[derive(Default)] +struct RefusalMemo { + /// Told, or a notice in flight. + told: HashSet<(Uuid, String)>, + /// A notice already failed once; the owner was told about it. + failed: HashSet<(Uuid, String)>, +} + +/// After a refusal notice's last try; returns the owner's texts to send now. +/// +/// A landed notice keeps its claim. A pair's first failure releases it, so +/// their next message tries again (the relay's cache may have caught up), and +/// the owner gets one card and one text (D1, 15 Nov 2026). Any later failure +/// keeps the claim, so a relay that keeps refusing costs no more posts, cards +/// or texts. The texts go out from here because the beat that sends queued +/// texts runs only while the pool is up, and a refusal needs no pool. fn settle_refusal_notice( posted: bool, - memo: &std::sync::Mutex>, + memo: &std::sync::Mutex, key: &(Uuid, String), factory: &factory::FactoryHandle, event_id: &str, -) { +) -> Vec { if posted { - return; + return Vec::new(); } - memo.lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .remove(key); + let first = { + let mut memo = memo + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let first = remember_gate_notice(&mut memo.failed, key.clone()); + if first { + memo.told.remove(key); + } + first + }; tracing::error!( channel_id = %key.0, event_id, - "refusal notice could not be posted — the sender was not told; raising to the owner" + first, + "refusal notice could not be posted — the sender was not told" ); - factory.lock().refusal_unseen(key.0, event_id); + if !first { + return Vec::new(); + } + let mut factory = factory.lock(); + factory.refusal_unseen(key.0, &key.1, event_id); + factory.take_alerts() } /// Whether a gate refusal earns the "not set up to take requests" notice. @@ -10585,38 +10621,39 @@ mod author_gate_tests { } /// 13 Nov: the failed reply used up Chris's one notice, so his next two - /// DMs met silence. A notice that never landed keeps no claim, and the - /// owner hears about it instead. + /// DMs met silence. A first failure releases the claim once and tells the + /// owner; a relay that keeps refusing costs no more posts, cards or texts. #[test] - fn refusal_memo_keeps_a_claim_only_once_the_notice_landed() { + fn refusal_memo_releases_a_failed_claim_once() { let bench = tempfile::tempdir().unwrap(); let mut factory = factory::Factory::new(None, "claude-agent-acp"); factory.reporting.short = "ade9d0e2".to_string(); factory.reporting.bench = Some(bench.path().to_path_buf()); let factory = factory::FactoryHandle::new(factory); - let memo = std::sync::Mutex::new(HashSet::new()); - let key = (Uuid::from_u128(1), "chris".to_string()); - let card = bench - .path() - .join("inbox") - .join(factory::CARD_WRITER) - .join("ade9d0e2-refused-abababababab.json"); - - assert!(remember_gate_notice(&mut memo.lock().unwrap(), key.clone())); - settle_refusal_notice(true, &memo, &key, &factory, &"ab".repeat(32)); - assert!(memo.lock().unwrap().contains(&key), "told: stays told"); - assert!(!card.exists(), "a landed notice needs no card"); + let memo = std::sync::Mutex::new(RefusalMemo::default()); + let key = (Uuid::from_u128(1), "cd".repeat(32)); + let event = "ab".repeat(32); + let cards = bench.path().join("inbox").join(factory::CARD_WRITER); + let card_count = || std::fs::read_dir(&cards).map_or(0, |d| d.count()); + let claim = || remember_gate_notice(&mut memo.lock().unwrap().told, key.clone()); + + assert!(claim()); + assert!(settle_refusal_notice(true, &memo, &key, &factory, &event).is_empty()); + assert!(!claim(), "told: stays told"); + assert_eq!(card_count(), 0, "a landed notice needs no card"); + + memo.lock().unwrap().told.clear(); + assert!(claim()); + let texts = settle_refusal_notice(false, &memo, &key, &factory, &event); + assert_eq!(texts.len(), 1, "the owner is texted, now: {texts:?}"); + assert_eq!(card_count(), 1, "and carded"); + assert!(claim(), "never told: their next message must try again"); + + // The retry fails too: the claim stays, and nothing more is raised. + assert!(settle_refusal_notice(false, &memo, &key, &factory, &event).is_empty()); + assert!(!claim(), "a relay that keeps refusing gets no more posts"); + assert_eq!(card_count(), 1); assert!(factory.lock().take_alerts().is_empty()); - - memo.lock().unwrap().clear(); - assert!(remember_gate_notice(&mut memo.lock().unwrap(), key.clone())); - settle_refusal_notice(false, &memo, &key, &factory, &"ab".repeat(32)); - assert!( - remember_gate_notice(&mut memo.lock().unwrap(), key.clone()), - "never told: their next message must try again" - ); - assert!(card.exists(), "the owner gets a card"); - assert_eq!(factory.lock().take_alerts().len(), 1, "and a text"); } #[tokio::test]