From 1a7e5a73641fd4fdc31a890d0459baf098ab7732 Mon Sep 17 00:00:00 2001 From: Camilo Sanchez Date: Tue, 17 Nov 2026 11:31:39 -0800 Subject: [PATCH 1/8] fix(workflows): resolve verified profile mention aliases Signed-off-by: Camilo Sanchez Amp-Thread-ID: https://ampcode.com/threads/T-01a1eab0-97d0-75be-af34-a93d1ee350c1 Co-authored-by: Amp Signed-off-by: Camilo Sanchez --- AGENTS.md | 5 + crates/buzz-db/src/runtime/observability.rs | 2 +- crates/buzz-db/src/store/channel_members.rs | 42 +++- crates/buzz-db/tests/observability_source.rs | 4 +- crates/buzz-relay/src/workflow_sink.rs | 203 ++++++++++++++++++- 5 files changed, 235 insertions(+), 21 deletions(-) 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..0fbce0f63d0 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]]) .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 82b66a7acae..6c3597425f9 100644 --- a/crates/buzz-db/src/store/channel_members.rs +++ b/crates/buzz-db/src/store/channel_members.rs @@ -2736,20 +2736,46 @@ 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 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( + ) -> 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?; + Ok(sqlx::query_as( + r#" + SELECT names.name, encode(member.pubkey, 'hex') + 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 v.community_id = $1 AND v.pubkey = encode(member.pubkey, 'hex') + CROSS JOIN LATERAL ( + SELECT u.display_name AS name + UNION + SELECT tag->>1 AS name + FROM jsonb_array_elements(v.event->'tags') AS tag + WHERE tag->>0 IN ('display_name', 'username', 'full_name') + ) names + WHERE names.name IS NOT NULL + "#, + ) + .bind(community_id.as_uuid()) + .bind(pubkeys) + .fetch_all(&mut *connection) + .await?) } /// 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 7b75dae59bd..43279805afe 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..b604e423a63 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. @@ -517,18 +518,11 @@ impl ActionSink for RelayActionSink { .await .map_err(|e| ActionSinkError::Database(e.to_string()))?; let member_pubkeys: Vec> = members.iter().map(|m| m.pubkey.clone()).collect(); - let users = state + let named_members = state .db - .get_users_bulk_for_event_write(tenant.community(), &member_pubkeys) + .get_mention_names_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, @@ -1536,6 +1530,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 +1688,103 @@ 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), + ("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" + ); + } + let p_tag_targets = tag_values(&explicit, "p"); assert!( p_tag_targets.contains(&author_hex), From 1e63f41621537cc95f3a8eb749bcdb850eb951b3 Mon Sep 17 00:00:00 2001 From: Camilo Sanchez Date: Tue, 17 Nov 2026 13:34:49 -0800 Subject: [PATCH 2/8] refactor(workflows): extract profile aliases in Rust Amp-Thread-ID: T-01a1eab0-97d0-75be-af34-a93d1ee350c1 Signed-off-by: Camilo Sanchez --- crates/buzz-db/src/store/channel_members.rs | 37 +++++++++++++-------- 1 file changed, 24 insertions(+), 13 deletions(-) diff --git a/crates/buzz-db/src/store/channel_members.rs b/crates/buzz-db/src/store/channel_members.rs index 6c3597425f9..62b81eea8e8 100644 --- a/crates/buzz-db/src/store/channel_members.rs +++ b/crates/buzz-db/src/store/channel_members.rs @@ -2754,28 +2754,39 @@ impl Db { crate::observability::WriterOperation::EventWrite, ) .await?; - Ok(sqlx::query_as( + let rows = sqlx::query( r#" - SELECT names.name, encode(member.pubkey, 'hex') + SELECT member.pubkey, u.display_name, v.event FROM unnest($2::bytea[]) AS member(pubkey) - LEFT JOIN users u - ON u.community_id = $1 AND u.pubkey = member.pubkey + LEFT JOIN users u ON u.community_id = $1 AND u.pubkey = member.pubkey LEFT JOIN nip_fi_profile_heads v ON v.community_id = $1 AND v.pubkey = encode(member.pubkey, 'hex') - CROSS JOIN LATERAL ( - SELECT u.display_name AS name - UNION - SELECT tag->>1 AS name - FROM jsonb_array_elements(v.event->'tags') AS tag - WHERE tag->>0 IN ('display_name', 'username', 'full_name') - ) names - WHERE names.name IS NOT NULL "#, ) .bind(community_id.as_uuid()) .bind(pubkeys) .fetch_all(&mut *connection) - .await?) + .await?; + + let mut names = Vec::new(); + for row in rows { + let pubkey = hex::encode(row.try_get::, _>("pubkey")?); + if let Some(name) = row.try_get::, _>("display_name")? { + names.push((name, pubkey.clone())); + } + let profile: Option> = row.try_get("event")?; + if let Some(profile) = profile { + for tag in profile.tags.iter() { + let [field, name, ..] = tag.as_slice() else { + continue; + }; + if matches!(field.as_str(), "display_name" | "username" | "full_name") { + names.push((name.clone(), pubkey.clone())); + } + } + } + } + Ok(names) } /// Returns the count of active members in a channel. From 3e0cdfa13fd1638e8469e4fb96b6d3fa6ba66c19 Mon Sep 17 00:00:00 2001 From: Camilo Sanchez Date: Wed, 18 Nov 2026 14:56:10 -0800 Subject: [PATCH 3/8] fix(workflows): normalize mention aliases and cover collisions Signed-off-by: Camilo Sanchez Amp-Thread-ID: https://ampcode.com/threads/T-01a1f0c7-8b00-70a9-94bd-c1d62fed3aab Co-authored-by: Amp Signed-off-by: Camilo Sanchez --- AGENTS.md | 8 +- Cargo.lock | 1 + crates/buzz-db/src/store/verified_profiles.rs | 8 +- crates/buzz-relay/Cargo.toml | 1 + crates/buzz-relay/src/workflow_sink.rs | 157 ++++++++++++++---- 5 files changed, 138 insertions(+), 37 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 7e201bae08c..9206d27db75 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -362,8 +362,12 @@ 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. +members in the same community. Matching and collision detection lowercase and +canonically normalize aliases. Alias collisions across distinct keys, including +ordinary names colliding with verified aliases, deliberately produce no recipient +or delegated agent-wake tag for that name rather than redirecting the mention or +notifying every matching member. 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 — diff --git a/Cargo.lock b/Cargo.lock index 312d7068436..d331ed4d77f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1504,6 +1504,7 @@ dependencies = [ "tracing-opentelemetry", "tracing-subscriber", "tungstenite 0.29.0", + "unicode-normalization", "url", "uuid", ] diff --git a/crates/buzz-db/src/store/verified_profiles.rs b/crates/buzz-db/src/store/verified_profiles.rs index db3d09b9942..189cb342168 100644 --- a/crates/buzz-db/src/store/verified_profiles.rs +++ b/crates/buzz-db/src/store/verified_profiles.rs @@ -1,9 +1,11 @@ -//! Durable output-only NIP-FI verified profiles. Authorization never reads -//! these tables. +//! Durable relay-verified NIP-FI profiles. Stored profiles do not authorize +//! admission. Workflow mentions read their name aliases for destination-channel +//! members, including delegated agent-wake tags when the workflow's authored +//! template names an unambiguous member and its authority checks allow it. //! //! A profile is a historical record ("verified as Alice at T"). It is never //! retracted: on a relay that enforces NIP-FI, a key cannot post without a -//! fresh issuer assertion, so a stale name labels only past activity. +//! fresh issuer assertion, regardless of its stored profile. use crate::{AdmittedTx, Db, DbError, Result}; use buzz_core::CommunityId; diff --git a/crates/buzz-relay/Cargo.toml b/crates/buzz-relay/Cargo.toml index cd5a79e526d..9db3dee08ef 100644 --- a/crates/buzz-relay/Cargo.toml +++ b/crates/buzz-relay/Cargo.toml @@ -90,6 +90,7 @@ metrics-exporter-prometheus = { workspace = true } metrics-util = { workspace = true } pulldown-cmark = { version = "0.13.4", default-features = false, features = ["html"] } async-compression = { version = "0.4.42", features = ["tokio", "gzip"] } +unicode-normalization = "0.1" [features] dev = ["buzz-auth/dev"] diff --git a/crates/buzz-relay/src/workflow_sink.rs b/crates/buzz-relay/src/workflow_sink.rs index b604e423a63..1e641bd8a57 100644 --- a/crates/buzz-relay/src/workflow_sink.rs +++ b/crates/buzz-relay/src/workflow_sink.rs @@ -14,6 +14,7 @@ use buzz_workflow::action_sink::{ActionSink, ActionSinkError, SentMessage}; use chrono::Utc; use nostr::{EventBuilder, Kind, Tag}; use tracing::info; +use unicode_normalization::{char::is_combining_mark, UnicodeNormalization}; use uuid::Uuid; use crate::handlers::event::dispatch_persistent_event; @@ -31,29 +32,42 @@ use crate::state::AppState; /// - **Members only.** Candidates are the destination channel's members; global /// users are never matched. /// - **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 +/// usernames, and full names are aliases. Matching ignores case and canonical +/// Unicode encoding differences, with no substring, prefix, or fuzzy matching. +/// Names may contain spaces/punctuation (`"Alex Example"`, `"Lep (Subagent)"`), so the /// match is anchored on `@` and terminated by a non-name boundary rather than /// whitespace. /// - **Greedy-longest, non-overlapping.** Longer names are matched first and -/// consume their span, so `@Will Pfleger` binds *Pfleger* and a bare `@Will` -/// does not match the member `"Will Pfleger"`. +/// consume their span, so `@Alex Example` binds *Example* and a bare `@Alex` +/// does not match the member `"Alex Example"`. /// - **Ambiguous names wake no one.** If two or more members share the matched /// display name, no `p` tag is emitted for it — arbitrary selection would /// silently misroute and tagging all of them is a false-wake firehose. /// /// Returns deduplicated pubkey hexes, in first-appearance order in `text`. fn resolve_mention_pubkeys(text: &str, members: &[(String, String)]) -> Vec { + let members: Vec<_> = members + .iter() + .map(|(name, pubkey)| { + ( + name.chars() + .flat_map(char::to_lowercase) + .nfd() + .collect::(), + pubkey.clone(), + ) + }) + .collect(); // Name → pubkey, folding case (client matches case-insensitively). A name // that maps to more than one distinct pubkey is ambiguous → wake no one. let mut by_name: std::collections::HashMap> = std::collections::HashMap::new(); - for (name, pubkey) in members { + for (name, pubkey) in &members { if name.trim().is_empty() { continue; } by_name - .entry(name.to_lowercase()) + .entry(name.clone()) .and_modify(|slot| { if slot.as_deref() != Some(pubkey.as_str()) { *slot = None; // ambiguous @@ -70,29 +84,25 @@ fn resolve_mention_pubkeys(text: &str, members: &[(String, String)]) -> Vec = text.chars().collect(); let mut consumed = vec![false; chars.len()]; - // Case-insensitivity folds *both* sides through `char::to_lowercase`, which - // can change length: `İ` (U+0130) lowercases to two code points (`i` + - // U+0307 combining dot). Comparing a pre-lowercased copy of the whole text - // against a lowercased name by index silently desyncs once any earlier char - // expands. Instead, fold on the fly: walk the original `chars` at the - // candidate `@`, folding each char, and match against the folded-name char - // stream — tracking how many *original* chars were consumed so - // boundary/`consumed` accounting stays in original coordinates. `None` = no - // match; `Some(n)` = matched, consuming `n` original chars after the `@`. + // Lowercasing and canonical decomposition can expand characters. Count the + // matching span in original coordinates, then normalize that whole span so + // combining marks can reorder across character boundaries. Never index the + // original text with normalized offsets. let match_name_len = |start: usize, folded_name: &[char]| -> Option { let mut ci = start; let mut ni = 0; while ni < folded_name.len() { let c = *chars.get(ci)?; - for fc in c.to_lowercase() { - if folded_name.get(ni) != Some(&fc) { - return None; - } - ni += 1; - } + ni += c.to_lowercase().nfd().count(); ci += 1; } - Some(ci - start) + chars[start..ci] + .iter() + .copied() + .flat_map(char::to_lowercase) + .nfd() + .eq(folded_name.iter().copied()) + .then_some(ci - start) }; // A mention is anchored on `@` at a left boundary (start / whitespace / `(`) @@ -101,14 +111,14 @@ fn resolve_mention_pubkeys(text: &str, members: &[(String, String)]) -> Vec = Vec::new(); let mut seen = std::collections::HashSet::new(); let mut hits: Vec<(usize, String)> = Vec::new(); for (name, _) in &names { - let folded_name: Vec = name.to_lowercase().chars().collect(); + let folded_name: Vec = name.chars().collect(); if folded_name.is_empty() { continue; } @@ -127,7 +137,7 @@ fn resolve_mention_pubkeys(text: &str, members: &[(String, String)]) -> Vec Date: Wed, 18 Nov 2026 16:53:56 -0800 Subject: [PATCH 4/8] fix(workflows): normalize mention text once per resolution Signed-off-by: Camilo Sanchez Amp-Thread-ID: https://ampcode.com/threads/T-01a1f101-9451-7674-ab92-1c2ea9f8515c Co-authored-by: Amp --- AGENTS.md | 4 ++- crates/buzz-relay/src/workflow_sink.rs | 36 ++++++++++++++------------ 2 files changed, 22 insertions(+), 18 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 9206d27db75..322bb7f76cd 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -363,7 +363,9 @@ 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. Matching and collision detection lowercase and -canonically normalize aliases. Alias collisions across distinct keys, including +canonically normalize aliases. Message text is normalized once per resolution, +with offsets preserving original-character boundaries rather than normalizing +again for each alias attempt. Alias collisions across distinct keys, including ordinary names colliding with verified aliases, deliberately produce no recipient or delegated agent-wake tag for that name rather than redirecting the mention or notifying every matching member. Verified-only profiles do not require a separate diff --git a/crates/buzz-relay/src/workflow_sink.rs b/crates/buzz-relay/src/workflow_sink.rs index 1e641bd8a57..d14bd10681b 100644 --- a/crates/buzz-relay/src/workflow_sink.rs +++ b/crates/buzz-relay/src/workflow_sink.rs @@ -84,25 +84,25 @@ fn resolve_mention_pubkeys(text: &str, members: &[(String, String)]) -> Vec = text.chars().collect(); let mut consumed = vec![false; chars.len()]; - // Lowercasing and canonical decomposition can expand characters. Count the - // matching span in original coordinates, then normalize that whole span so - // combining marks can reorder across character boundaries. Never index the - // original text with normalized offsets. + // Normalize once, not a candidate-length span at every `@`. Prefix lengths + // map back to original boundaries without splitting an expanded character. + // Reordering cannot cross `@` or a valid right boundary (no combining mark). + let folded_chars: Vec = text.chars().flat_map(char::to_lowercase).nfd().collect(); + let folded_offsets: Vec = std::iter::once(0) + .chain(chars.iter().scan(0, |offset, c| { + *offset += c.to_lowercase().nfd().count(); + Some(*offset) + })) + .collect(); let match_name_len = |start: usize, folded_name: &[char]| -> Option { - let mut ci = start; - let mut ni = 0; - while ni < folded_name.len() { - let c = *chars.get(ci)?; - ni += c.to_lowercase().nfd().count(); - ci += 1; + let offset = folded_offsets[start]; + if !folded_chars[offset..].starts_with(folded_name) { + return None; } - chars[start..ci] - .iter() - .copied() - .flat_map(char::to_lowercase) - .nfd() - .eq(folded_name.iter().copied()) - .then_some(ci - start) + folded_offsets + .binary_search(&(offset + folded_name.len())) + .ok() + .map(|end| end - start) }; // A mention is anchored on `@` at a left boundary (start / whitespace / `(`) @@ -795,6 +795,8 @@ mod tests { ("Jose\u{0301}", "@JOSÉ! @Robby", true), ("a\u{0301}\u{0323}", "@a\u{0323}\u{0301}! @Robby", true), ("각", "@\u{1100}\u{1161}\u{11a8}! @Robby", true), + ("\u{1100}", "@각! @Robby", false), + ("José", "İ 각 @Jose\u{0301}! @Robby", true), ("José", "@Jose\u{0301}x @Robby", false), ("Jose", "@Jose\u{0301} @Robby", false), ("José", "@Jose\u{0301}@Robby @Robby", true), From 89938dadfd3290db34a48a90f5d286d0c32ae32c Mon Sep 17 00:00:00 2001 From: Tom Brow Date: Thu, 19 Nov 2026 09:40:18 -0800 Subject: [PATCH 5/8] perf(workflows): bound verified mention alias cost (#9686) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Follow-up to https://github.com/block/buzz/pull/9685 (verified profile aliases in workflow mentions), targeting its branch. https://github.com/block/buzz/pull/9685 makes every workflow `send_message` load each channel member's full kind:30382 verified-profile event, parse it into a `nostr::Event` while holding the writer connection, and scan the message for about five times as many names, on a tokio worker. That cost lands on every workflow send, including ones that mention no one. It also reads verified names even when the community no longer advertises verified profiles, so leftover profile heads can make an ordinary `@Name` ambiguous after an operator turns the feature off. This keeps the same output tags and: - **Skips mention resolution when the rendered text has no `@`.** No `@` means no `p` or `buzz:workflow-mention` tag can result, so the member and alias reads are skipped. - **Projects only the three name tags in SQL** (`display_name`, `username`, `full_name`, the same `jsonb_path_query_first` expression profile search uses) instead of shipping and parsing whole events. Identical case-folded names for one member are deduplicated. A malformed head no longer fails the send. - **Tries names only at mention anchors.** The resolver collects the positions of `@` at a left boundary once and matches each name only there, so its cost is names × mentions instead of names × characters. Matching rules are unchanged. - **Reads verified names only where the community advertises them**, using the same `verified_profiles::discovery` check as profile search. Otherwise the heads join is skipped. ### Validation - Extended the existing workflow alias test ([`workflow_send_message_binds_authority_to_authored_mentions`](https://github.com/block/buzz/blob/e0526e62c8f70a1b55b50e0f2d5d160337197c34/crates/buzz-relay/src/workflow_sink.rs)): it now runs with verified profiles advertised, adds a message with no `@`, and repeats two cases on the same roster without the advertisement (`@alex` notifies no one, `@Alex Example` notifies the ordinary member). - The existing resolver unit tests cover the anchor-only scan. ### Regressions None expected. Output tags are identical for every advertised community. In a community that does not advertise verified profiles, workflow mentions fall back to ordinary names, which is what they matched before https://github.com/block/buzz/pull/9685. --------- Signed-off-by: Tom Brow --- crates/buzz-db/src/runtime/observability.rs | 2 +- crates/buzz-db/src/store/channel_members.rs | 36 +++-- crates/buzz-relay/src/verified_profiles.rs | 18 ++- crates/buzz-relay/src/workflow_sink.rs | 147 +++++++++++++++----- 4 files changed, 148 insertions(+), 55 deletions(-) diff --git a/crates/buzz-db/src/runtime/observability.rs b/crates/buzz-db/src/runtime/observability.rs index 0fbce0f63d0..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_mention_names_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 62b81eea8e8..8d8633a5a90 100644 --- a/crates/buzz-db/src/store/channel_members.rs +++ b/crates/buzz-db/src/store/channel_members.rs @@ -2736,7 +2736,8 @@ impl Db { get_users_bulk(&self.pool, community_id, pubkeys).await } - /// Fetch ordinary display names and verified name aliases for mention tags. + /// 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. @@ -2745,6 +2746,7 @@ impl Db { &self, community_id: CommunityId, pubkeys: &[Vec], + include_verified: bool, ) -> Result> { if pubkeys.is_empty() { return Ok(Vec::new()); @@ -2756,32 +2758,38 @@ impl Db { .await?; let rows = sqlx::query( r#" - SELECT member.pubkey, u.display_name, v.event + 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 v.community_id = $1 AND v.pubkey = encode(member.pubkey, 'hex') + 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")?); - if let Some(name) = row.try_get::, _>("display_name")? { - names.push((name, pubkey.clone())); - } - let profile: Option> = row.try_get("event")?; - if let Some(profile) = profile { - for tag in profile.tags.iter() { - let [field, name, ..] = tag.as_slice() else { - continue; - }; - if matches!(field.as_str(), "display_name" | "username" | "full_name") { - names.push((name.clone(), pubkey.clone())); + 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())); } } } diff --git a/crates/buzz-relay/src/verified_profiles.rs b/crates/buzz-relay/src/verified_profiles.rs index 22d62059fad..50031602aae 100644 --- a/crates/buzz-relay/src/verified_profiles.rs +++ b/crates/buzz-relay/src/verified_profiles.rs @@ -118,6 +118,16 @@ pub(crate) async fn discovery( state: &AppState, tenant: &TenantContext, ) -> Option { + try_discovery(state, tenant).await.ok().flatten() +} + +/// [`discovery`], but a failed binding lookup is an error rather than +/// "not advertised", for callers that must not mistake an outage for the +/// feature being off. +pub(crate) async fn try_discovery( + state: &AppState, + tenant: &TenantContext, +) -> Result, buzz_db::DbError> { let mut count = 0; for policy in enabled_policies(state) { let authorized = match state.config.nip_fi.source { @@ -130,9 +140,7 @@ pub(crate) async fn discovery( CommunitySource::Database => state .db .lookup_nip_fi_binding_by_host(tenant.host()) - .await - .ok() - .flatten() + .await? .is_some_and(|b| b.active && b.issuers.contains(&policy.issuer)), }; if authorized { @@ -140,7 +148,7 @@ pub(crate) async fn discovery( } } // `searchable`: `POST /profiles/search` also matches and returns these. - (count > 0).then( + Ok((count > 0).then( || serde_json::json!({"kind": 30382, "multiple_issuers": count > 1, "searchable": true}), - ) + )) } diff --git a/crates/buzz-relay/src/workflow_sink.rs b/crates/buzz-relay/src/workflow_sink.rs index d14bd10681b..65e57c0adcb 100644 --- a/crates/buzz-relay/src/workflow_sink.rs +++ b/crates/buzz-relay/src/workflow_sink.rs @@ -117,24 +117,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.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) { @@ -143,9 +152,6 @@ fn resolve_mention_pubkeys(text: &str, members: &[(String, String)]) -> Vec> = members.iter().map(|m| m.pubkey.clone()).collect(); - let named_members = state - .db - .get_mention_names_for_event_write(tenant.community(), &member_pubkeys) - .await - .map_err(|e| ActionSinkError::Database(e.to_string()))?; - 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. + // A failed lookup fails the send like the reads around it, + // rather than silently dropping verified-only mentions. + let include_verified = crate::verified_profiles::try_discovery(&state, &tenant) + .await + .map_err(|e| ActionSinkError::Database(e.to_string()))? + .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) @@ -1029,6 +1054,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 { @@ -1503,7 +1547,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(); @@ -1743,6 +1787,7 @@ mod postgres_tests { 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), ( @@ -1880,6 +1925,38 @@ mod postgres_tests { ); } + // 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), From 2d88657f19bf104ee7de2a01504e427eaedf6e50 Mon Sep 17 00:00:00 2001 From: Camilo Sanchez Date: Thu, 19 Nov 2026 10:49:50 -0800 Subject: [PATCH 6/8] chore(workflows): address review nits Signed-off-by: Camilo Sanchez --- AGENTS.md | 4 +--- crates/buzz-relay/Cargo.toml | 2 +- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 322bb7f76cd..9206d27db75 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -363,9 +363,7 @@ 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. Matching and collision detection lowercase and -canonically normalize aliases. Message text is normalized once per resolution, -with offsets preserving original-character boundaries rather than normalizing -again for each alias attempt. Alias collisions across distinct keys, including +canonically normalize aliases. Alias collisions across distinct keys, including ordinary names colliding with verified aliases, deliberately produce no recipient or delegated agent-wake tag for that name rather than redirecting the mention or notifying every matching member. Verified-only profiles do not require a separate diff --git a/crates/buzz-relay/Cargo.toml b/crates/buzz-relay/Cargo.toml index 9db3dee08ef..788e9f63428 100644 --- a/crates/buzz-relay/Cargo.toml +++ b/crates/buzz-relay/Cargo.toml @@ -90,7 +90,7 @@ metrics-exporter-prometheus = { workspace = true } metrics-util = { workspace = true } pulldown-cmark = { version = "0.13.4", default-features = false, features = ["html"] } async-compression = { version = "0.4.42", features = ["tokio", "gzip"] } -unicode-normalization = "0.1" +unicode-normalization = "0.1.25" [features] dev = ["buzz-auth/dev"] From 7d015a74f85213a98d2893b781354ab5c0523b73 Mon Sep 17 00:00:00 2001 From: Camilo Sanchez Date: Thu, 19 Nov 2026 11:43:29 -0800 Subject: [PATCH 7/8] fix(workflows): prefer verified mention aliases Signed-off-by: Camilo Sanchez Amp-Thread-ID: https://ampcode.com/threads/T-01a1f53d-3f92-75a5-84d3-cf4a28407929 Co-authored-by: Amp --- AGENTS.md | 11 +- crates/buzz-db/src/store/channel_members.rs | 30 ++++- crates/buzz-relay/src/workflow_sink.rs | 141 +++++++++++++------- 3 files changed, 121 insertions(+), 61 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 9206d27db75..5422b0f8e07 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -363,11 +363,12 @@ 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. Matching and collision detection lowercase and -canonically normalize aliases. Alias collisions across distinct keys, including -ordinary names colliding with verified aliases, deliberately produce no recipient -or delegated agent-wake tag for that name rather than redirecting the mention or -notifying every matching member. Verified-only profiles do not require a separate -kind:0 profile. +canonically normalize aliases. Verified aliases take precedence over ordinary +names with the same normalized value. Collisions across distinct verified keys, +or across ordinary keys when no verified alias matches, produce no recipient or +delegated agent-wake tag. Keep the highest verification level even when it is +ambiguous, so an ordinary name cannot break a verified tie. 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 — diff --git a/crates/buzz-db/src/store/channel_members.rs b/crates/buzz-db/src/store/channel_members.rs index 2bc8b4d5b46..20a1b504812 100644 --- a/crates/buzz-db/src/store/channel_members.rs +++ b/crates/buzz-db/src/store/channel_members.rs @@ -21,6 +21,17 @@ pub use buzz_core::channel::MemberRole; /// `(pubkey, channel_id)` membership rows. pub type PubkeyChannels = Vec<(Vec, Uuid)>; +/// A community-local profile alias used to resolve workflow mentions. +#[derive(Debug, Clone)] +pub struct MentionName { + /// Display name, username, or full name as stored in the profile. + pub name: String, + /// Hex-encoded public key of the channel member. + pub pubkey: String, + /// Whether the alias comes from a relay-verified profile. + pub verified: bool, +} + /// A channel membership row as returned from the database. #[derive(Debug, Clone)] pub struct MemberRecord { @@ -2972,15 +2983,15 @@ impl Db { /// 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. + /// Preserve alias provenance so the caller can prefer verified names and + /// reject collisions between distinct keys at the same verification level. #[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], include_verified: bool, - ) -> Result> { + ) -> Result> { if pubkeys.is_empty() { return Ok(Vec::new()); } @@ -3008,8 +3019,8 @@ impl Db { .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. + // Keep provenance even when a member's ordinary and verified names + // agree, or an ordinary alias could hide the verified claim. let mut seen = std::collections::HashSet::new(); let mut names = Vec::new(); for row in rows { @@ -3021,8 +3032,13 @@ impl Db { "verified_full_name", ] { if let Some(name) = row.try_get::, _>(column)? { - if seen.insert((name.to_lowercase(), pubkey.clone())) { - names.push((name, pubkey.clone())); + let verified = column != "display_name"; + if seen.insert((name.to_lowercase(), pubkey.clone(), verified)) { + names.push(MentionName { + name, + pubkey: pubkey.clone(), + verified, + }); } } } diff --git a/crates/buzz-relay/src/workflow_sink.rs b/crates/buzz-relay/src/workflow_sink.rs index b674544030e..271c118fef6 100644 --- a/crates/buzz-relay/src/workflow_sink.rs +++ b/crates/buzz-relay/src/workflow_sink.rs @@ -10,6 +10,7 @@ use std::sync::{Arc, Weak}; use buzz_core::kind::KIND_STREAM_MESSAGE; use buzz_core::tenant::CommunityId; +use buzz_db::channel_members::MentionName; use buzz_workflow::action_sink::{ActionSink, ActionSinkError, SentMessage}; use chrono::Utc; use nostr::{EventBuilder, Kind, Tag}; @@ -40,46 +41,47 @@ use crate::state::AppState; /// - **Greedy-longest, non-overlapping.** Longer names are matched first and /// consume their span, so `@Alex Example` binds *Example* and a bare `@Alex` /// does not match the member `"Alex Example"`. -/// - **Ambiguous names wake no one.** If two or more members share the matched -/// display name, no `p` tag is emitted for it — arbitrary selection would +/// - **Verified aliases take precedence.** An ordinary name cannot suppress a +/// verified alias. If distinct keys share a name at the highest verification +/// level present, no `p` tag is emitted for it: arbitrary selection would /// silently misroute and tagging all of them is a false-wake firehose. /// /// Returns deduplicated pubkey hexes, in first-appearance order in `text`. -fn resolve_mention_pubkeys(text: &str, members: &[(String, String)]) -> Vec { - let members: Vec<_> = members - .iter() - .map(|(name, pubkey)| { - ( - name.chars() - .flat_map(char::to_lowercase) - .nfd() - .collect::(), - pubkey.clone(), - ) - }) - .collect(); - // Name → pubkey, folding case (client matches case-insensitively). A name - // that maps to more than one distinct pubkey is ambiguous → wake no one. - let mut by_name: std::collections::HashMap> = +fn resolve_mention_pubkeys(text: &str, members: &[MentionName]) -> Vec { + // Resolve collisions only within the highest verification level present. + // Retain that level even for ambiguous names so an ordinary claim cannot + // revive or suppress a verified match, regardless of row order. + let mut by_name: std::collections::HashMap)> = std::collections::HashMap::new(); - for (name, pubkey) in &members { + for member in members { + let name: String = member + .name + .chars() + .flat_map(char::to_lowercase) + .nfd() + .collect(); if name.trim().is_empty() { continue; } by_name - .entry(name.clone()) - .and_modify(|slot| { - if slot.as_deref() != Some(pubkey.as_str()) { + .entry(name) + .and_modify(|(verified, slot)| { + if member.verified && !*verified { + *verified = true; + *slot = Some(member.pubkey.clone()); + } else if member.verified == *verified + && slot.as_deref() != Some(member.pubkey.as_str()) + { *slot = None; // ambiguous } }) - .or_insert_with(|| Some(pubkey.clone())); + .or_insert_with(|| (member.verified, Some(member.pubkey.clone()))); } // Match longest names first so a longer name consumes its span before a // shorter substring name can claim part of it. - let mut names: Vec<&(String, String)> = members.iter().collect(); - names.sort_by_key(|(name, _)| std::cmp::Reverse(name.chars().count())); + let mut names: Vec<&String> = by_name.keys().collect(); + names.sort_by_key(|name| std::cmp::Reverse(name.chars().count())); let chars: Vec = text.chars().collect(); let mut consumed = vec![false; chars.len()]; @@ -127,7 +129,7 @@ fn resolve_mention_pubkeys(text: &str, members: &[(String, String)]) -> Vec = name.chars().collect(); if folded_name.is_empty() { continue; @@ -146,7 +148,7 @@ fn resolve_mention_pubkeys(text: &str, members: &[(String, String)]) -> Vec Result { let rendered_mentions = resolve_mention_pubkeys(rendered_text, members); let authored_mentions: std::collections::HashSet = @@ -710,8 +712,12 @@ mod tests { )); } - fn m(name: &str, pubkey: &str) -> (String, String) { - (name.to_string(), pubkey.to_string()) + fn m(name: &str, pubkey: &str) -> MentionName { + MentionName { + name: name.to_string(), + pubkey: pubkey.to_string(), + verified: false, + } } // A 64-char hex pubkey built from a single repeated nibble, for readable tests. @@ -917,6 +923,30 @@ mod tests { assert_eq!(resolve_mention_pubkeys("@Fizz go", &members), vec![pk('6')]); } + #[test] + fn verified_aliases_win_only_over_ordinary_names() { + for (claims, expected) in [ + (vec![('a', false), ('b', true)], vec![pk('b')]), + (vec![('a', false), ('c', false), ('b', true)], vec![pk('b')]), + (vec![('a', true), ('b', true), ('c', false)], vec![]), + (vec![('a', false), ('b', false)], vec![]), + (vec![('a', false), ('a', true), ('b', false)], vec![pk('a')]), + ] { + let mut members: Vec<_> = claims + .iter() + .map(|&(key, verified)| MentionName { + name: if verified { "Zoë" } else { "ZOE\u{0308}" }.to_owned(), + pubkey: pk(key), + verified, + }) + .collect(); + for _ in 0..2 { + assert_eq!(resolve_mention_pubkeys("@Zoë", &members), expected); + members.reverse(); + } + } + } + #[test] fn dedupes_repeated_mentions_in_first_appearance_order() { let members = vec![m("Robby", &pk('a')), m("Max", &pk('b'))]; @@ -1665,7 +1695,7 @@ mod postgres_tests { None, ) .await - .expect("ambiguous ordinary name"); + .expect("ordinary name shadowing a verified alias"); for (key, username) in [(verified, "alex"), (outsider, "outsider")] { state .db @@ -1806,7 +1836,13 @@ mod postgres_tests { true, true, ), - ("ambiguous-full-name", "@Alex Example", "", false, false), + ( + "verified-over-ordinary-full-name", + "@Alex Example", + "", + true, + true, + ), ("no-at-sign", "alex, Alex Example", "", false, false), ("verified-nonmember", "@outsider", "", false, false), ("foreign-profile", "@foreign-only", "", false, false), @@ -1817,6 +1853,13 @@ mod postgres_tests { true, false, ), + ( + "injected-verified-over-ordinary", + "echo: {{trigger.text}}", + "@Alex Example", + true, + false, + ), ] { let id = execute_send_message_workflow( &state, @@ -1854,22 +1897,23 @@ mod postgres_tests { .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"), + for (name, text, ordinary_name) in [ + ("same-profile-name", "@Alex Example", "Alex Example"), + ("mixed-ordinary", "@Ally Example", "Ally Example"), + ("mixed-verified", "@alex", "Ally Example"), ] { + state + .db + .update_user_profile( + community, + &verified.to_bytes(), + Some(ordinary_name), + None, + None, + None, + ) + .await + .expect("add ordinary profile alongside verified profile"); let id = execute_send_message_workflow( &state, community, @@ -1945,8 +1989,7 @@ mod postgres_tests { ); } - // Same roster without the advertisement: leftover verified heads are - // ignored, so the ordinary name is no longer ambiguous. + // Without the advertisement, only ordinary names participate. let unadvertised = test_state().await; unadvertised .workflow_engine From 0777585a2be6c7593ea36fe0be3e87832f37202f Mon Sep 17 00:00:00 2001 From: Camilo Sanchez Date: Thu, 19 Nov 2026 12:08:35 -0800 Subject: [PATCH 8/8] docs(workflows): document alias reassignment limitation Signed-off-by: Camilo Sanchez Amp-Thread-ID: https://ampcode.com/threads/T-01a1f53d-3f92-75a5-84d3-cf4a28407929 Co-authored-by: Amp --- crates/buzz-db/src/store/verified_profiles.rs | 7 +++++++ crates/buzz-relay/src/workflow_sink.rs | 6 +++--- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/crates/buzz-db/src/store/verified_profiles.rs b/crates/buzz-db/src/store/verified_profiles.rs index 189cb342168..63fdd43d9bf 100644 --- a/crates/buzz-db/src/store/verified_profiles.rs +++ b/crates/buzz-db/src/store/verified_profiles.rs @@ -6,6 +6,13 @@ //! A profile is a historical record ("verified as Alice at T"). It is never //! retracted: on a relay that enforces NIP-FI, a key cannot post without a //! fresh issuer assertion, regardless of its stored profile. +//! +//! Alias reassignment is not reconciled across keys. If an issuer gives a +//! username or full name to a new key, workflow mentions can still resolve to +//! the old holder when only that holder is a channel member. If both holders +//! are members and retain that verified alias, the mention is silently dropped. +//! Retraction or supersession of conflicting heads belongs in the profile writer, +//! not an age bound in mention lookup, which would still leave a stale window. use crate::{AdmittedTx, Db, DbError, Result}; use buzz_core::CommunityId; diff --git a/crates/buzz-relay/src/workflow_sink.rs b/crates/buzz-relay/src/workflow_sink.rs index 271c118fef6..31595333db8 100644 --- a/crates/buzz-relay/src/workflow_sink.rs +++ b/crates/buzz-relay/src/workflow_sink.rs @@ -35,9 +35,9 @@ use crate::state::AppState; /// - **Exact profile name.** Ordinary display names and verified display names, /// usernames, and full names are aliases. Matching ignores case and canonical /// Unicode encoding differences, with no substring, prefix, or fuzzy matching. -/// Names may contain spaces/punctuation (`"Alex Example"`, `"Lep (Subagent)"`), so the -/// match is anchored on `@` and terminated by a non-name boundary rather than -/// whitespace. +/// Names may contain spaces/punctuation (`"Alex Example"`, `"Lep (Subagent)"`), +/// so the match is anchored on `@` and terminated by a non-name boundary rather +/// than whitespace. /// - **Greedy-longest, non-overlapping.** Longer names are matched first and /// consume their span, so `@Alex Example` binds *Example* and a bare `@Alex` /// does not match the member `"Alex Example"`.