diff --git a/AGENTS.md b/AGENTS.md index 752e82dd15c..7e201bae08c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -360,6 +360,11 @@ system channels out of these reads unless the filter asks for them (see [evalexpr](https://docs.rs/evalexpr) for condition evaluation. Keep expressions simple and testable. +Workflow mention candidates include ordinary display names and verified +`display_name`, `username`, and `full_name` aliases for destination-channel +members in the same community. Alias collisions across distinct keys remain +ambiguous. Verified-only profiles do not require a separate kind:0 profile. + **Thread counters**: `reply_count` and `descendant_count` are materialized on thread root events. Any code that inserts replies must update these counters — check existing reply handlers for the pattern. diff --git a/crates/buzz-db/src/runtime/observability.rs b/crates/buzz-db/src/runtime/observability.rs index d3979b5623d..b43a0b594b3 100644 --- a/crates/buzz-db/src/runtime/observability.rs +++ b/crates/buzz-db/src/runtime/observability.rs @@ -1619,7 +1619,7 @@ mod tests { .get_members_for_event_write(test_scope, Uuid::new_v4()) .await; let _ = writer_db - .get_users_bulk_for_event_write(test_scope, &[vec![11; 32]]) + .get_mention_names_for_event_write(test_scope, &[vec![11; 32]], true) .await; let _ = writer_db .huddle_started_link_exists_for_event_write( diff --git a/crates/buzz-db/src/store/channel_members.rs b/crates/buzz-db/src/store/channel_members.rs index 1ba517c547d..465f42d9aff 100644 --- a/crates/buzz-db/src/store/channel_members.rs +++ b/crates/buzz-db/src/store/channel_members.rs @@ -2781,20 +2781,65 @@ impl Db { get_users_bulk(&self.pool, community_id, pubkeys).await } - /// Bulk-fetch user names while constructing an event and its mention tags. - #[datastore_span(name = "get_users_bulk_for_event_write", system = "postgresql")] - pub async fn get_users_bulk_for_event_write( + /// Fetch ordinary display names and, when `include_verified`, verified + /// name aliases for mention tags. + /// + /// Returns `(name, pubkey_hex)` pairs for the supplied community-local members. + /// Keep every alias so the caller can reject names shared by distinct keys. + #[datastore_span(name = "get_mention_names_for_event_write", system = "postgresql")] + pub async fn get_mention_names_for_event_write( &self, community_id: CommunityId, pubkeys: &[Vec], - ) -> Result> { - get_users_bulk_with_operation( + include_verified: bool, + ) -> Result> { + if pubkeys.is_empty() { + return Ok(Vec::new()); + } + let mut connection = crate::observability::acquire_writer( &self.pool, - community_id, - pubkeys, crate::observability::WriterOperation::EventWrite, ) - .await + .await?; + let rows = sqlx::query( + r#" + SELECT member.pubkey, u.display_name, + jsonb_path_query_first(v.event, 'strict $.tags[*] ? (@[0] == "display_name")[1]', '{}', true) #>> '{}' AS verified_display_name, + jsonb_path_query_first(v.event, 'strict $.tags[*] ? (@[0] == "username")[1]', '{}', true) #>> '{}' AS verified_username, + jsonb_path_query_first(v.event, 'strict $.tags[*] ? (@[0] == "full_name")[1]', '{}', true) #>> '{}' AS verified_full_name + FROM unnest($2::bytea[]) AS member(pubkey) + LEFT JOIN users u ON u.community_id = $1 AND u.pubkey = member.pubkey + LEFT JOIN nip_fi_profile_heads v + ON $3 AND v.community_id = $1 AND v.pubkey = encode(member.pubkey, 'hex') + "#, + ) + .bind(community_id.as_uuid()) + .bind(pubkeys) + .bind(include_verified) + .fetch_all(&mut *connection) + .await?; + drop(connection); + + // One entry per case-folded name and member, so a member whose aliases + // repeat a name does not make the resolver scan for it again. + let mut seen = std::collections::HashSet::new(); + let mut names = Vec::new(); + for row in rows { + let pubkey = hex::encode(row.try_get::, _>("pubkey")?); + for column in [ + "display_name", + "verified_display_name", + "verified_username", + "verified_full_name", + ] { + if let Some(name) = row.try_get::, _>(column)? { + if seen.insert((name.to_lowercase(), pubkey.clone())) { + names.push((name, pubkey.clone())); + } + } + } + } + Ok(names) } /// Returns the count of active members in a channel. diff --git a/crates/buzz-db/tests/observability_source.rs b/crates/buzz-db/tests/observability_source.rs index f85af28be13..5734503fc2d 100644 --- a/crates/buzz-db/tests/observability_source.rs +++ b/crates/buzz-db/tests/observability_source.rs @@ -313,7 +313,7 @@ fn p0_pool_acquisitions_use_typed_operation_pairs_without_other() { assert!(channel_members.contains("async fn get_members_with_operation(")); assert!(channel_members.contains("pub async fn get_members_for_event_write(")); assert!(channel_members.contains("async fn get_users_bulk_with_operation(")); - assert!(channel_members.contains("pub async fn get_users_bulk_for_event_write(")); + assert!(channel_members.contains("pub async fn get_mention_names_for_event_write(")); let huddle_link = event .split_once("async fn huddle_started_link_exists_with_operation(") @@ -331,7 +331,7 @@ fn p0_pool_acquisitions_use_typed_operation_pairs_without_other() { let workflow_sink = include_str!("../../buzz-relay/src/workflow_sink.rs"); assert!(workflow_sink.contains(".get_members_for_event_write(")); - assert!(workflow_sink.contains(".get_users_bulk_for_event_write(")); + assert!(workflow_sink.contains(".get_mention_names_for_event_write(")); for write_caller in [ include_str!("../../buzz-relay/src/handlers/side_effects.rs"), diff --git a/crates/buzz-relay/src/workflow_sink.rs b/crates/buzz-relay/src/workflow_sink.rs index 62397fad861..c3fc15ecef6 100644 --- a/crates/buzz-relay/src/workflow_sink.rs +++ b/crates/buzz-relay/src/workflow_sink.rs @@ -30,7 +30,8 @@ use crate::state::AppState; /// /// - **Members only.** Candidates are the destination channel's members; global /// users are never matched. -/// - **Exact display name.** No substring, prefix, or fuzzy matching. Names may +/// - **Exact profile name.** Ordinary display names and verified display names, +/// usernames, and full names are aliases. No substring, prefix, or fuzzy matching. Names may /// contain spaces/punctuation (`"Will Pfleger"`, `"Lep (Subagent)"`), so the /// match is anchored on `@` and terminated by a non-name boundary rather than /// whitespace. @@ -106,24 +107,33 @@ fn resolve_mention_pubkeys(text: &str, members: &[(String, String)]) -> Vec = Vec::new(); + // Only an `@` at a left boundary can start a mention, so collect those + // positions once and try each name only there. This keeps the cost at + // names × mentions rather than names × text length. + let anchors: Vec = (0..chars.len()) + .filter(|&at| chars[at] == '@' && is_left_boundary(at)) + .collect(); + if anchors.is_empty() { + return out; + } + for (name, _) in &names { let folded_name: Vec = name.to_lowercase().chars().collect(); if folded_name.is_empty() { continue; } - let mut at = 0; - while at < chars.len() { - // Anchor on `@` at a left boundary and an unconsumed span; only then - // attempt the fold-match. `name_len` is measured in *original* chars, - // so `at + 1 + name_len` is the true position just past the name. - let name_len = (chars[at] == '@' && is_left_boundary(at) && !consumed[at]) - .then(|| match_name_len(at + 1, &folded_name)) - .flatten() - .filter(|&n| { - chars[at + 1 + n..] - .first() - .is_none_or(|&c| !extends_name(c)) - }); + for &at in &anchors { + // Skip anchors inside a span an earlier (longer) match consumed. + // `name_len` is measured in *original* chars, so `at + 1 + name_len` + // is the true position just past the name. + if consumed[at] { + continue; + } + let name_len = match_name_len(at + 1, &folded_name).filter(|&n| { + chars[at + 1 + n..] + .first() + .is_none_or(|&c| !extends_name(c)) + }); if let Some(name_len) = name_len { let span = 1 + name_len; if let Some(Some(pubkey)) = by_name.get(&name.to_lowercase()) { @@ -132,9 +142,6 @@ fn resolve_mention_pubkeys(text: &str, members: &[(String, String)]) -> Vec> = members.iter().map(|m| m.pubkey.clone()).collect(); - let users = state - .db - .get_users_bulk_for_event_write(tenant.community(), &member_pubkeys) - .await - .map_err(|e| ActionSinkError::Database(e.to_string()))?; - let named_members: Vec<(String, String)> = users - .into_iter() - .filter_map(|u| { - let name = u.display_name?; - Some((name, nostr::PublicKey::from_slice(&u.pubkey).ok()?.to_hex())) - }) - .collect(); - let agent_mentions_withheld = append_workflow_mention_tags( - &mut tags, - &text, - &authored_text, - may_direct_agents, - &named_members, - )?; + // Text without an `@` cannot name anyone, so it skips the member + // and alias reads entirely. + let agent_mentions_withheld = if text.contains('@') { + let members = state + .db + .get_members_for_event_write(tenant.community(), channel_uuid) + .await + .map_err(|e| ActionSinkError::Database(e.to_string()))?; + let member_pubkeys: Vec> = + members.iter().map(|m| m.pubkey.clone()).collect(); + // Verified names count only where the community advertises + // them, matching profile search; leftover heads stay inert. + let include_verified = crate::verified_profiles::discovery(&state, &tenant) + .await + .is_some(); + let named_members = state + .db + .get_mention_names_for_event_write( + tenant.community(), + &member_pubkeys, + include_verified, + ) + .await + .map_err(|e| ActionSinkError::Database(e.to_string()))?; + append_workflow_mention_tags( + &mut tags, + &text, + &authored_text, + may_direct_agents, + &named_members, + )? + } else { + false + }; let kind = Kind::from(KIND_STREAM_MESSAGE as u16); let event = EventBuilder::new(kind, &text) @@ -998,6 +1014,25 @@ mod postgres_tests { test_state_with_agent_mentions(buzz_workflow::AgentMentions::Any).await } + /// [`test_state`] with verified profiles advertised for every host, so + /// workflow mentions may resolve verified names. + async fn advertised_test_state() -> Arc { + let state = test_state().await; + let mut advertised = (*state).clone(); + let mut config = (*advertised.config).clone(); + config.relay_private_key = Some(advertised.relay_keypair.secret_key().to_secret_hex()); + config.nip_fi.mode = buzz_auth::NipFiMode::Enforce; + config.nip_fi.communities = + crate::nip_fi_core::test_support::any_host("https://relay.example"); + config.nip_fi.profile_policies = vec![buzz_db::verified_profiles::ProfilePolicy { + issuer: "https://issuer.test".to_owned(), + label: Some("Example".to_owned()), + refresh_seconds: 3600, + }]; + advertised.config = Arc::new(config); + Arc::new(advertised) + } + async fn test_state_with_agent_mentions( agent_mentions: buzz_workflow::AgentMentions, ) -> Arc { @@ -1472,7 +1507,7 @@ mod postgres_tests { #[tokio::test] #[ignore = "requires Postgres"] async fn workflow_send_message_binds_authority_to_authored_mentions() { - let state = test_state().await; + let state = advertised_test_state().await; let author = nostr::Keys::generate(); let author_hex = author.public_key().to_hex(); @@ -1536,6 +1571,98 @@ mod postgres_tests { .await .expect("add agent member"); + let verified = nostr::Keys::generate().public_key(); + let twin = nostr::Keys::generate().public_key(); + let outsider = nostr::Keys::generate().public_key(); + for key in [twin, outsider] { + state + .db + .ensure_user(community, &key.to_bytes()) + .await + .expect("ensure user"); + } + for key in [verified, twin] { + state + .db + .add_member( + community, + channel.id, + &key.to_bytes(), + MemberRole::Member, + Some(&author_bytes), + ) + .await + .expect("add member"); + } + state + .db + .update_user_profile( + community, + &twin.to_bytes(), + Some("Alex Example"), + None, + None, + None, + ) + .await + .expect("ambiguous ordinary name"); + for (key, username) in [(verified, "alex"), (outsider, "outsider")] { + state + .db + .publish_verified_profile( + buzz_db::verified_profiles::ProfileAdmission { + community, + issuer: "https://identity.example.org", + pubkey: &key.to_hex(), + issued_at: Utc::now(), + admitted_at: Utc::now(), + display_name: "Alex Example (@alex)", + username, + full_name: Some("Alex Example"), + label: "Example", + refresh_seconds: 3600, + membership_required: false, + }, + &state.relay_keypair, + ) + .await + .expect("publish verified profile"); + } + let other_community = match state + .db + .create_community_with_owner( + &format!("other-{}.example.org", Uuid::new_v4().simple()), + &author_hex, + &nostr::Keys::generate(), + ) + .await + .expect("other community") + .outcome + { + CreateCommunityWithOwnerResult::Created(rec) => rec.id, + other => panic!("expected fresh community: {other:?}"), + }; + state + .db + .publish_verified_profile( + buzz_db::verified_profiles::ProfileAdmission { + community: other_community, + issuer: "https://identity.example.org", + pubkey: &verified.to_hex(), + issued_at: Utc::now(), + admitted_at: Utc::now(), + display_name: "Foreign Name", + username: "foreign-only", + full_name: None, + label: "Example", + refresh_seconds: 3600, + membership_required: false, + }, + &state.relay_keypair, + ) + .await + .expect("foreign profile for the same key"); + let sink = Arc::new(RelayActionSink::new(&state)); state.workflow_engine.set_action_sink(sink); @@ -1602,6 +1729,136 @@ mod postgres_tests { ), "the first p tag attributes the message to its owner and is marked as attribution" ); + for (name, text, trigger, mentioned, authorized) in [ + ("verified-username", "@alex", "", true, true), + ( + "verified-display-name", + "@Alex Example (@alex)", + "", + true, + true, + ), + ( + "verified-dedup", + "@alex @Alex Example (@alex) @alex", + "", + true, + true, + ), + ("ambiguous-full-name", "@Alex Example", "", false, false), + ("no-at-sign", "alex, Alex Example", "", false, false), + ("verified-nonmember", "@outsider", "", false, false), + ("foreign-profile", "@foreign-only", "", false, false), + ( + "injected-verified", + "echo: {{trigger.text}}", + "@alex", + true, + false, + ), + ] { + let id = execute_send_message_workflow( + &state, + community, + channel.id, + &author_bytes, + name, + text, + trigger, + ) + .await; + let event = load_event(&id).await; + let expected_mentions = if mentioned { + vec![verified.to_hex()] + } else { + vec![] + }; + assert_eq!( + tag_values(&event, "p"), + [vec![author_hex.clone()], expected_mentions].concat(), + "{name}: recipient tags" + ); + assert_eq!( + tag_values(&event, "buzz:workflow-mention"), + if authorized { + vec![verified.to_hex()] + } else { + vec![] + }, + "{name}: delegated authority" + ); + } + state + .db + .ensure_user(community, &verified.to_bytes()) + .await + .expect("ensure ordinary profile user"); + state + .db + .update_user_profile( + community, + &verified.to_bytes(), + Some("Ally Example"), + None, + None, + None, + ) + .await + .expect("add ordinary profile alongside verified profile"); + for (name, text) in [ + ("mixed-ordinary", "@Ally Example"), + ("mixed-verified", "@alex"), + ] { + let id = execute_send_message_workflow( + &state, + community, + channel.id, + &author_bytes, + name, + text, + "", + ) + .await; + let event = load_event(&id).await; + assert_eq!( + tag_values(&event, "p"), + vec![author_hex.clone(), verified.to_hex()], + "{name}: both profile sources remain mentionable" + ); + } + + // Same roster without the advertisement: leftover verified heads are + // ignored, so the ordinary name is no longer ambiguous. + let unadvertised = test_state().await; + unadvertised + .workflow_engine + .set_action_sink(Arc::new(RelayActionSink::new(&unadvertised))); + for (name, text, expected) in [ + ("unadvertised-username", "@alex", vec![]), + ( + "unadvertised-ordinary", + "@Alex Example", + vec![twin.to_hex()], + ), + ] { + let id = execute_send_message_workflow( + &unadvertised, + community, + channel.id, + &author_bytes, + name, + text, + "", + ) + .await; + let event = load_event(&id).await; + assert_eq!( + tag_values(&event, "p"), + [vec![author_hex.clone()], expected].concat(), + "{name}: verified names need the advertisement" + ); + } + let p_tag_targets = tag_values(&explicit, "p"); assert!( p_tag_targets.contains(&author_hex),