Skip to content

Commit 1b87a09

Browse files
tlongwell-blocknpub1cc3ha7z055mu0rwwu7806t2wt8mj3pvu0uv5mfp2c50dahaqhczshdalg6Dawn
authored
refactor: extract shared @mention resolver into sprout-sdk (#580)
Signed-off-by: Tyler Longwell <[email protected]> Co-authored-by: npub1cc3ha7z055mu0rwwu7806t2wt8mj3pvu0uv5mfp2c50dahaqhczshdalg6 <c6237ef84fa537c78dcee78efd2d4e59f728859c7f194da42ac51ededfa0be05@sprout-oss.stage.blox.sqprod.co> Co-authored-by: Dawn <[email protected]>
1 parent 2ee7356 commit 1b87a09

6 files changed

Lines changed: 566 additions & 312 deletions

File tree

‎crates/sprout-cli/src/commands/messages.rs‎

Lines changed: 196 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,16 @@
1-
use nostr::EventId;
1+
use nostr::{EventId, PublicKey};
22
use sprout_sdk::{DiffMeta, ThreadRef, VoteDirection};
33
use uuid::Uuid;
44

55
use crate::client::SproutClient;
66
use crate::error::CliError;
77
use crate::validate::{
8-
extract_at_names, infer_language, merge_mentions, normalize_mention_pubkeys, read_or_stdin,
9-
truncate_diff, validate_content_size, validate_hex64, validate_uuid, MAX_DIFF_BYTES,
8+
infer_language, read_or_stdin, truncate_diff, validate_content_size, validate_hex64,
9+
validate_uuid, MAX_DIFF_BYTES,
10+
};
11+
use sprout_sdk::mentions::{
12+
extract_at_names, match_names_to_profiles, merge_mentions, normalize_mention_pubkeys,
13+
MentionProfile, MENTION_CAP,
1014
};
1115

1216
// ---------------------------------------------------------------------------
@@ -130,8 +134,13 @@ async fn resolve_channel_id(client: &SproutClient, event_id: &str) -> Result<Uui
130134
)))
131135
}
132136

133-
/// Resolve @names in content against channel members (queried from channel metadata).
134-
/// Returns matching pubkeys. On any error, returns empty vec — never blocks a send.
137+
/// Resolve `@name` mentions in `content` against this channel's members.
138+
///
139+
/// Mirrors the MCP implementation: queries kind 39002 (channel members),
140+
/// then kind 0 (profiles for those members), and delegates parsing and
141+
/// case-insensitive matching to [`sprout_sdk::mentions`]. On any I/O or
142+
/// parse failure, returns an empty vec — auto-tagging is best-effort and
143+
/// must never block a send.
135144
async fn resolve_content_mentions(
136145
client: &SproutClient,
137146
channel_id: &str,
@@ -141,27 +150,82 @@ async fn resolve_content_mentions(
141150
if names.is_empty() {
142151
return vec![];
143152
}
144-
// Query channel metadata to get member list from p-tags
145-
let filter = serde_json::json!({
153+
// 1. Membership list (kind 39002 is parameterized-replaceable, addressed by `d` tag).
154+
let members_filter = serde_json::json!({
146155
"kinds": [39002],
147-
"#h": [channel_id]
156+
"#d": [channel_id],
157+
"limit": 1,
148158
});
149-
let raw = client.query(&filter).await.unwrap_or_default();
150-
let parsed: serde_json::Value = serde_json::from_str(&raw).unwrap_or_default();
151-
// Channel metadata is returned as an array of events
152-
let Some(events) = parsed.as_array() else {
153-
return vec![];
159+
let member_pubkeys = match fetch_member_pubkeys(client, &members_filter).await {
160+
Some(pks) if !pks.is_empty() => pks,
161+
_ => return vec![],
154162
};
155-
let Some(event) = events.first() else {
156-
return vec![];
163+
164+
// 2. Profiles for those members (kind 0).
165+
let profiles_filter = serde_json::json!({
166+
"kinds": [0],
167+
"authors": member_pubkeys,
168+
"limit": member_pubkeys.len(),
169+
});
170+
let profile_events = match fetch_events(client, &profiles_filter).await {
171+
Some(v) => v,
172+
None => return vec![],
157173
};
174+
175+
// 3. Hand the parsed profile content + pubkey to the shared matcher.
176+
let entries: Vec<MentionProfile<'_>> = profile_events
177+
.iter()
178+
.filter_map(|e| {
179+
let pubkey = e.get("pubkey")?.as_str()?;
180+
let content_json = e.get("content")?.as_str()?;
181+
Some(MentionProfile {
182+
pubkey,
183+
content_json,
184+
})
185+
})
186+
.collect();
187+
match_names_to_profiles(&names, &entries)
188+
}
189+
190+
/// Fetch raw events for `filter` via the relay's `/query` endpoint.
191+
/// Returns `None` on any I/O or parse failure.
192+
async fn fetch_events(
193+
client: &SproutClient,
194+
filter: &serde_json::Value,
195+
) -> Option<Vec<serde_json::Value>> {
196+
let raw = client.query(filter).await.ok()?;
197+
let parsed: serde_json::Value = serde_json::from_str(&raw).ok()?;
198+
parsed.as_array().cloned()
199+
}
200+
201+
/// Extract member pubkeys (the `p` tag values) from a single 39002 event.
202+
async fn fetch_member_pubkeys(
203+
client: &SproutClient,
204+
filter: &serde_json::Value,
205+
) -> Option<Vec<String>> {
206+
let events = fetch_events(client, filter).await?;
207+
Some(parse_member_pubkeys(events.first()?))
208+
}
209+
210+
/// Parse member pubkeys from a kind 39002 event JSON value.
211+
///
212+
/// Filters and canonicalizes via `nostr::PublicKey::from_hex` — matching
213+
/// MCP's typed-Nostr behavior so both surfaces accept exactly the same
214+
/// pubkeys. Pure helper, split out for testing.
215+
fn parse_member_pubkeys(event: &serde_json::Value) -> Vec<String> {
158216
let Some(tags) = event.get("tags").and_then(|t| t.as_array()) else {
159217
return vec![];
160218
};
161-
// p-tags contain member pubkeys; we can't resolve display names without profiles
162-
// For now, return empty — @mention resolution requires profile lookup
163-
let _ = (tags, names);
164-
vec![]
219+
tags.iter()
220+
.filter_map(|t| {
221+
let arr = t.as_array()?;
222+
if arr.first()?.as_str()? != "p" {
223+
return None;
224+
}
225+
let pk = arr.get(1)?.as_str()?;
226+
PublicKey::from_hex(pk).ok().map(|k| k.to_hex())
227+
})
228+
.collect()
165229
}
166230

167231
// ---------------------------------------------------------------------------
@@ -301,10 +365,12 @@ pub async fn cmd_send_message(client: &SproutClient, p: SendMessageParams) -> Re
301365
None
302366
};
303367

304-
// Normalize explicit mentions, then merge auto-resolved up to SDK cap of 50.
305-
let mut merged: Vec<String> = normalize_mention_pubkeys(&p.mentions, "");
306-
let auto_resolved = resolve_content_mentions(client, &p.channel_id, &final_content).await;
307-
merge_mentions(&mut merged, &auto_resolved, 50);
368+
// Normalize explicit mentions, then merge auto-resolved up to the SDK mention cap.
369+
// Auto-resolution scans the author-written body only — not the media markdown we
370+
// append above, which is derived from upload metadata and can't carry `@names`.
371+
let mut merged: Vec<String> = normalize_mention_pubkeys(&p.mentions, None);
372+
let auto_resolved = resolve_content_mentions(client, &p.channel_id, &p.content).await;
373+
merge_mentions(&mut merged, &auto_resolved, MENTION_CAP);
308374
let mention_refs: Vec<&str> = merged.iter().map(|s| s.as_str()).collect();
309375

310376
let builder = sprout_sdk::build_message(
@@ -489,13 +555,20 @@ pub async fn cmd_vote_on_post(
489555

490556
#[cfg(test)]
491557
mod tests {
492-
use super::find_root_from_tags;
558+
use super::{find_root_from_tags, parse_member_pubkeys};
493559
use serde_json::json;
560+
use sprout_sdk::mentions::{extract_at_names, match_names_to_profiles, MentionProfile};
494561

495562
const ID_A: &str = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
496563
const ID_B: &str = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb";
497564
const PUBKEY: &str = "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc";
498565

566+
// Three real pubkeys (lowercase 64-char hex) used by parse_member_pubkeys tests.
567+
// See the test's own comment on what `PublicKey::from_hex` actually validates.
568+
const PK_VALID_A: &str = "35c18ae273fccfaf80d629e20e7f8721b90499379addff533054acc2504c12b4";
569+
const PK_VALID_B: &str = "c6237ef84fa537c78dcee78efd2d4e59f728859c7f194da42ac51ededfa0be05";
570+
const PK_VALID_C: &str = "f4a42a97e594b77bdbd8ee35191c8b28a94a4cb871d96f32921558275421fb68";
571+
499572
#[test]
500573
fn root_marker_wins_over_reply_marker() {
501574
let tags = json!([
@@ -561,4 +634,103 @@ mod tests {
561634
assert!(find_root_from_tags(&json!({})).is_none());
562635
assert!(find_root_from_tags(&json!(null)).is_none());
563636
}
637+
638+
// ── @mention resolution pipeline ────────────────────────────────────
639+
//
640+
// These tests don't hit the network — they prove that *given* the
641+
// events the relay returns, the CLI's parse + match wiring produces
642+
// the right pubkeys. The async I/O wrapper around them is one
643+
// straight line; the pure stages it composes are exercised here and
644+
// in sprout-sdk.
645+
646+
/// End-to-end (sans I/O): body text → extracted names → matched
647+
/// member pubkeys, using realistic 39002 + kind:0 event JSON.
648+
/// This is the regression guard for the previous stub that always
649+
/// returned `vec![]`.
650+
#[test]
651+
fn cli_pipeline_resolves_body_at_names_to_member_pubkeys() {
652+
// kind 39002 channel-members event with three members.
653+
let members_event = json!({
654+
"kind": 39002,
655+
"tags": [
656+
["d", "00000000-0000-0000-0000-000000000000"],
657+
["p", PK_VALID_A, "", "member"],
658+
["p", PK_VALID_B, "", "member"],
659+
["p", PK_VALID_C, "", "member"],
660+
],
661+
"content": "",
662+
});
663+
assert_eq!(
664+
parse_member_pubkeys(&members_event),
665+
vec![PK_VALID_A, PK_VALID_B, PK_VALID_C]
666+
);
667+
668+
// Three kind:0 profile events.
669+
let entries = vec![
670+
MentionProfile {
671+
pubkey: PK_VALID_A,
672+
content_json: r#"{"display_name":"Alice"}"#,
673+
},
674+
MentionProfile {
675+
pubkey: PK_VALID_B,
676+
content_json: r#"{"display_name":"Bob"}"#,
677+
},
678+
MentionProfile {
679+
pubkey: PK_VALID_C,
680+
content_json: r#"{"name":"Carol"}"#,
681+
},
682+
];
683+
684+
// Body mentions Alice and Carol (display_name fallback to `name`).
685+
let names = extract_at_names("hello @alice and @CAROL");
686+
let resolved = match_names_to_profiles(&names, &entries);
687+
assert_eq!(resolved, vec![PK_VALID_A, PK_VALID_C]);
688+
}
689+
690+
#[test]
691+
fn cli_pipeline_returns_empty_when_no_at_names() {
692+
// Sanity: no `@names` in body → no profile match attempt needed.
693+
let names = extract_at_names("plain message, no mentions");
694+
assert!(names.is_empty());
695+
}
696+
697+
#[test]
698+
fn parse_member_pubkeys_ignores_non_p_tags() {
699+
let event = json!({
700+
"tags": [
701+
["d", "channel-id"],
702+
["p", PK_VALID_A],
703+
["h", "channel-id"],
704+
["e", "some-event"],
705+
["p", PK_VALID_B, "wss://relay", "member"],
706+
],
707+
});
708+
assert_eq!(parse_member_pubkeys(&event), vec![PK_VALID_A, PK_VALID_B]);
709+
}
710+
711+
#[test]
712+
fn parse_member_pubkeys_handles_malformed_event() {
713+
assert!(parse_member_pubkeys(&json!({})).is_empty());
714+
assert!(parse_member_pubkeys(&json!({"tags": "not an array"})).is_empty());
715+
assert!(parse_member_pubkeys(&json!({"tags": [["p"]]})).is_empty());
716+
}
717+
718+
#[test]
719+
fn parse_member_pubkeys_filters_invalid_hex() {
720+
// `PublicKey::from_hex` rejects non-hex and wrong-length inputs and
721+
// canonicalizes hex case. (Note: it accepts any 64-char x-only hex
722+
// whose integer value is in field; it does not verify the point is
723+
// actually on the curve — same as MCP's behavior.)
724+
let pk_uppercase: String = PK_VALID_A.to_ascii_uppercase();
725+
let event = json!({
726+
"tags": [
727+
["p", PK_VALID_A], // valid, lowercase
728+
["p", pk_uppercase], // valid hex, canonicalized to lowercase
729+
["p", "too-short"], // length fail
730+
["p", "z".repeat(64)], // non-hex chars
731+
["p", "a".repeat(63)], // off-by-one length
732+
],
733+
});
734+
assert_eq!(parse_member_pubkeys(&event), vec![PK_VALID_A, PK_VALID_A]);
735+
}
564736
}

0 commit comments

Comments
 (0)