Skip to content

Commit 27e0f11

Browse files
author
Ivan Itzcovich
committed
fix(desktop,cli): let mentioned agents pass real eligibility, close CLI respond_to gap
buzz#2987 point 1 (the "gate" + its CLI companion), from the external-agents diagnostic report. Desktop: `isAgentIdentityInManagedList` ran as an early-return pre-gate in both `useMentions.ts` and `MembersSidebar.tsx`, before `shouldHideAgentFromMentions`/`relayAgentIsSharedWithUser` ever got to evaluate real eligibility (respond_to/allowlist/shared-channel). `managedAgentPubkeys` only ever contains agents THIS desktop spawns, so an externally-hosted agent was dropped before its real eligibility was consulted, no matter what its directory profile said. Removed the pre-gate from `useMentions.ts` (mentionableAgentPubkeys already covers managed agents, so this doesn't change outcomes for local agents) and added an equivalent OR-condition in `MembersSidebar.tsx`'s add-member picker. Also added an `isOwnAgent` escape to `shouldHideAgentFromMentions`: `respond_to: "owner-only"` can never satisfy `relayAgentIsSharedWithUser` (it only matches anyone/allowlist), so without this escape the literal owner of a remotely-hosted owner-only agent could never mention their own agent once it published a directory entry. Extracted the ownership check (candidate.ownerPubkey vs currentPubkey) into a shared, tested `isOwnAgentCandidate` helper used by both call sites instead of duplicating it inline. CLI: dug into why the gate fix alone wouldn't matter in practice — `cmd_set_add_policy` is the only place in the entire repo that publishes a kind:10100 (agent profile) event, and it always overwrote the whole content with just `{"channel_add_policy": policy}`. Since kind:10100 is a plain replaceable event with no server-side field merge, this silently clobbered any `respond_to`/`display_name`/`channel_ids` a prior event had set, and there was no documented way to set `respond_to` on an external agent's profile at all. `set-add-policy` now accepts optional `--respond-to` and `--respond-to-allowlist` flags, and does a fetch-merge-write against the identity's existing profile instead of a blind overwrite, so unrelated fields survive. Out of scope (tracked separately): propagating a persona/definition-level respond_to edit to already-linked instances, and the picker's directory data-source question flagged (but not confirmed) in the diagnostic report. Signed-off-by: Ivan Itzcovich <[email protected]>
1 parent 6300a6b commit 27e0f11

6 files changed

Lines changed: 332 additions & 39 deletions

File tree

‎crates/buzz-cli/src/commands/channels.rs‎

Lines changed: 231 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -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
11771280
mod 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 {

‎crates/buzz-cli/src/lib.rs‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -666,12 +666,18 @@ pub enum ChannelsCmd {
666666
#[arg(long)]
667667
pubkey: String,
668668
},
669-
/// Set your channel addition policy
669+
/// Set your channel addition policy and/or agent respond-to gate
670670
#[command(name = "set-add-policy")]
671671
SetAddPolicy {
672672
/// Policy: anyone | owner_only | nobody
673673
#[arg(long)]
674-
policy: String,
674+
policy: Option<String>,
675+
/// Who can @mention/address this agent: owner-only | anyone | allowlist
676+
#[arg(long = "respond-to")]
677+
respond_to: Option<String>,
678+
/// Comma-separated allowlist of 64-char hex pubkeys (used with --respond-to allowlist)
679+
#[arg(long = "respond-to-allowlist", value_delimiter = ',')]
680+
respond_to_allowlist: Option<Vec<String>>,
675681
},
676682
}
677683

‎desktop/src/features/agents/lib/agentAutocompleteEligibility.test.mjs‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -243,6 +243,48 @@ test("shouldHideAgentFromMentions: normalizes the pubkey before lookup", () => {
243243
);
244244
});
245245

246+
test("shouldHideAgentFromMentions: shows an owner-only agent to its own owner (buzz#2987)", () => {
247+
assert.equal(
248+
shouldHideAgentFromMentions({
249+
isAgent: true,
250+
isMember: false,
251+
isOwnAgent: true,
252+
pubkey: PUB_A,
253+
mentionableAgentPubkeys: new Set(),
254+
directoryAgentPubkeys: new Set([PUB_A]),
255+
}),
256+
false,
257+
);
258+
});
259+
260+
test("shouldHideAgentFromMentions: isOwnAgent does not override the non-agent guard", () => {
261+
assert.equal(
262+
shouldHideAgentFromMentions({
263+
isAgent: false,
264+
isMember: false,
265+
isOwnAgent: true,
266+
pubkey: PUB_A,
267+
mentionableAgentPubkeys: new Set(),
268+
directoryAgentPubkeys: new Set([PUB_A]),
269+
}),
270+
false,
271+
);
272+
});
273+
274+
test("shouldHideAgentFromMentions: still hides a non-owned non-invocable agent", () => {
275+
assert.equal(
276+
shouldHideAgentFromMentions({
277+
isAgent: true,
278+
isMember: false,
279+
isOwnAgent: false,
280+
pubkey: PUB_A,
281+
mentionableAgentPubkeys: new Set(),
282+
directoryAgentPubkeys: new Set([PUB_A]),
283+
}),
284+
true,
285+
);
286+
});
287+
246288
test("coalesceAgentAutocompleteCandidates: merges agents with the same persona id", () => {
247289
const first = makeAgent({ pubkey: PUB_A, personaId: "pinky" });
248290
const second = makeAgent({

0 commit comments

Comments
 (0)