Skip to content

Commit fc8c802

Browse files
wpfleger96Duncan
andauthored
feat(workflow): add owner-only agent mentions for workflow messages (#9227)
Adds owner-only agent mentions, a relay setting, `BUZZ_WORKFLOW_AGENT_MENTIONS`. Its values are `any`, the default and today's behaviour, and `owner`. Any other value fails startup. With `owner`, a workflow message can direct an agent only if the run's cause and definition allow it. The setting is relay-wide. **Recording what caused each run.** `workflow_runs` gets `cause_source` and `cause_pubkey` columns. Migration `0087` adds them with named checks marked `NOT VALID`, so it does not scan existing rows under its lock; `0088` validates the checks separately. `create_workflow_run` now takes a required `RunCause`, so every place that creates a run has to set one: - **Event trigger:** the cause is the signer of the message, reaction or diff. For a reaction, that is the reactor, not the author of the message being reacted to. - **Cron and interval schedules:** the cause is the timer. - **Webhook:** the caller is unknown. - **Manual trigger:** the cause is the invoking pubkey. Rows written before this change have no cause. A stored source without the pubkey it requires, or with one it forbids, is read as no cause. **Deciding eligibility.** A run's messages may direct agents only when all of these hold: - the cause is a schedule, or an event or manual trigger whose pubkey is the workflow owner's; - every step of the definition that is running is `send_message` or `delay`. This is an allowlist, so any other action, including one added later, makes the definition ineligible, even when an `if:` skips that step; - the run did not resume after an approval. Webhook runs and runs with no recorded cause are never eligible. The executor decides this from `WorkflowConfig::agent_mentions`, and passes `ActionSink::send_message` the owner's stored step text with a `may_direct_agents` flag. The sink adds `buzz:workflow-mention` tags only when the flag is set, and returns `SentMessage { event_id, agent_mentions_withheld }`, which is true only when it left out a tag that a member named in both the stored and rendered text would otherwise have received. Webhook and manual runs start through `execute_run`, so `execute_from_step` is used only to resume after an approval. **The gate.** With `owner`, the relay adds `buzz:workflow-mention` only to messages from eligible runs. Messages from other runs still post with their plain `p` tags and still notify people. With `any`, mention tags are added exactly as before. **Making it visible.** When a `send_message` step leaves the tags out: - its output in the run trace gets `"agent_mentions": {"withheld": true, "reasons": [...]}`, listing each reason that applies: `cause` (not started by the owner or a timer), `steps` (a step other than `send_message` or `delay`), `resumed` (resumed after an approval). The key is absent when nothing was withheld. The trace is what the app's run history shows; - the relay logs it at info level under the `buzz_relay::workflow_agent_mentions` target (visible under the default filter) with the community, workflow, run, step and reasons; - the counter `buzz_workflow_agent_mentions_withheld_total` increases once per reason, labelled `reason`. **Discovery.** The NIP-11 document always carries `"workflow_agent_mentions": "any" | "owner"`, so a missing field means an older relay. `NOSTR.md` now specifies `buzz:workflow-mention` for clients: what the tag means, the checks an agent makes before acting, that a relay may leave it out under a policy, and the NIP-11 `workflow_agent_mentions` field. The relay policy itself is in the new operator guide, `docs/operator-workflow-agent-mentions.md`: the setting and its values, what counts as a run's cause for each trigger, which steps are allowed, the trace key, the log and metric, the NIP-11 field, when to use `owner`, rollout across pods, and what it doesn't cover. The `TESTING.md` and `.env.example` entries link to it. --------- Signed-off-by: Will Pfleger <[email protected]> Co-authored-by: Duncan <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz>
1 parent cb69ad9 commit fc8c802

24 files changed

Lines changed: 1528 additions & 94 deletions

‎.env.example‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,9 @@ REDIS_URL=redis://localhost:6379
3939
# Emergency kill switch for all automatic partition DDL, including catch-all
4040
# advancement; audits remain enabled.
4141
# BUZZ_PARTITION_MANAGER_CREATE_ENABLED=true
42+
# Which workflow runs may direct agents: any (default) or owner (owner-only
43+
# agent mentions). See docs/operator-workflow-agent-mentions.md.
44+
# BUZZ_WORKFLOW_AGENT_MENTIONS=owner
4245
# Replace an empty partition catch-all with six months of dedicated monthlies,
4346
# at startup and on every audit interval (default true). Has no effect while the
4447
# kill switch above is off.

‎Cargo.lock‎

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎NOSTR.md‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -375,6 +375,37 @@ of the channel's messages: `buzz:workflow-owner` also names the owner. A
375375
marked `p` tag on any other event, for example a kind:39002 member list role,
376376
matches `#p` normally. See `docs/buzz-push.md` for the push rules.
377377

378+
### Workflow Mentions
379+
380+
A workflow message may carry `["buzz:workflow-mention", <pubkey>]` tags. Each
381+
one names a channel member whom the workflow's owner named in the stored text of
382+
the step, as opposed to text substituted into it when the step ran. The relay adds
383+
a plain `["p", <pubkey>]` for every member that the rendered text mentions, and a
384+
`buzz:workflow-mention` tag only for members that the stored text also names.
385+
386+
A `buzz:workflow-mention` tag is the relay's statement that the message may
387+
direct the named agent on the owner's behalf. An agent acts on a workflow
388+
message only if all of these hold:
389+
390+
- the message is signed by the relay key that the active community advertises;
391+
- a `buzz:workflow-mention` tag names the agent;
392+
- the workflow principal that `buzz:workflow-owner` names passes the receiving
393+
client's rule for whom the agent accepts work from: its owner, or an agent
394+
that its owner has attested.
395+
396+
`buzz:workflow-owner` is attribution. It does not by itself authorize anything.
397+
A plain `p` tag on a workflow message notifies the member but does not direct
398+
an agent.
399+
400+
A relay may leave out `buzz:workflow-mention` tags under a policy. The message
401+
still posts with its `p` tags, and an agent that no tag names does not act on
402+
it. A relay's NIP-11 document MUST carry `workflow_agent_mentions`: `"any"`
403+
when every run may carry the tags, or `"owner"` when only runs the workflow's
404+
owner or a timer started, on a definition of only `send_message` and `delay`
405+
steps, carry them; a client MUST treat a missing field as an older relay whose
406+
policy is unknown. For Buzz's owner-only agent mentions, see
407+
[docs/operator-workflow-agent-mentions.md](docs/operator-workflow-agent-mentions.md).
408+
378409
### Sending Messages
379410

380411
```bash

‎TESTING.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -419,6 +419,7 @@ out of the box with `just setup` or `just relay`. Common overrides:
419419
| `BUZZ_REQUIRE_RELAY_MEMBERSHIP` | `false` | When true, only pubkeys in `relay_members` can connect |
420420
| `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. |
421421
| `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. |
422+
| `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). |
422423
| `BUZZ_AUTO_MIGRATE` | `false` | Opt in with `true`/`1`/`yes`/`on` to run embedded SQLx migrations on relay startup |
423424
| `RELAY_OWNER_PUBKEY` | unset | Bootstrapped as `owner` in `relay_members` at first start |
424425
| `BUZZ_ALLOW_NIP_OA_AUTH` | `false` | Enable NIP-OA owner attestation for membership |

‎crates/buzz-db/src/runtime/migration.rs‎

Lines changed: 92 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -902,7 +902,7 @@ mod postgres_tests {
902902
let mut migrations: Vec<_> = MIGRATOR.iter().collect();
903903
migrations.sort_by_key(|migration| migration.version);
904904

905-
assert_eq!(migrations.len(), 86);
905+
assert_eq!(migrations.len(), 88);
906906
assert!(migrations[83]
907907
.sql
908908
.as_str()
@@ -915,6 +915,14 @@ mod postgres_tests {
915915
.sql
916916
.as_str()
917917
.contains("CREATE TABLE media_uploaders"));
918+
assert!(migrations[86]
919+
.sql
920+
.as_str()
921+
.contains("ADD COLUMN cause_source TEXT"));
922+
assert!(migrations[87]
923+
.sql
924+
.as_str()
925+
.contains("VALIDATE CONSTRAINT workflow_runs_cause_pubkey_check"));
918926
for (index, migration) in migrations.iter().enumerate() {
919927
assert_eq!(migration.version, (index + 1) as i64);
920928
}
@@ -3057,6 +3065,7 @@ mod postgres_tests {
30573065
"communities",
30583066
"entity_deletion_stage_history",
30593067
"user_deletion_fences",
3068+
"workflow_runs",
30603069
] {
30613070
assert_eq!(
30623071
columns(&desired, table).await,
@@ -3120,6 +3129,7 @@ mod postgres_tests {
31203129
"entity_deletion_stage_history",
31213130
"user_deletion_fences",
31223131
"entity_deletion_approvals",
3132+
"workflow_runs",
31233133
] {
31243134
assert_eq!(
31253135
constraints(&desired, table).await,
@@ -3300,6 +3310,87 @@ mod postgres_tests {
33003310
}
33013311
}
33023312

3313+
/// 0087 adds the run-cause columns and NOT VALID checks without scanning
3314+
/// existing runs, and 0088 validates them. Runs written before the upgrade,
3315+
/// and inserts from an older relay that omits both columns, keep no cause.
3316+
#[tokio::test]
3317+
#[ignore = "requires Postgres"]
3318+
async fn workflow_run_cause_upgrade_preserves_populated_rows_and_legacy_inserts() {
3319+
let pool = connect_test_pool().await;
3320+
reset_public_schema(&pool).await;
3321+
run_migrations_through(&pool, 86).await.unwrap();
3322+
let community_id = uuid::Uuid::new_v4();
3323+
let workflow_id = uuid::Uuid::new_v4();
3324+
let owner = vec![7u8; 32];
3325+
sqlx::query("INSERT INTO communities (id, host) VALUES ($1, $2)")
3326+
.bind(community_id)
3327+
.bind(format!("run-cause-{}.example", community_id.simple()))
3328+
.execute(&pool)
3329+
.await
3330+
.unwrap();
3331+
sqlx::query("INSERT INTO users (community_id, pubkey) VALUES ($1, $2)")
3332+
.bind(community_id)
3333+
.bind(&owner)
3334+
.execute(&pool)
3335+
.await
3336+
.unwrap();
3337+
sqlx::query(
3338+
"INSERT INTO workflows (community_id, id, name, owner_pubkey, definition, definition_hash) \
3339+
VALUES ($1, $2, 'cause', $3, '{}', $4)",
3340+
)
3341+
.bind(community_id)
3342+
.bind(workflow_id)
3343+
.bind(&owner)
3344+
.bind(vec![0u8; 32])
3345+
.execute(&pool)
3346+
.await
3347+
.unwrap();
3348+
let legacy_insert =
3349+
"INSERT INTO workflow_runs (community_id, id, workflow_id) VALUES ($1, $2, $3)";
3350+
let insert_legacy_run = |id| {
3351+
sqlx::query(legacy_insert)
3352+
.bind(community_id)
3353+
.bind(id)
3354+
.bind(workflow_id)
3355+
.execute(&pool)
3356+
};
3357+
let before = uuid::Uuid::new_v4();
3358+
insert_legacy_run(before).await.unwrap();
3359+
run_migrations(&pool).await.unwrap();
3360+
let after = uuid::Uuid::new_v4();
3361+
insert_legacy_run(after).await.unwrap();
3362+
3363+
for id in [before, after] {
3364+
let cause: (Option<String>, Option<Vec<u8>>) = sqlx::query_as(
3365+
"SELECT cause_source, cause_pubkey FROM workflow_runs WHERE id = $1",
3366+
)
3367+
.bind(id)
3368+
.fetch_one(&pool)
3369+
.await
3370+
.unwrap();
3371+
assert_eq!(cause, (None, None));
3372+
}
3373+
let unvalidated: i64 = sqlx::query_scalar(
3374+
"SELECT count(*) FROM pg_constraint \
3375+
WHERE conrelid = 'public.workflow_runs'::regclass AND contype = 'c' \
3376+
AND conname LIKE 'workflow_runs_%' AND NOT convalidated",
3377+
)
3378+
.fetch_one(&pool)
3379+
.await
3380+
.unwrap();
3381+
assert_eq!(unvalidated, 0, "0088 validates every cause check");
3382+
let unknown_source = sqlx::query(
3383+
"INSERT INTO workflow_runs (community_id, id, workflow_id, cause_source) \
3384+
VALUES ($1, $2, $3, 'relay')",
3385+
)
3386+
.bind(community_id)
3387+
.bind(uuid::Uuid::new_v4())
3388+
.bind(workflow_id)
3389+
.execute(&pool)
3390+
.await;
3391+
assert!(unknown_source.is_err(), "the trigger source check holds");
3392+
}
3393+
33033394
/// Migrations 0076 and 0078 refuse a populated table whose index was not
33043395
/// prebuilt concurrently. A relay that auto-migrated through earlier
33053396
/// releases and holds artifact data must still boot through every migration. When a

‎crates/buzz-db/src/store/admission_postgres_tests.rs‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -318,9 +318,16 @@ async fn workflow_writers_require_application_admission() {
318318
.expect_err("workflow create must reject"),
319319
);
320320
assert_fenced(
321-
super::workflow::create_workflow_run(&db.pool, *community, Uuid::new_v4(), None, None)
322-
.await
323-
.expect_err("workflow run create must reject"),
321+
super::workflow::create_workflow_run(
322+
&db.pool,
323+
*community,
324+
Uuid::new_v4(),
325+
None,
326+
None,
327+
&super::workflow::RunCause::Schedule,
328+
)
329+
.await
330+
.expect_err("workflow run create must reject"),
324331
);
325332
assert_fenced(
326333
super::workflow::claim_scheduled_workflow_fire(

0 commit comments

Comments
 (0)