Skip to content

Commit 31e2f5c

Browse files
author
Michael Feth
committed
fix(workflow): attribute workflow messages via actor so p means wake only
Addresses the two review findings left open on the previous commit. ## Finding 1 — the owner was woken as a second agent ACP's mention test is pure `p`-tag equality (`event_mentions` / `event_mentions_agent`), with no attribution/wake distinction. Both workflow actions p-tagged the workflow owner for attribution, so whenever an agent owned the workflow that agent was woken alongside the real target — defeating exactly the single-assignee contract `assign_agent` exists to provide. Owner attribution moves to the `actor` tag, which is already the relay-trusted attribution channel: `effective_message_author` (ingest.rs) prefers `actor` and only falls back to the first `p` tag. `p` now means "wake" and nothing else. Applied to **both** actions, not just `assign_agent`. `send_message` has the same defect, and fixing one action while leaving the other would have left two workflow message shapes that disagree about what a `p` tag means. `assign_agent` consequently emits exactly one `p` tag. The owner==assignee dedup is gone with it: a self-assignment is a real assignment and must still wake, and there is no longer a second owner tag to collide with. Companion change, without which this would be a regression: desktop's `resolveEventAuthorPubkey` only consults `actor` when the caller passes `preferActorTag`. All eight timeline/typing call sites already do; `shared/api/forum.ts` did not, so it would have fallen through to the first `p` tag — now the assignee — and attributed forum posts to the wrong person. Both call sites there now opt in. Mobile needs no change: it renders the author the relay computed at ingest. ## Finding 2 — templated routing fields could not be saved The executor resolves `{{...}}` templates in `channel` and `task_id`, but `validate_action` required a literal UUID for both, and `parse_yaml` always validates — so a workflow using the templates the executor was written to resolve could never be saved. The executor test hid this by constructing a `Step` directly and asserting a non-UUID resolved `task_id`. Definition validation now accepts either a literal UUID or a single `{{...}}` placeholder for both fields — the same contract `agent_pubkey` already had — and the resolved value is re-checked before dispatch: `resolve_action_channel` re-parses the channel, and the executor now re-parses `task_id` as a UUID and fails the run with `invalid_definition` rather than putting a malformed correlation id on the wire. The masking test now resolves a real UUID, and two tests were added: one proving the templated form actually validates (the save path the mismatch blocked), one proving a literal non-UUID is still rejected, so widening the shape check did not turn it into a rubber stamp. ## Verification x86_64-pc-windows-msvc, with Postgres and Redis up — the gated tests are no longer skipped: - `cargo test -p buzz-relay --lib workflow_sink -- --ignored`: **3 passed**. This is the end-to-end proof for both findings: the assign_agent test now asserts exactly one `p` tag (the assignee) plus `actor` == owner, and the send_message test asserts the author is attributed via `actor` and is NOT p-tagged. - `cargo test -p buzz-relay --lib workflow_sink`: 20 passed. - `cargo test -p buzz-workflow --lib`: 171 passed (169 before + 2 new). - `cargo test -p buzz-workflow --lib -- --ignored`: 2 passed. - `cargo clippy -p buzz-workflow -p buzz-relay --all-targets -- -D warnings`: clean. `cargo fmt --check`: clean. - Desktop `pnpm exec tsc --noEmit`: clean. `pnpm check`: exit 0. `pnpm test`: 5023/5024 — the one failure, `focused polling pauses on blur`, passes in isolation and is untouched by this branch. Signed-off-by: Michael Feth <[email protected]>
1 parent a24d84b commit 31e2f5c

4 files changed

Lines changed: 188 additions & 38 deletions

File tree

‎crates/buzz-relay/src/workflow_sink.rs‎

Lines changed: 84 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -155,7 +155,13 @@ fn resolve_mention_pubkeys(text: &str, members: &[(String, String)]) -> Vec<Stri
155155
/// is exactly how the missing `buzz:workflow-owner` tag went unnoticed.
156156
///
157157
/// The set is:
158-
/// - `p` (owner) — attribution, matching `send_message`.
158+
/// - `actor` (owner) — attribution, matching `send_message`. Attribution
159+
/// deliberately does not ride on a `p` tag: ACP wakes on *any* `p` tag
160+
/// matching an agent's pubkey, so p-tagging the owner woke them as a second
161+
/// agent whenever an agent owned the workflow — which defeats the
162+
/// single-assignee contract this action exists to provide. `actor` is the
163+
/// relay-trusted attribution channel `effective_message_author` already
164+
/// prefers, leaving `p` to mean "wake" and nothing else.
159165
/// - `h` — the destination channel.
160166
/// - `buzz:workflow` — marks the event as workflow-emitted (prevents recursive
161167
/// triggering).
@@ -167,7 +173,7 @@ fn resolve_mention_pubkeys(text: &str, members: &[(String, String)]) -> Vec<Stri
167173
/// rejects under `owner-only` — the mode official desktop builds hard-clamp
168174
/// — so the assignee never wakes and the action cannot do the one thing it
169175
/// exists for. Mention `p` tags are explicitly *not* used for attribution.
170-
/// - `p` (assignee) — the wake, omitted when the owner is the assignee.
176+
/// - `p` (assignee) — **exactly one**, the sole wake target.
171177
/// - `task` — optional correlation id, trimmed, omitted when empty.
172178
fn assign_agent_tags(
173179
author_pubkey_hex: &str,
@@ -176,23 +182,22 @@ fn assign_agent_tags(
176182
task_id: Option<&str>,
177183
) -> Result<Vec<Tag>, ActionSinkError> {
178184
let mut tags = vec![
179-
Tag::parse(["p", author_pubkey_hex])
180-
.map_err(|e| ActionSinkError::EventBuild(format!("p tag: {e}")))?,
185+
Tag::parse(["actor", author_pubkey_hex])
186+
.map_err(|e| ActionSinkError::EventBuild(format!("actor tag: {e}")))?,
181187
Tag::parse(["h", channel_id_canonical])
182188
.map_err(|e| ActionSinkError::EventBuild(format!("h tag: {e}")))?,
183189
Tag::parse(["buzz:workflow", "true"])
184190
.map_err(|e| ActionSinkError::EventBuild(format!("workflow tag: {e}")))?,
185191
Tag::parse(["buzz:workflow-owner", author_pubkey_hex])
186192
.map_err(|e| ActionSinkError::EventBuild(format!("workflow owner tag: {e}")))?,
193+
// The one and only wake target. No dedup against the owner is needed
194+
// now that the owner is attributed via `actor` rather than `p`: a
195+
// self-assignment is a genuine assignment and must still wake.
196+
// No reverse-parse of `@Name` mentions in `text` either — that is the
197+
// failure mode assign_agent exists to avoid.
198+
Tag::parse(["p", agent_pk_hex])
199+
.map_err(|e| ActionSinkError::EventBuild(format!("assignee p tag: {e}")))?,
187200
];
188-
// No reverse-parse of `@Name` mentions in `text` — that is the failure
189-
// mode assign_agent exists to avoid.
190-
if agent_pk_hex != author_pubkey_hex {
191-
tags.push(
192-
Tag::parse(["p", agent_pk_hex])
193-
.map_err(|e| ActionSinkError::EventBuild(format!("assignee p tag: {e}")))?,
194-
);
195-
}
196201
// Emit the trimmed id, not the caller's string: definition-time validation
197202
// checks `tid.trim()` but stores the original, so a padded `task_id` would
198203
// otherwise put whitespace on the wire and break correlation for every
@@ -312,7 +317,13 @@ impl ActionSink for RelayActionSink {
312317

313318
// 3. Build kind:9 Nostr event
314319
// - Signed by relay keypair (event.pubkey = relay pubkey)
315-
// - `p` tag attributes the message to the workflow owner
320+
// - `actor` tag attributes the message to the workflow owner.
321+
// Attribution deliberately does NOT ride on a `p` tag: ACP
322+
// wakes on *any* `p` tag matching an agent's pubkey, so
323+
// p-tagging the owner woke them as a second agent whenever an
324+
// agent owned the workflow. `actor` is the relay-trusted
325+
// attribution channel `effective_message_author` already
326+
// prefers, so `p` can mean "wake" and nothing else.
316327
// - `h` tag scopes to the channel (NIP-29, canonical UUID)
317328
// - `buzz:workflow` tag prevents recursive workflow triggering
318329
// - `buzz:workflow-owner` tag names the workflow owner explicitly,
@@ -321,8 +332,8 @@ impl ActionSink for RelayActionSink {
321332
// - one `p` tag per `@Name` that resolves to a channel member,
322333
// so mentioned agents are woken (wake is `p`-tag gated)
323334
let mut tags = vec![
324-
Tag::parse(["p", &author_pubkey_hex])
325-
.map_err(|e| ActionSinkError::EventBuild(format!("p tag: {e}")))?,
335+
Tag::parse(["actor", &author_pubkey_hex])
336+
.map_err(|e| ActionSinkError::EventBuild(format!("actor tag: {e}")))?,
326337
Tag::parse(["h", &channel_id_canonical])
327338
.map_err(|e| ActionSinkError::EventBuild(format!("h tag: {e}")))?,
328339
Tag::parse(["buzz:workflow", "true"])
@@ -353,6 +364,9 @@ impl ActionSink for RelayActionSink {
353364
Some((name, nostr::PublicKey::from_slice(&u.pubkey).ok()?.to_hex()))
354365
})
355366
.collect();
367+
// The owner is attributed via `actor`, never p-tagged, so they are
368+
// not woken by their own workflow's output even if the text names
369+
// them. Skipping them here keeps that true.
356370
for mentioned in resolve_mention_pubkeys(&text, &named_members) {
357371
if mentioned == author_pubkey_hex {
358372
continue;
@@ -817,21 +831,36 @@ mod tests {
817831
vec!["true"],
818832
"exactly one buzz:workflow marker — the gate rejects duplicates"
819833
);
820-
assert_eq!(tag_values(&tags, "p"), vec![owner.as_str(), agent.as_str()]);
834+
// Exactly one `p` tag: the assignee. ACP wakes on any `p` matching an
835+
// agent's pubkey, so an owner `p` here would wake the owner as a
836+
// second agent whenever an agent owns the workflow.
837+
assert_eq!(
838+
tag_values(&tags, "p"),
839+
vec![agent.as_str()],
840+
"the assignee must be the only wake target"
841+
);
842+
assert_eq!(
843+
tag_values(&tags, "actor"),
844+
vec![owner.as_str()],
845+
"owner attribution rides on `actor`, which effective_message_author prefers"
846+
);
821847
}
822848

823-
/// Owner == assignee collapses the wake `p` tag, but attribution must
824-
/// survive: the owner tag is what the author gate reads.
849+
/// A workflow may assign its own owner. That is a genuine assignment and
850+
/// must still wake them — the owner is only excluded from `p` when they are
851+
/// *not* the assignee, and attribution is unaffected either way because it
852+
/// rides on `actor`.
825853
#[test]
826-
fn assign_agent_self_assignment_keeps_the_owner_tag() {
854+
fn assign_agent_self_assignment_still_wakes_the_owner() {
827855
let owner = pk('c');
828856
let tags = assign_agent_tags(&owner, "chan-1", &owner, None).expect("tags build");
829857

830858
assert_eq!(
831859
tag_values(&tags, "p"),
832860
vec![owner.as_str()],
833-
"no duplicate p"
861+
"self-assignment is an assignment: exactly one wake, no duplicate"
834862
);
863+
assert_eq!(tag_values(&tags, "actor"), vec![owner.as_str()]);
835864
assert_eq!(
836865
tag_values(&tags, "buzz:workflow-owner"),
837866
vec![owner.as_str()]
@@ -1001,9 +1030,24 @@ mod integration_tests {
10011030
.filter_map(|t| t.as_slice().get(1).map(|s| s.as_str()))
10021031
.collect();
10031032

1033+
// Attribution moved off `p` and onto `actor`: ACP wakes on any `p`
1034+
// matching an agent's pubkey, so p-tagging the owner woke them as an
1035+
// extra agent whenever an agent owned the workflow.
1036+
let actor_targets: Vec<&str> = stored
1037+
.event
1038+
.tags
1039+
.iter()
1040+
.filter(|t| t.as_slice().first().map(|s| s.as_str()) == Some("actor"))
1041+
.filter_map(|t| t.as_slice().get(1).map(|s| s.as_str()))
1042+
.collect();
1043+
assert_eq!(
1044+
actor_targets,
1045+
vec![author_hex.as_str()],
1046+
"author must be attributed via the actor tag; got {actor_targets:?}"
1047+
);
10041048
assert!(
1005-
p_tag_targets.contains(&author_hex.as_str()),
1006-
"author should still be attributed via p tag; got {p_tag_targets:?}"
1049+
!p_tag_targets.contains(&author_hex.as_str()),
1050+
"author must NOT be p-tagged — that wakes them as a second agent; got {p_tag_targets:?}"
10071051
);
10081052
assert!(
10091053
p_tag_targets.contains(&agent_hex.as_str()),
@@ -1137,11 +1181,26 @@ mod integration_tests {
11371181
.filter_map(|t| t.as_slice().get(1).map(|s| s.as_str()))
11381182
.collect();
11391183

1140-
// Exactly two `p` tags — owner + selected agent — in that order.
1184+
// Exactly ONE `p` tag: the selected agent. The owner is attributed via
1185+
// `actor`, not `p` — ACP wakes on any `p` matching an agent's pubkey,
1186+
// so an owner `p` woke them as a second agent and broke the
1187+
// single-assignee contract this action exists to provide.
11411188
assert_eq!(
11421189
p_tag_targets,
1143-
vec![author_hex.as_str(), winnie_a_hex.as_str()],
1144-
"p-tag set must be exactly {{owner, selected}}; got {p_tag_targets:?}"
1190+
vec![winnie_a_hex.as_str()],
1191+
"the assignee must be the sole wake target; got {p_tag_targets:?}"
1192+
);
1193+
let actor_targets: Vec<&str> = stored
1194+
.event
1195+
.tags
1196+
.iter()
1197+
.filter(|t| t.as_slice().first().map(|s| s.as_str()) == Some("actor"))
1198+
.filter_map(|t| t.as_slice().get(1).map(|s| s.as_str()))
1199+
.collect();
1200+
assert_eq!(
1201+
actor_targets,
1202+
vec![author_hex.as_str()],
1203+
"owner must be attributed via actor; got {actor_targets:?}"
11451204
);
11461205
// The other same-name member must NOT wake.
11471206
assert!(

‎crates/buzz-workflow/src/executor.rs‎

Lines changed: 68 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -629,6 +629,21 @@ pub async fn dispatch_action(
629629
)));
630630
}
631631

632+
// Same contract for the correlation id. Definition-time
633+
// validation now accepts a `{{...}}` placeholder here, so
634+
// the UUID guarantee the action documents can only be
635+
// enforced after resolution. Without this a resolved
636+
// non-UUID reached the sink and went out on the `task`
637+
// tag, breaking correlation for every reader.
638+
if let Some(tid) = task_id.as_deref() {
639+
let tid = tid.trim();
640+
if tid.parse::<Uuid>().is_err() {
641+
return Err(WorkflowError::InvalidDefinition(format!(
642+
"AssignAgent: resolved task_id '{tid}' is not a valid UUID"
643+
)));
644+
}
645+
}
646+
632647
let wf_run = engine
633648
.db
634649
.get_workflow_run(community_id, run_id)
@@ -2003,6 +2018,12 @@ mod tests {
20032018
"New incident: {{trigger.text}}",
20042019
Some("{{trigger.message_id}}"),
20052020
);
2021+
// A realistic trigger id: the action documents `task_id` as a
2022+
// correlation UUID and the executor now enforces that on the resolved
2023+
// value, so a fixture resolving to "event-id-hex" would assert a shape
2024+
// the run rejects — which is precisely what hid the validate/resolve
2025+
// mismatch before.
2026+
ctx.message_id = "11111111-2222-3333-4444-555555555555".to_owned();
20062027
let resolved = resolve_step_templates(&step, &ctx, &outputs).unwrap();
20072028
match resolved {
20082029
ActionDef::AssignAgent {
@@ -2014,12 +2035,58 @@ mod tests {
20142035
// Static agent_pubkey is preserved verbatim.
20152036
assert_eq!(agent_pubkey, AGENT_HEX_FIXTURE);
20162037
assert_eq!(text, "New incident: P1 in prod");
2017-
assert_eq!(task_id.as_deref(), Some("event-id-hex"));
2038+
assert_eq!(
2039+
task_id.as_deref(),
2040+
Some("11111111-2222-3333-4444-555555555555")
2041+
);
20182042
}
20192043
other => panic!("unexpected resolved action: {other:?}"),
20202044
}
20212045
}
20222046

2047+
/// The step above must also be *saveable*. `parse_yaml` always calls
2048+
/// `validate()`, so a templated routing field that validation rejects can
2049+
/// never reach the executor that resolves it — the definition and the
2050+
/// runtime have to agree on the accepted shapes.
2051+
#[test]
2052+
fn assign_agent_templated_channel_and_task_id_pass_definition_validation() {
2053+
let step = Step {
2054+
id: "assign".to_owned(),
2055+
name: None,
2056+
if_expr: None,
2057+
timeout_secs: None,
2058+
action: ActionDef::AssignAgent {
2059+
agent_pubkey: AGENT_HEX_FIXTURE.to_owned(),
2060+
text: "New incident".to_owned(),
2061+
channel: Some("{{trigger.channel_id}}".to_owned()),
2062+
task_id: Some("{{trigger.message_id}}".to_owned()),
2063+
},
2064+
};
2065+
crate::schema::validate_action(&step.id, &step.action)
2066+
.expect("templated channel/task_id must be saveable");
2067+
}
2068+
2069+
/// A literal that is neither a UUID nor a template is still rejected —
2070+
/// widening the shape check must not turn it into a rubber stamp.
2071+
#[test]
2072+
fn assign_agent_rejects_a_literal_non_uuid_task_id() {
2073+
let step = Step {
2074+
id: "assign".to_owned(),
2075+
name: None,
2076+
if_expr: None,
2077+
timeout_secs: None,
2078+
action: ActionDef::AssignAgent {
2079+
agent_pubkey: AGENT_HEX_FIXTURE.to_owned(),
2080+
text: "New incident".to_owned(),
2081+
channel: None,
2082+
task_id: Some("not-a-uuid".to_owned()),
2083+
},
2084+
};
2085+
let err = crate::schema::validate_action(&step.id, &step.action)
2086+
.expect_err("a literal non-UUID task_id must not validate");
2087+
assert!(err.to_string().contains("task_id"), "got: {err}");
2088+
}
2089+
20232090
#[test]
20242091
fn assign_agent_resolves_agent_pubkey_template_through_trigger_author() {
20252092
// `{{trigger.author}}` is the "reply to the sender" pattern — the

‎crates/buzz-workflow/src/schema.rs‎

Lines changed: 31 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -149,10 +149,12 @@ pub enum ActionDef {
149149
/// Unlike [`ActionDef::SendMessage`], which reverse-parses `@Name` from
150150
/// prose against channel membership (ambiguous names silently wake no one;
151151
/// renames silently rewrite the target), `assign_agent` binds dispatch to
152-
/// the target's hex pubkey. The relay sink emits exactly two `p` tags on
153-
/// the resulting message: the workflow owner (attribution) and
154-
/// `agent_pubkey` (wake). The message body is never scanned for narrative
155-
/// names.
152+
/// the target's hex pubkey. The relay sink emits exactly **one** `p` tag on
153+
/// the resulting message — `agent_pubkey`, the sole wake target. The
154+
/// workflow owner is attributed via the `actor` tag instead: ACP wakes on
155+
/// any `p` tag matching an agent's pubkey, so p-tagging the owner woke them
156+
/// as a second agent whenever an agent owned the workflow. The message body
157+
/// is never scanned for narrative names.
156158
///
157159
/// `agent_pubkey` accepts either a static 64-char lowercase hex pubkey or a
158160
/// single `{{...}}` template placeholder (e.g. `{{trigger.author}}`).
@@ -166,12 +168,14 @@ pub enum ActionDef {
166168
agent_pubkey: String,
167169
/// Task text posted to the channel (supports template variables).
168170
text: String,
169-
/// Optional channel UUID override. Must equal the workflow's channel
170-
/// when the workflow is bound to one (matches `send_message`).
171+
/// Optional channel UUID override, or a single `{{...}}` template that
172+
/// resolves to one. Must equal the workflow's channel when the workflow
173+
/// is bound to one (matches `send_message`).
171174
#[serde(default)]
172175
channel: Option<String>,
173176
/// Optional caller-supplied correlation id for downstream tracking.
174-
/// Must be a valid UUID when set.
177+
/// A UUID, or a single `{{...}}` template that resolves to one — the
178+
/// resolved value is re-checked before dispatch.
175179
#[serde(default)]
176180
task_id: Option<String>,
177181
},
@@ -278,7 +282,7 @@ impl WorkflowDef {
278282
/// for every step. Rejects malformed inputs that would otherwise only surface
279283
/// as a runtime failure — for `assign_agent` this is the identity-safety line:
280284
/// a workflow that mistypes an agent pubkey should never save.
281-
fn validate_action(step_id: &str, action: &ActionDef) -> Result<(), WorkflowError> {
285+
pub(crate) fn validate_action(step_id: &str, action: &ActionDef) -> Result<(), WorkflowError> {
282286
if let ActionDef::AssignAgent {
283287
agent_pubkey,
284288
text,
@@ -297,19 +301,34 @@ fn validate_action(step_id: &str, action: &ActionDef) -> Result<(), WorkflowErro
297301
or a single {{{{...}}}} template placeholder (got '{agent_pubkey}')"
298302
)));
299303
}
304+
// `channel` and `task_id` are template-resolved at run time, exactly
305+
// like `agent_pubkey`, so the definition-time check accepts either a
306+
// literal UUID or a single `{{...}}` placeholder. Requiring a literal
307+
// here made a workflow the executor was written to run unsaveable:
308+
// `parse_yaml` always validates, so a templated routing field could
309+
// never reach the executor that resolves it. The resolved values are
310+
// re-checked before dispatch — `resolve_action_channel` re-parses the
311+
// channel, and the executor re-parses `task_id`.
300312
if let Some(ch) = channel {
301313
let trimmed = ch.trim();
302-
if !trimmed.is_empty() && trimmed.parse::<uuid::Uuid>().is_err() {
314+
if !trimmed.is_empty()
315+
&& !is_single_template(trimmed)
316+
&& trimmed.parse::<uuid::Uuid>().is_err()
317+
{
303318
return Err(WorkflowError::InvalidDefinition(format!(
304-
"assign_agent step '{step_id}': channel override '{ch}' is not a valid UUID"
319+
"assign_agent step '{step_id}': channel override '{ch}' must be a valid UUID \
320+
or a single {{{{...}}}} template placeholder"
305321
)));
306322
}
307323
}
308324
if let Some(tid) = task_id {
309325
let trimmed = tid.trim();
310-
if trimmed.is_empty() || trimmed.parse::<uuid::Uuid>().is_err() {
326+
if trimmed.is_empty()
327+
|| (!is_single_template(trimmed) && trimmed.parse::<uuid::Uuid>().is_err())
328+
{
311329
return Err(WorkflowError::InvalidDefinition(format!(
312-
"assign_agent step '{step_id}': task_id '{tid}' must be a valid UUID when set"
330+
"assign_agent step '{step_id}': task_id '{tid}' must be a valid UUID or a \
331+
single {{{{...}}}} template placeholder when set"
313332
)));
314333
}
315334
}

‎desktop/src/shared/api/forum.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,9 @@ function fromRawForumPost(
7474
sig: post.sig,
7575
},
7676
relaySelfPubkey,
77+
// Workflow messages attribute their owner via `actor`; without this the
78+
// resolver falls back to the first `p` tag, which is now the assignee.
79+
preferActorTag: true,
7780
}),
7881
content: post.content,
7982
kind: post.kind,
@@ -108,6 +111,8 @@ function fromRawThreadReply(
108111
sig: reply.sig,
109112
},
110113
relaySelfPubkey,
114+
// See fromRawForumPost: attribution comes from `actor`, not `p`.
115+
preferActorTag: true,
111116
}),
112117
content: reply.content,
113118
kind: reply.kind,

0 commit comments

Comments
 (0)