Skip to content

A platform for community discussion. Free, open, simple.

FEATURE: Attribute workflow flags to the contributing AI agent (#44332)

Gabriel Grubba89ecc992a5ec
diff --git a/plugins/discourse-ai/discourse_workflows/nodes/ai_agent/v1.rb b/plugins/discourse-ai/discourse_workflows/nodes/ai_agent/v1.rb
index 870ae291713..dde3d33ed72 100644
--- a/plugins/discourse-ai/discourse_workflows/nodes/ai_agent/v1.rb
+++ b/plugins/discourse-ai/discourse_workflows/nodes/ai_agent/v1.rb
@@ -217,6 +217,12 @@ if defined?(DiscourseWorkflows)
validate_mode!(mode)
agent = resolve_agent(exec_ctx)
+ exec_ctx.set_metadata(
+ review_agent: {
+ id: agent[:record].id,
+ name: agent[:record].name,
+ },
+ )
return [[run_once_for_all_items(exec_ctx, agent)]] if mode == RUN_ONCE_FOR_ALL_ITEMS
diff --git a/plugins/discourse-workflows/USE_CASES.md b/plugins/discourse-workflows/USE_CASES.md
index 34d0ebeb5e2..d5364959bfe 100644
--- a/plugins/discourse-workflows/USE_CASES.md
+++ b/plugins/discourse-workflows/USE_CASES.md
@@ -78,6 +78,7 @@ For each run, record:
- Connections leaving `condition:filter` or `condition:if` use `connection_type: "main"`; select the passing branch with `output_index: 0` and the rejected branch with `output_index: 1`.
- Group membership checks should use `action:group` with `operation: check_membership` and the resolved `group_id` instead of Code nodes. Branch with `condition:if` on `$json.group_membership.in_group` when different member and non-member paths are needed.
- Deleting a post is `action:post` with `operation: delete`; `action:flag_post` with `review_delete` is for moderation flows that also need a reviewable. Restoring one is `operation: recover`.
+- Flag post reasons and Flag user notes name the nearest AI Agent on the item's executed input path. Conditions preserve that attribution; merged inputs from different Agents or incomplete item links retain Workflow-only attribution. This applies to new flags and does not change the Workflow filter context.
- `trigger:post_destroyed` and `trigger:post_recovered` expose `$json.user` as the acting moderator, not the post author; use `$json.post.username` for the author.
- DM/personal-message notifications should use `action:send_personal_message` instead of chat or topic reply nodes.
- Forum `search`/`read` should not be used for node/schema discovery; use `workflow_node_catalog` and `workflow_validate_patch`.
diff --git a/plugins/discourse-workflows/config/locales/server.en.yml b/plugins/discourse-workflows/config/locales/server.en.yml
index 54d6ff69afd..13499682014 100644
--- a/plugins/discourse-workflows/config/locales/server.en.yml
+++ b/plugins/discourse-workflows/config/locales/server.en.yml
@@ -202,10 +202,12 @@ en:
destroy_context: "Deleted by a workflow"
flag_post:
flagged_by_workflow: "Flagged by the '%{workflow_name}' workflow."
+ flagged_by_agent: "Flagged following review by '%{agent_name}' in the '%{workflow_name}' workflow."
user:
check_email_context: "Workflow user node"
flag_user:
flagged_by_workflow: "Flagged by the '%{workflow_name}' workflow."
+ flagged_by_agent: "Flagged following review by '%{agent_name}' in the '%{workflow_name}' workflow."
pin_data:
errors:
unsupported_node: "Only nodes with a single output can have pinned data."
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/executor.rb b/plugins/discourse-workflows/lib/discourse_workflows/executor.rb
index 3b8d20c82d1..fd9952db531 100644
--- a/plugins/discourse-workflows/lib/discourse_workflows/executor.rb
+++ b/plugins/discourse-workflows/lib/discourse_workflows/executor.rb
@@ -399,6 +399,7 @@ module DiscourseWorkflows
inputs: input_groups_for_storage(input_groups),
outputs: output_arrays,
input_sources: input_sources_for_storage(input_sources, input_groups),
+ metadata: runtime_state.metadata,
)
route_downstream(node, output_arrays)
rescue ExecutionPaused
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/executor/execution_context.rb b/plugins/discourse-workflows/lib/discourse_workflows/executor/execution_context.rb
index cf3ca74f554..b327ca9689b 100644
--- a/plugins/discourse-workflows/lib/discourse_workflows/executor/execution_context.rb
+++ b/plugins/discourse-workflows/lib/discourse_workflows/executor/execution_context.rb
@@ -96,16 +96,14 @@ module DiscourseWorkflows
store_context(node.name, value)
end
- def store_node_run(node, inputs:, outputs:, input_sources: [])
+ def store_node_run(node, inputs:, outputs:, input_sources: [], metadata: {})
return if node.name.blank?
@context["__node_runs"] ||= {}
@context["__node_runs"][node.name] ||= []
- @context["__node_runs"][node.name] << {
- "inputs" => inputs,
- "outputs" => outputs,
- "input_sources" => input_sources,
- }
+ run = { "inputs" => inputs, "outputs" => outputs, "input_sources" => input_sources }
+ run["metadata"] = metadata.deep_stringify_keys if metadata.present?
+ @context["__node_runs"][node.name] << run
end
def store_waiting_input_sources(input_sources)
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/executor/execution_store.rb b/plugins/discourse-workflows/lib/discourse_workflows/executor/execution_store.rb
index 9a2af9f55ce..e364d19c6bc 100644
--- a/plugins/discourse-workflows/lib/discourse_workflows/executor/execution_store.rb
+++ b/plugins/discourse-workflows/lib/discourse_workflows/executor/execution_store.rb
@@ -401,7 +401,7 @@ module DiscourseWorkflows
"inputs" => ports_to_item_groups(run["inputs"]),
"outputs" => ports_to_item_groups(run["outputs"]),
"input_sources" => input_sources(run["inputs"]),
- }
+ }.tap { |restored| restored["metadata"] = run["metadata"] if run["metadata"].present? }
end
end
end
@@ -430,6 +430,7 @@ module DiscourseWorkflows
"node_type" => step&.node_type,
"status" => step&.status,
"run_index" => run_index,
+ "metadata" => run["metadata"],
"inputs" =>
serialize_ports(
run["inputs"] || run[:inputs],
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/executor/node_execution_context.rb b/plugins/discourse-workflows/lib/discourse_workflows/executor/node_execution_context.rb
index 1d6b3e791b2..6fdc7b7d7dd 100644
--- a/plugins/discourse-workflows/lib/discourse_workflows/executor/node_execution_context.rb
+++ b/plugins/discourse-workflows/lib/discourse_workflows/executor/node_execution_context.rb
@@ -244,6 +244,10 @@ module DiscourseWorkflows
)
end
+ def nearest_upstream_metadata(key, item_index: 0)
+ NodeOutputProxy.new(@resolver_context).nearest_upstream_metadata(key, item_index:)
+ end
+
def get_input_data(input_index = 0, _connection_type = nil)
input_items(input_index)
end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/node_output_proxy.rb b/plugins/discourse-workflows/lib/discourse_workflows/node_output_proxy.rb
index 2efda510a77..6882a4df086 100644
--- a/plugins/discourse-workflows/lib/discourse_workflows/node_output_proxy.rb
+++ b/plugins/discourse-workflows/lib/discourse_workflows/node_output_proxy.rb
@@ -51,8 +51,52 @@ module DiscourseWorkflows
@context.key?(name_str)
end
+ def nearest_upstream_metadata(key, item_index: 0)
+ source = current_input_source
+ return [] if source.blank?
+
+ trace_upstream_metadata(
+ source["node_name"],
+ source["output_index"].to_i,
+ item_index,
+ key,
+ Set.new,
+ )&.uniq
+ end
+
private
+ def trace_upstream_metadata(node_name, output_index, item_index, metadata_key, visited)
+ key = [node_name, output_index, item_index]
+ return if visited.include?(key)
+ visited = visited.dup.add(key)
+ run = node_run(node_name)
+ item = run&.dig("outputs", output_index, item_index)
+ return unless item
+
+ metadata = run.dig("metadata", metadata_key)
+ return [metadata] if metadata.present?
+ return [] if Array(run["input_sources"]).all?(&:blank?)
+
+ pairs = normalized_paired_items(item)
+ return if pairs.blank?
+
+ matches =
+ pairs.map do |pair|
+ source = run.dig("input_sources", pair["input"])
+ next if source.blank?
+ trace_upstream_metadata(
+ source["node_name"],
+ source["output_index"].to_i,
+ pair["item"],
+ metadata_key,
+ visited,
+ )
+ end
+ return if matches.any?(&:nil?)
+ matches.flatten(1)
+ end
+
def blocked_node_name?(name)
name.start_with?("_") || BLOCKED_NODE_NAMES.include?(name)
end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/nodes/flag_post/v1.rb b/plugins/discourse-workflows/lib/discourse_workflows/nodes/flag_post/v1.rb
index cf7cc30b4e8..fa0dec3d079 100644
--- a/plugins/discourse-workflows/lib/discourse_workflows/nodes/flag_post/v1.rb
+++ b/plugins/discourse-workflows/lib/discourse_workflows/nodes/flag_post/v1.rb
@@ -114,7 +114,7 @@ module DiscourseWorkflows
end
raise Discourse::InvalidAccess if !actor.guardian.can_see?(post)
- reason = score_reason_for(exec_ctx, config["reason"])
+ reason = score_reason_for(exec_ctx, config["reason"], item_index)
context = DiscourseWorkflows.reviewable_score_context(exec_ctx.get_workflow.id)
reviewable =
@@ -126,7 +126,7 @@ module DiscourseWorkflows
actor,
flag_type,
reason,
- attribution_for(exec_ctx),
+ attribution_for(exec_ctx, item_index),
context,
)
end
@@ -134,14 +134,17 @@ module DiscourseWorkflows
output(post, flag_type, reviewable)
end
- def attribution_for(exec_ctx, escape: false)
- workflow_name = exec_ctx.get_workflow.name
- workflow_name = ERB::Util.html_escape(workflow_name) if escape
- I18n.t("discourse_workflows.flag_post.flagged_by_workflow", workflow_name: workflow_name)
+ def attribution_for(exec_ctx, item_index, escape: false)
+ DiscourseWorkflows.review_attribution(
+ exec_ctx,
+ item_index:,
+ flag_type: :flag_post,
+ escape:,
+ )
end
- def score_reason_for(exec_ctx, custom_reason)
- parts = [attribution_for(exec_ctx, escape: true)]
+ def score_reason_for(exec_ctx, custom_reason, item_index)
+ parts = [attribution_for(exec_ctx, item_index, escape: true)]
custom_reason = custom_reason.to_s.strip
parts << custom_reason if custom_reason.present?
parts.join("<br>")
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/nodes/flag_user/v1.rb b/plugins/discourse-workflows/lib/discourse_workflows/nodes/flag_user/v1.rb
index 048383eed63..b8bd5d119d6 100644
--- a/plugins/discourse-workflows/lib/discourse_workflows/nodes/flag_user/v1.rb
+++ b/plugins/discourse-workflows/lib/discourse_workflows/nodes/flag_user/v1.rb
@@ -121,7 +121,7 @@ module DiscourseWorkflows
)
context = DiscourseWorkflows.reviewable_score_context(exec_ctx.get_workflow.id)
score_added = add_review_score(reviewable, actor, context)
- add_provenance_note(exec_ctx, reviewable, actor, config["reason"])
+ add_provenance_note(exec_ctx, reviewable, actor, config["reason"], item_index)
output(
user,
@@ -175,12 +175,9 @@ module DiscourseWorkflows
true
end
- def add_provenance_note(exec_ctx, reviewable, actor, custom_reason)
+ def add_provenance_note(exec_ctx, reviewable, actor, custom_reason, item_index)
parts = [
- I18n.t(
- "discourse_workflows.flag_user.flagged_by_workflow",
- workflow_name: exec_ctx.get_workflow.name,
- ),
+ DiscourseWorkflows.review_attribution(exec_ctx, item_index:, flag_type: :flag_user),
]
custom_reason = custom_reason.to_s.strip
parts << custom_reason if custom_reason.present?
diff --git a/plugins/discourse-workflows/plugin.rb b/plugins/discourse-workflows/plugin.rb
index d3a84c7a574..640c0ec4635 100644
--- a/plugins/discourse-workflows/plugin.rb
+++ b/plugins/discourse-workflows/plugin.rb
@@ -16,6 +16,18 @@ module ::DiscourseWorkflows
def self.reviewable_score_context(workflow_id)
"discourse_workflows:workflow:#{workflow_id}" if workflow_id.present?
end
+
+ def self.review_attribution(exec_ctx, item_index:, flag_type:, escape: false)
+ agents = exec_ctx.nearest_upstream_metadata("review_agent", item_index:)
+ values = { workflow_name: exec_ctx.get_workflow.name }
+ key = "discourse_workflows.#{flag_type}.flagged_by_workflow"
+ if agents&.one?
+ key = "discourse_workflows.#{flag_type}.flagged_by_agent"
+ values[:agent_name] = agents.first.fetch("name")
+ end
+ values.transform_values! { |value| ERB::Util.html_escape(value) } if escape
+ I18n.t(key, **values)
+ end
end
require_relative "lib/discourse_workflows/engine"
diff --git a/plugins/discourse-workflows/spec/integration/ai_agent_review_attribution_spec.rb b/plugins/discourse-workflows/spec/integration/ai_agent_review_attribution_spec.rb
new file mode 100644
index 00000000000..8b1e8575cca
--- /dev/null
+++ b/plugins/discourse-workflows/spec/integration/ai_agent_review_attribution_spec.rb
@@ -0,0 +1,220 @@
+# frozen_string_literal: true
+
+RSpec.describe "Agent attribution on workflow flags" do
+ fab!(:llm, :llm_model)
+ fab!(:spam_agent) do
+ Fabricate(
+ :ai_agent,
+ name: "Spam detection",
+ default_llm: llm,
+ response_format: [{ key: "verdict", type: "string" }],
+ )
+ end
+ fab!(:billing_agent) do
+ Fabricate(
+ :ai_agent,
+ name: "Billing <review>",
+ default_llm: llm,
+ response_format: [{ key: "verdict", type: "string" }],
+ )
+ end
+ fab!(:pii_agent) do
+ Fabricate(
+ :ai_agent,
+ name: "PII detection",
+ default_llm: llm,
+ response_format: [{ key: "verdict", type: "string" }],
+ )
+ end
+
+ before { SiteSetting.discourse_ai_enabled = true }
+
+ it "preserves agent attribution after a timed wait resumes" do
+ graph =
+ build_workflow_graph do |builder|
+ builder.node "trigger", "trigger:manual"
+ builder.node "agent",
+ "action:ai_agent",
+ configuration: {
+ agent_id: spam_agent.id,
+ prompt: "Check spam",
+ }
+ builder.node "wait",
+ "flow:wait",
+ configuration: {
+ resume: "time_interval",
+ wait_amount: 1,
+ wait_unit: "seconds",
+ }
+ builder.node "flag",
+ "action:flag_post",
+ configuration: {
+ post_id: "={{ $trigger.post_id }}",
+ flag_type: "review",
+ }
+ builder.chain "trigger", "agent", "wait", "flag"
+ end
+ workflow =
+ Fabricate(:discourse_workflows_workflow, name: "Moderation", published: true, **graph)
+ post = Fabricate(:post)
+ execution =
+ DiscourseAi::Completions::Llm.with_prepared_responses([{ verdict: "yes" }.to_json]) do
+ DiscourseWorkflows::Executor.new(workflow, "trigger", { post_id: post.id }).run
+ end
+ expect(execution.status).to eq("waiting")
+
+ freeze_time(execution.waiting_until + 1.second) do
+ Jobs::DiscourseWorkflows::ResumeWaitingExecution.new.execute(execution_id: execution.id)
+ end
+
+ expect(execution.reload.status).to eq("success")
+ expect(ReviewablePost.find_by!(target: post).reviewable_scores.last.reason).to eq(
+ I18n.t(
+ "discourse_workflows.flag_post.flagged_by_agent",
+ agent_name: spam_agent.name,
+ workflow_name: workflow.name,
+ ),
+ )
+ end
+
+ it "keeps workflow attribution when two agents contribute to a merged item" do
+ graph =
+ build_workflow_graph do |builder|
+ builder.node "trigger", "trigger:manual"
+ builder.node "spam",
+ "action:ai_agent",
+ configuration: {
+ agent_id: spam_agent.id,
+ prompt: "Check spam",
+ }
+ builder.node "billing",
+ "action:ai_agent",
+ configuration: {
+ agent_id: billing_agent.id,
+ prompt: "Check billing",
+ }
+ builder.node "merge", "flow:merge", configuration: { mode: "combine" }
+ builder.node "flag",
+ "action:flag_post",
+ configuration: {
+ post_id: "={{ $trigger.post_id }}",
+ flag_type: "review",
+ }
+ builder.connect "trigger", "spam"
+ builder.connect "trigger", "billing"
+ builder.connect "spam", "merge", input: "input_1"
+ builder.connect "billing", "merge", input: "input_2"
+ builder.connect "merge", "flag"
+ end
+ workflow =
+ Fabricate(:discourse_workflows_workflow, name: "Moderation", published: true, **graph)
+ post = Fabricate(:post)
+ execution =
+ DiscourseAi::Completions::Llm.with_prepared_responses(
+ Array.new(2) { { verdict: "yes" }.to_json },
+ ) { DiscourseWorkflows::Executor.new(workflow, "trigger", { post_id: post.id }).run }
+
+ expect(execution.status).to eq("success")
+ expect(ReviewablePost.find_by!(target: post).reviewable_scores.last.reason).to eq(
+ I18n.t("discourse_workflows.flag_post.flagged_by_workflow", workflow_name: workflow.name),
+ )
+ end
+
+ it "adds the agent attribution to a flagged user's provenance note" do
+ graph =
+ build_workflow_graph do |builder|
+ builder.node "trigger", "trigger:manual"
+ builder.node "agent",
+ "action:ai_agent",
+ configuration: {
+ agent_id: spam_agent.id,
+ prompt: "Check user",
+ }
+ builder.node "flag",
+ "action:flag_user",
+ configuration: {
+ username: "={{ $trigger.username }}",
+ }
+ builder.chain "trigger", "agent", "flag"
+ end
+ workflow =
+ Fabricate(:discourse_workflows_workflow, name: "Moderation", published: true, **graph)
+ user = Fabricate(:user)
+ execution =
+ DiscourseAi::Completions::Llm.with_prepared_responses([{ verdict: "yes" }.to_json]) do
+ DiscourseWorkflows::Executor.new(workflow, "trigger", { username: user.username }).run
+ end
+
+ expect(execution.status).to eq("success")
+ expect(ReviewableUser.find_by!(target: user).reviewable_notes.last.content).to eq(
+ I18n.t(
+ "discourse_workflows.flag_user.flagged_by_agent",
+ agent_name: spam_agent.name,
+ workflow_name: workflow.name,
+ ),
+ )
+ end
+
+ it "attributes each flag to the nearest agent through the executed condition branches" do
+ graph =
+ build_workflow_graph do |builder|
+ builder.node "trigger", "trigger:manual"
+ [spam_agent, billing_agent, pii_agent].each_with_index do |agent, index|
+ builder.node "agent-#{index}",
+ "action:ai_agent",
+ name: "Agent #{index}",
+ configuration: {
+ agent_id: agent.id,
+ prompt: "Classify this post",
+ }
+ builder.node "if-#{index}",
+ "condition:if",
+ configuration: {
+ conditions: [
+ {
+ leftValue: "={{ $json.verdict }}",
+ rightValue: "yes",
+ operator: {
+ type: "string",
+ operation: "equals",
+ },
+ },
+ ],
+ }
+ builder.node "flag-#{index}",
+ "action:flag_post",
+ configuration: {
+ post_id: "={{ $trigger.post_id }}",
+ flag_type: index.zero? ? "spam" : "review",
+ }
+ builder.connect "agent-#{index}", "if-#{index}"
+ builder.connect "if-#{index}", "flag-#{index}", output: "true"
+ end
+ builder.connect "if-0", "agent-1", output: "false"
+ builder.connect "if-1", "agent-2", output: "false"
+ builder.connect "trigger", "agent-0"
+ end
+ workflow =
+ Fabricate(:discourse_workflows_workflow, name: "Moderation", published: true, **graph)
+
+ [spam_agent, billing_agent, pii_agent].each_with_index do |agent, index|
+ post = Fabricate(:post)
+ responses = Array.new(index) { { verdict: "no" }.to_json } + [{ verdict: "yes" }.to_json]
+ execution =
+ DiscourseAi::Completions::Llm.with_prepared_responses(responses) do
+ DiscourseWorkflows::Executor.new(workflow, "trigger", { post_id: post.id }).run
+ end
+
+ expect(execution.status).to eq("success")
+ score = Reviewable.find_by!(target: post).reviewable_scores.last
+ expect(score.reason).to eq(
+ I18n.t(
+ "discourse_workflows.flag_post.flagged_by_agent",
+ agent_name: ERB::Util.html_escape(agent.name),
+ workflow_name: workflow.name,
+ ),
+ )
+ expect(score.context).to eq("discourse_workflows:workflow:#{workflow.id}")
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/executor/execution_store_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/executor/execution_store_spec.rb
index 45d5f607e27..354663e0745 100644
--- a/plugins/discourse-workflows/spec/lib/discourse_workflows/executor/execution_store_spec.rb
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/executor/execution_store_spec.rb
@@ -353,11 +353,13 @@ RSpec.describe DiscourseWorkflows::Executor::ExecutionStore do
execution_context.store_context("node_a", "data_a")
node = OpenStruct.new(id: "1", name: "Node A", type: "action:code", typeVersion: "1.0")
output_groups = [[{ "json" => { "saved" => true } }]]
+ metadata = { "review_agent" => { "id" => 1, "name" => "Content review" } }
execution_context.store_node_run(
node,
inputs: [[{ "json" => { "input" => true } }]],
outputs: output_groups,
input_sources: [{ "node_name" => "Trigger", "output_index" => 0 }],
+ metadata: metadata,
)
steps = [
DiscourseWorkflows::Executor::Step.build(
@@ -394,6 +396,7 @@ RSpec.describe DiscourseWorkflows::Executor::ExecutionStore do
expect(
restored_context.context.dig("__node_runs", "Node A", 0, "outputs", 0, 0, "json"),
).to eq("saved" => true)
+ expect(restored_context.context.dig("__node_runs", "Node A", 0, "metadata")).to eq(metadata)
expect(restored_context.node_context_for(OpenStruct.new(id: "node_a", name: "node_a"))).to eq(
"counter" => 1,
)
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/node_output_proxy_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/node_output_proxy_spec.rb
new file mode 100644
index 00000000000..a8aabe6d3ce
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/node_output_proxy_spec.rb
@@ -0,0 +1,88 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::NodeOutputProxy do
+ def run(items:, sources: [], metadata: {})
+ { "outputs" => [items], "input_sources" => sources, "metadata" => metadata }
+ end
+
+ def source(name, output_index: 0)
+ { "node_name" => name, "output_index" => output_index }
+ end
+
+ describe "#nearest_upstream_metadata" do
+ it "follows item links through conditions and chooses the nearest metadata" do
+ upstream = { "id" => 1, "name" => "First" }
+ nearest = { "id" => 2, "name" => "Second" }
+ context = {
+ "__input_sources" => [source("Filter")],
+ "__node_runs" => {
+ "First" => [run(items: [{ "json" => {} }], metadata: { "review_agent" => upstream })],
+ "Second" => [
+ run(
+ items: [{ "json" => {} }, { "json" => {} }],
+ sources: [source("First")],
+ metadata: {
+ "review_agent" => nearest,
+ },
+ ),
+ ],
+ "Filter" => [
+ run(
+ items: [{ "json" => {}, "pairedItem" => { "item" => 1 } }],
+ sources: [source("Second")],
+ ),
+ ],
+ },
+ }
+
+ expect(described_class.new(context).nearest_upstream_metadata("review_agent")).to eq(
+ [nearest],
+ )
+ end
+
+ it "keeps multiple contributing sources ambiguous and rejects incomplete or cyclic paths" do
+ first = { "id" => 1, "name" => "First" }
+ second = { "id" => 2, "name" => "Second" }
+ context = {
+ "__input_sources" => [source("Merge")],
+ "__node_runs" => {
+ "First" => [run(items: [{ "json" => {} }], metadata: { "review_agent" => first })],
+ "Second" => [run(items: [{ "json" => {} }], metadata: { "review_agent" => second })],
+ "Merge" => [
+ run(
+ items: [
+ {
+ "json" => {
+ },
+ "pairedItem" => [{ "input" => 0, "item" => 0 }, { "input" => 1, "item" => 0 }],
+ },
+ ],
+ sources: [source("First"), source("Second")],
+ ),
+ ],
+ },
+ }
+ proxy = described_class.new(context)
+ expect(proxy.nearest_upstream_metadata("review_agent")).to contain_exactly(first, second)
+
+ context["__node_runs"]["Second"].last.delete("metadata")
+ context["__node_runs"]["Second"].last["input_sources"] = [source("Missing")]
+ expect(proxy.nearest_upstream_metadata("review_agent")).to be_nil
+
+ context["__node_runs"]["Second"] = [
+ run(items: [{ "json" => {}, "pairedItem" => { "item" => 0 } }], sources: [source("Merge")]),
+ ]
+ expect(proxy.nearest_upstream_metadata("review_agent")).to be_nil
+ end
+
+ it "returns no attribution for roots and pinned outputs without execution metadata" do
+ context = {
+ "__input_sources" => [source("Pinned")],
+ "__node_runs" => {
+ "Pinned" => [run(items: [{ "json" => {} }])],
+ },
+ }
+ expect(described_class.new(context).nearest_upstream_metadata("review_agent")).to eq([])
+ end
+ end
+end