Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,23 @@ BUZZ_PUSH_GATEWAY_DELIVERY_URL=https://push.buzz.xyz/v1/deliveries/apns
# BUZZ_RATE_LIMIT_AGENT_STANDARD_API_CALLS_PER_MIN=600
# BUZZ_RATE_LIMIT_AGENT_ELEVATED_MESSAGES_PER_MIN=300
# BUZZ_RATE_LIMIT_AGENT_PLATFORM_MESSAGES_PER_MIN=600
# NIP-CI imported history events per pubkey, any tier. Charged instead of the
# messages limit.
# BUZZ_RATE_LIMIT_IMPORT_EVENTS_PER_MIN=600

# NIP-CI: longest import session lifetime in days; a proposal's expires_at is
# capped at now plus this value.
# BUZZ_IMPORT_SESSION_MAX_DAYS=30

# NIP-CI: caps on the counts a proposal may declare, per participant (messages
# plus reactions) and summed over the session.
# BUZZ_IMPORT_MAX_EVENTS_PER_PARTICIPANT=50000
# BUZZ_IMPORT_MAX_EVENTS_PER_SESSION=200000

# NIP-CI: caps on unended (proposed or active, unexpired) import sessions per
# destination channel and per proposer.
# BUZZ_IMPORT_MAX_ACTIVE_SESSIONS_PER_CHANNEL=2
# BUZZ_IMPORT_MAX_ACTIVE_SESSIONS_PER_PROPOSER=8

# -----------------------------------------------------------------------------
# Git (NIP-34 bare repositories)
Expand Down
2 changes: 2 additions & 0 deletions ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -182,8 +182,10 @@ The `kind` integer is the only dispatch switch. The relay routes, stores, and fa
|------|------|-------------|
| 7 | KIND_REACTION | Emoji reaction (standard NIP-25) |
| 9 | KIND_STREAM_MESSAGE | Chat message in a Stream channel (NIP-29 group chat) |
| 30623 | KIND_IMPORT_SESSION_SNAPSHOT | Relay-signed import session state (NIP-CI) |
| 40002 | KIND_STREAM_MESSAGE_V2 | Stream message v2 format |
| 40003 | KIND_STREAM_MESSAGE_EDIT | Edit of a stream message |
| 42110 to 42113 | KIND_IMPORT_* | Conversation import proposal, consent, withdraw and complete (NIP-CI) |
| 43001 | KIND_JOB_REQUEST | Agent job request |
| 45001 | KIND_FORUM_POST | Forum thread root |
| 45003 | KIND_FORUM_COMMENT | Forum thread reply |
Expand Down
2 changes: 2 additions & 0 deletions NOSTR.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ PGPASSWORD=buzz_dev psql -h localhost -U buzz -d buzz -c \
| **NIP-17 DMs (gift wrap)** | ✅ | kind:1059 accepted with ephemeral signing keys. Stored community-globally (`channel_id=None` inside the connected community). Delivered via `#p`-filtered subscriptions. Not indexed in search. |
| **DM discovery** | ✅ | DM creation emits kind:39000 (with `hidden` tag) + kind:44100 membership notifications. NIP-29 clients discover DMs via standard group discovery flow. |
| **Join request (kind:9021)** | ✅ | Open channels only. Adds the joiner with the channel's `join_role` (`member` by default), emits system message + group discovery events + kind:44100 membership notification. Private channels rejected at ingest. The same body joins new community members to [default channels](#default-channels). |
| **Conversation import (kinds 42110 to 42113, 30623)** | ✅ | [NIP-CI](docs/nips/NIP-CI.md). Each participant signs their own history as kind:9 and kind:7 with `import` and `source` tags; the relay accepts original timestamps only inside a session every participant consented to. Relay-signed kind:30623 snapshot (`d` = proposal id) carries status, consents and counts and is readable like the channel's messages. Imported events never notify, mention, mark unread, push or trigger workflows and agents. |
| **Edits (kind:40003)** | ⚠️ | Works on the wire but Buzz-only — no standard NIP-29 client renders these |
| **Rich content (kind:40002)** | ⚠️ | Works on the wire but Buzz-only — no standard NIP-29 client renders these |

Expand Down Expand Up @@ -577,6 +578,7 @@ but only admins/owners can set it. Full spec:
- **kind:7 derives channel from target.** Reactions look up the target event's channel via `#e` — client-supplied `#h` tags are ignored. Reactions to unknown events are rejected (fail-closed).
- **kind:5 uses `#h` if present, but doesn't require it.** Deletions validate author-match against target events via `#e` tags. Only self-authored events can be deleted (admin deletions use kind:9005).
- **Client-submitted kind:44100/44101 rejected.** Membership notifications can only be signed by the relay keypair.
- **Backdated kind:9 and kind:7 need a consented import session.** An `import` tag skips the timestamp drift check only when every [NIP-CI](docs/nips/NIP-CI.md) rule holds; client-submitted kind:30623 is rejected.

---

Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ Agents are part of the room, not haunted cron jobs.
| Relay, channels, threads, DMs, canvases, media, search, audit log | Mobile clients (iOS + Android, Flutter) | Web-of-trust reputation across relays |
| Desktop app (Tauri + React) | Workflow approval gates (infra exists, glue still drying) | Push notifications |
| `buzz-cli` (agent-first, JSON in / JSON out) + ACP harness (Goose, Codex, Claude Code) | Huddle lifecycle events | Culture features |
| YAML workflows: message / reaction / schedule / webhook triggers | | |
| YAML workflows: message / reaction / schedule / webhook triggers | Consented conversation import with original timestamps (relay side, NIP-CI) | |
| Git events (NIP-34: patches, repo announcements, status) | | |
| Git hosting backend | | |

Expand Down
35 changes: 35 additions & 0 deletions crates/buzz-acp/src/filter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -371,6 +371,11 @@ pub async fn match_event(
rules: &[SubscriptionRule],
agent_pubkey_hex: &str,
) -> Option<MatchedRule> {
// NIP-CI imported history is past conversation; it never triggers an agent.
if buzz_core::import::is_import_event(event) {
return None;
}

let filter_ctx = FilterContext::from_event(event, channel_id);

for (index, rule) in rules.iter().enumerate() {
Expand Down Expand Up @@ -577,6 +582,36 @@ mod tests {
assert!(result);
}

#[tokio::test]
async fn test_match_event_skips_imported_history() {
let agent = Keys::generate().public_key().to_hex();
let rules = vec![make_rule(
"mentions",
ChannelScope::All("all".into()),
vec![9],
true,
None,
None,
)];
let live = make_event_with_p_tag(9, "hello", &agent);
assert!(match_event(&live, any_channel(), &rules, &agent)
.await
.is_some());

let tags = [
Tag::parse(["p", agent.as_str()]).expect("tag parse"),
Tag::parse(["import", &"ab".repeat(32)]).expect("tag parse"),
Tag::parse(["source", "test", "1"]).expect("tag parse"),
];
let imported = EventBuilder::new(Kind::Custom(9), "hello")
.tags(tags)
.sign_with_keys(&Keys::generate())
.unwrap();
assert!(match_event(&imported, any_channel(), &rules, &agent)
.await
.is_none());
}

#[tokio::test]
async fn test_match_event_first_match_wins() {
let event = make_event(9, "hello");
Expand Down
78 changes: 78 additions & 0 deletions crates/buzz-acp/src/pool.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4672,6 +4672,11 @@ fn parse_dm_response(json: serde_json::Value, limit: u32) -> Option<Conversation
///
/// Works with both thread reply objects and channel message objects.
fn json_to_context_message(obj: &serde_json::Value) -> Option<ContextMessage> {
// Imported history (NIP-CI) is consented to by its human participants
// only, so it never enters an agent prompt.
if carries_import_tag(obj) {
return None;
}
let content = obj.get("content").and_then(|v| v.as_str())?;
let pubkey = obj
.get("pubkey")
Expand Down Expand Up @@ -4705,6 +4710,17 @@ fn json_to_context_message(obj: &serde_json::Value) -> Option<ContextMessage> {
})
}

/// Whether a query-response event carries a NIP-CI `import` tag.
fn carries_import_tag(obj: &serde_json::Value) -> bool {
obj.get("tags")
.and_then(|tags| tags.as_array())
.is_some_and(|tags| {
tags.iter().any(|tag| {
tag.get(0).and_then(|name| name.as_str()) == Some(buzz_core::import::IMPORT_TAG)
})
})
}

/// Parse a Nostr query response (array of events) into thread context.
///
/// Separates the root event (matching `root_event_id`) from replies, then sorts
Expand Down Expand Up @@ -6394,6 +6410,68 @@ pub(crate) mod tests {
}
}

#[tokio::test]
async fn test_context_fetchers_drop_imported_history() {
let agent = Keys::generate();
let root_id = "1111111111111111111111111111111111111111111111111111111111111111";
let channel_id = Uuid::new_v4();
let mut imported = thread_event(
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"humanpub",
"imported history",
2000,
);
imported["tags"] = json!([
["h", channel_id.to_string()],
[
"import",
"2222222222222222222222222222222222222222222222222222222222222222"
],
["source", "test", "1"]
]);
let live = thread_event(
"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
"humanpub",
"live reply",
3000,
);
let json = json!([
thread_event(root_id, "rootpub", "root", 1000),
imported,
live
]);

let thread_json = json.clone();
let thread = fetch_thread_context_with(
channel_id,
root_id,
10,
agent.public_key(),
move |_| std::future::ready(Ok(thread_json.clone())),
|_| std::future::ready(Ok(json!({ "count": 0 }))),
ThreadContextSessionDelta {
overfetch: false,
delivered_ids: &HashSet::new(),
},
)
.await
.expect("thread context");
let dm = fetch_dm_context_with(channel_id, 10, move |_| {
std::future::ready(Ok(json.clone()))
})
.await
.expect("dm context");

for ctx in [thread, dm] {
let messages = match ctx {
ConversationContext::Thread { messages, .. }
| ConversationContext::Dm { messages, .. } => messages,
};
assert!(messages.iter().any(|m| m.content == "live reply"));
assert!(messages.iter().all(|m| m.content != "imported history"));
}
}

#[tokio::test]
async fn test_fetch_thread_context_uses_exact_count_when_above_sentinel_minimum() {
let agent = Keys::generate();
Expand Down
12 changes: 12 additions & 0 deletions crates/buzz-auth/src/rate_limit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,9 @@ pub enum LimitType {
WsEvents,
/// Concurrent WebSocket connections from a single IP address.
IpConnections,
/// NIP-CI imported history events (kinds 9 and 7 carrying an `import`
/// tag). Charged instead of `Messages`.
ImportEvents,
}

impl LimitType {
Expand All @@ -77,6 +80,7 @@ impl LimitType {
Self::GifSearches => "gif",
Self::WsEvents => "ws",
Self::IpConnections => "conn",
Self::ImportEvents => "import",
}
}
}
Expand Down Expand Up @@ -112,6 +116,10 @@ pub struct RateLimitConfig {
/// Maximum messages per minute for platform-tier agent tokens. Default: 600.
#[serde(default = "default_agent_plat_msg")]
pub agent_platform_messages_per_min: u64,
/// Maximum NIP-CI imported events per minute for each pubkey, any tier.
/// Default: 600.
#[serde(default = "default_import_events")]
pub import_events_per_min: u64,
}

fn default_human_msg() -> u64 {
Expand All @@ -138,6 +146,9 @@ fn default_agent_elev_msg() -> u64 {
fn default_agent_plat_msg() -> u64 {
600
}
fn default_import_events() -> u64 {
600
}

impl Default for RateLimitConfig {
fn default() -> Self {
Expand All @@ -150,6 +161,7 @@ impl Default for RateLimitConfig {
agent_standard_api_calls_per_min: default_agent_std_api(),
agent_elevated_messages_per_min: default_agent_elev_msg(),
agent_platform_messages_per_min: default_agent_plat_msg(),
import_events_per_min: default_import_events(),
}
}
}
Expand Down
Loading
Loading