diff --git a/.env.example b/.env.example index 46b9ceed12..eabaefc922 100644 --- a/.env.example +++ b/.env.example @@ -39,6 +39,9 @@ REDIS_URL=redis://localhost:6379 # Emergency kill switch for all automatic partition DDL, including catch-all # advancement; audits remain enabled. # BUZZ_PARTITION_MANAGER_CREATE_ENABLED=true +# Which workflow runs may direct agents: any (default) or owner (owner-only +# agent mentions). See docs/operator-workflow-agent-mentions.md. +# BUZZ_WORKFLOW_AGENT_MENTIONS=owner # Replace an empty partition catch-all with six months of dedicated monthlies, # at startup and on every audit interval (default true). Has no effect while the # kill switch above is off. diff --git a/Cargo.lock b/Cargo.lock index 475705a205..78a9fdf31e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1624,6 +1624,7 @@ dependencies = [ "dashmap", "evalexpr", "hex", + "metrics", "moka", "nostr 0.44.7", "reqwest 0.13.4", diff --git a/NOSTR.md b/NOSTR.md index 629c4f808a..a6836b6dd2 100644 --- a/NOSTR.md +++ b/NOSTR.md @@ -375,6 +375,37 @@ of the channel's messages: `buzz:workflow-owner` also names the owner. A marked `p` tag on any other event, for example a kind:39002 member list role, matches `#p` normally. See `docs/buzz-push.md` for the push rules. +### Workflow Mentions + +A workflow message may carry `["buzz:workflow-mention", ]` tags. Each +one names a channel member whom the workflow's owner named in the stored text of +the step, as opposed to text substituted into it when the step ran. The relay adds +a plain `["p", ]` for every member that the rendered text mentions, and a +`buzz:workflow-mention` tag only for members that the stored text also names. + +A `buzz:workflow-mention` tag is the relay's statement that the message may +direct the named agent on the owner's behalf. An agent acts on a workflow +message only if all of these hold: + +- the message is signed by the relay key that the active community advertises; +- a `buzz:workflow-mention` tag names the agent; +- the workflow principal that `buzz:workflow-owner` names passes the receiving + client's rule for whom the agent accepts work from: its owner, or an agent + that its owner has attested. + +`buzz:workflow-owner` is attribution. It does not by itself authorize anything. +A plain `p` tag on a workflow message notifies the member but does not direct +an agent. + +A relay may leave out `buzz:workflow-mention` tags under a policy. The message +still posts with its `p` tags, and an agent that no tag names does not act on +it. A relay's NIP-11 document MUST carry `workflow_agent_mentions`: `"any"` +when every run may carry the tags, or `"owner"` when only runs the workflow's +owner or a timer started, on a definition of only `send_message` and `delay` +steps, carry them; a client MUST treat a missing field as an older relay whose +policy is unknown. For Buzz's owner-only agent mentions, see +[docs/operator-workflow-agent-mentions.md](docs/operator-workflow-agent-mentions.md). + ### Sending Messages ```bash diff --git a/TESTING.md b/TESTING.md index cc41319f64..0a7acf817e 100644 --- a/TESTING.md +++ b/TESTING.md @@ -419,6 +419,7 @@ out of the box with `just setup` or `just relay`. Common overrides: | `BUZZ_REQUIRE_RELAY_MEMBERSHIP` | `false` | When true, only pubkeys in `relay_members` can connect | | `BUZZ_DRAIN_JITTER_MS` | `0` (off) | Per-connection upper bound, in ms, for the random delay before each live WebSocket gets its `1012 Service Restart` close on graceful shutdown. `0` closes every socket at once (the previous behavior). A positive value spreads closes uniformly over `[1, value]` ms to avoid a reconnect thundering herd on rolling deploys. Values above `20000` are capped to `20000` (`MAX_DRAIN_JITTER_MS`) to leave close-frame delivery headroom under the relay's 30s hard-drain timeout. Empty or whitespace-only is treated as unset (off); a non-integer fails startup loudly. | | `BUZZ_AUDIT_ENABLED` | `true` | Tamper-evident event/media audit log. Set `false`/`0`/`off` to skip its DB pool and writes. Does not disable the separate moderation audit trail. | +| `BUZZ_WORKFLOW_AGENT_MENTIONS` | `any` | `owner` turns on owner-only agent mentions: only runs the owner or a timer started can direct agents. Any value other than `any` or `owner` fails startup. See [docs/operator-workflow-agent-mentions.md](docs/operator-workflow-agent-mentions.md). | | `BUZZ_AUTO_MIGRATE` | `false` | Opt in with `true`/`1`/`yes`/`on` to run embedded SQLx migrations on relay startup | | `RELAY_OWNER_PUBKEY` | unset | Bootstrapped as `owner` in `relay_members` at first start | | `BUZZ_ALLOW_NIP_OA_AUTH` | `false` | Enable NIP-OA owner attestation for membership | diff --git a/crates/buzz-db/src/runtime/migration.rs b/crates/buzz-db/src/runtime/migration.rs index f7f0888e96..7a9a2b7bf8 100644 --- a/crates/buzz-db/src/runtime/migration.rs +++ b/crates/buzz-db/src/runtime/migration.rs @@ -902,7 +902,7 @@ mod postgres_tests { let mut migrations: Vec<_> = MIGRATOR.iter().collect(); migrations.sort_by_key(|migration| migration.version); - assert_eq!(migrations.len(), 86); + assert_eq!(migrations.len(), 88); assert!(migrations[83] .sql .as_str() @@ -915,6 +915,14 @@ mod postgres_tests { .sql .as_str() .contains("CREATE TABLE media_uploaders")); + assert!(migrations[86] + .sql + .as_str() + .contains("ADD COLUMN cause_source TEXT")); + assert!(migrations[87] + .sql + .as_str() + .contains("VALIDATE CONSTRAINT workflow_runs_cause_pubkey_check")); for (index, migration) in migrations.iter().enumerate() { assert_eq!(migration.version, (index + 1) as i64); } @@ -3057,6 +3065,7 @@ mod postgres_tests { "communities", "entity_deletion_stage_history", "user_deletion_fences", + "workflow_runs", ] { assert_eq!( columns(&desired, table).await, @@ -3120,6 +3129,7 @@ mod postgres_tests { "entity_deletion_stage_history", "user_deletion_fences", "entity_deletion_approvals", + "workflow_runs", ] { assert_eq!( constraints(&desired, table).await, @@ -3300,6 +3310,87 @@ mod postgres_tests { } } + /// 0087 adds the run-cause columns and NOT VALID checks without scanning + /// existing runs, and 0088 validates them. Runs written before the upgrade, + /// and inserts from an older relay that omits both columns, keep no cause. + #[tokio::test] + #[ignore = "requires Postgres"] + async fn workflow_run_cause_upgrade_preserves_populated_rows_and_legacy_inserts() { + let pool = connect_test_pool().await; + reset_public_schema(&pool).await; + run_migrations_through(&pool, 86).await.unwrap(); + let community_id = uuid::Uuid::new_v4(); + let workflow_id = uuid::Uuid::new_v4(); + let owner = vec![7u8; 32]; + sqlx::query("INSERT INTO communities (id, host) VALUES ($1, $2)") + .bind(community_id) + .bind(format!("run-cause-{}.example", community_id.simple())) + .execute(&pool) + .await + .unwrap(); + sqlx::query("INSERT INTO users (community_id, pubkey) VALUES ($1, $2)") + .bind(community_id) + .bind(&owner) + .execute(&pool) + .await + .unwrap(); + sqlx::query( + "INSERT INTO workflows (community_id, id, name, owner_pubkey, definition, definition_hash) \ + VALUES ($1, $2, 'cause', $3, '{}', $4)", + ) + .bind(community_id) + .bind(workflow_id) + .bind(&owner) + .bind(vec![0u8; 32]) + .execute(&pool) + .await + .unwrap(); + let legacy_insert = + "INSERT INTO workflow_runs (community_id, id, workflow_id) VALUES ($1, $2, $3)"; + let insert_legacy_run = |id| { + sqlx::query(legacy_insert) + .bind(community_id) + .bind(id) + .bind(workflow_id) + .execute(&pool) + }; + let before = uuid::Uuid::new_v4(); + insert_legacy_run(before).await.unwrap(); + run_migrations(&pool).await.unwrap(); + let after = uuid::Uuid::new_v4(); + insert_legacy_run(after).await.unwrap(); + + for id in [before, after] { + let cause: (Option, Option>) = sqlx::query_as( + "SELECT cause_source, cause_pubkey FROM workflow_runs WHERE id = $1", + ) + .bind(id) + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!(cause, (None, None)); + } + let unvalidated: i64 = sqlx::query_scalar( + "SELECT count(*) FROM pg_constraint \ + WHERE conrelid = 'public.workflow_runs'::regclass AND contype = 'c' \ + AND conname LIKE 'workflow_runs_%' AND NOT convalidated", + ) + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!(unvalidated, 0, "0088 validates every cause check"); + let unknown_source = sqlx::query( + "INSERT INTO workflow_runs (community_id, id, workflow_id, cause_source) \ + VALUES ($1, $2, $3, 'relay')", + ) + .bind(community_id) + .bind(uuid::Uuid::new_v4()) + .bind(workflow_id) + .execute(&pool) + .await; + assert!(unknown_source.is_err(), "the trigger source check holds"); + } + /// Migrations 0076 and 0078 refuse a populated table whose index was not /// prebuilt concurrently. A relay that auto-migrated through earlier /// releases and holds artifact data must still boot through every migration. When a diff --git a/crates/buzz-db/src/store/admission_postgres_tests.rs b/crates/buzz-db/src/store/admission_postgres_tests.rs index c5b23f41e6..8cef51834e 100644 --- a/crates/buzz-db/src/store/admission_postgres_tests.rs +++ b/crates/buzz-db/src/store/admission_postgres_tests.rs @@ -318,9 +318,16 @@ async fn workflow_writers_require_application_admission() { .expect_err("workflow create must reject"), ); assert_fenced( - super::workflow::create_workflow_run(&db.pool, *community, Uuid::new_v4(), None, None) - .await - .expect_err("workflow run create must reject"), + super::workflow::create_workflow_run( + &db.pool, + *community, + Uuid::new_v4(), + None, + None, + &super::workflow::RunCause::Schedule, + ) + .await + .expect_err("workflow run create must reject"), ); assert_fenced( super::workflow::claim_scheduled_workflow_fire( diff --git a/crates/buzz-db/src/store/workflow.rs b/crates/buzz-db/src/store/workflow.rs index cbe29522db..968e773bc5 100644 --- a/crates/buzz-db/src/store/workflow.rs +++ b/crates/buzz-db/src/store/workflow.rs @@ -192,6 +192,48 @@ pub struct WorkflowRecord { pub updated_at: DateTime, } +/// What caused a workflow run, recorded when the run is created. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum RunCause { + /// A signed event: the message, reaction or diff signer's pubkey. + Event(Vec), + /// A cron or interval timer. + Schedule, + /// A webhook call. The caller is unknown. + Webhook, + /// A manual trigger: the invoking pubkey. + Manual(Vec), +} + +impl RunCause { + fn source(&self) -> &'static str { + match self { + Self::Event(_) => "event", + Self::Schedule => "schedule", + Self::Webhook => "webhook", + Self::Manual(_) => "manual", + } + } + + fn pubkey(&self) -> Option<&[u8]> { + match self { + Self::Event(pubkey) | Self::Manual(pubkey) => Some(pubkey), + Self::Schedule | Self::Webhook => None, + } + } + + /// Rebuild a stored cause. Missing or inconsistent values give `None`. + fn from_columns(source: Option<&str>, pubkey: Option>) -> Option { + match (source?, pubkey) { + ("event", Some(pubkey)) => Some(Self::Event(pubkey)), + ("manual", Some(pubkey)) => Some(Self::Manual(pubkey)), + ("schedule", None) => Some(Self::Schedule), + ("webhook", None) => Some(Self::Webhook), + _ => None, + } + } +} + /// A single execution of a workflow. #[derive(Debug, Clone)] pub struct WorkflowRunRecord { @@ -217,6 +259,8 @@ pub struct WorkflowRunRecord { /// Serialized `TriggerContext` captured at workflow start. /// NULL for runs created before this column was added (backwards-compatible). pub trigger_context: Option, + /// What caused this run. `None` for runs created before causes were recorded. + pub cause: Option, /// When execution began. pub started_at: Option>, /// When execution finished (success or failure). @@ -871,6 +915,7 @@ pub async fn create_workflow_run( workflow_id: Uuid, trigger_event_id: Option<&[u8]>, trigger_context: Option<&serde_json::Value>, + cause: &RunCause, ) -> Result { let mut tx = crate::begin_community_write_transaction( pool, @@ -883,8 +928,9 @@ pub async fn create_workflow_run( sqlx::query( r#" INSERT INTO workflow_runs - (community_id, id, workflow_id, status, trigger_event_id, current_step, execution_trace, trigger_context) - VALUES ($1, $2, $3, 'pending', $4, 0, '[]', $5) + (community_id, id, workflow_id, status, trigger_event_id, current_step, execution_trace, + trigger_context, cause_source, cause_pubkey) + VALUES ($1, $2, $3, 'pending', $4, 0, '[]', $5, $6, $7) "#, ) .bind(community_id.as_uuid()) @@ -892,6 +938,8 @@ pub async fn create_workflow_run( .bind(workflow_id) .bind(trigger_event_id) .bind(trigger_context) + .bind(cause.source()) + .bind(cause.pubkey()) .execute(tx.conn()) .await?; tx.commit().await?; @@ -908,7 +956,8 @@ pub async fn get_workflow_run( let row = sqlx::query( r#" SELECT community_id, id, workflow_id, status::text AS status, trigger_event_id, current_step, - execution_trace, trigger_context, started_at, completed_at, error_message, error_code, created_at + execution_trace, trigger_context, cause_source, cause_pubkey, started_at, completed_at, + error_message, error_code, created_at FROM workflow_runs WHERE community_id = $1 AND id = $2 "#, @@ -940,7 +989,8 @@ pub async fn list_workflow_runs_page( let rows = sqlx::query( r#" SELECT community_id, id, workflow_id, status::text AS status, trigger_event_id, current_step, - execution_trace, trigger_context, started_at, completed_at, error_message, error_code, created_at + execution_trace, trigger_context, cause_source, cause_pubkey, started_at, completed_at, + error_message, error_code, created_at FROM workflow_runs WHERE community_id = $1 AND workflow_id = $2 AND ( @@ -1302,6 +1352,10 @@ fn row_to_run_record(row: sqlx::postgres::PgRow) -> Result { current_step: row.try_get("current_step")?, execution_trace: row.try_get("execution_trace")?, trigger_context: row.try_get("trigger_context")?, + cause: RunCause::from_columns( + row.try_get::, _>("cause_source")?.as_deref(), + row.try_get("cause_pubkey")?, + ), started_at: row.try_get("started_at")?, completed_at: row.try_get("completed_at")?, error_message: row.try_get("error_message")?, @@ -1372,6 +1426,7 @@ impl Db { workflow_id: Uuid, trigger_event_id: Option<&[u8]>, trigger_context: Option<&serde_json::Value>, + cause: &RunCause, ) -> Result { crate::workflow::create_workflow_run( &self.pool, @@ -1379,6 +1434,7 @@ impl Db { workflow_id, trigger_event_id, trigger_context, + cause, ) .await } @@ -1762,6 +1818,30 @@ impl Db { #[cfg(test)] mod postgres_tests { + #[test] + fn stored_cause_requires_a_consistent_source_and_pubkey() { + let pubkey = vec![1u8; 32]; + assert_eq!( + RunCause::from_columns(Some("event"), Some(pubkey.clone())), + Some(RunCause::Event(pubkey.clone())) + ); + assert_eq!( + RunCause::from_columns(Some("schedule"), None), + Some(RunCause::Schedule) + ); + for (source, key) in [ + (Some("event"), None), + (Some("manual"), None), + (Some("schedule"), Some(pubkey.clone())), + (Some("webhook"), Some(pubkey.clone())), + (Some("unknown"), None), + (None, Some(pubkey.clone())), + (None, None), + ] { + assert_eq!(RunCause::from_columns(source, key), None, "{source:?}"); + } + } + use super::*; use chrono::TimeZone; @@ -2004,6 +2084,7 @@ mod postgres_tests { { "step": "s1", "status": "completed" } ]), trigger_context: None, + cause: None, started_at: Some(now), completed_at: None, error_message: None, @@ -2033,6 +2114,7 @@ mod postgres_tests { current_step: 0, execution_trace: serde_json::json!([]), trigger_context: None, + cause: None, started_at: None, completed_at: None, error_message: None, @@ -2057,6 +2139,7 @@ mod postgres_tests { current_step: 1, execution_trace: serde_json::json!([]), trigger_context: None, + cause: None, started_at: Some(now), completed_at: Some(now), error_message: Some("step timeout exceeded".to_owned()), @@ -2089,6 +2172,7 @@ mod postgres_tests { current_step: 2, execution_trace: trace.clone(), trigger_context: None, + cause: None, started_at: Some(now), completed_at: Some(now), error_message: None, @@ -2112,6 +2196,7 @@ mod postgres_tests { current_step: 0, execution_trace: serde_json::json!([]), trigger_context: None, + cause: None, started_at: None, completed_at: None, error_message: None, @@ -2455,9 +2540,16 @@ mod postgres_tests { .expect("claim wins"); // Create the run the won claim is responsible for, then attach it. - let run_id = create_workflow_run(&pool, community, workflow_id, None, None) - .await - .expect("create run ok"); + let run_id = create_workflow_run( + &pool, + community, + workflow_id, + None, + None, + &RunCause::Schedule, + ) + .await + .expect("create run ok"); let attached = attach_scheduled_workflow_run(&pool, community, workflow_id, scheduled_for, run_id) @@ -2484,9 +2576,16 @@ mod postgres_tests { // A second attach is a no-op: the `workflow_run_id IS NULL` guard means // an already-linked claim is never re-pointed to a different run. - let other_run = create_workflow_run(&pool, community, workflow_id, None, None) - .await - .expect("create second run ok"); + let other_run = create_workflow_run( + &pool, + community, + workflow_id, + None, + None, + &RunCause::Schedule, + ) + .await + .expect("create second run ok"); let reattached = attach_scheduled_workflow_run(&pool, community, workflow_id, scheduled_for, other_run) .await @@ -2808,12 +2907,26 @@ mod postgres_tests { insert_workflow_with_ids(&pool, community_a, workflow_id, channel_id, "wf-A").await; insert_workflow_with_ids(&pool, community_b, workflow_id, Uuid::new_v4(), "wf-B").await; - let run_a = create_workflow_run(&pool, community_a, workflow_id, None, None) - .await - .expect("run A"); - let run_b = create_workflow_run(&pool, community_b, workflow_id, None, None) - .await - .expect("run B"); + let run_a = create_workflow_run( + &pool, + community_a, + workflow_id, + None, + None, + &RunCause::Schedule, + ) + .await + .expect("run A"); + let run_b = create_workflow_run( + &pool, + community_b, + workflow_id, + None, + None, + &RunCause::Schedule, + ) + .await + .expect("run B"); let token = "shared-approval-token"; let expires = Utc::now() + chrono::Duration::hours(1); diff --git a/crates/buzz-db/src/store/workflow/deletion_tests.rs b/crates/buzz-db/src/store/workflow/deletion_tests.rs index 7210d2efb7..7ddcfa3b0c 100644 --- a/crates/buzz-db/src/store/workflow/deletion_tests.rs +++ b/crates/buzz-db/src/store/workflow/deletion_tests.rs @@ -112,9 +112,16 @@ async fn workflow_deletion_removes_both_projections_and_is_scoped_and_retryable( assert!(!unchanged.changed); assert_present(&db, &query, id).await; - let run_id = create_workflow_run(&db.pool, community, id, None, None) - .await - .expect("run"); + let run_id = create_workflow_run( + &db.pool, + community, + id, + None, + None, + &crate::workflow::RunCause::Schedule, + ) + .await + .expect("run"); // A fired schedule links both the workflow and a cascading run. Deletion // must also remove the claim despite its NO ACTION run foreign key. sqlx::query( @@ -391,9 +398,16 @@ async fn workflow_deletion_removes_children_without_cascades() { let query = seed(&db, community, &keys, id, &d_tag, now).await; let other = Uuid::new_v4(); seed(&db, community, &keys, other, &other.to_string(), now).await; - let run_id = create_workflow_run(&db.pool, community, id, None, None) - .await - .expect("run"); + let run_id = create_workflow_run( + &db.pool, + community, + id, + None, + None, + &crate::workflow::RunCause::Schedule, + ) + .await + .expect("run"); sqlx::query( "INSERT INTO scheduled_workflow_fires \ (community_id, workflow_id, scheduled_for, workflow_run_id) VALUES ($1, $2, NOW(), $3)", @@ -512,9 +526,16 @@ async fn workflow_deletion_waits_for_and_removes_concurrent_cross_workflow_appro seed(&db, community, &keys, id, &d_tag, now).await; let other = Uuid::new_v4(); seed(&db, community, &keys, other, &other.to_string(), now).await; - let run_id = create_workflow_run(&db.pool, community, id, None, None) - .await - .expect("run"); + let run_id = create_workflow_run( + &db.pool, + community, + id, + None, + None, + &crate::workflow::RunCause::Schedule, + ) + .await + .expect("run"); let mut inserter = db.pool.begin().await.expect("begin approval insert"); sqlx::query( @@ -573,9 +594,16 @@ async fn workflow_deletion_waits_for_concurrent_fire_attach_without_deadlock() { let d_tag = id.to_string(); let now = Timestamp::now().as_secs(); seed(&db, community, &keys, id, &d_tag, now).await; - let run_id = create_workflow_run(&db.pool, community, id, None, None) - .await - .expect("run"); + let run_id = create_workflow_run( + &db.pool, + community, + id, + None, + None, + &crate::workflow::RunCause::Schedule, + ) + .await + .expect("run"); let scheduled_for: chrono::DateTime = sqlx::query_scalar( "INSERT INTO scheduled_workflow_fires (community_id, workflow_id, scheduled_for) \ VALUES ($1, $2, date_trunc('second', NOW())) RETURNING scheduled_for", diff --git a/crates/buzz-relay/src/api/bridge.rs b/crates/buzz-relay/src/api/bridge.rs index 6204f3d936..2986c35cfb 100644 --- a/crates/buzz-relay/src/api/bridge.rs +++ b/crates/buzz-relay/src/api/bridge.rs @@ -2986,7 +2986,13 @@ pub async fn workflow_webhook( let run_id = state .db - .create_workflow_run(community_id, id, None, trigger_ctx_json.as_ref()) + .create_workflow_run( + community_id, + id, + None, + trigger_ctx_json.as_ref(), + &buzz_db::workflow::RunCause::Webhook, + ) .await .map_err(|e| super::internal_error(&format!("db error: {e}")))?; @@ -3020,14 +3026,12 @@ pub async fn workflow_webhook( } }; - let result = buzz_workflow::executor::execute_from_step( + let result = buzz_workflow::executor::execute_run( &engine, community_id, run_id, &def, &trigger_ctx_clone, - 0, - None, ) .await; engine diff --git a/crates/buzz-relay/src/api/media_access_postgres_tests.rs b/crates/buzz-relay/src/api/media_access_postgres_tests.rs index b2a8f7d9c5..ec6d9140c7 100644 --- a/crates/buzz-relay/src/api/media_access_postgres_tests.rs +++ b/crates/buzz-relay/src/api/media_access_postgres_tests.rs @@ -711,6 +711,7 @@ async fn private_media_revocation_http_journey() { &open.to_string(), &text, &text, + true, &member.public_key().to_hex(), None, ) diff --git a/crates/buzz-relay/src/config.rs b/crates/buzz-relay/src/config.rs index b9bb918893..286e86ba24 100644 --- a/crates/buzz-relay/src/config.rs +++ b/crates/buzz-relay/src/config.rs @@ -339,6 +339,15 @@ pub struct Config { /// Set `BUZZ_AUDIT_ENABLED=false` for deployments that do not require it. pub audit_enabled: bool, + /// Which workflow runs may direct agents. With `owner` (owner-only agent + /// mentions), a workflow message carries `buzz:workflow-mention` tags only + /// if its run was started by the workflow's owner or by a timer and every + /// step of the definition is `send_message` or `delay`. Use `owner` when + /// people other than a workflow's owner can trigger it. + /// + /// Default: `any`. Set via `BUZZ_WORKFLOW_AGENT_MENTIONS=any|owner`. + pub workflow_agent_mentions: buzz_workflow::AgentMentions, + /// Optional override for ephemeral channel TTL (in seconds). /// When set, any channel created with a TTL tag will use this value instead /// of the client-provided one. Useful for testing ephemeral expiry quickly. @@ -636,6 +645,19 @@ fn parse_bool(name: &str, default: bool) -> Result { } } +fn parse_workflow_agent_mentions() -> Result { + const NAME: &str = "BUZZ_WORKFLOW_AGENT_MENTIONS"; + match std::env::var(NAME) { + Err(std::env::VarError::NotPresent) => Ok(buzz_workflow::AgentMentions::Any), + Err(error) => Err(ConfigError::InvalidValue(format!( + "{NAME} must be valid UTF-8: {error}" + ))), + Ok(value) => value + .parse() + .map_err(|error| ConfigError::InvalidValue(format!("{NAME}: {error}"))), + } +} + fn parse_optional_bool(name: &str) -> Result { parse_bool(name, false) } @@ -1291,6 +1313,7 @@ impl Config { let privacy_markdown = read_policy_markdown("BUZZ_PRIVACY_POLICY_MARKDOWN")?; let age_attestation_required = parse_optional_bool("BUZZ_AGE_ATTESTATION_REQUIRED")?; let audit_enabled = parse_bool("BUZZ_AUDIT_ENABLED", true)?; + let workflow_agent_mentions = parse_workflow_agent_mentions()?; let join_policy = if terms_markdown.is_none() && privacy_markdown.is_none() && !age_attestation_required @@ -1553,6 +1576,7 @@ impl Config { media_max_concurrent_uploads_per_pubkey, media_uploads_per_minute, audit_enabled, + workflow_agent_mentions, ephemeral_ttl_override, git_repo_path, git_pack_cache_path, @@ -2669,6 +2693,32 @@ mod tests { } } + #[test] + fn workflow_agent_mentions_defaults_to_any_and_rejects_other_values() { + use buzz_workflow::AgentMentions; + const NAME: &str = "BUZZ_WORKFLOW_AGENT_MENTIONS"; + let _guards = env_guards(); + let previous = std::env::var_os(NAME); + std::env::remove_var(NAME); + assert_eq!(parse_workflow_agent_mentions().unwrap(), AgentMentions::Any); + std::env::set_var(NAME, "any"); + assert_eq!(parse_workflow_agent_mentions().unwrap(), AgentMentions::Any); + std::env::set_var(NAME, "owner"); + assert_eq!( + parse_workflow_agent_mentions().unwrap(), + AgentMentions::Owner + ); + for invalid in ["true", "", "OWNER"] { + std::env::set_var(NAME, invalid); + assert!(parse_workflow_agent_mentions().is_err(), "{invalid:?}"); + } + if let Some(value) = previous { + std::env::set_var(NAME, value); + } else { + std::env::remove_var(NAME); + } + } + #[test] fn audit_logging_rejects_invalid_boolean() { let _guards = env_guards(); diff --git a/crates/buzz-relay/src/handlers/command_executor.rs b/crates/buzz-relay/src/handlers/command_executor.rs index 14559007e3..6ffa7204a1 100644 --- a/crates/buzz-relay/src/handlers/command_executor.rs +++ b/crates/buzz-relay/src/handlers/command_executor.rs @@ -958,6 +958,7 @@ async fn handle_workflow_trigger( workflow_id, Some(&event_id_bytes), trigger_ctx_json.as_ref(), + &buzz_db::workflow::RunCause::Manual(self_bytes.clone()), ) .await .map_err(|e| IngestError::Internal(format!("error: db create_workflow_run: {e}")))?; @@ -997,14 +998,12 @@ async fn handle_workflow_trigger( } }; - let result = buzz_workflow::executor::execute_from_step( + let result = buzz_workflow::executor::execute_run( &engine, community_id, run_id, &def, &trigger_ctx_clone, - 0, - None, ) .await; engine @@ -1310,7 +1309,7 @@ async fn handle_approval_deny( } /// Resume a suspended workflow run after an approval gate has been granted. -async fn resume_workflow_after_approval( +pub(crate) async fn resume_workflow_after_approval( engine: Arc, db: buzz_db::Db, community_id: CommunityId, diff --git a/crates/buzz-relay/src/main.rs b/crates/buzz-relay/src/main.rs index 532207a3db..ab591799fa 100644 --- a/crates/buzz-relay/src/main.rs +++ b/crates/buzz-relay/src/main.rs @@ -666,7 +666,10 @@ async fn run_relay_main(boot: BootTracker) -> anyhow::Result<()> { "Search service ready (Postgres FTS)" ); - let workflow_config = buzz_workflow::WorkflowConfig::default(); + let workflow_config = buzz_workflow::WorkflowConfig { + agent_mentions: config.workflow_agent_mentions, + ..Default::default() + }; let workflow_engine = Arc::new(WorkflowEngine::new(db.clone(), workflow_config)); config @@ -1703,6 +1706,28 @@ mod env_filter_tests { assert!(access.is_empty(), "{access}"); } + #[test] + fn withheld_agent_mentions_log_under_default_filters() { + let example = + std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/../../.env.example")) + .unwrap(); + let example = example + .lines() + .find_map(|line| line.strip_prefix("RUST_LOG=")) + .unwrap() + .to_owned(); + for filter in [log_filter(None), log_filter(Some(&example))] { + let logs = logged(filter, || { + tracing::info!(target: buzz_workflow::AGENT_MENTIONS_LOG_TARGET, "withheld"); + tracing::info!(target: "buzz_workflow::executor", "workflow-noise"); + }); + assert!( + logs.contains("withheld") && !logs.contains("workflow-noise"), + "{logs}" + ); + } + } + #[test] fn explicit_filters_replace_the_defaults() { let off = logged( diff --git a/crates/buzz-relay/src/nip11.rs b/crates/buzz-relay/src/nip11.rs index 6c1eee3aba..e58ec30096 100644 --- a/crates/buzz-relay/src/nip11.rs +++ b/crates/buzz-relay/src/nip11.rs @@ -88,6 +88,9 @@ pub struct RelayInfo { /// Absent when the relay is in `Off` mode. [FI-TRACE-DISCOVERY-PRIVATE] #[serde(skip_serializing_if = "Option::is_none")] pub federated_identity: Option, + /// Which workflow runs may direct agents (`any` or `owner`). Relay-wide, + /// and always sent, so a missing field means an older relay. + pub workflow_agent_mentions: buzz_workflow::AgentMentions, } /// Private read-state accessory contract and enforced client request limits. @@ -326,6 +329,7 @@ impl RelayInfo { relay_self: relay_self.map(|s| s.to_string()), federated_identity, requires_nip_fi: false, + workflow_agent_mentions: buzz_workflow::AgentMentions::Any, } } } @@ -472,6 +476,7 @@ pub(crate) async fn nip11_document( state.config.klipy.as_ref().map(|_| "klipy"), ); info.requires_nip_fi = policy.required; + info.workflow_agent_mentions = state.config.workflow_agent_mentions; info.artifacts["incremental"] = crate::api::artifact_sync::capability(); if let Some(tenant) = tenant.as_ref() { if let Some(profile) = crate::verified_profiles::discovery(state, tenant).await { @@ -651,6 +656,35 @@ mod tests { assert_eq!(docs[2], docs[1]); } + #[tokio::test] + async fn advertises_the_relay_wide_workflow_agent_mentions_mode() { + use buzz_workflow::AgentMentions; + let base = crate::state::tests::test_state_with_unreachable_database_url( + "postgres://127.0.0.1:1/none", + ) + .await; + base.tenant_host_cache.insert( + "relay.example".into(), + ( + buzz_core::CommunityId::from_uuid(uuid::Uuid::nil()), + std::time::Instant::now(), + ), + ); + for (mode, wire) in [(AgentMentions::Any, "any"), (AgentMentions::Owner, "owner")] { + let mut state = (*base).clone(); + let mut config = (*state.config).clone(); + config.workflow_agent_mentions = mode; + state.config = std::sync::Arc::new(config); + let document = serde_json::to_value( + super::nip11_document(&state, "relay.example") + .await + .unwrap(), + ) + .unwrap(); + assert_eq!(document["workflow_agent_mentions"], wire); + } + } + use super::*; #[test] diff --git a/crates/buzz-relay/src/push_runtime.rs b/crates/buzz-relay/src/push_runtime.rs index d44245cd41..f4e614f009 100644 --- a/crates/buzz-relay/src/push_runtime.rs +++ b/crates/buzz-relay/src/push_runtime.rs @@ -1222,11 +1222,13 @@ mod postgres_tests { &channel.to_string(), text, text, + true, &owner.public_key().to_hex(), None, ) .await - .expect("send workflow message"); + .expect("send workflow message") + .event_id; let stored = state .db .get_event_by_id( diff --git a/crates/buzz-relay/src/workflow_sink.rs b/crates/buzz-relay/src/workflow_sink.rs index 4994bfcd14..21b050b411 100644 --- a/crates/buzz-relay/src/workflow_sink.rs +++ b/crates/buzz-relay/src/workflow_sink.rs @@ -10,7 +10,7 @@ use std::sync::{Arc, Weak}; use buzz_core::kind::KIND_STREAM_MESSAGE; use buzz_core::tenant::CommunityId; -use buzz_workflow::action_sink::{ActionSink, ActionSinkError}; +use buzz_workflow::action_sink::{ActionSink, ActionSinkError, SentMessage}; use chrono::Utc; use nostr::{EventBuilder, Kind, Tag}; use tracing::info; @@ -149,33 +149,41 @@ fn resolve_mention_pubkeys(text: &str, members: &[(String, String)]) -> Vec, rendered_text: &str, authored_text: &str, + may_direct_agents: bool, members: &[(String, String)], -) -> Result<(), ActionSinkError> { +) -> Result { let rendered_mentions = resolve_mention_pubkeys(rendered_text, members); let authored_mentions: std::collections::HashSet = resolve_mention_pubkeys(authored_text, members) .into_iter() .collect(); + let mut withheld = false; for mentioned in rendered_mentions { tags.push( Tag::parse(["p", &mentioned]) .map_err(|e| ActionSinkError::EventBuild(format!("mention p tag: {e}")))?, ); - if authored_mentions.contains(&mentioned) { - tags.push( - Tag::parse(["buzz:workflow-mention", &mentioned]).map_err(|e| { - ActionSinkError::EventBuild(format!("workflow mention tag: {e}")) - })?, - ); + if !authored_mentions.contains(&mentioned) { + continue; } + if !may_direct_agents { + withheld = true; + continue; + } + tags.push( + Tag::parse(["buzz:workflow-mention", &mentioned]) + .map_err(|e| ActionSinkError::EventBuild(format!("workflow mention tag: {e}")))?, + ); } - Ok(()) + Ok(withheld) } /// Relay-side action sink — executes workflow side-effects directly. @@ -206,9 +214,10 @@ impl ActionSink for RelayActionSink { channel_id: &str, text: &str, authored_text: &str, + may_direct_agents: bool, author_pubkey: &str, reply_to: Option<&str>, - ) -> Pin> + Send + '_>> { + ) -> Pin> + Send + '_>> { let channel_id = channel_id.to_owned(); let text = text.to_owned(); let authored_text = authored_text.to_owned(); @@ -327,7 +336,10 @@ impl ActionSink for RelayActionSink { // - one `buzz:workflow-mention` tag only when the same target was // named in the workflow owner's stored step template. This is the // authority-bearing provenance used by ACP; trigger-controlled - // template substitutions cannot create it. + // template substitutions cannot create it. Under owner-only agent mentions, the + // executor passes `may_direct_agents = false` when the run's + // cause or definition may not direct agents, so no such tag is + // added; the plain `p` tags are still published. let mut tags = vec![ Tag::parse(["p", &author_pubkey_hex, "", "owner"]) .map_err(|e| ActionSinkError::EventBuild(format!("p tag: {e}")))?, @@ -409,7 +421,13 @@ impl ActionSink for RelayActionSink { Some((name, nostr::PublicKey::from_slice(&u.pubkey).ok()?.to_hex())) }) .collect(); - append_workflow_mention_tags(&mut tags, &text, &authored_text, &named_members)?; + let agent_mentions_withheld = append_workflow_mention_tags( + &mut tags, + &text, + &authored_text, + may_direct_agents, + &named_members, + )?; let kind = Kind::from(KIND_STREAM_MESSAGE as u16); let event = EventBuilder::new(kind, &text) @@ -499,7 +517,10 @@ impl ActionSink for RelayActionSink { } } - Ok(event_id_hex) + Ok(SentMessage { + event_id: event_id_hex, + agent_mentions_withheld, + }) }) } } @@ -709,6 +730,7 @@ mod tests { &mut tags, "@First then @Second", "@First then @Second", + true, &members, ) .expect("append mention tags"); @@ -736,13 +758,18 @@ mod tests { let members = vec![m("Agent", &agent)]; let mut tags = vec![Tag::parse(["p", owner.as_str(), "", "owner"]).expect("owner p tag")]; - append_workflow_mention_tags( + let withheld = append_workflow_mention_tags( &mut tags, "echo: @Agent do something unsafe", "echo: {{trigger.text}}", + false, &members, ) .expect("append mention tags"); + assert!( + !withheld, + "a substituted mention was never eligible to withhold" + ); assert!( tags.iter() @@ -763,8 +790,14 @@ mod tests { let attribution = Tag::parse(["p", owner.as_str(), "", "owner"]).expect("owner p tag"); let mut tags = vec![attribution.clone()]; - append_workflow_mention_tags(&mut tags, "@Owner Agent run", "@Owner Agent run", &members) - .expect("append owner mention tag"); + append_workflow_mention_tags( + &mut tags, + "@Owner Agent run", + "@Owner Agent run", + true, + &members, + ) + .expect("append owner mention tag"); assert_eq!( tags, @@ -777,13 +810,36 @@ mod tests { ); } + #[test] + fn withheld_authority_keeps_legacy_mention_tags() { + let owner = pk('1'); + let agent = pk('2'); + let members = vec![m("Agent", &agent)]; + let mut tags = vec![Tag::parse(["p", owner.as_str(), "", "owner"]).expect("owner p tag")]; + + let withheld = + append_workflow_mention_tags(&mut tags, "@Agent go", "@Agent go", false, &members) + .expect("append mention tags"); + assert!(withheld, "the authored mention lost its authority tag"); + + assert_eq!( + tags, + vec![ + Tag::parse(["p", owner.as_str(), "", "owner"]).expect("owner p tag"), + Tag::parse(["p", agent.as_str()]).expect("mention p tag"), + ], + "an ineligible message still notifies but cannot direct the agent" + ); + } + #[test] fn no_mentions_adds_no_tags() { let owner = pk('1'); let mut tags = vec![Tag::parse(["p", owner.as_str(), "", "owner"]).expect("owner p tag")]; - append_workflow_mention_tags(&mut tags, "plain", "plain", &[]) + let withheld = append_workflow_mention_tags(&mut tags, "plain", "plain", false, &[]) .expect("append no mention tags"); + assert!(!withheld); assert_eq!(tags.len(), 1); assert_eq!(tags[0].as_slice(), ["p", owner.as_str(), "", "owner"]); @@ -807,6 +863,12 @@ mod postgres_tests { /// Real-PG state mirroring `handlers::event::tests::test_state_with_redis_url`. async fn test_state() -> Arc { + test_state_with_agent_mentions(buzz_workflow::AgentMentions::Any).await + } + + async fn test_state_with_agent_mentions( + agent_mentions: buzz_workflow::AgentMentions, + ) -> Arc { let mut config = crate::config::Config::for_test(); // [FI-TRACE-ENV-RACE] config.require_relay_membership = false; config.redis_url = "redis://127.0.0.1:1".to_string(); @@ -823,7 +885,10 @@ mod postgres_tests { let search = buzz_search::SearchService::new(pool.clone()); let workflow_engine = Arc::new(buzz_workflow::WorkflowEngine::new( db.clone(), - buzz_workflow::WorkflowConfig::default(), + buzz_workflow::WorkflowConfig { + agent_mentions, + ..Default::default() + }, )); let media_storage = buzz_media::MediaStorage::new(&config.media).expect("media storage"); let (state, _audit_shutdown) = AppState::new( @@ -860,6 +925,37 @@ mod postgres_tests { }], "enabled": true, }); + run_workflow( + state, + community, + channel_id, + owner_pubkey, + definition, + trigger_text, + Some(&buzz_db::workflow::RunCause::Event(owner_pubkey.to_vec())), + ) + .await + } + + /// Store `definition` and create a run with `cause` (`None` writes a + /// legacy row with no cause). Returns the workflow and run ids, the run's + /// trigger context and the definition as loaded back from Postgres, which + /// pins the authority source to the durable owner-authored template. + async fn create_run( + state: &Arc, + community: CommunityId, + channel_id: Uuid, + owner_pubkey: &[u8], + definition: serde_json::Value, + trigger_text: &str, + cause: Option<&buzz_db::workflow::RunCause>, + ) -> ( + Uuid, + Uuid, + buzz_workflow::executor::TriggerContext, + buzz_workflow::WorkflowDef, + ) { + let name = definition["name"].as_str().expect("name").to_owned(); let definition_hash_byte = name.as_bytes().first().copied().unwrap_or_default(); let workflow_id = state .db @@ -867,7 +963,7 @@ mod postgres_tests { community, Some(channel_id), owner_pubkey, - name, + &name, &definition.to_string(), &[definition_hash_byte; 32], ) @@ -881,13 +977,26 @@ mod postgres_tests { let trigger_ctx_json = serde_json::to_value(&trigger_ctx).expect("serialize trigger"); let run_id = state .db - .create_workflow_run(community, workflow_id, None, Some(&trigger_ctx_json)) + .create_workflow_run( + community, + workflow_id, + None, + Some(&trigger_ctx_json), + cause.unwrap_or(&buzz_db::workflow::RunCause::Webhook), + ) .await .expect("create workflow run"); - - // Load the definition back from Postgres before execution. This pins the - // authority source to the durable owner-authored template rather than a - // second test-only string passed directly to RelayActionSink. + if cause.is_none() { + sqlx::query( + "UPDATE workflow_runs SET cause_source = NULL, cause_pubkey = NULL \ + WHERE community_id = $1 AND id = $2", + ) + .bind(community.as_uuid()) + .bind(run_id) + .execute(state.db.pool()) + .await + .expect("clear cause to model a legacy run"); + } let stored_workflow = state .db .get_workflow(community, workflow_id) @@ -895,20 +1004,66 @@ mod postgres_tests { .expect("load stored workflow"); let stored_definition: buzz_workflow::WorkflowDef = serde_json::from_value(stored_workflow.definition).expect("parse stored definition"); + (workflow_id, run_id, trigger_ctx, stored_definition) + } + + /// Create a run as [`create_run`] does, execute it from the start and + /// return the `send` step's event id. + async fn run_workflow( + state: &Arc, + community: CommunityId, + channel_id: Uuid, + owner_pubkey: &[u8], + definition: serde_json::Value, + trigger_text: &str, + cause: Option<&buzz_db::workflow::RunCause>, + ) -> String { + run_workflow_send_output( + state, + community, + channel_id, + owner_pubkey, + definition, + trigger_text, + cause, + ) + .await["event_id"] + .as_str() + .expect("send_message event id") + .to_owned() + } + + /// Runs a workflow and returns its `send` step's recorded output. + async fn run_workflow_send_output( + state: &Arc, + community: CommunityId, + channel_id: Uuid, + owner_pubkey: &[u8], + definition: serde_json::Value, + trigger_text: &str, + cause: Option<&buzz_db::workflow::RunCause>, + ) -> serde_json::Value { + let (_, run_id, trigger_ctx, definition) = create_run( + state, + community, + channel_id, + owner_pubkey, + definition, + trigger_text, + cause, + ) + .await; let result = buzz_workflow::executor::execute_run( &state.workflow_engine, community, run_id, - &stored_definition, + &definition, &trigger_ctx, ) .await .expect("execute workflow"); - result.step_outputs["send"]["event_id"] - .as_str() - .expect("send_message event id") - .to_owned() + result.step_outputs["send"].clone() } #[tokio::test] @@ -1122,11 +1277,13 @@ mod postgres_tests { &channel.id.to_string(), "root message", "root message", + true, &author_hex, None, ) .await - .expect("send root"); + .expect("send root") + .event_id; // 2. A reply_in_thread message threads onto it. let reply_hex = sink @@ -1135,11 +1292,13 @@ mod postgres_tests { &channel.id.to_string(), "threaded reply", "threaded reply", + true, &author_hex, Some(&root_hex), ) .await - .expect("send reply"); + .expect("send reply") + .event_id; // A direct reply carries a single NIP-10 reply e-tag at the root (no // root marker), matching SDK `thread_tags`. @@ -1279,11 +1438,13 @@ mod postgres_tests { &channel_hex, "workflow reply", "workflow reply", + true, &author_hex, Some(&parent_hex), ) .await - .expect("send reply"); + .expect("send reply") + .event_id; let reply_id_bytes = nostr::EventId::from_hex(&reply_hex) .expect("reply id") @@ -1361,11 +1522,13 @@ mod postgres_tests { &channel_hex, "workflow reply to root-only parent", "workflow reply to root-only parent", + true, &author_hex, Some(&root_only_parent_hex), ) .await - .expect("send root-only reply"); + .expect("send root-only reply") + .event_id; let root_only_reply_bytes = nostr::EventId::from_hex(&root_only_reply_hex) .expect("reply id") .as_bytes() @@ -1511,6 +1674,7 @@ mod postgres_tests { &channel.id.to_string(), "orphan reply", "orphan reply", + true, &author_hex, Some(&unknown), ) @@ -1610,6 +1774,7 @@ mod postgres_tests { &channel, "reply", "reply", + true, &author_hex, Some(&parent), ) @@ -1642,4 +1807,396 @@ mod postgres_tests { .await .expect("owner replies to a parent only they can read"); } + /// With owner-only agent mentions, only runs started by the owner or a + /// timer whose definitions have only `send_message` and `delay` steps + /// carry `buzz:workflow-mention`; the step's trace output records every + /// reason it was withheld. Every message keeps its plain `p` tags. With + /// `any`, every authored mention is stamped as before and nothing is + /// recorded. + #[tokio::test] + #[ignore = "requires Postgres"] + async fn owner_only_agent_mentions_stamp_mentions_only_for_eligible_runs() { + use buzz_db::workflow::RunCause; + + let setup_state = test_state().await; + let owner = nostr::Keys::generate(); + let owner_hex = owner.public_key().to_hex(); + let owner_bytes = owner.public_key().to_bytes().to_vec(); + let outsider_bytes = nostr::Keys::generate().public_key().to_bytes().to_vec(); + let agent = nostr::Keys::generate(); + let agent_hex = agent.public_key().to_hex(); + let agent_bytes = agent.public_key().to_bytes().to_vec(); + + let host = format!("wf-secure-{}.example", uuid::Uuid::new_v4().simple()); + let community = match setup_state + .db + .create_community_with_owner(&host, &owner_hex, &nostr::Keys::generate()) + .await + .map(|write| write.outcome) + .expect("create community") + { + CreateCommunityWithOwnerResult::Created(rec) => rec.id, + other => panic!("expected fresh community, got {other:?}"), + }; + for pubkey in [&owner_bytes, &agent_bytes] { + setup_state + .db + .ensure_user(community, pubkey) + .await + .expect("ensure user row"); + } + let channel = setup_state + .db + .create_channel( + community, + "wf-secure", + ChannelType::Stream, + ChannelVisibility::Open, + None, + &owner.public_key().to_bytes(), + None, + ) + .await + .expect("create channel"); + setup_state + .db + .update_user_profile(community, &agent_bytes, Some("Robby"), None, None, None) + .await + .expect("set agent display name"); + setup_state + .db + .add_member( + community, + channel.id, + &agent_bytes, + MemberRole::Bot, + Some(&owner_bytes), + ) + .await + .expect("add agent member"); + // Two members share a name, so `@Twin` resolves to nobody. + for _ in 0..2 { + let twin = nostr::Keys::generate().public_key().to_bytes().to_vec(); + setup_state + .db + .ensure_user(community, &twin) + .await + .expect("ensure twin user row"); + setup_state + .db + .update_user_profile(community, &twin, Some("Twin"), None, None, None) + .await + .expect("set twin display name"); + setup_state + .db + .add_member( + community, + channel.id, + &twin, + MemberRole::Bot, + Some(&owner_bytes), + ) + .await + .expect("add twin member"); + } + + let send = + serde_json::json!({"id": "send", "action": "send_message", "text": "@Robby review"}); + let delay = serde_json::json!({"id": "wait", "action": "delay", "duration": "1s"}); + // Skipped on every run: the definition is ineligible regardless. + let hook = serde_json::json!({ + "id": "hook", "action": "call_webhook", "url": "https://example.invalid/x", "if": "1 == 2", + }); + let owner_event = RunCause::Event(owner_bytes.clone()); + let outsider_event = RunCause::Event(outsider_bytes.clone()); + let cases = vec![ + ( + "owner-message", + serde_json::json!({"on": "message_posted"}), + vec![send.clone()], + Some(owner_event.clone()), + Vec::<&str>::new(), + ), + ( + "outsider-message", + serde_json::json!({"on": "message_posted"}), + vec![send.clone()], + Some(outsider_event.clone()), + vec!["cause"], + ), + // The reaction signer is the cause, whoever wrote the reacted-to message. + ( + "owner-reaction", + serde_json::json!({"on": "reaction_added"}), + vec![send.clone()], + Some(owner_event.clone()), + Vec::<&str>::new(), + ), + ( + "outsider-reaction", + serde_json::json!({"on": "reaction_added"}), + vec![send.clone()], + Some(outsider_event.clone()), + vec!["cause"], + ), + ( + "owner-diff", + serde_json::json!({"on": "diff_posted"}), + vec![send.clone()], + Some(owner_event.clone()), + Vec::<&str>::new(), + ), + ( + "outsider-diff", + serde_json::json!({"on": "diff_posted"}), + vec![send.clone()], + Some(outsider_event.clone()), + vec!["cause"], + ), + ( + "webhook", + serde_json::json!({"on": "webhook"}), + vec![send.clone()], + Some(RunCause::Webhook), + vec!["cause"], + ), + ( + "cron", + serde_json::json!({"on": "schedule", "cron": "0 * * * *"}), + vec![send.clone(), delay.clone()], + Some(RunCause::Schedule), + Vec::<&str>::new(), + ), + ( + "interval", + serde_json::json!({"on": "schedule", "interval": "1h"}), + vec![send.clone()], + Some(RunCause::Schedule), + Vec::<&str>::new(), + ), + ( + "manual-schedule", + serde_json::json!({"on": "schedule", "cron": "0 * * * *"}), + vec![send.clone()], + Some(RunCause::Manual(owner_bytes.clone())), + Vec::<&str>::new(), + ), + ( + "call-webhook", + serde_json::json!({"on": "message_posted"}), + vec![hook.clone(), send.clone()], + Some(owner_event.clone()), + vec!["steps"], + ), + ( + "legacy", + serde_json::json!({"on": "message_posted"}), + vec![send.clone()], + None, + vec!["cause"], + ), + ]; + + // Whether the stored message carries the agent's plain `p` tag and its + // `buzz:workflow-mention` tag. + async fn agent_tags( + state: &Arc, + community: CommunityId, + event_id_hex: &str, + agent_hex: &str, + ) -> (bool, bool) { + let id_bytes = nostr::EventId::from_hex(event_id_hex) + .expect("event id") + .as_bytes() + .to_vec(); + let stored = state + .db + .get_event_by_id_for_event_write(community, &id_bytes) + .await + .expect("query event") + .expect("event persisted"); + let has_tag = |tag_name: &str| { + stored + .event + .tags + .iter() + .any(|tag| tag.as_slice() == [tag_name, agent_hex]) + }; + (has_tag("p"), has_tag("buzz:workflow-mention")) + } + + for secure in [false, true] { + let state = test_state_with_agent_mentions(if secure { + buzz_workflow::AgentMentions::Owner + } else { + buzz_workflow::AgentMentions::Any + }) + .await; + state + .workflow_engine + .set_action_sink(Arc::new(RelayActionSink::new(&state))); + for (name, trigger, steps, cause, reasons) in &cases { + let definition = serde_json::json!({ + "name": format!("{name}-{secure}"), + "trigger": trigger, + "steps": steps, + "enabled": true, + }); + let output = run_workflow_send_output( + &state, + community, + channel.id, + &owner_bytes, + definition, + "trigger text", + cause.as_ref(), + ) + .await; + let withheld = secure && !reasons.is_empty(); + let event_id_hex = output["event_id"].as_str().expect("send_message event id"); + assert_eq!( + agent_tags(&state, community, event_id_hex, &agent_hex).await, + (true, !withheld), + "{name} (secure={secure}): (p, workflow-mention)" + ); + let expected_trace = + withheld.then(|| serde_json::json!({"withheld": true, "reasons": reasons})); + assert_eq!( + output.get("agent_mentions").cloned(), + expected_trace, + "{name} (secure={secure}): trace agent_mentions" + ); + } + + // An ineligible run reports nothing when no authored mention + // would have been stamped: there was no tag to withhold. + for (name, text, trigger_text) in [ + ("no-mention", "Build completed", "trigger text"), + ("substituted-mention", "echo: {{trigger.text}}", "@Robby go"), + ("unresolved-mention", "@Nobody review", "trigger text"), + ("ambiguous-mention", "@Twin review", "trigger text"), + ] { + let definition = serde_json::json!({ + "name": format!("{name}-{secure}"), + "trigger": {"on": "message_posted"}, + "steps": [{"id": "send", "action": "send_message", "text": text}], + "enabled": true, + }); + let output = run_workflow_send_output( + &state, + community, + channel.id, + &owner_bytes, + definition, + trigger_text, + Some(&outsider_event), + ) + .await; + assert_eq!( + output.get("agent_mentions"), + None, + "{name} (secure={secure}): nothing withheld, nothing reported" + ); + let event_id_hex = output["event_id"].as_str().expect("send_message event id"); + assert!( + !agent_tags(&state, community, event_id_hex, &agent_hex) + .await + .1, + "{name} (secure={secure}): no workflow-mention for the agent" + ); + } + + // Approval resume. The owner caused the run, and the current + // definition has only allowed steps: the owner may have edited it + // while the run waited. The run resumes through the real resume + // path on output restored from before the approval. A fresh run + // of the same definition is the positive control. + let definition = serde_json::json!({ + "name": format!("approval-resume-{secure}"), + "trigger": {"on": "message_posted"}, + "steps": [ + {"id": "approve", "action": "delay", "duration": "1s"}, + {"id": "send", "action": "send_message", "text": "@Robby {{steps.approve.output.note}}"}, + ], + "enabled": true, + }); + let (workflow_id, run_id, _, _) = create_run( + &state, + community, + channel.id, + &owner_bytes, + definition.clone(), + "trigger text", + Some(&owner_event), + ) + .await; + state + .db + .update_workflow_run( + community, + run_id, + buzz_db::workflow::RunStatus::WaitingApproval, + 1, + &serde_json::json!([ + {"step_id": "approve", "status": "completed", "output": {"note": "restored"}}, + ]), + None, + ) + .await + .expect("park run waiting for approval"); + crate::handlers::command_executor::resume_workflow_after_approval( + Arc::clone(&state.workflow_engine), + state.db.clone(), + community, + run_id, + workflow_id, + 1, + ) + .await; + let resumed = state + .db + .get_workflow_run(community, run_id) + .await + .expect("load resumed run"); + let resumed_output = resumed + .execution_trace + .as_array() + .and_then(|trace| trace.iter().find(|entry| entry["step_id"] == "send")) + .map(|entry| entry["output"].clone()) + .unwrap_or_else(|| panic!("resumed run posted: {:?}", resumed.execution_trace)); + // The persisted run trace, which the app's run history shows. + assert_eq!( + resumed_output.get("agent_mentions").cloned(), + secure.then(|| serde_json::json!({"withheld": true, "reasons": ["resumed"]})), + "approval resume (secure={secure}): trace agent_mentions" + ); + let resumed_event_id = resumed_output["event_id"] + .as_str() + .expect("resumed send_message event id") + .to_owned(); + assert_eq!( + agent_tags(&state, community, &resumed_event_id, &agent_hex).await, + (true, !secure), + "approval resume (secure={secure}): (p, workflow-mention)" + ); + + let mut fresh = definition; + fresh["name"] = serde_json::json!(format!("approval-fresh-{secure}")); + let fresh_event_id = run_workflow( + &state, + community, + channel.id, + &owner_bytes, + fresh, + "trigger text", + Some(&owner_event), + ) + .await; + assert_eq!( + agent_tags(&state, community, &fresh_event_id, &agent_hex).await, + (true, true), + "fresh run of the same definition (secure={secure}): (p, workflow-mention)" + ); + } + } } diff --git a/crates/buzz-workflow/Cargo.toml b/crates/buzz-workflow/Cargo.toml index 25e2294cf5..84fcd382c6 100644 --- a/crates/buzz-workflow/Cargo.toml +++ b/crates/buzz-workflow/Cargo.toml @@ -12,6 +12,7 @@ buzz-core = { workspace = true } buzz-db = { workspace = true } buzz-deletion = { workspace = true } hex = { workspace = true } +metrics = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } serde_yaml = { workspace = true } diff --git a/crates/buzz-workflow/src/action_sink.rs b/crates/buzz-workflow/src/action_sink.rs index b8c7f4dd80..6607ce7ee6 100644 --- a/crates/buzz-workflow/src/action_sink.rs +++ b/crates/buzz-workflow/src/action_sink.rs @@ -37,6 +37,16 @@ impl From for crate::WorkflowError { } } +/// A message an [`ActionSink`] posted. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SentMessage { + /// Hex event ID. + pub event_id: String, + /// Whether at least one agent-authority tag was left off because the run + /// may not direct agents. + pub agent_mentions_withheld: bool, +} + /// Interface for workflow actions that produce side effects. /// /// Implemented by the relay to provide direct DB/event access to the executor. @@ -55,23 +65,28 @@ pub trait ActionSink: Send + Sync { /// even though the side effect has no inbound connection to bind. /// - `channel_id`: UUID string of the target channel /// - `text`: rendered message body (must not be empty/whitespace-only) - /// - `authored_text`: the workflow owner's stored, unrendered step template; - /// consumers must use this rather than trigger-controlled rendered output - /// when attaching authority-bearing metadata + /// - `authored_text`: the workflow owner's stored, unrendered step + /// template. Consumers attach authority-bearing metadata only for + /// targets named in this text, never from trigger-controlled rendered + /// output alone. + /// - `may_direct_agents`: whether this run may attach that metadata; when + /// `false`, the consumer withholds it. /// - `author_pubkey`: hex-encoded pubkey of the workflow owner (used for /// the `p` attribution tag; the relay keypair signs the event) /// - `reply_to`: when `Some(event_id_hex)`, the message is posted as a /// threaded reply to that event (NIP-10 root/reply tags + real thread /// metadata); when `None`, it is a top-level channel message. /// - /// Returns the event ID hex string on success. + /// Returns the sent message on success. + #[allow(clippy::too_many_arguments)] fn send_message( &self, community_id: CommunityId, channel_id: &str, text: &str, authored_text: &str, + may_direct_agents: bool, author_pubkey: &str, reply_to: Option<&str>, - ) -> Pin> + Send + '_>>; + ) -> Pin> + Send + '_>>; } diff --git a/crates/buzz-workflow/src/executor.rs b/crates/buzz-workflow/src/executor.rs index 0fe33033bb..eae10044be 100644 --- a/crates/buzz-workflow/src/executor.rs +++ b/crates/buzz-workflow/src/executor.rs @@ -12,6 +12,9 @@ use std::collections::HashMap; use buzz_core::tenant::CommunityId; +use buzz_db::workflow::RunCause; + +use crate::AgentMentions; use evalexpr::HashMapContext; use nostr::ToBech32; use serde_json::Value as JsonValue; @@ -527,6 +530,53 @@ fn resolve_send_message_channel( Ok(trigger_channel.trim().to_string()) } +/// Whether every step of `def` is an action that takes no input from outside +/// the owner's control. An allowlist: any other action, including one added +/// later, makes the definition ineligible to direct agents. +pub fn definition_may_direct_agents(def: &WorkflowDef) -> bool { + def.steps.iter().all(|step| { + matches!( + step.action, + ActionDef::SendMessage { .. } | ActionDef::Delay { .. } + ) + }) +} + +/// Whether a run's recorded cause lets its messages direct the owner's agents: +/// a timer, or an event or manual trigger signed by the owner. Webhook calls +/// and runs with no recorded cause never qualify. +pub fn cause_may_direct_agents(cause: Option<&RunCause>, owner_pubkey: &[u8]) -> bool { + match cause { + Some(RunCause::Schedule) => true, + Some(RunCause::Event(pubkey) | RunCause::Manual(pubkey)) => pubkey == owner_pubkey, + Some(RunCause::Webhook) | None => false, + } +} + +/// Why a `send_message` step withholds `buzz:workflow-mention` tags, in the +/// order recorded in its trace: `cause` (not started by the owner or a timer), +/// `steps` (the definition has a step other than `send_message` or `delay`), +/// and `resumed` (the run resumed after an approval). Empty when the message +/// may direct agents, which is always the case in [`AgentMentions::Any`]. +pub fn agent_mentions_withheld_reasons( + mode: AgentMentions, + cause_may_direct_agents: bool, + definition_may_direct_agents: bool, + resumed: bool, +) -> Vec<&'static str> { + if mode == AgentMentions::Any { + return Vec::new(); + } + [ + (!cause_may_direct_agents, "cause"), + (!definition_may_direct_agents, "steps"), + (resumed, "resumed"), + ] + .into_iter() + .filter_map(|(applies, reason)| applies.then_some(reason)) + .collect() +} + /// Dispatch a resolved action and return its output. /// /// For MVP, most actions log their intent and return a success output. @@ -534,6 +584,7 @@ fn resolve_send_message_channel( /// /// `RequestApproval` returns `StepResult::Suspended` — the caller must /// persist state and stop the execution loop. +#[allow(clippy::too_many_arguments)] pub async fn dispatch_action( step: &Step, action: &ActionDef, @@ -541,6 +592,8 @@ pub async fn dispatch_action( community_id: CommunityId, run_id: Uuid, trigger_ctx: &TriggerContext, + definition_may_direct_agents: bool, + resumed: bool, ) -> Result { use ActionDef::*; @@ -600,6 +653,12 @@ pub async fn dispatch_action( workflow.channel_id, )?; let owner_pubkey_hex = hex::encode(&workflow.owner_pubkey); + let withheld_reasons = agent_mentions_withheld_reasons( + engine.config.agent_mentions, + cause_may_direct_agents(wf_run.cause.as_ref(), &workflow.owner_pubkey), + definition_may_direct_agents, + resumed, + ); // Thread the reply onto the triggering message when requested. // The trigger must carry the event to reply to; schema @@ -633,23 +692,47 @@ pub async fn dispatch_action( )); } }; - let event_id = engine + let sent = engine .action_sink()? .send_message( community_id, &channel_id, text, authored_text, + withheld_reasons.is_empty(), &owner_pubkey_hex, reply_to, ) .await .map_err(WorkflowError::from)?; - Ok(StepResult::Completed(serde_json::json!({ + let mut output = serde_json::json!({ "sent": true, - "event_id": event_id, - }))) + "event_id": sent.event_id, + }); + if sent.agent_mentions_withheld { + info!( + target: crate::AGENT_MENTIONS_LOG_TARGET, + community = %community_id, + workflow = %wf_run.workflow_id, + run_id = %run_id, + step = step_id, + reasons = ?withheld_reasons, + "owner-only agent mentions withheld buzz:workflow-mention tags" + ); + for reason in &withheld_reasons { + metrics::counter!( + "buzz_workflow_agent_mentions_withheld_total", + "reason" => *reason + ) + .increment(1); + } + output["agent_mentions"] = serde_json::json!({ + "withheld": true, + "reasons": withheld_reasons, + }); + } + Ok(StepResult::Completed(output)) } SendDm { to, text: _ } => { @@ -1093,10 +1176,11 @@ pub async fn execute_run( ) })?; - execute_steps(engine, community_id, run_id, def, trigger_ctx, 0, None).await + execute_steps(engine, community_id, run_id, def, trigger_ctx, None).await } -/// Resume execution from a specific step index (used for approval resume). +/// Resume a run after its approval was granted, from a specific step index. +/// With owner-only agent mentions, messages from a resumed run never direct agents. /// /// Acquires a concurrency permit from `engine.run_semaphore` before executing — /// returns [`WorkflowError::CapacityExceeded`] immediately if all permits are @@ -1161,13 +1245,13 @@ pub async fn execute_from_step( run_id, def, trigger_ctx, - start_index, - initial_outputs, + Some((start_index, initial_outputs.unwrap_or_default())), ) .await } -/// Internal: execute workflow steps starting from `start_index`, without +/// Internal: execute workflow steps from the start, or from `resume`'s step +/// index with its restored outputs, without /// acquiring the semaphore. Called by both [`execute_run`] and /// [`execute_from_step`] after they have already acquired a permit. /// @@ -1179,10 +1263,13 @@ async fn execute_steps( run_id: Uuid, def: &WorkflowDef, trigger_ctx: &TriggerContext, - start_index: usize, - initial_outputs: Option>, + resume: Option<(usize, HashMap)>, ) -> Result { - let mut step_outputs: HashMap = initial_outputs.unwrap_or_default(); + // A resumed run continues on restored outputs and on a definition that + // may have changed since the approval, so it never directs agents. + let resumed = resume.is_some(); + let definition_may_direct_agents = definition_may_direct_agents(def); + let (start_index, mut step_outputs) = resume.unwrap_or_default(); let mut trace: Vec = Vec::new(); for (i, step) in def.steps.iter().enumerate() { @@ -1243,6 +1330,8 @@ async fn execute_steps( community_id, run_id, trigger_ctx, + definition_may_direct_agents, + resumed, ), ) .await; @@ -1983,4 +2072,93 @@ mod tests { .expect("override should be accepted"); assert_eq!(resolved, override_channel_id.to_string()); } + fn def_with_steps(steps: &str) -> WorkflowDef { + crate::WorkflowEngine::parse_yaml(&format!( + "name: eligibility\ntrigger:\n on: message_posted\nsteps:\n{steps}" + )) + .expect("parse definition") + .0 + } + + #[test] + fn only_send_message_and_delay_definitions_may_direct_agents() { + let send = " - id: send\n action: send_message\n text: '@Agent go'\n"; + let delay = " - id: wait\n action: delay\n duration: 1m\n"; + assert!(definition_may_direct_agents(&def_with_steps(&format!( + "{send}{delay}" + )))); + + // A webhook response can choose fixed text through `if:` without + // contributing any rendered characters; the whole definition is out. + let webhook_selects_text = format!( + " - id: hook\n action: call_webhook\n url: https://example.com/x\n\ + {send} if: steps.hook.output.status == 200\n" + ); + assert!(!definition_may_direct_agents(&def_with_steps( + &webhook_selects_text + ))); + + for other in [ + " - id: approve\n action: request_approval\n from: '@manager'\n message: ok?\n", + " - id: react\n action: add_reaction\n emoji: eyes\n", + " - id: dm\n action: send_dm\n to: '@manager'\n text: hi\n", + " - id: topic\n action: set_channel_topic\n topic: hi\n", + ] { + assert!( + !definition_may_direct_agents(&def_with_steps(&format!("{send}{other}"))), + "{other}" + ); + } + } + + #[test] + fn owner_mode_lists_every_withheld_reason_in_order() { + use AgentMentions::{Any, Owner}; + assert!(agent_mentions_withheld_reasons(Any, false, false, true).is_empty()); + assert!(agent_mentions_withheld_reasons(Owner, true, true, false).is_empty()); + assert_eq!( + agent_mentions_withheld_reasons(Owner, false, true, false), + ["cause"] + ); + assert_eq!( + agent_mentions_withheld_reasons(Owner, true, false, false), + ["steps"] + ); + assert_eq!( + agent_mentions_withheld_reasons(Owner, true, true, true), + ["resumed"] + ); + assert_eq!( + agent_mentions_withheld_reasons(Owner, false, false, true), + ["cause", "steps", "resumed"] + ); + } + + #[test] + fn only_owner_and_timer_causes_may_direct_agents() { + let owner = vec![1u8; 32]; + let other = vec![2u8; 32]; + assert!(cause_may_direct_agents(Some(&RunCause::Schedule), &owner)); + assert!(cause_may_direct_agents( + Some(&RunCause::Event(owner.clone())), + &owner + )); + assert!(cause_may_direct_agents( + Some(&RunCause::Manual(owner.clone())), + &owner + )); + assert!(!cause_may_direct_agents( + Some(&RunCause::Event(other.clone())), + &owner + )); + assert!(!cause_may_direct_agents( + Some(&RunCause::Manual(other)), + &owner + )); + assert!(!cause_may_direct_agents(Some(&RunCause::Webhook), &owner)); + assert!( + !cause_may_direct_agents(None, &owner), + "legacy runs have no cause" + ); + } } diff --git a/crates/buzz-workflow/src/lib.rs b/crates/buzz-workflow/src/lib.rs index 9dabc5732a..625919e20d 100644 --- a/crates/buzz-workflow/src/lib.rs +++ b/crates/buzz-workflow/src/lib.rs @@ -35,11 +35,15 @@ pub mod error; pub mod executor; pub mod schema; -pub use action_sink::{ActionSink, ActionSinkError}; +pub use action_sink::{ActionSink, ActionSinkError, SentMessage}; pub use error::{PartialProgress, WorkflowError}; pub use executor::ExecutionResult; pub use schema::{ActionDef, Step, TriggerDef, WorkflowDef}; +/// Tracing target for withheld agent mentions. It sits under `buzz_relay` so +/// the relay's default log filter shows it without enabling other workflow logs. +pub const AGENT_MENTIONS_LOG_TARGET: &str = "buzz_relay::workflow_agent_mentions"; + use std::collections::HashMap; use std::sync::Arc; use std::sync::OnceLock; @@ -60,6 +64,33 @@ pub struct WorkflowConfig { pub max_concurrent: usize, /// Default per-step timeout in seconds. Default: 300 (5 minutes). pub default_timeout_secs: u64, + /// Which workflow runs may direct agents. Default: [`AgentMentions::Any`]. + pub agent_mentions: AgentMentions, +} + +/// Which workflow runs' messages carry agent-directing `buzz:workflow-mention` +/// tags. Set relay-wide by `BUZZ_WORKFLOW_AGENT_MENTIONS`. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum AgentMentions { + /// Every run may direct the agents its owner's step text names. + #[default] + Any, + /// Owner-only agent mentions: only runs the owner or a timer started, on a + /// definition of only `send_message` and `delay` steps, may direct agents. + Owner, +} + +impl std::str::FromStr for AgentMentions { + type Err = String; + + fn from_str(value: &str) -> Result { + match value { + "any" => Ok(Self::Any), + "owner" => Ok(Self::Owner), + other => Err(format!("expected `any` or `owner`, got `{other}`")), + } + } } impl Default for WorkflowConfig { @@ -67,6 +98,7 @@ impl Default for WorkflowConfig { Self { max_concurrent: 100, default_timeout_secs: 300, + agent_mentions: AgentMentions::Any, } } } @@ -459,6 +491,9 @@ impl WorkflowEngine { workflow.id, Some(&trigger_event_id_bytes), Some(&trigger_ctx_json), + // The signer of the triggering event: for a reaction, the + // reactor, never the author of the reacted-to message. + &buzz_db::workflow::RunCause::Event(event.event.pubkey.to_bytes().to_vec()), ) .await { @@ -723,6 +758,7 @@ impl WorkflowEngine { workflow.id, None, // no trigger event for cron trigger_ctx_json.as_ref(), + &buzz_db::workflow::RunCause::Schedule, ) .await { @@ -1405,6 +1441,7 @@ mod postgres_tests { let cfg = WorkflowConfig::default(); assert_eq!(cfg.max_concurrent, 100); assert_eq!(cfg.default_timeout_secs, 300); + assert_eq!(cfg.agent_mentions, AgentMentions::Any); } #[test] @@ -1626,14 +1663,25 @@ steps: assert!(trigger_matches_event(&trigger, 9)); } + #[test] + fn agent_mentions_parses_only_any_and_owner() { + assert_eq!("any".parse(), Ok(AgentMentions::Any)); + assert_eq!("owner".parse(), Ok(AgentMentions::Owner)); + for invalid in ["", "true", "Owner", "all"] { + assert!(invalid.parse::().is_err(), "{invalid}"); + } + } + #[test] fn workflow_config_custom_values() { let cfg = WorkflowConfig { max_concurrent: 50, default_timeout_secs: 600, + agent_mentions: AgentMentions::Owner, }; assert_eq!(cfg.max_concurrent, 50); assert_eq!(cfg.default_timeout_secs, 600); + assert_eq!(cfg.agent_mentions, AgentMentions::Owner); } fn make_message_event() -> buzz_core::StoredEvent { @@ -2618,4 +2666,127 @@ steps: run.error_message ); } + + /// Every run records what caused it: the signer of the triggering message, + /// reaction or diff (for a reaction, the reactor, not the author of the + /// message reacted to), or the timer for cron and interval schedules. + #[tokio::test] + #[ignore = "requires Postgres"] + async fn runs_record_their_cause() { + use buzz_core::kind::{KIND_REACTION, KIND_STREAM_MESSAGE, KIND_STREAM_MESSAGE_DIFF}; + use buzz_db::workflow::RunCause; + + let db = setup_db().await; + let creator = nostr::Keys::generate().public_key().to_bytes().to_vec(); + let owner = nostr::Keys::generate(); + let outsider = nostr::Keys::generate(); + let owner_bytes = owner.public_key().to_bytes().to_vec(); + let outsider_bytes = outsider.public_key().to_bytes().to_vec(); + let (community, channel_id) = setup_channel(&db, &creator, &owner_bytes).await; + + let mut workflows = Vec::new(); + for (name, trigger) in [ + ("cause-message", serde_json::json!({"on": "message_posted"})), + ( + "cause-reaction", + serde_json::json!({"on": "reaction_added"}), + ), + ("cause-diff", serde_json::json!({"on": "diff_posted"})), + ( + "cause-cron", + serde_json::json!({"on": "schedule", "cron": "* * * * *"}), + ), + ( + "cause-interval", + serde_json::json!({"on": "schedule", "interval": "1m"}), + ), + ] { + let def = serde_json::json!({ + "name": name, + "trigger": trigger, + "steps": [{"id": "s1", "action": "send_message", "text": "hi"}], + "enabled": true, + }); + let id = db + .create_workflow( + community, + Some(channel_id), + &owner_bytes, + name, + &def.to_string(), + &[workflows.len() as u8; 32], + ) + .await + .expect("create workflow"); + workflows.push(id); + } + let [message_wf, reaction_wf, diff_wf, cron_wf, interval_wf] = + <[Uuid; 5]>::try_from(workflows).expect("five workflows created"); + let engine = Arc::new(WorkflowEngine::new(db.clone(), WorkflowConfig::default())); + + let event = |keys: &nostr::Keys, kind: u32, tags: Vec| { + let event = nostr::EventBuilder::new(nostr::Kind::Custom(kind as u16), "+") + .tags(tags) + .sign_with_keys(keys) + .expect("sign"); + buzz_core::StoredEvent::new(event, Some(channel_id)) + }; + let latest_cause = |workflow_id| { + let db = db.clone(); + async move { + db.list_workflow_runs(community, workflow_id, 10) + .await + .expect("list runs") + .into_iter() + .max_by_key(|run| run.created_at) + .expect("a run was created") + .cause + } + }; + + let owner_message = event(&owner, KIND_STREAM_MESSAGE, vec![]); + let outsider_message = event(&outsider, KIND_STREAM_MESSAGE, vec![]); + for (message, signer) in [ + (&owner_message, &owner_bytes), + (&outsider_message, &outsider_bytes), + ] { + engine.on_event(community, message).await.expect("message"); + assert_eq!( + latest_cause(message_wf).await, + Some(RunCause::Event(signer.clone())) + ); + } + + for (reactor, target, signer) in [ + (&owner, &outsider_message, &owner_bytes), + (&outsider, &owner_message, &outsider_bytes), + ] { + let target_tag = nostr::Tag::parse(["e", &target.event.id.to_hex()]).expect("e tag"); + let reaction = event(reactor, KIND_REACTION, vec![target_tag]); + engine + .on_event(community, &reaction) + .await + .expect("reaction"); + assert_eq!( + latest_cause(reaction_wf).await, + Some(RunCause::Event(signer.clone())), + "a reaction's cause is its signer, not the reacted-to author" + ); + } + + let diff = event(&outsider, KIND_STREAM_MESSAGE_DIFF, vec![]); + engine.on_event(community, &diff).await.expect("diff"); + assert_eq!( + latest_cause(diff_wf).await, + Some(RunCause::Event(outsider_bytes.clone())) + ); + + // The first tick fires the cron and seeds the interval anchor; the + // interval fires once a full interval has elapsed. + let now = Utc::now(); + engine.cron_tick(now).await; + assert_eq!(latest_cause(cron_wf).await, Some(RunCause::Schedule)); + engine.cron_tick(now + chrono::Duration::seconds(61)).await; + assert_eq!(latest_cause(interval_wf).await, Some(RunCause::Schedule)); + } } diff --git a/docs/operator-workflow-agent-mentions.md b/docs/operator-workflow-agent-mentions.md new file mode 100644 index 0000000000..35790b8dba --- /dev/null +++ b/docs/operator-workflow-agent-mentions.md @@ -0,0 +1,95 @@ +# Owner-Only Agent Mentions + +A workflow message carries a `buzz:workflow-mention` tag for each agent the +owner's stored step text names. That tag lets the message direct the agent on +the owner's behalf (see "Workflow Mentions" in [NOSTR.md](../NOSTR.md)). +Owner-only agent mentions keep the tag off messages from runs that someone +other than the owner could have steered. + +| Setting | Values | Default | +|---------|--------|---------| +| `BUZZ_WORKFLOW_AGENT_MENTIONS` | `any`, `owner` | `any` | + +Any other value fails startup. With `any`, the relay adds the tags for every +run. With `owner`, a `send_message` step adds them only when the run is +eligible: its cause qualifies and its steps qualify. The setting is +relay-wide: it applies to every community the relay serves. + +## Cause + +The relay records what caused each run when it creates it. + +| Trigger | Cause | Eligible | +|---------|-------|----------| +| Event (message, reaction, diff) | the event's signer; for a reaction, the reactor, not the author of the message reacted to | only if that is the owner | +| Schedule (cron or interval) | the timer | yes | +| Webhook | unknown | never | +| Manual | whoever ran it | only if that is the owner | + +Only the owner or a timer makes a run eligible. The owner's other agents count +as someone else. + +Runs created before causes were recorded have no cause, and are never eligible. + +## Steps + +Every step of the workflow definition must be `send_message` or `delay`. Any +other step makes the run ineligible, even one the run skips. A run that +resumes after an approval is ineligible too. + +## What people see + +An ineligible run's messages still post, with their `p` tags, so mentioned +people are still notified. No agent acts on them. + +When an ineligible run's message names a channel member in the workflow's +stored text, and that name is also in the posted text, the relay leaves off +that member's `buzz:workflow-mention` tag. The step's output in the run's +trace, which the owner sees in the app's run history, then records why: + +```json +{"sent": true, "event_id": "…", "agent_mentions": {"withheld": true, "reasons": ["cause", "steps"]}} +``` + +`reasons` lists every reason that applies, in this order: + +| Reason | Meaning | +|--------|---------| +| `cause` | Neither the owner nor a timer started the run. | +| `steps` | The definition has a step other than `send_message` or `delay`. | +| `resumed` | The run resumed after an approval. | + +The key is absent when no tag was left off: on eligible runs, with `any`, and +for messages with no such mention, such as plain text, a mention that comes +only from substituted text, or a name that matches no member or more than one. + +## Logs and metrics + +Each withheld step logs at info level `owner-only agent mentions withheld +buzz:workflow-mention tags`, with `community`, `workflow`, `run_id`, `step` +and `reasons`. The counter `buzz_workflow_agent_mentions_withheld_total` +increases by one for each reason, labelled `reason` (`cause`, `steps` or +`resumed`), so one step with two reasons counts under both. + +## Discovery + +The NIP-11 relay information document always carries +`"workflow_agent_mentions": "any"` or `"owner"`. A client that finds no field +is talking to a relay older than this setting. + +## When to use `owner` + +When people other than a workflow's owner can trigger it: by posting or +reacting in its channel, or through its webhook. + +## Rollout + +Any pod set to `any` still adds the tags, so the setting protects agents only +once every relay pod runs with `owner`. Keep client-side defenses in +place until then. + +## What it does not cover + +- An agent that acts on a workflow message still reads thread, pull request + and repository text that anyone can write, the same as for a direct mention. +- A replayed workflow message behaves as it does with `any`. diff --git a/migrations/0087_workflow_run_cause.sql b/migrations/0087_workflow_run_cause.sql new file mode 100644 index 0000000000..e32889631d --- /dev/null +++ b/migrations/0087_workflow_run_cause.sql @@ -0,0 +1,14 @@ +SET LOCAL lock_timeout = '5s'; +SET LOCAL statement_timeout = '30s'; + +-- What caused each run. NULL on rows written before these columns existed; +-- such runs are never eligible to direct agents, and neither is a stored +-- source without the pubkey it requires, or with one it forbids. The checks are added NOT VALID +-- so this write-blocking DDL does not scan existing rows; 0088 validates them. +ALTER TABLE workflow_runs + ADD COLUMN cause_source TEXT, + ADD COLUMN cause_pubkey BYTEA, + ADD CONSTRAINT workflow_runs_cause_source_check + CHECK (cause_source IN ('event', 'schedule', 'webhook', 'manual')) NOT VALID, + ADD CONSTRAINT workflow_runs_cause_pubkey_check + CHECK (length(cause_pubkey) = 32) NOT VALID; diff --git a/migrations/0088_validate_workflow_run_cause.sql b/migrations/0088_validate_workflow_run_cause.sql new file mode 100644 index 0000000000..2a38bc6338 --- /dev/null +++ b/migrations/0088_validate_workflow_run_cause.sql @@ -0,0 +1,7 @@ +SET LOCAL lock_timeout = '5s'; +SET LOCAL statement_timeout = '30s'; + +-- Validate separately from the write-blocking DDL transaction. +ALTER TABLE workflow_runs + VALIDATE CONSTRAINT workflow_runs_cause_source_check, + VALIDATE CONSTRAINT workflow_runs_cause_pubkey_check; diff --git a/schema/tables/public/workflow_runs.sql b/schema/tables/public/workflow_runs.sql index 12a51809a7..61d48b0f9e 100644 --- a/schema/tables/public/workflow_runs.sql +++ b/schema/tables/public/workflow_runs.sql @@ -9,12 +9,18 @@ CREATE TABLE workflow_runs ( current_step INT NOT NULL DEFAULT 0, execution_trace JSONB NOT NULL DEFAULT '[]', trigger_context JSONB, + cause_source TEXT, + cause_pubkey BYTEA, started_at TIMESTAMPTZ, completed_at TIMESTAMPTZ, error_message TEXT, error_code TEXT, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), PRIMARY KEY (community_id, id), + CONSTRAINT workflow_runs_cause_source_check + CHECK (cause_source IN ('event', 'schedule', 'webhook', 'manual')), + CONSTRAINT workflow_runs_cause_pubkey_check + CHECK (length(cause_pubkey) = 32), FOREIGN KEY (community_id, workflow_id) REFERENCES workflows (community_id, id) ON DELETE CASCADE );