@@ -1001,38 +1001,129 @@ pub async fn cmd_remove_channel_member(
10011001 Ok ( ( ) )
10021002}
10031003
1004- /// Set the channel addition policy — sign and submit a kind:10100 (agent profile) event.
1005- pub async fn cmd_set_add_policy ( client : & BuzzClient , policy : & str ) -> Result < ( ) , CliError > {
1006- match policy {
1007- "anyone" | "owner_only" | "nobody" => { }
1008- _ => {
1009- return Err ( CliError :: Usage ( format ! (
1010- "--policy must be 'anyone', 'owner_only', or 'nobody' (got: {policy})"
1011- ) ) )
1004+ /// Merge new agent-profile fields into an existing kind:10100 content blob.
1005+ ///
1006+ /// `kind:10100` is a plain replaceable event — the relay keeps only the
1007+ /// latest per pubkey, with no server-side field merge. A client that
1008+ /// publishes a partial object therefore clobbers every field the previous
1009+ /// event carried. This merges onto the fetched prior content instead of
1010+ /// replacing it outright (buzz#2987: `set-add-policy` was the only
1011+ /// documented publisher of this event and always overwrote the whole
1012+ /// content with just `channel_add_policy`, silently discarding any
1013+ /// `respond_to`/`display_name`/`channel_ids` set by another mechanism).
1014+ fn merge_agent_profile_content (
1015+ existing_content : Option < & str > ,
1016+ channel_add_policy : Option < & str > ,
1017+ respond_to : Option < & str > ,
1018+ respond_to_allowlist : Option < & [ String ] > ,
1019+ ) -> String {
1020+ let mut obj = existing_content
1021+ . and_then ( |raw| serde_json:: from_str :: < serde_json:: Value > ( raw) . ok ( ) )
1022+ . and_then ( |value| value. as_object ( ) . cloned ( ) )
1023+ . unwrap_or_default ( ) ;
1024+
1025+ if let Some ( policy) = channel_add_policy {
1026+ obj. insert ( "channel_add_policy" . to_string ( ) , serde_json:: json!( policy) ) ;
1027+ }
1028+ if let Some ( mode) = respond_to {
1029+ obj. insert ( "respond_to" . to_string ( ) , serde_json:: json!( mode) ) ;
1030+ }
1031+ if let Some ( allowlist) = respond_to_allowlist {
1032+ obj. insert (
1033+ "respond_to_allowlist" . to_string ( ) ,
1034+ serde_json:: json!( allowlist) ,
1035+ ) ;
1036+ }
1037+
1038+ serde_json:: Value :: Object ( obj) . to_string ( )
1039+ }
1040+
1041+ /// Fetch the current identity's own kind:10100 (agent profile) content, if any.
1042+ async fn fetch_own_agent_profile_content ( client : & BuzzClient ) -> Result < Option < String > , CliError > {
1043+ let filter = serde_json:: json!( {
1044+ "kinds" : [ buzz_sdk:: kind:: KIND_AGENT_PROFILE ] ,
1045+ "authors" : [ client. keys( ) . public_key( ) . to_hex( ) ] ,
1046+ "limit" : 1 ,
1047+ } ) ;
1048+ let raw = client. query ( & filter) . await ?;
1049+ let mut events: Vec < nostr:: Event > = serde_json:: from_str ( & raw)
1050+ . map_err ( |e| CliError :: Other ( format ! ( "failed to parse relay response: {e}" ) ) ) ?;
1051+ events. sort_by_key ( |event| std:: cmp:: Reverse ( event. created_at ) ) ;
1052+ Ok ( events. into_iter ( ) . next ( ) . map ( |event| event. content ) )
1053+ }
1054+
1055+ /// Set the channel addition policy and/or the agent respond-to gate — sign
1056+ /// and submit a kind:10100 (agent profile) event, merged onto any existing
1057+ /// profile so unrelated fields survive (see [`merge_agent_profile_content`]).
1058+ pub async fn cmd_set_add_policy (
1059+ client : & BuzzClient ,
1060+ policy : Option < & str > ,
1061+ respond_to : Option < & str > ,
1062+ respond_to_allowlist : Option < & [ String ] > ,
1063+ ) -> Result < ( ) , CliError > {
1064+ if policy. is_none ( ) && respond_to. is_none ( ) && respond_to_allowlist. is_none ( ) {
1065+ return Err ( CliError :: Usage (
1066+ "at least one of --policy, --respond-to, or --respond-to-allowlist is required"
1067+ . to_string ( ) ,
1068+ ) ) ;
1069+ }
1070+
1071+ if let Some ( policy) = policy {
1072+ match policy {
1073+ "anyone" | "owner_only" | "nobody" => { }
1074+ _ => {
1075+ return Err ( CliError :: Usage ( format ! (
1076+ "--policy must be 'anyone', 'owner_only', or 'nobody' (got: {policy})"
1077+ ) ) )
1078+ }
1079+ }
1080+
1081+ // Check if this policy is allowed by the deployment.
1082+ // NOTE: This gate covers only the `buzz channels set-add-policy` CLI path.
1083+ // A client that submits a kind:10100 event directly to the relay bypasses
1084+ // this check. Full enforcement requires relay-side validation, which is
1085+ // intentionally out of scope for this change (see team decision: no
1086+ // relay-side enforcement of client behavior).
1087+ if let Ok ( allowed_raw) = std:: env:: var ( "BUZZ_ACP_ALLOWED_CHANNEL_ADD_POLICIES" ) {
1088+ let allowed: Vec < & str > = allowed_raw
1089+ . split ( ',' )
1090+ . map ( str:: trim)
1091+ . filter ( |s| !s. is_empty ( ) )
1092+ . collect ( ) ;
1093+ if !allowed. is_empty ( ) && !allowed. contains ( & policy) {
1094+ return Err ( CliError :: Usage ( format ! (
1095+ "channel_add_policy '{policy}' is not permitted on this deployment \
1096+ (BUZZ_ACP_ALLOWED_CHANNEL_ADD_POLICIES={allowed_raw})"
1097+ ) ) ) ;
1098+ }
10121099 }
10131100 }
10141101
1015- // Check if this policy is allowed by the deployment.
1016- // NOTE: This gate covers only the `buzz channels set-add-policy` CLI path.
1017- // A client that submits a kind:10100 event directly to the relay bypasses
1018- // this check. Full enforcement requires relay-side validation, which is
1019- // intentionally out of scope for this change (see team decision: no
1020- // relay-side enforcement of client behavior).
1021- if let Ok ( allowed_raw) = std:: env:: var ( "BUZZ_ACP_ALLOWED_CHANNEL_ADD_POLICIES" ) {
1022- let allowed: Vec < & str > = allowed_raw
1023- . split ( ',' )
1024- . map ( str:: trim)
1025- . filter ( |s| !s. is_empty ( ) )
1026- . collect ( ) ;
1027- if !allowed. is_empty ( ) && !allowed. contains ( & policy) {
1028- return Err ( CliError :: Usage ( format ! (
1029- "channel_add_policy '{policy}' is not permitted on this deployment \
1030- (BUZZ_ACP_ALLOWED_CHANNEL_ADD_POLICIES={allowed_raw})"
1031- ) ) ) ;
1102+ if let Some ( mode) = respond_to {
1103+ match mode {
1104+ "owner-only" | "anyone" | "allowlist" => { }
1105+ _ => {
1106+ return Err ( CliError :: Usage ( format ! (
1107+ "--respond-to must be 'owner-only', 'anyone', or 'allowlist' (got: {mode})"
1108+ ) ) )
1109+ }
10321110 }
10331111 }
10341112
1035- let content = serde_json:: json!( { "channel_add_policy" : policy } ) . to_string ( ) ;
1113+ if let Some ( allowlist) = respond_to_allowlist {
1114+ for pubkey in allowlist {
1115+ validate_hex64 ( pubkey) ?;
1116+ }
1117+ }
1118+
1119+ let existing_content = fetch_own_agent_profile_content ( client) . await ?;
1120+ let content = merge_agent_profile_content (
1121+ existing_content. as_deref ( ) ,
1122+ policy,
1123+ respond_to,
1124+ respond_to_allowlist,
1125+ ) ;
1126+
10361127 use nostr:: { EventBuilder , Kind } ;
10371128 let builder = EventBuilder :: new (
10381129 Kind :: Custom ( buzz_sdk:: kind:: KIND_AGENT_PROFILE as u16 ) ,
@@ -1161,7 +1252,19 @@ pub async fn dispatch(
11611252 ChannelsCmd :: RemoveMember { channel, pubkey } => {
11621253 cmd_remove_channel_member ( client, & channel, & pubkey) . await
11631254 }
1164- ChannelsCmd :: SetAddPolicy { policy } => cmd_set_add_policy ( client, & policy) . await ,
1255+ ChannelsCmd :: SetAddPolicy {
1256+ policy,
1257+ respond_to,
1258+ respond_to_allowlist,
1259+ } => {
1260+ cmd_set_add_policy (
1261+ client,
1262+ policy. as_deref ( ) ,
1263+ respond_to. as_deref ( ) ,
1264+ respond_to_allowlist. as_deref ( ) ,
1265+ )
1266+ . await
1267+ }
11651268 }
11661269}
11671270
@@ -1177,9 +1280,9 @@ pub async fn dispatch_canvas(cmd: crate::CanvasCmd, client: &BuzzClient) -> Resu
11771280mod tests {
11781281 use super :: {
11791282 apply_cardinality_rule, build_template_report, cmd_set_add_policy,
1180- finalize_roster_resolution, name_matches , resolve_roster_with_archive_filter ,
1181- validate_ttl_seconds , ArchivedExclusion , ChannelSummary , ResolvedAgent , RosterResolution ,
1182- SkippedSlug ,
1283+ finalize_roster_resolution, merge_agent_profile_content , name_matches ,
1284+ resolve_roster_with_archive_filter , validate_ttl_seconds , ArchivedExclusion ,
1285+ ChannelSummary , ResolvedAgent , RosterResolution , SkippedSlug ,
11831286 } ;
11841287 use crate :: client:: BuzzClient ;
11851288 use crate :: CliError ;
@@ -1362,7 +1465,7 @@ mod tests {
13621465 async fn set_add_policy_env_gate_rejects_disallowed_via_full_path ( ) {
13631466 std:: env:: set_var ( "BUZZ_ACP_ALLOWED_CHANNEL_ADD_POLICIES" , "owner_only,nobody" ) ;
13641467 let client = make_test_client ( ) ;
1365- let result = cmd_set_add_policy ( & client, "anyone" ) . await ;
1468+ let result = cmd_set_add_policy ( & client, Some ( "anyone" ) , None , None ) . await ;
13661469 std:: env:: remove_var ( "BUZZ_ACP_ALLOWED_CHANNEL_ADD_POLICIES" ) ;
13671470
13681471 assert ! (
@@ -1380,6 +1483,103 @@ mod tests {
13801483 }
13811484 }
13821485
1486+ #[ tokio:: test]
1487+ async fn set_add_policy_requires_at_least_one_field ( ) {
1488+ let client = make_test_client ( ) ;
1489+ let result = cmd_set_add_policy ( & client, None , None , None ) . await ;
1490+
1491+ match result. unwrap_err ( ) {
1492+ crate :: CliError :: Usage ( msg) => {
1493+ assert ! (
1494+ msg. contains( "at least one of" ) ,
1495+ "error should ask for at least one field: {msg}"
1496+ ) ;
1497+ }
1498+ other => panic ! ( "expected CliError::Usage, got {other:?}" ) ,
1499+ }
1500+ }
1501+
1502+ #[ tokio:: test]
1503+ async fn set_add_policy_rejects_invalid_respond_to_before_any_network_call ( ) {
1504+ let client = make_test_client ( ) ;
1505+ let result = cmd_set_add_policy ( & client, None , Some ( "everyone" ) , None ) . await ;
1506+
1507+ match result. unwrap_err ( ) {
1508+ crate :: CliError :: Usage ( msg) => {
1509+ assert ! (
1510+ msg. contains( "--respond-to" ) ,
1511+ "error should name the offending flag: {msg}"
1512+ ) ;
1513+ }
1514+ other => panic ! ( "expected CliError::Usage, got {other:?}" ) ,
1515+ }
1516+ }
1517+
1518+ #[ tokio:: test]
1519+ async fn set_add_policy_rejects_malformed_allowlist_pubkey_before_any_network_call ( ) {
1520+ let client = make_test_client ( ) ;
1521+ let result =
1522+ cmd_set_add_policy ( & client, None , None , Some ( & [ "not-a-pubkey" . to_string ( ) ] ) ) . await ;
1523+
1524+ assert ! ( result. is_err( ) , "malformed pubkey should be rejected" ) ;
1525+ }
1526+
1527+ // --- merge_agent_profile_content (buzz#2987: read-modify-write, not clobber) ---
1528+
1529+ #[ test]
1530+ fn merge_agent_profile_content_preserves_unrelated_fields ( ) {
1531+ let existing = r#"{"display_name":"Scout","channel_ids":["a-b-c"]}"# ;
1532+ let merged = merge_agent_profile_content ( Some ( existing) , None , Some ( "anyone" ) , None ) ;
1533+ let parsed: serde_json:: Value = serde_json:: from_str ( & merged) . unwrap ( ) ;
1534+
1535+ assert_eq ! ( parsed[ "display_name" ] , "Scout" ) ;
1536+ assert_eq ! ( parsed[ "channel_ids" ] , serde_json:: json!( [ "a-b-c" ] ) ) ;
1537+ assert_eq ! ( parsed[ "respond_to" ] , "anyone" ) ;
1538+ }
1539+
1540+ #[ test]
1541+ fn merge_agent_profile_content_overwrites_only_the_fields_given ( ) {
1542+ let existing = r#"{"respond_to":"owner-only","respond_to_allowlist":[],"channel_add_policy":"nobody"}"# ;
1543+ let merged = merge_agent_profile_content ( Some ( existing) , Some ( "anyone" ) , None , None ) ;
1544+ let parsed: serde_json:: Value = serde_json:: from_str ( & merged) . unwrap ( ) ;
1545+
1546+ assert_eq ! ( parsed[ "channel_add_policy" ] , "anyone" ) ;
1547+ // respond_to untouched — this call only updated channel_add_policy.
1548+ assert_eq ! ( parsed[ "respond_to" ] , "owner-only" ) ;
1549+ }
1550+
1551+ #[ test]
1552+ fn merge_agent_profile_content_with_no_existing_profile_starts_from_empty ( ) {
1553+ let merged = merge_agent_profile_content ( None , Some ( "owner_only" ) , None , None ) ;
1554+ let parsed: serde_json:: Value = serde_json:: from_str ( & merged) . unwrap ( ) ;
1555+
1556+ assert_eq ! ( parsed[ "channel_add_policy" ] , "owner_only" ) ;
1557+ assert ! ( parsed. get( "respond_to" ) . is_none( ) ) ;
1558+ }
1559+
1560+ #[ test]
1561+ fn merge_agent_profile_content_sets_respond_to_allowlist ( ) {
1562+ let allowlist = vec ! [ "a" . repeat( 64 ) ] ;
1563+ let merged = merge_agent_profile_content ( None , None , Some ( "allowlist" ) , Some ( & allowlist) ) ;
1564+ let parsed: serde_json:: Value = serde_json:: from_str ( & merged) . unwrap ( ) ;
1565+
1566+ assert_eq ! ( parsed[ "respond_to" ] , "allowlist" ) ;
1567+ assert_eq ! (
1568+ parsed[ "respond_to_allowlist" ] ,
1569+ serde_json:: json!( [ "a" . repeat( 64 ) ] )
1570+ ) ;
1571+ }
1572+
1573+ #[ test]
1574+ fn merge_agent_profile_content_ignores_non_object_existing_content ( ) {
1575+ // Defensive: a corrupt or unexpected prior event (e.g. a bare JSON
1576+ // array) must not panic — fall back to an empty profile.
1577+ let merged = merge_agent_profile_content ( Some ( "[1,2,3]" ) , Some ( "anyone" ) , None , None ) ;
1578+ let parsed: serde_json:: Value = serde_json:: from_str ( & merged) . unwrap ( ) ;
1579+
1580+ assert_eq ! ( parsed[ "channel_add_policy" ] , "anyone" ) ;
1581+ }
1582+
13831583 // --- Template roster cardinality (F4) ---
13841584
13851585 fn agent ( persona_id : & str , pubkey : & str ) -> ResolvedAgent {
0 commit comments