Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(workflows): add the proposal api behind the self-optimising flag (#91709)

Daniel Marchuk7f1acdf6ec2a
diff --git a/posthog/api/app_metrics2.py b/posthog/api/app_metrics2.py
index 2b4af5e9fc7d..bbcc0e22887f 100644
--- a/posthog/api/app_metrics2.py
+++ b/posthog/api/app_metrics2.py
@@ -215,6 +215,9 @@ def fetch_app_metric_totals(
"app_source_id": app_source_id,
"after": after.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%S") if after else None,
"before": before.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%S") if before else None,
+ "instance_id": instance_id,
+ "name": name,
+ "kind": kind,
}
clickhouse_query = f"""
diff --git a/posthog/api/test/test_app_metrics2.py b/posthog/api/test/test_app_metrics2.py
index 68d64a61d9cf..885c8258d7ca 100644
--- a/posthog/api/test/test_app_metrics2.py
+++ b/posthog/api/test/test_app_metrics2.py
@@ -1,4 +1,5 @@
from datetime import UTC, datetime, timedelta
+from typing import Any
from zoneinfo import ZoneInfo
from posthog.test.base import BaseTest, ClickhouseTestMixin
@@ -10,16 +11,32 @@ from posthog.test.fixtures import create_app_metric2
class TestAppMetrics2Timezone(ClickhouseTestMixin, BaseTest):
- def _seed(self, when_utc: datetime):
+ def _seed(self, when_utc: datetime, app_source_id: str = "fn-1") -> None:
create_app_metric2(
team_id=self.team.pk,
app_source="hog_function",
- app_source_id="fn-1",
+ app_source_id=app_source_id,
metric_kind="success",
metric_name="succeeded",
timestamp=when_utc,
)
+ @parameterized.expand(
+ [
+ ("instance_id", {"instance_id": "54321"}), # the fixture's default instance
+ ("name", {"name": ["succeeded"]}),
+ ("kind", {"kind": ["success"]}),
+ ]
+ )
+ def test_totals_optional_filters_are_bound(self, _name: str, filters: dict[str, Any]) -> None:
+ self._seed(datetime(2026, 6, 8, 12, 0, 0, tzinfo=UTC), app_source_id="fn-filters")
+
+ result = fetch_app_metric_totals(
+ team_id=self.team.pk, app_source="hog_function", app_source_id="fn-filters", **filters
+ )
+
+ assert result.totals == {"success": 1}
+
@parameterized.expand(
[
("America/Los_Angeles",), # -07:00 (PDT in June)
diff --git a/products/workflows/backend/api/hog_flow.py b/products/workflows/backend/api/hog_flow.py
index 0b6cb8011d87..4a3a5f663a96 100644
--- a/products/workflows/backend/api/hog_flow.py
+++ b/products/workflows/backend/api/hog_flow.py
@@ -1,4 +1,5 @@
import re
+import copy
import json
import uuid as uuid_mod
import hashlib
@@ -13,7 +14,7 @@ from django.conf import settings
from django.core.cache import cache
from django.core.exceptions import ValidationError as DjangoValidationError
from django.core.signing import BadSignature, SignatureExpired, TimestampSigner
-from django.db import models, transaction
+from django.db import IntegrityError, models, transaction
from django.db.models import Q, QuerySet
from django.db.models.expressions import RawSQL
from django.http import Http404, HttpResponse
@@ -22,6 +23,7 @@ from django.utils.dateparse import parse_datetime
import requests
import structlog
+import posthoganalytics
from django_filters import BaseInFilter, CharFilter, FilterSet
from django_filters.rest_framework import DjangoFilterBackend
from drf_spectacular.types import OpenApiTypes
@@ -47,6 +49,7 @@ from posthog.hogql.parser import parse_expr
from posthog.api.app_metrics2 import (
AppMetricsMixin,
+ fetch_app_metric_totals,
fetch_app_metric_totals_by_source,
fetch_app_metric_totals_by_team_and_source,
)
@@ -137,6 +140,17 @@ from products.workflows.backend.api.message_assets import (
fetch_message_assets,
)
from products.workflows.backend.api.publish_impact import build_publish_impact
+from products.workflows.backend.metrics import (
+ GUARDRAIL_LABELS,
+ GUARDRAIL_METRICS,
+ HOG_FLOW_VERSION_APP_SOURCE,
+ MIN_EVIDENCE_SAMPLE,
+ TARGET_CLICK_METRIC,
+ TARGET_OPEN_METRIC,
+ TARGET_SEND_METRIC,
+ TARGET_UNTRACKED_METRIC,
+ UNAVAILABLE_GUARDRAILS,
+)
from products.workflows.backend.models.hog_flow.hog_flow import (
BILLABLE_ACTION_TYPES,
MESSAGING_ACTION_TYPES,
@@ -151,6 +165,7 @@ from products.workflows.backend.models.hog_flow_batch_job import HogFlowBatchJob
from products.workflows.backend.models.hog_flow_revision import HogFlowRevision
from products.workflows.backend.models.hog_flow_schedule import SCHEDULED_TRIGGER_TYPES, HogFlowSchedule
from products.workflows.backend.models.team_workflows_config import TeamWorkflowsConfig
+from products.workflows.backend.models.workflow_proposal import WorkflowProposal
from products.workflows.backend.providers.ses import SESProvider
from products.workflows.backend.services.account_audience import (
ACCOUNT_BATCH_SIZE,
@@ -534,6 +549,26 @@ def strip_content_secrets(content: dict, template_cache: Optional[TemplateCache]
return normalized
+def strip_proposal_secrets(content: dict, live_content: dict, template_cache: Optional[TemplateCache] = None) -> dict:
+ """Strip secret inputs from a proposal's content, classifying each step against the live step it
+ patches. A patch carries only the fields it changes, so it can set a secret input without the
+ `type` or `template_id` that says the input is secret, and `strip_content_secrets` alone would
+ store that value in plaintext."""
+ stripped = strip_content_secrets(content, template_cache)
+ actions = stripped.get("actions")
+ if not isinstance(actions, list):
+ return stripped
+ live_by_id = {_item_id(item): item for item in live_content.get("actions") or []}
+ for item in actions:
+ live_step = live_by_id.get(_item_id(item))
+ inputs = (item.get("config") or {}).get("inputs") if isinstance(item, dict) else None
+ if live_step is None or not isinstance(inputs, dict):
+ continue
+ for key in _secret_keys_for_action(_deep_merge(deepcopy(live_step), item), template_cache):
+ inputs.pop(key, None)
+ return stripped
+
+
def rehydrate_flow_secrets(actions: list[dict], secrets_by_action: dict[str, dict]) -> list[dict]:
# Fold decrypted secrets back into each action's config.inputs. Used for inline test runs that
# ship a config to the executor directly, bypassing the worker's manager (which decrypts normally).
@@ -3783,6 +3818,515 @@ class HogFlowRevisionRestoreRequestSerializer(serializers.Serializer):
)
+SELF_OPTIMISING_FEATURE_FLAG = "self-optimising-workflows"
+
+# `trigger` and `abort_action` are read-only on the workflow serializer, so publish would drop them.
+PROPOSAL_CONTENT_FIELDS = tuple(field for field in DRAFT_CONTENT_FIELDS if field not in ("trigger", "abort_action"))
+
+
+# Fields a proposal replaces wholesale. `actions` merges per step instead, since steps carry stable
+# ids; edges have no id, and a variable list is short enough to carry whole.
+PROPOSAL_WHOLE_LIST_FIELDS = ("edges", "variables")
+
+PROPOSAL_MERGE_BY_ID_FIELDS = ("actions",)
+
+# Their items reach helpers that read each item as a mapping, so anything else has to fail here as a 400.
+PROPOSAL_LIST_OF_OBJECT_FIELDS = ("actions", "edges", "variables")
+
+# 1.0 is either every message or one of them; only the producer knows which.
+EVIDENCE_UNITS = ("rate", "count")
+
+WORKFLOW_PROPOSAL_CONTENT_SCHEMA = {
+ "type": "object",
+ "additionalProperties": True,
+ "description": (
+ "Only the content fields the proposal changes. Valid keys: "
+ f"{', '.join(PROPOSAL_CONTENT_FIELDS)}. Each value has the same shape as on the workflow itself."
+ ),
+}
+
+
+@extend_schema_field(WORKFLOW_PROPOSAL_CONTENT_SCHEMA)
+class WorkflowProposalContentField(serializers.JSONField):
+ # Lenient at write time, like a restored revision: publish is what revalidates the staged
+ # content strictly and recompiles bytecode.
+ pass
+
+
+WORKFLOW_PROPOSAL_EVIDENCE_SCHEMA = {
+ "type": "object",
+ "additionalProperties": True,
+ "description": (
+ "The numbers behind the proposal, read back by name. Five keys are required: `metric`, the "
+ "metric name; `current_value`, its value as a number (a rate as a fraction, 0.0865, never a "
+ "string); `unit`, either `rate` or `count`, since 1.0 is either every message or one of them; "
+ "`n`, the denominator that value was computed over; and `guardrails`, a list of "
+ "{metric, value, n, unit} counter-metrics read over the same window, empty only if none apply. "
+ "Also conventional: target_value, window, query, app_source_id. A rate with no denominator "
+ "lets a reviewer mistake noise for a result, a target with no counter-metrics hides a change "
+ "that lifts one number by harming another, and a number under a key of your own reads to a "
+ "person as no evidence at all."
+ ),
+}
+
+
+@extend_schema_field(WORKFLOW_PROPOSAL_EVIDENCE_SCHEMA)
+class WorkflowProposalEvidenceField(serializers.JSONField):
+ pass
+
+
+class WorkflowProposalSerializer(serializers.ModelSerializer):
+ resolved_by = UserBasicSerializer(read_only=True, allow_null=True)
+ content = WorkflowProposalContentField(read_only=True)
+ evidence = WorkflowProposalEvidenceField(read_only=True)
+ is_stale = serializers.SerializerMethodField(
+ help_text=(
+ "Whether approving this would undo an edit made since it was proposed. False while the "
+ "workflow only changed elsewhere, because approving merges per step."
+ )
+ )
+
+ class Meta:
+ model = WorkflowProposal
+ fields = [
+ "id",
+ "title",
+ "rationale",
+ "content",
+ "evidence",
+ "step_id",
+ "base_version",
+ "is_stale",
+ "status",
+ "source_id",
+ "created_at",
+ "resolved_at",
+ "resolved_by",
+ "applied_version",
+ ]
+ read_only_fields = fields
+
+ @extend_schema_field(serializers.BooleanField)
+ def get_is_stale(self, proposal: WorkflowProposal) -> bool:
+ if (proposal.hog_flow.version or 0) <= proposal.base_version:
+ return False
+ # One revision read per base version, shared across the page.
+ cache = self.context.setdefault("proposal_conflicts", {})
+ key = (proposal.hog_flow_id, proposal.base_version, json.dumps(proposal.content, sort_keys=True))
+ if key not in cache:
+ cache[key] = conflicting_parts(proposal.hog_flow, proposal)
+ return bool(cache[key])
+
+
+class WorkflowProposalCreateSerializer(serializers.Serializer):
+ title = serializers.CharField(max_length=200, help_text="Short summary of the proposed change.")
+ rationale = serializers.CharField(help_text="Why this change is worth making, in prose a human reads.")
+ content = WorkflowProposalContentField(
+ help_text=(
+ "Only the workflow content fields this proposal changes. Approving merges them over the live "
+ "content to build the staged draft, so unrelated parts of the workflow stay as they are. "
+ "In `actions`, send each step you change with its `id` and only the fields you change; they "
+ "merge into the live step, and a null field deletes it."
+ )
+ )
+ evidence = WorkflowProposalEvidenceField(
+ required=False,
+ help_text="The metric numbers behind the proposal, so a human can judge it without re-deriving them.",
+ )
+ base_version = serializers.IntegerField(
+ required=False,
+ help_text=(
+ "Workflow version this was authored against. Required when the proposal changes actions, "
+ "edges or variables: it is the snapshot approve compares against to tell whether someone "
+ "edited the same steps since, and a defaulted version would read as current however long "
+ "the producer took. Defaults to the current live version otherwise."
+ ),
+ )
+ step_id = serializers.CharField(
+ required=False,
+ allow_null=True,
+ max_length=200,
+ help_text=(
+ "The step this is about. Send it for a change to one step: both the evidence and the outcome "
+ "then read that step's metrics, so a change to one email in a sequence is not measured "
+ "against the rest. Leave it out only for a change that spans the workflow, such as its exit "
+ "condition or a step being taken out, which is measured on the workflow's own numbers."
+ ),
+ )
+ source_id = serializers.CharField(
+ required=False,
+ allow_null=True,
+ max_length=200,
+ help_text=(
+ "Stable id of the producing agent run or finding. Posting the same one twice returns the "
+ "existing proposal instead of creating a duplicate."
+ ),
+ )
+
+ def validate_evidence(self, value: Any) -> dict:
+ if not isinstance(value, dict) or not value:
+ return value or {}
+ # The panel reads these back by name; a producer's own key would render as "no data".
+ if not isinstance(value.get("metric"), str) or not value["metric"].strip():
+ raise exceptions.ValidationError(
+ "Include `metric`, the name of the metric this suggestion is about, as a string."
+ )
+ if not isinstance(value.get("current_value"), int | float) or isinstance(value.get("current_value"), bool):
+ raise exceptions.ValidationError(
+ "Include `current_value`, the metric's current value as a number. Send a rate as a "
+ "fraction (0.0865), not as a string ('8.65%')."
+ )
+ if value.get("unit") not in EVIDENCE_UNITS:
+ raise exceptions.ValidationError(
+ f"Include `unit`, one of: {', '.join(EVIDENCE_UNITS)}. Without it the panel cannot tell "
+ "a rate of 1.0 from a count of 1, and would show the count as 100%."
+ )
+ if not isinstance(value.get("n"), int) or isinstance(value.get("n"), bool):
+ raise exceptions.ValidationError(
+ "Include `n`, the number of observations behind current_value. A rate without its "
+ "denominator cannot be judged."
+ )
+ if not isinstance(value.get("guardrails"), list):
+ raise exceptions.ValidationError(
+ "Include `guardrails`: a list of {metric, value, n, unit} counter-metrics read over the "
+ "same window, so a change that lifts the target by harming something else is visible. "
+ "Send an empty list only if none apply."
+ )
+ for guardrail in value.get("guardrails") or []:
+ if not isinstance(guardrail, dict) or "metric" not in guardrail:
+ raise exceptions.ValidationError("Each guardrail needs at least a `metric` name.")
+ if guardrail.get("unit") not in EVIDENCE_UNITS:
+ raise exceptions.ValidationError(
+ f"Guardrail `{guardrail['metric']}` needs a `unit`, one of: {', '.join(EVIDENCE_UNITS)}."
+ )
+ return value
+
+ def validate_content(self, value: Any) -> dict:
+ if not isinstance(value, dict) or not value:
+ raise exceptions.ValidationError("Provide at least one workflow content field to change.")
+ unknown = sorted(set(value) - set(PROPOSAL_CONTENT_FIELDS))
+ if unknown:
+ raise exceptions.ValidationError(
+ f"Unknown content field(s): {', '.join(unknown)}. Valid fields: {', '.join(PROPOSAL_CONTENT_FIELDS)}."
+ )
+ for field in PROPOSAL_LIST_OF_OBJECT_FIELDS:
+ if field not in value:
+ continue
+ items = value[field]
+ if not isinstance(items, list) or any(not isinstance(item, dict) for item in items):
+ raise exceptions.ValidationError(f"`{field}` must be a list of objects.")
+ for field in PROPOSAL_MERGE_BY_ID_FIELDS:
+ _validate_merge_keys(field, value.get(field))
+ return value
+
+ def validate(self, attrs: dict) -> dict:
+ changes_the_graph = any(
+ field in attrs.get("content", {}) for field in (*PROPOSAL_WHOLE_LIST_FIELDS, *PROPOSAL_MERGE_BY_ID_FIELDS)
+ )
+ if changes_the_graph and attrs.get("base_version") is None:
+ raise exceptions.ValidationError(
+ {
+ "base_version": (
+ "Send the workflow version you read, so approving this can tell whether the "
+ "workflow moved on while you were writing it."
+ )
+ }
+ )
+ return attrs
+
+
+class WorkflowProposalApproveRequestSerializer(serializers.Serializer):
+ overwrite = serializers.BooleanField(
+ default=False,
+ help_text=(
+ "Replace the open staged draft with this proposal's content. Without it, approving while a "
+ "draft is open returns 409."
+ ),
+ )
+ expected_draft_updated_at = serializers.DateTimeField(
+ required=False,
+ allow_null=True,
+ help_text=(
+ "The draft_updated_at of the staged draft this overwrite was confirmed against. A draft with "
+ "a different stamp returns 409 instead of being overwritten. Omit to overwrite unconditionally."
+ ),
+ )
+
+
+class WorkflowProposalRejectRequestSerializer(serializers.Serializer):
+ """Rejecting takes no body today. The serializer stays so a reason can be added without a new endpoint."""
+
+
+def _flatten_graph_errors(error: serializers.ValidationError) -> list[str]:
+ detail = error.detail
+ if isinstance(detail, dict):
+ return [str(message) for messages in detail.values() for message in messages]
+ return [str(message) for message in detail]
+
+
+class WorkflowProposalMetricSerializer(serializers.Serializer):
+ metric = serializers.CharField(help_text="What was measured, e.g. 'email open rate'.")
+ value = serializers.FloatField(
+ allow_null=True, help_text="The rate over the window, or null when there was nothing to divide."
+ )
+ n = serializers.IntegerField(help_text="Observations the rate was computed over.")
+ below_minimum_sample = serializers.BooleanField(
+ help_text="True when n is too small for the rate to mean anything. Show it labelled, not as a finding."
+ )
+
+
+class WorkflowProposalVersionOutcomeSerializer(serializers.Serializer):
+ version = serializers.IntegerField(help_text="Workflow version these numbers belong to.")
+ target = WorkflowProposalMetricSerializer(help_text="The metric the suggestion aimed at.")
+ click_through = WorkflowProposalMetricSerializer(
+ help_text="Click-through rate over the same window and denominator, since opens alone can move without clicks."
+ )
+ guardrails = WorkflowProposalMetricSerializer(
+ many=True, help_text="Counter-metrics over the same window, so a harmful win is visible."
+ )
+
+
+class WorkflowProposalOutcomeSerializer(serializers.Serializer):
+ window = serializers.CharField(help_text="Relative window both sides were measured over.")
+ before = WorkflowProposalVersionOutcomeSerializer(
+ allow_null=True, help_text="The version the change was proposed against."
+ )
+ after = WorkflowProposalVersionOutcomeSerializer(
+ allow_null=True, help_text="The version it went live as. Null until the proposal is applied."
+ )
+ unavailable_guardrails = serializers.ListField(
+ child=serializers.CharField(),
+ help_text="Counter-metrics that cannot be read yet, named so their absence is not read as zero.",
+ )
+
+
+class ProposalAlreadyResolvedError(exceptions.APIException):
+ status_code = status.HTTP_409_CONFLICT
+ default_detail = "This suggestion has already been resolved. Reload to see where it ended up."
+ default_code = "proposal_already_resolved"
+
+
+class ProposalNotRunnableError(exceptions.APIException):
+ status_code = status.HTTP_409_CONFLICT
+ default_detail = (
+ "Applying this suggestion no longer describes a runnable workflow, because the workflow "
+ "changed around it. Ask for a fresh suggestion."
+ )
+ default_code = "proposal_not_runnable"
+
+ def __init__(self, reasons: list[str] | None = None) -> None:
+ detail = self.default_detail
+ if reasons:
+ detail = f"{detail} {' '.join(reasons)}"
+ super().__init__(detail)
+
+
+class ProposalOutOfDateError(exceptions.APIException):
+ status_code = status.HTTP_409_CONFLICT
+ default_detail = (
+ "Someone changed this workflow where the suggestion changes it, so approving it would undo "
+ "their edit. Ask for a fresh suggestion."
+ )
+ default_code = "proposal_out_of_date"
+
+ def __init__(self, conflicts: list[str] | None = None) -> None:
+ detail = self.default_detail
+ if conflicts:
+ detail = f"{detail} It changes: {', '.join(conflicts)}."
+ super().__init__(detail)
+
+
+def merge_proposal_content(live_content: dict, proposal_content: dict) -> dict:
+ """Live content with the proposal applied. Whole-list fields replace; `actions` merges per step
+ and, within a step, per field, so a proposal that rewrites one subject line leaves the rest of
+ that email and the rest of the graph exactly as they are now."""
+ merged = {**live_content, **proposal_content}
+ for field in PROPOSAL_MERGE_BY_ID_FIELDS:
+ if field in proposal_content:
+ merged[field] = _merge_by_id(live_content.get(field) or [], proposal_content[field] or [])
+ return merged
+
+
+def _merge_by_id(live_items: list, changed_items: list) -> list:
+ """Merge each changed step into the live step with the same id, field by field, the way the
+ graph API's `update_action` does: a producer sends the fields it changes and nothing else, so a
+ step can never lose its template inputs to a payload that only carried a subject line."""
+ changed_by_id = {item["id"]: item for item in changed_items if isinstance(item, dict) and "id" in item}
+ merged = []
+ for item in live_items:
+ patch = changed_by_id.pop(_item_id(item), None)
+ merged.append(_deep_merge(copy.deepcopy(item), patch) if patch is not None else item)
+ # Anything left names a step the workflow does not have yet, so the proposal is adding it whole.
+ merged.extend(changed_by_id.values())
+ return merged
+
+
+def _item_id(item: Any) -> Any:
+ return item.get("id") if isinstance(item, dict) else None
+
+
+def _validate_merge_keys(field: str, items: Any) -> None:
+ """Merging is keyed on `id`, so a missing or repeated one has no defined meaning. Reject it here
+ rather than picking a winner and staging a draft the author did not write."""
+ if not isinstance(items, list):
+ return
+ seen: set[str] = set()
+ for index, item in enumerate(items):
+ item_id = _item_id(item)
+ if not isinstance(item_id, str) or not item_id:
+ raise exceptions.ValidationError(
+ f"`{field}[{index}]` needs the `id` of the step it changes. Send only the steps you change."
+ )
+ if item_id in seen:
+ raise exceptions.ValidationError(f"`{field}` names `{item_id}` twice.")
+ seen.add(item_id)
+
+
+def describe_steps(hog_flow: HogFlow, step_ids: list[str]) -> list[str]:
+ """Step names for a person to read. A step deleted since has no name left, so it keeps its id."""
+ names = {_item_id(item): item.get("name") for item in snapshot_flow_content(hog_flow).get("actions") or []}
+ return [names.get(step_id) or step_id for step_id in step_ids]
+
+
+def conflicting_parts(hog_flow: HogFlow, proposal: WorkflowProposal, content: Optional[dict] = None) -> list[str]:
+ """Parts of the workflow the proposal changes that someone else already changed since it was
+ written: step ids for `actions`, field names for everything else.
+
+ The check follows merge semantics. A step merges per field, so only the fields the proposal sets
+ on the steps it names are compared, as they were at `base_version` against as they are now. A
+ whole-list field replaces the list, so any publish since counts. Every other field replaces one
+ value, so that value is compared. An edit elsewhere merges cleanly, and an edit that already made
+ the proposed change is nothing to undo, so neither is a reason to refuse."""
+ if hog_flow.version == proposal.base_version:
+ return []
+ base_content = base_content_of(hog_flow, proposal)
+ content = proposal_changes(proposal, base_content) if content is None else content
+ touched_steps = {_item_id(item) for item in content.get("actions") or []} - {None}
+ touched_lists = [field for field in PROPOSAL_WHOLE_LIST_FIELDS if field in content]
+ touched_fields = [
+ field
+ for field in content
+ if field not in PROPOSAL_MERGE_BY_ID_FIELDS and field not in PROPOSAL_WHOLE_LIST_FIELDS
+ ]
+ if touched_lists:
+ # A whole-list field replaces the list, so any publish since counts.
+ return sorted({*touched_steps, *touched_lists, *touched_fields})
+ if base_content is None:
+ # Without the snapshot the proposal read, "changed since" is unanswerable.
+ return sorted({*touched_steps, *touched_fields})
+ live_content = snapshot_flow_content(hog_flow)
+ base_actions = {_item_id(item): item for item in base_content.get("actions") or []}
+ live_actions = {_item_id(item): item for item in live_content.get("actions") or []}
+ proposed_actions = {_item_id(item): item for item in content.get("actions") or []}
+ moved_steps = [
+ step_id
+ for step_id in touched_steps
+ # A step the proposal adds is only a conflict if that id now exists.
+ if not (step_id not in base_actions and step_id not in live_actions)
+ and _moved_since(base_actions.get(step_id), live_actions.get(step_id), proposed_actions[step_id])
+ ]
+ moved_fields = [
+ field
+ for field in touched_fields
+ # These replace the whole value, so a key the proposal does not name still goes with it.
+ if base_content.get(field) != live_content.get(field) and live_content.get(field) != content[field]
+ ]
+ return sorted({*moved_steps, *moved_fields})
+
+
+def base_content_of(hog_flow: HogFlow, proposal: WorkflowProposal) -> dict | None:
+ """The workflow as the proposal read it. That is the live workflow while its version has not
+ moved; after a publish it is the revision snapshot, which a workflow that has never been
+ published under revision tracking may not have."""
+ if hog_flow.version == proposal.base_version:
+ return snapshot_flow_content(hog_flow)
+ revision = HogFlowRevision.objects.filter(hog_flow=hog_flow, version=proposal.base_version).first()
+ return dict(revision.content) if revision is not None else None
+
+
+def proposal_changes(proposal: WorkflowProposal, base_content: dict | None) -> dict:
+ """The proposal's content reduced to what it changes against the workflow as it read it: a
+ step keeps only the fields that read differently there, and a step that reads the same drops
+ out. A producer that sends a whole step therefore still merges as the one-field change it made,
+ and never writes the rest of that step back over a later edit. Without the snapshot the content
+ stands as sent."""
+ content = dict(proposal.content)
+ if base_content is None or "actions" not in content:
+ return content
+ base_steps = {_item_id(item): item for item in base_content.get("actions") or []}
+ changed_steps = []
+ for item in content.get("actions") or []:
+ base_step = base_steps.get(_item_id(item))
+ if not isinstance(item, dict) or base_step is None:
+ changed_steps.append(item)
+ continue
+ changed = _changed_leaves(base_step, {key: value for key, value in item.items() if key != "id"})
+ if changed is not _ABSENT:
+ changed_steps.append({"id": item["id"], **changed})
+ content["actions"] = changed_steps
+ return content
+
+
+_ABSENT = object()
+
+
+def _changed_leaves(base: Any, patch: Any) -> Any:
+ """`patch` without every leaf that already reads the same in `base`, read the way `_deep_merge`
+ writes it; `_ABSENT` when nothing is left."""
+ if isinstance(patch, dict) and isinstance(base, dict):
+ kept = {}
+ for key, value in patch.items():
+ changed = _changed_leaves(base.get(key), value)
+ if changed is not _ABSENT:
+ kept[key] = changed
+ return kept if kept else _ABSENT
+ if patch is None:
+ return _ABSENT if base is None else None
+ return _ABSENT if patch == base else patch
+
+
+def _moved_since(base: Any, live: Any, proposed: Any) -> bool:
+ """Whether someone changed, since `base`, something the proposal sets, and to a value other than
+ the proposed one. Reads the patch the way `_deep_merge` writes it: a dict compares leaf by leaf,
+ anything else as one value."""
+ if not isinstance(proposed, dict) or base is None or live is None:
+ return base != live and live != proposed
+ return any(
+ _leaf(live, path) != _leaf(base, path) and _leaf(live, path) != _leaf(proposed, path)
+ for path in _patch_paths(proposed)
+ )
+
+
+def _patch_paths(patch: Any, prefix: tuple[str, ...] = ()) -> list[tuple[str, ...]]:
+ if not isinstance(patch, dict) or not patch:
+ return [prefix]
+ return [path for key, value in patch.items() for path in _patch_paths(value, (*prefix, key))]
+
+
+def _leaf(item: Any, path: tuple[str, ...]) -> Any:
+ for key in path:
+ if not isinstance(item, dict) or key not in item:
+ return _ABSENT
+ item = item[key]
+ # A null leaf in a patch deletes the key, so it reads as the key being absent.
+ return _ABSENT if item is None else item
+
+
+def unstage_workflow_proposals(hog_flow: HogFlow) -> None:
+ """Put every approved suggestion back in the queue, because the draft it was approved into is
+ about to be replaced.
+
+ Approved means one thing here: this suggestion is what sits in the draft. Discarding the draft,
+ restoring a revision, approving a different suggestion or editing over it all replace that
+ draft, and publish reads approved as "this is what shipped", so it must not record one against
+ a version that never carried it. A suggestion whose change survives the replacement comes back
+ to the queue too, which costs a person one more approval rather than a wrong history entry.
+ """
+ WorkflowProposal.objects.filter(hog_flow=hog_flow, status=WorkflowProposal.Status.APPROVED).update(
+ status=WorkflowProposal.Status.SUGGESTED, resolved_at=None, resolved_by=None
+ )
+
+
class CommaSeparatedListFilter(BaseInFilter, CharFilter):
pass
@@ -4028,6 +4572,8 @@ class HogFlowViewSet(
"asset_content",
"revisions",
"revision_detail",
+ "proposal_detail",
+ "proposal_outcome",
]
scope_object_write_actions = [
"create",
@@ -4047,6 +4593,8 @@ class HogFlowViewSet(
"discard_draft",
"restore_revision",
"resume_email_sending",
+ "approve_proposal",
+ "reject_proposal",
]
queryset = HogFlow.objects.all()
pagination_class = HogFlowPagination
@@ -4060,6 +4608,11 @@ class HogFlowViewSet(
# Dual-method custom actions need method-aware scopes — the action-name-based read/write
# lists above can't distinguish GET (read) from POST (write) on the same action. Without
# this, these actions declare no scope and reject all personal-API-key (MCP) access.
+ if self.action == "proposals":
+ # Reading is workflow-read; authoring stages content into the draft, so it is a workflow write.
+ if request.method in ("GET", "HEAD", "OPTIONS"):
+ return ["hog_flow:read"]
+ return ["hog_flow:write"]
if self.action in ("batch_jobs", "schedules"):
# Dispatching (or scheduling) fans out to persons and renders person properties into
# outbound messages, so it's person-data access on top of the workflow write - same
@@ -4503,6 +5056,7 @@ class HogFlowViewSet(
bump = self._stage_revision_bump(serializer.instance, before_update, serializer.validated_data)
if clears_staged_draft:
serializer.save(draft=None, draft_updated_at=None, draft_encrypted_inputs=None)
+ unstage_workflow_proposals(serializer.instance)
else:
serializer.save()
if bump:
@@ -4616,6 +5170,9 @@ class HogFlowViewSet(
instance.draft_encrypted_inputs = draft_encrypted_inputs
instance.save(update_fields=["draft", "draft_updated_at", "draft_encrypted_inputs"])
+ # An edit over an approved draft may undo the suggestion, and publish reads approved as shipped.
+ unstage_workflow_proposals(instance)
+
@extend_schema(request=HogFlowGraphUpdateSerializer, responses={200: HogFlowSerializer})
@action(detail=True, methods=["PATCH"])
def graph(self, request: Request, *args, **kwargs):
@@ -5002,6 +5559,10 @@ class HogFlowViewSet(
locked.draft_updated_at = None
locked.draft_encrypted_inputs = None
locked.save(update_fields=["draft", "draft_updated_at", "draft_encrypted_inputs"])
+ # Every path that changes the draft unstages what it dropped, so whatever is approved here just went live.
+ WorkflowProposal.objects.filter(hog_flow=locked, status=WorkflowProposal.Status.APPROVED).update(
+ status=WorkflowProposal.Status.APPLIED, applied_version=locked.version
+ )
self._maybe_reschedule_timing_edits(before_update, locked)
self._pause_schedules_on_audience_change(before_update, locked)
@@ -5033,6 +5594,7 @@ class HogFlowViewSet(
locked.draft = None
locked.draft_updated_at = None
locked.draft_encrypted_inputs = None
+ unstage_workflow_proposals(locked)
# updated_at (auto_now) is deliberately bumped: without a fresh live stamp the
# resource_edited broadcast carries the old updated_at — older than the draft stamp
# concurrent editors loaded, so they'd ignore the discard, and their next draft save
@@ -5110,6 +5672,7 @@ class HogFlowViewSet(
before_update = HogFlow.objects.get(pk=instance.pk)
locked.draft = dict(revision.content)
locked.draft_updated_at = timezone.now()
+ unstage_workflow_proposals(locked)
# Revision snapshots carry no secrets (they're stripped before snapshotting), so the
# restored draft re-attaches from the live encrypted_inputs on the follow-up publish.
# Clear any stale draft secrets from a prior draft so they can't bleed into this one.
@@ -5122,6 +5685,337 @@ class HogFlowViewSet(
return Response(self.get_serializer(locked).data)
+ def _require_self_optimising_enabled(self) -> None:
+ # Invisible while the flag is off, rather than 403: an endpoint that admits it exists gets built against.
+ if not posthoganalytics.feature_enabled(
+ SELF_OPTIMISING_FEATURE_FLAG,
+ str(self.team.uuid),
+ groups={"organization": str(self.team.organization_id)},
+ group_properties={
+ "organization": {
+ "id": str(self.team.organization_id),
+ "created_at": self.team.organization.created_at,
+ }
+ },
+ send_feature_flag_events=False,
+ ):
+ raise exceptions.NotFound()
+
+ @extend_schema(
+ methods=["GET"],
+ parameters=[
+ OpenApiParameter(
+ "status",
+ OpenApiTypes.STR,
+ description="Only return proposals in this status (suggested, approved, rejected, applied).",
+ enum=[choice.value for choice in WorkflowProposal.Status],
+ )
+ ],
+ responses={200: WorkflowProposalSerializer(many=True)},
+ )
+ @extend_schema(
+ methods=["POST"], request=WorkflowProposalCreateSerializer, responses={201: WorkflowProposalSerializer}
+ )
+ @action(detail=True, methods=["GET", "POST"], filter_backends=[])
+ def proposals(self, request: Request, *args, **kwargs):
+ """Agent-authored changes to this workflow, awaiting a human's decision.
+
+ Creating one stages nothing: a proposal only reaches the workflow's draft once a human
+ approves it, and only reaches the live config once someone publishes that draft.
+ """
+ self._require_self_optimising_enabled()
+ instance = self.get_object()
+
+ # DRF routes HEAD to the GET handler, and the scope gate reads it as a read.
+ if request.method in ("GET", "HEAD"):
+ requested_status = request.query_params.get("status")
+ if requested_status and requested_status not in WorkflowProposal.Status.values:
+ raise exceptions.ValidationError(
+ {"status": f"Must be one of: {', '.join(WorkflowProposal.Status.values)}."}
+ )
+ # Applied ones order by the version that shipped them; the rest read as a queue, newest first.
+ applied_only = requested_status == WorkflowProposal.Status.APPLIED
+ ordering = ("-applied_version", "-created_at") if applied_only else ("-created_at",)
+ queryset = WorkflowProposal.objects.filter(hog_flow=instance).order_by(*ordering)
+ if requested_status:
+ queryset = queryset.filter(status=requested_status)
+ queryset = queryset.select_related("resolved_by", "hog_flow")
+ page = self.paginate_queryset(queryset)
+ return self.get_paginated_response(WorkflowProposalSerializer(page, many=True).data)
+
+ param_serializer = WorkflowProposalCreateSerializer(data=request.data)
+ param_serializer.is_valid(raise_exception=True)
+ params = param_serializer.validated_data
+
+ live_content = snapshot_flow_content(instance)
+ # Proposal content is stored in plaintext like a revision snapshot, so secrets are stripped.
+ content = strip_proposal_secrets(dict(params["content"]), live_content)
+ source_id = params.get("source_id") or None
+
+ if "actions" in content or "edges" in content:
+ merged = merge_proposal_content(live_content, content)
+ try:
+ # Warnings are fine to ignore; only raised errors mean the graph could not run.
+ validate_graph(merged.get("actions") or [], merged.get("edges") or [], merged.get("abort_action"))
+ except serializers.ValidationError as error:
+ raise exceptions.ValidationError(
+ {
+ "content": [
+ "The proposed change does not describe a runnable workflow. Note that steps merge "
+ "by `id` while `edges` replaces the whole list, so an edge to a step that no longer "
+ "exists is the usual cause.",
+ *_flatten_graph_errors(error),
+ ]
+ }
+ )
+
+ if source_id:
+ existing = WorkflowProposal.objects.filter(hog_flow=instance, source_id=source_id).first()
+ if existing:
+ return Response(WorkflowProposalSerializer(existing).data, status=status.HTTP_200_OK)
+
+ proposal = WorkflowProposal(
+ hog_flow=instance,
+ title=params["title"],
+ rationale=params["rationale"],
+ content=content,
+ evidence=params.get("evidence") or {},
+ step_id=params.get("step_id") or None,
+ base_version=params.get("base_version") or instance.version or 1,
+ source_id=source_id,
+ )
+ try:
+ with transaction.atomic():
+ proposal.save()
+ except IntegrityError:
+ # A concurrent create with the same source_id landed between the read and this save.
+ existing = (
+ WorkflowProposal.objects.filter(hog_flow=instance, source_id=source_id).first() if source_id else None
+ )
+ if existing is None:
+ raise
+ return Response(WorkflowProposalSerializer(existing).data, status=status.HTTP_200_OK)
+ self._report_workflow_action(
+ "hog_flow_proposal_created",
+ instance,
+ {"proposal_id": str(proposal.id)},
+ )
+ return Response(WorkflowProposalSerializer(proposal).data, status=status.HTTP_201_CREATED)
+
+ @extend_schema(
+ parameters=[
+ OpenApiParameter("proposal_id", OpenApiTypes.UUID, OpenApiParameter.PATH, description="Proposal to fetch.")
+ ],
+ responses={200: WorkflowProposalSerializer},
+ )
+ @action(detail=True, methods=["GET"], url_path=r"proposals/(?P<proposal_id>[^/.]+)", filter_backends=[])
+ def proposal_detail(self, request: Request, proposal_id: Optional[str] = None, *args, **kwargs):
+ self._require_self_optimising_enabled()
+ instance = self.get_object()
+ proposal = self._get_proposal_or_404(instance, proposal_id)
+ return Response(WorkflowProposalSerializer(proposal).data)
+
+ def _get_proposal_or_404(self, hog_flow: HogFlow, proposal_id: Optional[str]) -> WorkflowProposal:
+ parsed = _parse_uuid_or_none(proposal_id)
+ if parsed is None:
+ raise exceptions.NotFound("No such suggestion for this workflow.")
+ try:
+ return WorkflowProposal.objects.select_related("resolved_by", "hog_flow").get(
+ team_id=self.team_id, hog_flow_id=hog_flow.pk, id=parsed
+ )
+ except WorkflowProposal.DoesNotExist:
+ raise exceptions.NotFound("No such suggestion for this workflow.")
+
+ @extend_schema(
+ parameters=[
+ OpenApiParameter(
+ "proposal_id", OpenApiTypes.UUID, OpenApiParameter.PATH, description="Proposal to approve."
+ )
+ ],
+ request=WorkflowProposalApproveRequestSerializer,
+ responses={200: WorkflowProposalSerializer},
+ )
+ @action(
+ detail=True,
+ methods=["POST"],
+ url_path=r"proposals/(?P<proposal_id>[^/.]+)/approve",
+ filter_backends=[],
+ )
+ def approve_proposal(self, request: Request, proposal_id: Optional[str] = None, *args, **kwargs):
+ # Approval only stages into the draft, like restore_revision; publish still previews and confirms.
+ self._require_self_optimising_enabled()
+ param_serializer = WorkflowProposalApproveRequestSerializer(data=request.data)
+ param_serializer.is_valid(raise_exception=True)
+
+ instance = self.get_object()
+ with transaction.atomic():
+ # nosemgrep: idor-lookup-without-team (re-fetch of already-authorized instance, locked for update)
+ locked = HogFlow.objects.select_for_update().get(pk=instance.pk)
+ proposal = self._get_proposal_or_404(locked, proposal_id)
+ # The row lock serializes concurrent approvals; the second sees what the first wrote.
+ locked_proposal = WorkflowProposal.objects.select_for_update().get(pk=proposal.pk)
+ if locked_proposal.status != WorkflowProposal.Status.SUGGESTED:
+ raise ProposalAlreadyResolvedError()
+ if locked.draft and not param_serializer.validated_data["overwrite"]:
+ raise DraftExistsError()
+ changes = proposal_changes(locked_proposal, base_content_of(locked, locked_proposal))
+ conflicts = conflicting_parts(locked, locked_proposal, changes)
+ if conflicts:
+ raise ProposalOutOfDateError(describe_steps(locked, conflicts))
+ expected_draft_updated_at = param_serializer.validated_data.get("expected_draft_updated_at")
+ if (
+ locked.draft
+ and expected_draft_updated_at is not None
+ and locked.draft_updated_at != expected_draft_updated_at
+ ):
+ raise StaleWorkflowUpdateError()
+ # nosemgrep: idor-lookup-without-team (re-fetch of already-authorized instance for activity logging)
+ before_update = HogFlow.objects.get(pk=instance.pk)
+ # The draft is a full snapshot (live plus what the suggestion changes), so publish stays
+ # a plain copy. A field the suggestion merely echoed is not staged, since writing it back
+ # would undo a later edit the conflict check let through.
+ merged = merge_proposal_content(snapshot_flow_content(locked), changes)
+ try:
+ # Create validated the merge against the graph as it was then; it can have moved since.
+ validate_graph(merged.get("actions") or [], merged.get("edges") or [], merged.get("abort_action"))
+ except serializers.ValidationError as error:
+ raise ProposalNotRunnableError(_flatten_graph_errors(error))
+ locked.draft = merged
+ locked.draft_updated_at = timezone.now()
+ # Proposal content carries no secrets, so the draft re-attaches them from live on publish.
+ locked.draft_encrypted_inputs = None
+ locked.save(update_fields=["draft", "draft_updated_at", "draft_encrypted_inputs"])
+
+ # The new draft replaces what was staged; an earlier approval stays only if the draft still carries it.
+ unstage_workflow_proposals(locked)
+
+ locked_proposal.status = WorkflowProposal.Status.APPROVED
+ locked_proposal.resolved_at = timezone.now()
+ locked_proposal.resolved_by = request.user if request.user.is_authenticated else None
+ locked_proposal.save(update_fields=["status", "resolved_at", "resolved_by"])
+
+ log_activity_from_viewset(self, locked, activity="proposal_approved", name=locked.name, previous=before_update)
+ self._emit_resource_edited(locked)
+ self._report_workflow_action("hog_flow_proposal_approved", locked, {"proposal_id": str(locked_proposal.id)})
+ return Response(WorkflowProposalSerializer(locked_proposal).data)
+
+ @extend_schema(
+ parameters=[
+ OpenApiParameter(
+ "proposal_id", OpenApiTypes.UUID, OpenApiParameter.PATH, description="Proposal to read outcomes for."
+ ),
+ OpenApiParameter("window", OpenApiTypes.STR, description="Relative window, e.g. -7d. Defaults to -7d."),
+ ],
+ responses={200: WorkflowProposalOutcomeSerializer},
+ )
+ @action(
+ detail=True,
+ methods=["GET"],
+ url_path=r"proposals/(?P<proposal_id>[^/.]+)/outcome",
+ filter_backends=[],
+ )
+ def proposal_outcome(self, request: Request, proposal_id: Optional[str] = None, *args, **kwargs):
+ """What the change did: the target metric and its counter-metrics, before and after.
+
+ Both sides are read from the per-version metric series, so "before" is the version the
+ suggestion was written against and "after" is the version it went live as. Each number
+ carries its own `n`, and anything under the minimum sample is flagged rather than presented
+ as a result — a verdict off twenty sends is the loop's most embarrassing failure mode.
+ Comparing two windows is not a controlled experiment; that is what the A/B step is for.
+ """
+ self._require_self_optimising_enabled()
+ instance = self.get_object()
+ proposal = self._get_proposal_or_404(instance, proposal_id)
+ window = request.query_params.get("window") or "-7d"
+ after_date, _, _ = relative_date_parse_with_delta_mapping(window, self.team.timezone_info)
+ # Both reads below go to ClickHouse, which refuses an untagged query.
+ tag_queries(product=ProductKey.WORKFLOWS, feature=Feature.QUERY)
+
+ return Response(
+ WorkflowProposalOutcomeSerializer(
+ {
+ "window": window,
+ "before": self._version_outcome(instance, proposal.base_version, after_date, proposal.step_id),
+ "after": self._version_outcome(instance, proposal.applied_version, after_date, proposal.step_id),
+ "unavailable_guardrails": list(UNAVAILABLE_GUARDRAILS),
+ }
+ ).data
+ )
+
+ def _version_outcome(
+ self, hog_flow: HogFlow, version: Optional[int], after: Any, step_id: Optional[str] = None
+ ) -> Optional[dict]:
+ if version is None:
+ return None
+ # Scoped to the step the suggestion names; several email steps would otherwise share one denominator.
+ totals = fetch_app_metric_totals(
+ team_id=self.team_id,
+ app_source=HOG_FLOW_VERSION_APP_SOURCE,
+ app_source_id=f"{hog_flow.id}/{version}",
+ breakdown_by="name",
+ after=after,
+ instance_id=step_id or None,
+ name=[
+ TARGET_SEND_METRIC,
+ TARGET_OPEN_METRIC,
+ TARGET_CLICK_METRIC,
+ TARGET_UNTRACKED_METRIC,
+ *GUARDRAIL_METRICS,
+ ],
+ ).totals
+ sends = int(totals.get(TARGET_SEND_METRIC, 0))
+ # Untracked sends can never record an open, so opens read against tracked sends; guardrails keep every send.
+ tracked_sends = max(0, sends - int(totals.get(TARGET_UNTRACKED_METRIC, 0)))
+
+ def rate(count: int, label: str, denominator: int) -> dict:
+ return {
+ "metric": label,
+ "value": (count / denominator) if denominator else None,
+ "n": denominator,
+ "below_minimum_sample": denominator < MIN_EVIDENCE_SAMPLE,
+ }
+
+ return {
+ "version": version,
+ "target": rate(int(totals.get(TARGET_OPEN_METRIC, 0)), "email open rate", tracked_sends),
+ # Same denominator as opens: a send with tracking off can record neither.
+ "click_through": rate(int(totals.get(TARGET_CLICK_METRIC, 0)), "click rate", tracked_sends),
+ "guardrails": [rate(int(totals.get(name, 0)), GUARDRAIL_LABELS[name], sends) for name in GUARDRAIL_METRICS],
+ }
+
+ @extend_schema(
+ parameters=[
+ OpenApiParameter("proposal_id", OpenApiTypes.UUID, OpenApiParameter.PATH, description="Proposal to reject.")
+ ],
+ request=WorkflowProposalRejectRequestSerializer,
+ responses={200: WorkflowProposalSerializer},
+ )
+ @action(
+ detail=True,
+ methods=["POST"],
+ url_path=r"proposals/(?P<proposal_id>[^/.]+)/reject",
+ filter_backends=[],
+ )
+ def reject_proposal(self, request: Request, proposal_id: Optional[str] = None, *args, **kwargs):
+ self._require_self_optimising_enabled()
+ param_serializer = WorkflowProposalRejectRequestSerializer(data=request.data)
+ param_serializer.is_valid(raise_exception=True)
+
+ instance = self.get_object()
+ with transaction.atomic():
+ proposal = self._get_proposal_or_404(instance, proposal_id)
+ locked_proposal = WorkflowProposal.objects.select_for_update().get(pk=proposal.pk)
+ if locked_proposal.status != WorkflowProposal.Status.SUGGESTED:
+ raise ProposalAlreadyResolvedError()
+ locked_proposal.status = WorkflowProposal.Status.REJECTED
+ locked_proposal.resolved_at = timezone.now()
+ locked_proposal.resolved_by = request.user if request.user.is_authenticated else None
+ locked_proposal.save(update_fields=["status", "resolved_at", "resolved_by"])
+
+ log_activity_from_viewset(self, instance, activity="proposal_rejected", name=instance.name)
+ self._report_workflow_action("hog_flow_proposal_rejected", instance, {"proposal_id": str(locked_proposal.id)})
+ return Response(WorkflowProposalSerializer(locked_proposal).data)
+
@extend_schema(request=HogFlowInvocationSerializer, responses={200: _FallbackSerializer})
@action(detail=True, methods=["POST"])
def invocations(self, request: Request, *args, **kwargs):
diff --git a/products/workflows/backend/api/test/test_workflow_proposals.py b/products/workflows/backend/api/test/test_workflow_proposals.py
new file mode 100644
index 000000000000..241570848075
--- /dev/null
+++ b/products/workflows/backend/api/test/test_workflow_proposals.py
@@ -0,0 +1,809 @@
+import json
+from types import SimpleNamespace
+
+from posthog.test.base import APIBaseTest
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+
+from posthog.cdp.templates.hog_function_template import sync_template_to_db
+from posthog.models.activity_logging.activity_log import ActivityLog
+from posthog.models.personal_api_key import PersonalAPIKey
+from posthog.models.utils import generate_random_token_personal, hash_key_value
+
+from products.cdp.backend.api.test.test_hog_function_templates import MOCK_NODE_TEMPLATES
+from products.workflows.backend.api.hog_flow import DRAFT_CONTENT_FIELDS
+from products.workflows.backend.models.hog_flow.hog_flow import HogFlow
+from products.workflows.backend.models.workflow_proposal import WorkflowProposal
+
+webhook_template = MOCK_NODE_TEMPLATES[0]
+
+
+def _trigger_action() -> dict:
+ return {
+ "id": "trigger_node",
+ "name": "trigger_1",
+ "type": "trigger",
+ "config": {
+ "type": "event",
+ "filters": {"events": [{"id": "$pageview", "name": "$pageview", "type": "events", "order": 0}]},
+ },
+ }
+
+
+def _webhook_action(action_id: str = "action_1", url: str = "https://example.com") -> dict:
+ return {
+ "id": action_id,
+ "name": action_id,
+ "type": "function",
+ "config": {"template_id": "template-webhook", "inputs": {"url": {"value": url}}},
+ }
+
+
+@patch("products.workflows.backend.api.hog_flow.posthoganalytics.feature_enabled", return_value=True)
+class TestWorkflowProposals(APIBaseTest):
+ def setUp(self):
+ super().setUp()
+ sync_template_to_db(webhook_template)
+
+ def _create_active_flow(self) -> str:
+ create = self.client.post(
+ f"/api/projects/{self.team.id}/hog_flows",
+ {"name": "Proposal Flow", "actions": [_trigger_action(), _webhook_action()]},
+ )
+ assert create.status_code == 201, create.json()
+ flow_id = create.json()["id"]
+ activate = self.client.patch(f"/api/projects/{self.team.id}/hog_flows/{flow_id}", {"status": "active"})
+ assert activate.status_code == 200, activate.json()
+ return flow_id
+
+ def _propose(self, flow_id: str, **overrides) -> dict:
+ payload = {
+ "title": "Point the webhook somewhere that answers",
+ "rationale": "Every call to the current URL failed over the last week.",
+ "content": {"actions": [_trigger_action(), _webhook_action(url="https://proposed.example.com")]},
+ "evidence": {
+ "metric": "failure rate",
+ "current_value": 1.0,
+ "target_value": 0.0,
+ "window": "-7d",
+ "n": 240,
+ "unit": "rate",
+ "guardrails": [{"metric": "complaint rate", "value": 0.0, "n": 240, "unit": "rate"}],
+ },
+ **overrides,
+ }
+ if "base_version" not in payload:
+ live = self.client.get(f"/api/projects/{self.team.id}/hog_flows/{flow_id}")
+ payload["base_version"] = live.json()["version"]
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/proposals/", payload, format="json"
+ )
+ assert response.status_code == 201, response.json()
+ return response.json()
+
+ def _publish(self, flow_id: str):
+ with patch("products.workflows.backend.api.hog_flow.get_hog_flow_in_flight_count") as mock_count:
+ mock_count.return_value = MagicMock(
+ status_code=200, json=lambda: {"count": 0, "by_action": {}, "position_unknown": 0}
+ )
+ preview = self.client.post(f"/api/projects/{self.team.id}/hog_flows/{flow_id}/publish", {})
+ assert preview.status_code == 200, preview.json()
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/publish",
+ {"confirm": True, "confirm_token": preview.json()["confirm_token"]},
+ )
+ assert response.status_code == 200, response.json()
+ return response
+
+ def test_approve_stages_a_full_draft_and_leaves_live_alone(self, _mock_flag):
+ flow_id = self._create_active_flow()
+ proposal = self._propose(flow_id)
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/proposals/{proposal['id']}/approve/", {}
+ )
+ assert response.status_code == 200, response.json()
+ assert response.json()["status"] == "approved"
+
+ flow = HogFlow.objects.get(id=flow_id)
+ assert flow.actions[1]["config"]["inputs"]["url"]["value"] == "https://example.com"
+ assert flow.version == 1
+ draft = flow.draft
+ assert draft is not None
+ assert set(draft.keys()) == set(DRAFT_CONTENT_FIELDS)
+ assert draft["actions"][1]["config"]["inputs"]["url"]["value"] == "https://proposed.example.com"
+
+ def test_publish_marks_the_approved_proposal_applied(self, _mock_flag):
+ flow_id = self._create_active_flow()
+ proposal = self._propose(flow_id)
+ self.client.post(f"/api/projects/{self.team.id}/hog_flows/{flow_id}/proposals/{proposal['id']}/approve/", {})
+
+ self._publish(flow_id)
+
+ stored = WorkflowProposal.objects.for_team(self.team.id).get(id=proposal["id"])
+ assert stored.status == "applied"
+ assert HogFlow.objects.get(id=flow_id).version == 2
+ assert stored.applied_version == 2
+
+ def test_only_the_suggestion_still_staged_is_recorded_as_applied(self, _mock_flag):
+ flow_id = self._create_active_flow()
+ first = self._propose(flow_id, source_id="stub:first")
+ second = self._propose(
+ flow_id,
+ source_id="stub:second",
+ content={"actions": [_trigger_action(), _webhook_action(url="https://second.example.com")]},
+ )
+
+ self.client.post(f"/api/projects/{self.team.id}/hog_flows/{flow_id}/proposals/{first['id']}/approve/", {})
+ approve_second = self.client.post(
+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/proposals/{second['id']}/approve/", {"overwrite": True}
+ )
+ assert approve_second.status_code == 200, approve_second.json()
+
+ self._publish(flow_id)
+
+ assert WorkflowProposal.objects.for_team(self.team.id).get(id=second["id"]).status == "applied"
+ replaced = WorkflowProposal.objects.for_team(self.team.id).get(id=first["id"])
+ assert replaced.status == "suggested"
+ assert replaced.applied_version is None
+ assert HogFlow.objects.get(id=flow_id).actions[1]["config"]["inputs"]["url"]["value"] == (
+ "https://second.example.com"
+ )
+
+ def test_discarding_the_draft_returns_the_suggestion_to_the_queue(self, _mock_flag):
+ flow_id = self._create_active_flow()
+ proposal = self._propose(flow_id)
+ self.client.post(f"/api/projects/{self.team.id}/hog_flows/{flow_id}/proposals/{proposal['id']}/approve/", {})
+
+ discard = self.client.post(f"/api/projects/{self.team.id}/hog_flows/{flow_id}/discard_draft", {})
+ assert discard.status_code == 200, discard.json()
+
+ stored = WorkflowProposal.objects.for_team(self.team.id).get(id=proposal["id"])
+ assert stored.status == "suggested"
+ assert stored.resolved_at is None
+
+ self.client.patch(
+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/graph",
+ {"operations": [{"op": "update_action", "id": "action_1", "patch": {"name": "renamed"}}]},
+ HTTP_X_POSTHOG_CLIENT="mcp",
+ )
+ self._publish(flow_id)
+ assert WorkflowProposal.objects.for_team(self.team.id).get(id=proposal["id"]).status == "suggested"
+
+ def _edit_the_webhook_step_and_publish(self, flow_id: str) -> None:
+ self.client.patch(
+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/graph",
+ {
+ "operations": [
+ {
+ "op": "update_action",
+ "id": "action_1",
+ "patch": {
+ "name": "renamed",
+ "config": {"inputs": {"url": {"value": "https://moved.example.com"}}},
+ },
+ }
+ ]
+ },
+ HTTP_X_POSTHOG_CLIENT="mcp",
+ )
+ self._publish(flow_id)
+
+ def test_a_suggestion_is_refused_once_someone_edits_the_step_it_changes(self, _mock_flag):
+ flow_id = self._create_active_flow()
+ proposal = self._propose(
+ flow_id,
+ content={"actions": [_webhook_action(url="https://proposed.example.com")]},
+ source_id="stale:actions",
+ )
+ self._edit_the_webhook_step_and_publish(flow_id)
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/proposals/{proposal['id']}/approve/", {"overwrite": True}
+ )
+
+ assert response.status_code == 409, response.json()
+ assert response.json()["code"] == "proposal_out_of_date"
+ assert HogFlow.objects.get(id=flow_id).draft is None
+
+ def test_a_variables_suggestion_is_refused_after_any_publish(self, _mock_flag):
+ # Variables replace the whole list, so there is nothing to merge onto and an edit
+ # anywhere in the workflow puts the suggestion out of date.
+ flow_id = self._create_active_flow()
+ proposal = self._propose(
+ flow_id,
+ content={"variables": [{"key": "greeting", "type": "string", "default": "hi"}]},
+ source_id="stale:variables",
+ )
+ self._edit_the_webhook_step_and_publish(flow_id)
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/proposals/{proposal['id']}/approve/", {"overwrite": True}
+ )
+
+ assert response.status_code == 409, response.json()
+ assert response.json()["code"] == "proposal_out_of_date"
+ assert HogFlow.objects.get(id=flow_id).draft is None
+
+ def test_a_step_sent_whole_leaves_the_fields_it_did_not_change(self, _mock_flag):
+ flow_id = self._create_active_flow()
+ # The producer sends the step as it read it, changing only the name.
+ whole_step = _webhook_action()
+ whole_step["name"] = "renamed by the suggestion"
+ proposal = self._propose(flow_id, content={"actions": [whole_step]})
+ self.client.patch(
+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/graph",
+ {
+ "operations": [
+ {
+ "op": "update_action",
+ "id": "action_1",
+ "patch": {"config": {"inputs": {"url": {"value": "https://moved.example.com"}}}},
+ }
+ ]
+ },
+ HTTP_X_POSTHOG_CLIENT="mcp",
+ )
+ self._publish(flow_id)
+
+ approve = self.client.post(
+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/proposals/{proposal['id']}/approve/", {"overwrite": True}
+ )
+
+ assert approve.status_code == 200, approve.json()
+ draft = HogFlow.objects.get(id=flow_id).draft
+ assert draft is not None
+ assert draft["actions"][1]["name"] == "renamed by the suggestion"
+ assert draft["actions"][1]["config"]["inputs"]["url"]["value"] == "https://moved.example.com"
+
+ def test_a_secret_input_in_a_patch_is_not_stored(self, _mock_flag):
+ # The patch carries no template_id, so the secret is only knowable from the step it patches.
+ secret_template = {
+ **webhook_template,
+ "id": "template-webhook-secret",
+ "inputs_schema": [
+ *(webhook_template.get("inputs_schema") or []),
+ {"key": "api_key", "type": "string", "secret": True},
+ ],
+ }
+ sync_template_to_db(secret_template)
+ flow_id = self._create_active_flow()
+ self.client.patch(
+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/graph",
+ {
+ "operations": [
+ {
+ "op": "update_action",
+ "id": "action_1",
+ "patch": {"config": {"template_id": "template-webhook-secret"}},
+ }
+ ]
+ },
+ HTTP_X_POSTHOG_CLIENT="mcp",
+ )
+ self._publish(flow_id)
+
+ proposal = self._propose(
+ flow_id,
+ content={
+ "actions": [{"id": "action_1", "config": {"inputs": {"api_key": {"value": "sk-live-not-a-real-key"}}}}]
+ },
+ )
+
+ stored = WorkflowProposal.objects.for_team(self.team.id).get(id=proposal["id"])
+ assert "api_key" not in stored.content["actions"][0]["config"]["inputs"]
+ assert "sk-live-not-a-real-key" not in json.dumps(proposal)
+
+ def test_a_field_the_merge_replaces_is_compared_whole(self, _mock_flag):
+ flow_id = self._create_active_flow()
+ proposal = self._propose(
+ flow_id,
+ content={
+ "conversion": {
+ "filters": {"events": [{"id": "$pageview", "name": "$pageview", "type": "events"}]},
+ "window": "7d",
+ }
+ },
+ base_version=1,
+ )
+ # The person changes a key the suggestion does not name; replacing the value would drop it.
+ patched = self.client.patch(
+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}",
+ {
+ "conversion": {
+ "filters": {"events": [{"id": "$identify", "name": "$identify", "type": "events"}]},
+ "window": "30d",
+ }
+ },
+ format="json",
+ )
+ assert patched.status_code == 200, patched.json()
+
+ approve = self.client.post(
+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/proposals/{proposal['id']}/approve/", {"overwrite": True}
+ )
+
+ assert approve.status_code == 409, approve.json()
+ assert approve.json()["code"] == "proposal_out_of_date"
+
+ def test_a_field_change_is_refused_once_that_field_moved(self, _mock_flag):
+ flow_id = self._create_active_flow()
+ proposal = self._propose(
+ flow_id, content={"exit_condition": "exit_only_at_end"}, source_id="scalar", base_version=1
+ )
+ patched = self.client.patch(
+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}",
+ {"exit_condition": "exit_on_trigger_not_matched"},
+ format="json",
+ )
+ assert patched.status_code == 200, patched.json()
+ assert patched.json()["version"] == 2
+
+ listed = self.client.get(f"/api/projects/{self.team.id}/hog_flows/{flow_id}/proposals/").json()["results"]
+ assert [item["is_stale"] for item in listed] == [True]
+ approve = self.client.post(
+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/proposals/{proposal['id']}/approve/", {"overwrite": True}
+ )
+ assert approve.status_code == 409, approve.json()
+ assert approve.json()["code"] == "proposal_out_of_date"
+ assert HogFlow.objects.get(id=flow_id).exit_condition == "exit_on_trigger_not_matched"
+ assert HogFlow.objects.get(id=flow_id).draft is None
+
+ def test_a_field_change_still_approves_after_an_edit_elsewhere(self, _mock_flag):
+ flow_id = self._create_active_flow()
+ proposal = self._propose(
+ flow_id, content={"exit_condition": "exit_only_at_end"}, source_id="scalar", base_version=1
+ )
+ self.client.patch(
+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/graph",
+ {"operations": [{"op": "update_action", "id": "action_1", "patch": {"name": "renamed"}}]},
+ HTTP_X_POSTHOG_CLIENT="mcp",
+ )
+ self._publish(flow_id)
+
+ listed = self.client.get(f"/api/projects/{self.team.id}/hog_flows/{flow_id}/proposals/").json()["results"]
+ assert [item["is_stale"] for item in listed] == [False]
+ approve = self.client.post(
+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/proposals/{proposal['id']}/approve/", {"overwrite": True}
+ )
+ assert approve.status_code == 200, approve.json()
+ draft = HogFlow.objects.get(id=flow_id).draft
+ assert draft is not None
+ assert draft["exit_condition"] == "exit_only_at_end"
+ assert {action["name"] for action in draft["actions"]} >= {"renamed"}
+
+ def test_repeat_source_id_returns_the_same_proposal(self, _mock_flag):
+ flow_id = self._create_active_flow()
+ first = self._propose(flow_id, source_id="run:1:finding:webhook-url")
+
+ again = self.client.post(
+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/proposals/",
+ {
+ "title": "Retry of the same finding",
+ "rationale": "A retried agent run must not queue a second copy for the human.",
+ "content": {"actions": [_trigger_action(), _webhook_action()]},
+ "base_version": 1,
+ "source_id": "run:1:finding:webhook-url",
+ },
+ format="json",
+ )
+ assert again.status_code == 200, again.json()
+ assert again.json()["id"] == first["id"]
+ assert WorkflowProposal.objects.for_team(self.team.id).filter(hog_flow_id=flow_id).count() == 1
+
+ @parameterized.expand(
+ [
+ (
+ "no sample size",
+ {"metric": "email open rate", "current_value": 0.07, "unit": "rate", "guardrails": []},
+ "`n`",
+ ),
+ (
+ "no counter-metrics",
+ {"metric": "email open rate", "current_value": 0.07, "unit": "rate", "n": 120},
+ "guardrails",
+ ),
+ (
+ "rate under the producer's own key",
+ {"metric": "email open rate", "current_open_rate": "8.65%", "n": 208, "guardrails": []},
+ "current_value",
+ ),
+ (
+ "a number with no unit",
+ {"metric": "complaints", "current_value": 1, "n": 208, "guardrails": []},
+ "`unit`",
+ ),
+ (
+ "a denominator that is a boolean",
+ {"metric": "email open rate", "current_value": 0.07, "unit": "rate", "n": True, "guardrails": []},
+ "`n`",
+ ),
+ (
+ "a guardrail with no unit",
+ {
+ "metric": "email open rate",
+ "current_value": 0.07,
+ "unit": "rate",
+ "n": 120,
+ "guardrails": [{"metric": "complaints", "value": 1, "n": 120}],
+ },
+ "needs a `unit`",
+ ),
+ ]
+ )
+ def test_a_rate_the_panel_cannot_read_back_is_refused(self, _mock_flag, _name: str, evidence: dict, expected: str):
+ flow_id = self._create_active_flow()
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/proposals/",
+ {
+ "title": "Shorten the subject",
+ "rationale": "Testing the evidence contract.",
+ "content": {"actions": [_trigger_action(), _webhook_action()]},
+ "evidence": evidence,
+ },
+ format="json",
+ )
+ assert response.status_code == 400, response.json()
+ assert expected in str(response.json())
+
+ def test_evidence_with_a_denominator_and_guardrails_is_accepted(self, _mock_flag):
+ flow_id = self._create_active_flow()
+ proposal = self._propose(
+ flow_id,
+ evidence={
+ "metric": "email open rate",
+ "current_value": 0.07,
+ "unit": "rate",
+ "n": 120,
+ "guardrails": [{"metric": "complaint rate", "value": 0.001, "n": 120, "unit": "rate"}],
+ },
+ )
+ assert proposal["evidence"]["guardrails"][0]["metric"] == "complaint rate"
+
+ def test_the_outcome_reads_the_step_the_suggestion_named(self, _mock_flag):
+ flow_id = self._create_active_flow()
+ proposal = self._propose(flow_id, step_id="action_1")
+ self.client.post(f"/api/projects/{self.team.id}/hog_flows/{flow_id}/proposals/{proposal['id']}/approve/", {})
+ self._publish(flow_id)
+
+ with patch("products.workflows.backend.api.hog_flow.fetch_app_metric_totals") as mock_totals:
+ mock_totals.return_value = SimpleNamespace(totals={})
+ response = self.client.get(
+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/proposals/{proposal['id']}/outcome"
+ )
+
+ assert response.status_code == 200, response.json()
+ assert {call.kwargs["instance_id"] for call in mock_totals.call_args_list} == {"action_1"}
+
+ def test_outcome_reports_both_versions_with_their_sample_sizes(self, _mock_flag):
+ flow_id = self._create_active_flow()
+ proposal = self._propose(flow_id)
+ self.client.post(f"/api/projects/{self.team.id}/hog_flows/{flow_id}/proposals/{proposal['id']}/approve/", {})
+ self._publish(flow_id)
+
+ response = self.client.get(
+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/proposals/{proposal['id']}/outcome"
+ )
+ assert response.status_code == 200, response.json()
+ body = response.json()
+ assert body["before"]["version"] == 1
+ assert body["after"]["version"] == 2
+ assert body["after"]["target"]["n"] == 0
+ assert body["after"]["target"]["below_minimum_sample"] is True
+ assert body["after"]["click_through"]["metric"] == "click rate"
+ assert body["after"]["click_through"]["n"] == body["after"]["target"]["n"]
+ assert [guardrail["metric"] for guardrail in body["after"]["guardrails"]] == [
+ "complaint rate",
+ "bounce rate",
+ ]
+ assert body["unavailable_guardrails"] == ["unsubscribe rate"]
+
+ def test_an_api_key_can_read_the_outcome_of_what_it_proposed(self, _mock_flag):
+ flow_id = self._create_active_flow()
+ proposal = self._propose(flow_id)
+ self.client.post(f"/api/projects/{self.team.id}/hog_flows/{flow_id}/proposals/{proposal['id']}/approve/", {})
+ self._publish(flow_id)
+
+ value = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ label="scout", user=self.user, secure_value=hash_key_value(value), scopes=["hog_flow:read"]
+ )
+ self.client.logout()
+
+ response = self.client.get(
+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/proposals/{proposal['id']}/outcome",
+ headers={"authorization": f"Bearer {value}"},
+ )
+ assert response.status_code == 200, response.json()
+ assert response.json()["after"]["version"] == 2
+
+ def test_a_suggestion_carries_only_the_step_it_changes(self, _mock_flag):
+ flow_id = self._create_active_flow()
+ proposal = self._propose(
+ flow_id,
+ content={"actions": [_webhook_action(url="https://proposed.example.com")]},
+ )
+
+ approve = self.client.post(
+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/proposals/{proposal['id']}/approve/", {}
+ )
+
+ assert approve.status_code == 200, approve.json()
+ draft = HogFlow.objects.get(id=flow_id).draft
+ assert draft is not None
+ assert [action["id"] for action in draft["actions"]] == ["trigger_node", "action_1"]
+ assert draft["actions"][1]["config"]["inputs"]["url"]["value"] == "https://proposed.example.com"
+
+ def test_a_suggestion_survives_an_edit_to_a_different_step(self, _mock_flag):
+ flow_id = self._create_active_flow()
+ proposal = self._propose(
+ flow_id,
+ content={"actions": [_webhook_action(url="https://proposed.example.com")]},
+ )
+ self.client.patch(
+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/graph",
+ {"operations": [{"op": "update_action", "id": "trigger_node", "patch": {"name": "renamed by a human"}}]},
+ HTTP_X_POSTHOG_CLIENT="mcp",
+ )
+ self._publish(flow_id)
+
+ approve = self.client.post(
+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/proposals/{proposal['id']}/approve/", {}
+ )
+
+ assert approve.status_code == 200, approve.json()
+ draft = HogFlow.objects.get(id=flow_id).draft
+ assert draft is not None
+ assert draft["actions"][0]["name"] == "renamed by a human"
+ assert draft["actions"][1]["config"]["inputs"]["url"]["value"] == "https://proposed.example.com"
+
+ def test_a_suggestion_is_refused_once_the_step_it_changes_is_deleted(self, _mock_flag):
+ flow_id = self._create_active_flow()
+ proposal = self._propose(
+ flow_id,
+ content={"actions": [_webhook_action(url="https://proposed.example.com")]},
+ )
+ self.client.patch(
+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/graph",
+ {"operations": [{"op": "remove_action", "id": "action_1"}]},
+ HTTP_X_POSTHOG_CLIENT="mcp",
+ )
+ self._publish(flow_id)
+
+ approve = self.client.post(
+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/proposals/{proposal['id']}/approve/",
+ {"overwrite": True},
+ )
+
+ assert approve.status_code == 409, approve.json()
+ assert "action_1" in approve.json()["detail"]
+
+ def test_a_step_needs_the_id_of_the_step_it_changes(self, _mock_flag):
+ flow_id = self._create_active_flow()
+ webhook = _webhook_action(url="https://proposed.example.com")
+ webhook.pop("id")
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/proposals/",
+ {
+ "title": "A step with no id",
+ "rationale": "Merging is keyed on the id, so there is nothing to merge onto.",
+ "content": {"actions": [webhook]},
+ "base_version": 1,
+ },
+ format="json",
+ )
+
+ assert response.status_code == 400, response.json()
+ assert "needs the `id`" in str(response.json())
+ assert WorkflowProposal.objects.for_team(self.team.id).filter(hog_flow_id=flow_id).count() == 0
+
+ @parameterized.expand([("approve",), ("reject",)])
+ def test_resolving_twice_is_refused(self, _mock_flag, action: str):
+ flow_id = self._create_active_flow()
+ proposal = self._propose(flow_id)
+ url = f"/api/projects/{self.team.id}/hog_flows/{flow_id}/proposals/{proposal['id']}/{action}/"
+
+ assert self.client.post(url, {}).status_code == 200
+ second = self.client.post(url, {})
+ assert second.status_code == 409, second.json()
+ assert second.json()["code"] == "proposal_already_resolved"
+
+ def test_approving_over_a_staged_draft_needs_the_draft_stamp_it_saw(self, _mock_flag):
+ flow_id = self._create_active_flow()
+ proposal = self._propose(flow_id)
+ staged = self.client.patch(
+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/graph",
+ {"operations": [{"op": "update_action", "id": "action_1", "patch": {"name": "renamed"}}]},
+ HTTP_X_POSTHOG_CLIENT="mcp",
+ )
+ assert staged.status_code == 200, staged.json()
+
+ url = f"/api/projects/{self.team.id}/hog_flows/{flow_id}/proposals/{proposal['id']}/approve/"
+ blocked = self.client.post(url, {})
+ assert blocked.status_code == 409, blocked.json()
+ assert blocked.json()["code"] == "draft_exists"
+ stale = self.client.post(url, {"overwrite": True, "expected_draft_updated_at": "2020-01-01T00:00:00Z"})
+ assert stale.status_code == 409, stale.json()
+ assert WorkflowProposal.objects.for_team(self.team.id).get(id=proposal["id"]).status == "suggested"
+
+ def test_a_whole_list_proposal_must_say_which_version_it_read(self, _mock_flag):
+ flow_id = self._create_active_flow()
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/proposals/",
+ {
+ "title": "Point the webhook somewhere else",
+ "rationale": "Testing the version contract.",
+ "content": {"actions": [_trigger_action(), _webhook_action()]},
+ },
+ format="json",
+ )
+ assert response.status_code == 400, response.json()
+ assert "base_version" in str(response.json())
+
+ @parameterized.expand(
+ [
+ ("read-only trigger", {"trigger": {"type": "event"}}, "Unknown content field"),
+ ("read-only abort action", {"abort_action": "action_1"}, "Unknown content field"),
+ ("actions holding a string", {"actions": ["oops"]}, "list of objects"),
+ ("actions that are not a list", {"actions": "oops"}, "list of objects"),
+ ("edges holding a string", {"edges": ["oops"]}, "list of objects"),
+ ]
+ )
+ def test_content_the_publish_path_cannot_carry_is_refused(
+ self, _mock_flag, _name: str, content: dict, expected: str
+ ):
+ flow_id = self._create_active_flow()
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/proposals/",
+ {
+ "title": "Change something publish would drop",
+ "rationale": "Testing the content contract.",
+ "content": content,
+ "base_version": 1,
+ },
+ format="json",
+ )
+ assert response.status_code == 400, response.json()
+ assert expected in str(response.json())
+
+ def test_editing_the_draft_returns_the_approved_suggestion_to_the_queue(self, _mock_flag):
+ flow_id = self._create_active_flow()
+ proposal = self._propose(flow_id)
+ approve = self.client.post(
+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/proposals/{proposal['id']}/approve/", {}
+ )
+ assert approve.status_code == 200, approve.json()
+
+ edit = self.client.patch(
+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}",
+ {
+ "actions": [_trigger_action(), _webhook_action(url="https://edited.example.com")],
+ "stage_draft": True,
+ },
+ format="json",
+ )
+ assert edit.status_code == 200, edit.json()
+
+ assert (
+ WorkflowProposal.objects.for_team(self.team.id).get(id=proposal["id"]).status
+ == WorkflowProposal.Status.SUGGESTED
+ )
+
+ self._publish(flow_id)
+ applied = WorkflowProposal.objects.for_team(self.team.id).get(id=proposal["id"])
+ assert applied.status == WorkflowProposal.Status.SUGGESTED
+ assert applied.applied_version is None
+
+ def test_folding_the_draft_into_a_save_returns_the_suggestion_to_the_queue(self, _mock_flag):
+ flow_id = self._create_active_flow()
+ proposal = self._propose(flow_id)
+ self.client.post(f"/api/projects/{self.team.id}/hog_flows/{flow_id}/proposals/{proposal['id']}/approve/", {})
+ # The save below only clears the draft on a workflow that is not live, so pause it first.
+ paused = self.client.patch(f"/api/projects/{self.team.id}/hog_flows/{flow_id}", {"status": "draft"})
+ assert paused.status_code == 200, paused.json()
+
+ # The builder saves a non-active workflow with the staged draft merged in, which clears the draft.
+ saved = self.client.patch(
+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}",
+ {
+ "includes_staged_draft": True,
+ "actions": [_trigger_action(), _webhook_action(url="https://saved.example.com")],
+ "edges": [],
+ "variables": [],
+ "conversion": None,
+ "exit_condition": "exit_only_at_end",
+ "email_sending_rate_limit": None,
+ "trigger_masking": None,
+ },
+ format="json",
+ )
+ assert saved.status_code == 200, saved.json()
+ assert HogFlow.objects.get(id=flow_id).draft is None
+ assert WorkflowProposal.objects.for_team(self.team.id).get(id=proposal["id"]).status == "suggested"
+
+ def test_resolving_a_suggestion_lands_in_the_workflow_history(self, _mock_flag):
+ flow_id = self._create_active_flow()
+ approved = self._propose(flow_id, source_id="history:approved")
+ rejected = self._propose(flow_id, source_id="history:rejected")
+ self.client.post(f"/api/projects/{self.team.id}/hog_flows/{flow_id}/proposals/{rejected['id']}/reject/", {})
+ self.client.post(f"/api/projects/{self.team.id}/hog_flows/{flow_id}/proposals/{approved['id']}/approve/", {})
+
+ activities = list(
+ ActivityLog.objects.filter(team_id=self.team.id, item_id=flow_id).values_list("activity", flat=True)
+ )
+ assert "proposal_approved" in activities
+ assert "proposal_rejected" in activities
+
+ def test_applied_suggestions_are_listed_by_the_version_that_carried_them(self, _mock_flag):
+ flow_id = self._create_active_flow()
+ flow = HogFlow.objects.get(id=flow_id)
+ written_first = WorkflowProposal(
+ hog_flow=flow,
+ team=self.team,
+ title="Written first, shipped last",
+ rationale="Approved after the other one had already shipped.",
+ content={"exit_condition": "exit_on_conversion"},
+ base_version=1,
+ status=WorkflowProposal.Status.APPLIED,
+ applied_version=3,
+ )
+ written_first.save()
+ written_last = WorkflowProposal(
+ hog_flow=flow,
+ team=self.team,
+ title="Written last, shipped first",
+ rationale="Approved and published before the other one.",
+ content={"exit_condition": "exit_on_conversion"},
+ base_version=1,
+ status=WorkflowProposal.Status.APPLIED,
+ applied_version=2,
+ )
+ written_last.save()
+
+ listed = self.client.get(f"/api/projects/{self.team.id}/hog_flows/{flow_id}/proposals/?status=applied&limit=1")
+ assert listed.status_code == 200, listed.json()
+ assert [row["id"] for row in listed.json()["results"]] == [str(written_first.id)]
+
+
+@patch("products.workflows.backend.api.hog_flow.posthoganalytics.feature_enabled", return_value=False)
+class TestWorkflowProposalsFlagOff(APIBaseTest):
+ def setUp(self):
+ super().setUp()
+ sync_template_to_db(webhook_template)
+
+ def test_the_surface_does_not_exist_without_the_flag(self, _mock_flag):
+ create = self.client.post(
+ f"/api/projects/{self.team.id}/hog_flows",
+ {"name": "Proposal Flow", "actions": [_trigger_action(), _webhook_action()]},
+ )
+ flow_id = create.json()["id"]
+
+ listed = self.client.get(f"/api/projects/{self.team.id}/hog_flows/{flow_id}/proposals/")
+ assert listed.status_code == 404, listed.json()
+ created = self.client.post(
+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/proposals/",
+ {"title": "x", "rationale": "y", "content": {"actions": []}},
+ format="json",
+ )
+ assert created.status_code == 404, created.json()
+
+
+class TestWorkflowProposalModel(APIBaseTest):
+ def test_team_is_mirrored_from_the_workflow(self):
+ flow = HogFlow.objects.create(team=self.team, name="Scoped flow")
+ other_team = self.organization.teams.create(name="Other team")
+
+ proposal = WorkflowProposal(
+ hog_flow=flow,
+ team=other_team,
+ title="Wrong team on the way in",
+ rationale="Fail-closed reads filter on this row's team, so it has to match the workflow's.",
+ content={"actions": []},
+ base_version=1,
+ )
+ proposal.save()
+
+ assert proposal.team_id == self.team.id
+ assert WorkflowProposal.objects.for_team(other_team.id).filter(id=proposal.id).count() == 0
diff --git a/products/workflows/backend/metrics.py b/products/workflows/backend/metrics.py
new file mode 100644
index 000000000000..49932580ffbb
--- /dev/null
+++ b/products/workflows/backend/metrics.py
@@ -0,0 +1,32 @@
+"""The metric vocabulary the self-optimising loop reads.
+
+Kept in one place because the two sides of a suggestion have to agree: whatever writes the evidence
+- a Scout, over the API - and the outcome endpoint that reports what the change did. If they name
+different metrics, a proposal's "before" and "after" stop being comparable.
+"""
+
+# Every hog flow metric is mirrored under this app source with the version appended to the flow id,
+# which is what makes a per-version read possible at all. See "Metrics and version attribution" in
+# products/workflows/CONTRIBUTING.md.
+HOG_FLOW_VERSION_APP_SOURCE = "hog_flow_version"
+
+TARGET_SEND_METRIC = "email_sent"
+TARGET_OPEN_METRIC = "email_opened"
+# Both rates count what the window recorded, not what a cohort went on to do.
+# Clicks read against the same denominator as opens; the two move for different reasons.
+TARGET_CLICK_METRIC = "email_link_clicked"
+
+# Sends with tracking off can never record an open, so the open rate reads against
+# (email_sent - email_untracked); guardrail rates keep the raw send count.
+TARGET_UNTRACKED_METRIC = "email_untracked"
+
+# Counter-metrics read over the same window, step and version as the target.
+GUARDRAIL_METRICS = ("email_blocked", "email_bounced")
+GUARDRAIL_LABELS = {"email_blocked": "complaint rate", "email_bounced": "bounce rate"}
+
+# `email_unsubscribed` exists only as a name in the worker's metric union with no producer. Named so
+# the surfaces can say the number is missing rather than imply a zero.
+UNAVAILABLE_GUARDRAILS = ("unsubscribe rate",)
+
+# Below this many observations a rate is noise.
+MIN_EVIDENCE_SAMPLE = 20
diff --git a/products/workflows/frontend/generated/api.schemas.ts b/products/workflows/frontend/generated/api.schemas.ts
index 239539bc8893..1036597b7257 100644
--- a/products/workflows/frontend/generated/api.schemas.ts
+++ b/products/workflows/frontend/generated/api.schemas.ts
@@ -1170,6 +1170,161 @@ export interface AppMetricsTotalsResponseApi {
totals: AppMetricsTotalsResponseApiTotals
}
+/**
+ * * `suggested` - Suggested
+ * * `approved` - Approved
+ * * `rejected` - Rejected
+ * * `applied` - Applied
+ */
+export type WorkflowProposalStatusEnumApi =
+ (typeof WorkflowProposalStatusEnumApi)[keyof typeof WorkflowProposalStatusEnumApi]
+
+export const WorkflowProposalStatusEnumApi = {
+ Suggested: 'suggested',
+ Approved: 'approved',
+ Rejected: 'rejected',
+ Applied: 'applied',
+} as const
+
+/**
+ * Only the content fields the proposal changes. Valid keys: actions, edges, trigger_masking, conversion, exit_condition, email_sending_rate_limit, variables. Each value has the same shape as on the workflow itself.
+ */
+export type WorkflowProposalApiContent = { [key: string]: unknown }
+
+/**
+ * The numbers behind the proposal, read back by name. Five keys are required: `metric`, the metric name; `current_value`, its value as a number (a rate as a fraction, 0.0865, never a string); `unit`, either `rate` or `count`, since 1.0 is either every message or one of them; `n`, the denominator that value was computed over; and `guardrails`, a list of {metric, value, n, unit} counter-metrics read over the same window, empty only if none apply. Also conventional: target_value, window, query, app_source_id. A rate with no denominator lets a reviewer mistake noise for a result, a target with no counter-metrics hides a change that lifts one number by harming another, and a number under a key of your own reads to a person as no evidence at all.
+ */
+export type WorkflowProposalApiEvidence = { [key: string]: unknown }
+
+export interface WorkflowProposalApi {
+ readonly id: string
+ /** Short summary of the proposed change. */
+ readonly title: string
+ /** Why the producer thinks this change is worth making. */
+ readonly rationale: string
+ /** Only the content fields the proposal changes. Valid keys: actions, edges, trigger_masking, conversion, exit_condition, email_sending_rate_limit, variables. Each value has the same shape as on the workflow itself. */
+ readonly content: WorkflowProposalApiContent
+ /** The numbers behind the proposal, read back by name. Five keys are required: `metric`, the metric name; `current_value`, its value as a number (a rate as a fraction, 0.0865, never a string); `unit`, either `rate` or `count`, since 1.0 is either every message or one of them; `n`, the denominator that value was computed over; and `guardrails`, a list of {metric, value, n, unit} counter-metrics read over the same window, empty only if none apply. Also conventional: target_value, window, query, app_source_id. A rate with no denominator lets a reviewer mistake noise for a result, a target with no counter-metrics hides a change that lifts one number by harming another, and a number under a key of your own reads to a person as no evidence at all. */
+ readonly evidence: WorkflowProposalApiEvidence
+ /**
+ * The workflow step this is about. Set for a change to one step: the evidence and the outcome then read that step's metrics, so a change to one email in a sequence is not measured against the rest. Null only for a change that spans the workflow, such as its exit condition or a step being taken out, which is measured on the workflow's own numbers.
+ * @nullable
+ */
+ readonly step_id: string | null
+ /** Live workflow version this was authored against. Approving compares the steps and fields this changes against that version to tell whether somebody else already changed them. */
+ readonly base_version: number
+ /** Whether approving this would undo an edit made since it was proposed. False while the workflow only changed elsewhere, because approving merges per step. */
+ readonly is_stale: boolean
+ readonly status: WorkflowProposalStatusEnumApi
+ /**
+ * Stable id of the producing agent run or finding, e.g. 'run:<run id>:finding:<finding id>'.
+ * @nullable
+ */
+ readonly source_id: string | null
+ readonly created_at: string
+ /** @nullable */
+ readonly resolved_at: string | null
+ readonly resolved_by: UserBasicApi | null
+ /**
+ * Workflow version the approved change went live as.
+ * @nullable
+ */
+ readonly applied_version: number | null
+}
+
+export interface PaginatedWorkflowProposalListApi {
+ count: number
+ /** @nullable */
+ next?: string | null
+ /** @nullable */
+ previous?: string | null
+ results: WorkflowProposalApi[]
+}
+
+/**
+ * Only the workflow content fields this proposal changes. Approving merges them over the live content to build the staged draft, so unrelated parts of the workflow stay as they are. In `actions`, send each step you change with its `id` and only the fields you change; they merge into the live step, and a null field deletes it.
+ */
+export type WorkflowProposalCreateApiContent = { [key: string]: unknown }
+
+/**
+ * The metric numbers behind the proposal, so a human can judge it without re-deriving them.
+ */
+export type WorkflowProposalCreateApiEvidence = { [key: string]: unknown }
+
+export interface WorkflowProposalCreateApi {
+ /**
+ * Short summary of the proposed change.
+ * @maxLength 200
+ */
+ title: string
+ /** Why this change is worth making, in prose a human reads. */
+ rationale: string
+ /** Only the workflow content fields this proposal changes. Approving merges them over the live content to build the staged draft, so unrelated parts of the workflow stay as they are. In `actions`, send each step you change with its `id` and only the fields you change; they merge into the live step, and a null field deletes it. */
+ content: WorkflowProposalCreateApiContent
+ /** The metric numbers behind the proposal, so a human can judge it without re-deriving them. */
+ evidence?: WorkflowProposalCreateApiEvidence
+ /** Workflow version this was authored against. Required when the proposal changes actions, edges or variables: it is the snapshot approve compares against to tell whether someone edited the same steps since, and a defaulted version would read as current however long the producer took. Defaults to the current live version otherwise. */
+ base_version?: number
+ /**
+ * The step this is about. Send it for a change to one step: both the evidence and the outcome then read that step's metrics, so a change to one email in a sequence is not measured against the rest. Leave it out only for a change that spans the workflow, such as its exit condition or a step being taken out, which is measured on the workflow's own numbers.
+ * @maxLength 200
+ * @nullable
+ */
+ step_id?: string | null
+ /**
+ * Stable id of the producing agent run or finding. Posting the same one twice returns the existing proposal instead of creating a duplicate.
+ * @maxLength 200
+ * @nullable
+ */
+ source_id?: string | null
+}
+
+export interface WorkflowProposalApproveRequestApi {
+ /** Replace the open staged draft with this proposal's content. Without it, approving while a draft is open returns 409. */
+ overwrite?: boolean
+ /**
+ * The draft_updated_at of the staged draft this overwrite was confirmed against. A draft with a different stamp returns 409 instead of being overwritten. Omit to overwrite unconditionally.
+ * @nullable
+ */
+ expected_draft_updated_at?: string | null
+}
+
+export interface WorkflowProposalMetricApi {
+ /** What was measured, e.g. 'email open rate'. */
+ metric: string
+ /**
+ * The rate over the window, or null when there was nothing to divide.
+ * @nullable
+ */
+ value: number | null
+ /** Observations the rate was computed over. */
+ n: number
+ /** True when n is too small for the rate to mean anything. Show it labelled, not as a finding. */
+ below_minimum_sample: boolean
+}
+
+export interface WorkflowProposalVersionOutcomeApi {
+ /** Workflow version these numbers belong to. */
+ version: number
+ /** The metric the suggestion aimed at. */
+ target: WorkflowProposalMetricApi
+ /** Click-through rate over the same window and denominator, since opens alone can move without clicks. */
+ click_through: WorkflowProposalMetricApi
+ /** Counter-metrics over the same window, so a harmful win is visible. */
+ guardrails: WorkflowProposalMetricApi[]
+}
+
+export interface WorkflowProposalOutcomeApi {
+ /** Relative window both sides were measured over. */
+ window: string
+ /** The version the change was proposed against. */
+ before: WorkflowProposalVersionOutcomeApi | null
+ /** The version it went live as. Null until the proposal is applied. */
+ after: WorkflowProposalVersionOutcomeApi | null
+ /** Counter-metrics that cannot be read yet, named so their absence is not read as zero. */
+ unavailable_guardrails: string[]
+}
+
export interface HogFlowPublishRequestApi {
/** False (default) previews the publish: returns the impact on people in-flight without changing anything. True applies the staged draft to the live workflow. */
confirm?: boolean
@@ -2115,6 +2270,37 @@ export const HogFlowsMetricsTotalsRetrieveInterval = {
Week: 'week',
} as const
+export type HogFlowsProposalsListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number
+ /**
+ * Only return proposals in this status (suggested, approved, rejected, applied).
+ */
+ status?: HogFlowsProposalsListStatus
+}
+
+export type HogFlowsProposalsListStatus = (typeof HogFlowsProposalsListStatus)[keyof typeof HogFlowsProposalsListStatus]
+
+export const HogFlowsProposalsListStatus = {
+ Applied: 'applied',
+ Approved: 'approved',
+ Rejected: 'rejected',
+ Suggested: 'suggested',
+} as const
+
+export type HogFlowsProposalsOutcomeRetrieveParams = {
+ /**
+ * Relative window, e.g. -7d. Defaults to -7d.
+ */
+ window?: string
+}
+
export type HogFlowsRevisionsListParams = {
/**
* Number of results to return per page.
diff --git a/products/workflows/frontend/generated/api.ts b/products/workflows/frontend/generated/api.ts
index 5b47b1fcb725..cd4561803511 100644
--- a/products/workflows/frontend/generated/api.ts
+++ b/products/workflows/frontend/generated/api.ts
@@ -38,6 +38,8 @@ import type {
HogFlowsMetricsGlobalRetrieveParams,
HogFlowsMetricsRetrieveParams,
HogFlowsMetricsTotalsRetrieveParams,
+ HogFlowsProposalsListParams,
+ HogFlowsProposalsOutcomeRetrieveParams,
HogFlowsReputationRetrieveParams,
HogFlowsRevisionsListParams,
HogInvocationCancelRequestApi,
@@ -51,6 +53,7 @@ import type {
PaginatedHogFlowMinimalListApi,
PaginatedHogFlowRevisionBasicListApi,
PaginatedHogFlowTemplateListApi,
+ PaginatedWorkflowProposalListApi,
PatchedHogFlowActionEmailUpdateApi,
PatchedHogFlowGraphUpdateApi,
PatchedHogFlowScheduleApi,
@@ -58,6 +61,10 @@ import type {
PatchedHogFlowUpdateApi,
TeamEmailReputationResponseApi,
WorkflowEmailPauseStatusApi,
+ WorkflowProposalApi,
+ WorkflowProposalApproveRequestApi,
+ WorkflowProposalCreateApi,
+ WorkflowProposalOutcomeApi,
WorkflowStatsRowApi,
} from './api.schemas'
@@ -738,6 +745,161 @@ export const hogFlowsMetricsTotalsRetrieve = async (
})
}
+export const getHogFlowsProposalsListUrl = (projectId: string, id: string, params?: HogFlowsProposalsListParams) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/hog_flows/${id}/proposals/?${stringifiedParams}`
+ : `/api/projects/${projectId}/hog_flows/${id}/proposals/`
+}
+
+/**
+ * Agent-authored changes to this workflow, awaiting a human's decision.
+ *
+ * Creating one stages nothing: a proposal only reaches the workflow's draft once a human
+ * approves it, and only reaches the live config once someone publishes that draft.
+ */
+export const hogFlowsProposalsList = async (
+ projectId: string,
+ id: string,
+ params?: HogFlowsProposalsListParams,
+ options?: RequestInit
+): Promise<PaginatedWorkflowProposalListApi> => {
+ return apiMutator<PaginatedWorkflowProposalListApi>(getHogFlowsProposalsListUrl(projectId, id, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getHogFlowsProposalsCreateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/hog_flows/${id}/proposals/`
+}
+
+/**
+ * Agent-authored changes to this workflow, awaiting a human's decision.
+ *
+ * Creating one stages nothing: a proposal only reaches the workflow's draft once a human
+ * approves it, and only reaches the live config once someone publishes that draft.
+ */
+export const hogFlowsProposalsCreate = async (
+ projectId: string,
+ id: string,
+ workflowProposalCreateApi: WorkflowProposalCreateApi,
+ options?: RequestInit
+): Promise<WorkflowProposalApi> => {
+ return apiMutator<WorkflowProposalApi>(getHogFlowsProposalsCreateUrl(projectId, id), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(workflowProposalCreateApi),
+ })
+}
+
+export const getHogFlowsProposalsRetrieveUrl = (projectId: string, id: string, proposalId: string) => {
+ return `/api/projects/${projectId}/hog_flows/${id}/proposals/${proposalId}/`
+}
+
+export const hogFlowsProposalsRetrieve = async (
+ projectId: string,
+ id: string,
+ proposalId: string,
+ options?: RequestInit
+): Promise<WorkflowProposalApi> => {
+ return apiMutator<WorkflowProposalApi>(getHogFlowsProposalsRetrieveUrl(projectId, id, proposalId), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getHogFlowsProposalsApproveCreateUrl = (projectId: string, id: string, proposalId: string) => {
+ return `/api/projects/${projectId}/hog_flows/${id}/proposals/${proposalId}/approve/`
+}
+
+export const hogFlowsProposalsApproveCreate = async (
+ projectId: string,
+ id: string,
+ proposalId: string,
+ workflowProposalApproveRequestApi?: WorkflowProposalApproveRequestApi,
+ options?: RequestInit
+): Promise<WorkflowProposalApi> => {
+ return apiMutator<WorkflowProposalApi>(getHogFlowsProposalsApproveCreateUrl(projectId, id, proposalId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(workflowProposalApproveRequestApi),
+ })
+}
+
+export const getHogFlowsProposalsOutcomeRetrieveUrl = (
+ projectId: string,
+ id: string,
+ proposalId: string,
+ params?: HogFlowsProposalsOutcomeRetrieveParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/hog_flows/${id}/proposals/${proposalId}/outcome/?${stringifiedParams}`
+ : `/api/projects/${projectId}/hog_flows/${id}/proposals/${proposalId}/outcome/`
+}
+
+/**
+ * What the change did: the target metric and its counter-metrics, before and after.
+ *
+ * Both sides are read from the per-version metric series, so "before" is the version the
+ * suggestion was written against and "after" is the version it went live as. Each number
+ * carries its own `n`, and anything under the minimum sample is flagged rather than presented
+ * as a result — a verdict off twenty sends is the loop's most embarrassing failure mode.
+ * Comparing two windows is not a controlled experiment; that is what the A/B step is for.
+ */
+export const hogFlowsProposalsOutcomeRetrieve = async (
+ projectId: string,
+ id: string,
+ proposalId: string,
+ params?: HogFlowsProposalsOutcomeRetrieveParams,
+ options?: RequestInit
+): Promise<WorkflowProposalOutcomeApi> => {
+ return apiMutator<WorkflowProposalOutcomeApi>(
+ getHogFlowsProposalsOutcomeRetrieveUrl(projectId, id, proposalId, params),
+ {
+ ...options,
+ method: 'GET',
+ }
+ )
+}
+
+export const getHogFlowsProposalsRejectCreateUrl = (projectId: string, id: string, proposalId: string) => {
+ return `/api/projects/${projectId}/hog_flows/${id}/proposals/${proposalId}/reject/`
+}
+
+export const hogFlowsProposalsRejectCreate = async (
+ projectId: string,
+ id: string,
+ proposalId: string,
+ options?: RequestInit
+): Promise<WorkflowProposalApi> => {
+ return apiMutator<WorkflowProposalApi>(getHogFlowsProposalsRejectCreateUrl(projectId, id, proposalId), {
+ ...options,
+ method: 'POST',
+ })
+}
+
export const getHogFlowsPublishCreateUrl = (projectId: string, id: string) => {
return `/api/projects/${projectId}/hog_flows/${id}/publish/`
}
diff --git a/products/workflows/frontend/generated/api.zod.ts b/products/workflows/frontend/generated/api.zod.ts
index 0765512bfde8..ee8fc7badce3 100644
--- a/products/workflows/frontend/generated/api.zod.ts
+++ b/products/workflows/frontend/generated/api.zod.ts
@@ -2412,6 +2412,69 @@ export const HogFlowsInvocationsCancelCreateBody = /* @__PURE__ */ zod
})
.describe('Cancel in-flight invocations of a workflow. Provide exactly one selector.')
+/**
+ * Agent-authored changes to this workflow, awaiting a human's decision.
+ *
+ * Creating one stages nothing: a proposal only reaches the workflow's draft once a human
+ * approves it, and only reaches the live config once someone publishes that draft.
+ */
+export const hogFlowsProposalsCreateBodyTitleMax = 200
+
+export const hogFlowsProposalsCreateBodyStepIdMax = 200
+
+export const hogFlowsProposalsCreateBodySourceIdMax = 200
+
+export const HogFlowsProposalsCreateBody = /* @__PURE__ */ zod.object({
+ title: zod.string().max(hogFlowsProposalsCreateBodyTitleMax).describe('Short summary of the proposed change.'),
+ rationale: zod.string().describe('Why this change is worth making, in prose a human reads.'),
+ content: zod
+ .record(zod.string(), zod.unknown())
+ .describe(
+ 'Only the workflow content fields this proposal changes. Approving merges them over the live content to build the staged draft, so unrelated parts of the workflow stay as they are. In `actions`, send each step you change with its `id` and only the fields you change; they merge into the live step, and a null field deletes it.'
+ ),
+ evidence: zod
+ .record(zod.string(), zod.unknown())
+ .optional()
+ .describe('The metric numbers behind the proposal, so a human can judge it without re-deriving them.'),
+ base_version: zod
+ .number()
+ .optional()
+ .describe(
+ 'Workflow version this was authored against. Required when the proposal changes actions, edges or variables: it is the snapshot approve compares against to tell whether someone edited the same steps since, and a defaulted version would read as current however long the producer took. Defaults to the current live version otherwise.'
+ ),
+ step_id: zod
+ .string()
+ .max(hogFlowsProposalsCreateBodyStepIdMax)
+ .nullish()
+ .describe(
+ "The step this is about. Send it for a change to one step: both the evidence and the outcome then read that step's metrics, so a change to one email in a sequence is not measured against the rest. Leave it out only for a change that spans the workflow, such as its exit condition or a step being taken out, which is measured on the workflow's own numbers."
+ ),
+ source_id: zod
+ .string()
+ .max(hogFlowsProposalsCreateBodySourceIdMax)
+ .nullish()
+ .describe(
+ 'Stable id of the producing agent run or finding. Posting the same one twice returns the existing proposal instead of creating a duplicate.'
+ ),
+})
+
+export const hogFlowsProposalsApproveCreateBodyOverwriteDefault = false
+
+export const HogFlowsProposalsApproveCreateBody = /* @__PURE__ */ zod.object({
+ overwrite: zod
+ .boolean()
+ .default(hogFlowsProposalsApproveCreateBodyOverwriteDefault)
+ .describe(
+ "Replace the open staged draft with this proposal's content. Without it, approving while a draft is open returns 409."
+ ),
+ expected_draft_updated_at: zod.iso
+ .datetime({ offset: true })
+ .nullish()
+ .describe(
+ 'The draft_updated_at of the staged draft this overwrite was confirmed against. A draft with a different stamp returns 409 instead of being overwritten. Omit to overwrite unconditionally.'
+ ),
+})
+
export const hogFlowsPublishCreateBodyConfirmDefault = false
export const HogFlowsPublishCreateBody = /* @__PURE__ */ zod.object({
diff --git a/products/workflows/mcp/tools.yaml b/products/workflows/mcp/tools.yaml
index c93550b9b4c8..38e778002978 100644
--- a/products/workflows/mcp/tools.yaml
+++ b/products/workflows/mcp/tools.yaml
@@ -78,6 +78,24 @@ tools:
hog-flows-partial-update:
operation: hog_flows_partial_update
enabled: false
+ hog-flows-proposals-approve-create:
+ operation: hog_flows_proposals_approve_create
+ enabled: false
+ hog-flows-proposals-create:
+ operation: hog_flows_proposals_create
+ enabled: false
+ hog-flows-proposals-list:
+ operation: hog_flows_proposals_list
+ enabled: false
+ hog-flows-proposals-outcome-retrieve:
+ operation: hog_flows_proposals_outcome_retrieve
+ enabled: false
+ hog-flows-proposals-reject-create:
+ operation: hog_flows_proposals_reject_create
+ enabled: false
+ hog-flows-proposals-retrieve:
+ operation: hog_flows_proposals_retrieve
+ enabled: false
hog-flows-publish-create:
operation: hog_flows_publish_create
enabled: false
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index d55ce499fb99..886d6533fd85 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -70515,6 +70515,77 @@ export namespace Schemas {
results: WizardSessionDTO[];
}
+ /**
+ * * `suggested` - Suggested
+ * * `approved` - Approved
+ * * `rejected` - Rejected
+ * * `applied` - Applied
+ */
+ export type WorkflowProposalStatusEnum = typeof WorkflowProposalStatusEnum[keyof typeof WorkflowProposalStatusEnum];
+
+
+ export const WorkflowProposalStatusEnum = {
+ Suggested: 'suggested',
+ Approved: 'approved',
+ Rejected: 'rejected',
+ Applied: 'applied',
+ } as const;
+
+ /**
+ * Only the content fields the proposal changes. Valid keys: actions, edges, trigger_masking, conversion, exit_condition, email_sending_rate_limit, variables. Each value has the same shape as on the workflow itself.
+ */
+ export type WorkflowProposalContent = { [key: string]: unknown };
+
+ /**
+ * The numbers behind the proposal, read back by name. Five keys are required: `metric`, the metric name; `current_value`, its value as a number (a rate as a fraction, 0.0865, never a string); `unit`, either `rate` or `count`, since 1.0 is either every message or one of them; `n`, the denominator that value was computed over; and `guardrails`, a list of {metric, value, n, unit} counter-metrics read over the same window, empty only if none apply. Also conventional: target_value, window, query, app_source_id. A rate with no denominator lets a reviewer mistake noise for a result, a target with no counter-metrics hides a change that lifts one number by harming another, and a number under a key of your own reads to a person as no evidence at all.
+ */
+ export type WorkflowProposalEvidence = { [key: string]: unknown };
+
+ export interface WorkflowProposal {
+ readonly id: string;
+ /** Short summary of the proposed change. */
+ readonly title: string;
+ /** Why the producer thinks this change is worth making. */
+ readonly rationale: string;
+ /** Only the content fields the proposal changes. Valid keys: actions, edges, trigger_masking, conversion, exit_condition, email_sending_rate_limit, variables. Each value has the same shape as on the workflow itself. */
+ readonly content: WorkflowProposalContent;
+ /** The numbers behind the proposal, read back by name. Five keys are required: `metric`, the metric name; `current_value`, its value as a number (a rate as a fraction, 0.0865, never a string); `unit`, either `rate` or `count`, since 1.0 is either every message or one of them; `n`, the denominator that value was computed over; and `guardrails`, a list of {metric, value, n, unit} counter-metrics read over the same window, empty only if none apply. Also conventional: target_value, window, query, app_source_id. A rate with no denominator lets a reviewer mistake noise for a result, a target with no counter-metrics hides a change that lifts one number by harming another, and a number under a key of your own reads to a person as no evidence at all. */
+ readonly evidence: WorkflowProposalEvidence;
+ /**
+ * The workflow step this is about. Set for a change to one step: the evidence and the outcome then read that step's metrics, so a change to one email in a sequence is not measured against the rest. Null only for a change that spans the workflow, such as its exit condition or a step being taken out, which is measured on the workflow's own numbers.
+ * @nullable
+ */
+ readonly step_id: string | null;
+ /** Live workflow version this was authored against. Approving compares the steps and fields this changes against that version to tell whether somebody else already changed them. */
+ readonly base_version: number;
+ /** Whether approving this would undo an edit made since it was proposed. False while the workflow only changed elsewhere, because approving merges per step. */
+ readonly is_stale: boolean;
+ readonly status: WorkflowProposalStatusEnum;
+ /**
+ * Stable id of the producing agent run or finding, e.g. 'run:<run id>:finding:<finding id>'.
+ * @nullable
+ */
+ readonly source_id: string | null;
+ readonly created_at: string;
+ /** @nullable */
+ readonly resolved_at: string | null;
+ readonly resolved_by: UserBasic | null;
+ /**
+ * Workflow version the approved change went live as.
+ * @nullable
+ */
+ readonly applied_version: number | null;
+ }
+
+ export interface PaginatedWorkflowProposalList {
+ count: number;
+ /** @nullable */
+ next?: string | null;
+ /** @nullable */
+ previous?: string | null;
+ results: WorkflowProposal[];
+ }
+
export interface PassRateBucket {
/** Bucket start, aligned to success_rate_series_granularity (top of hour, midnight, or Monday). */
bucket_start: string;
@@ -102870,6 +102941,90 @@ export namespace Schemas {
estimated_cost_usd: number | null;
}
+ export interface WorkflowProposalApproveRequest {
+ /** Replace the open staged draft with this proposal's content. Without it, approving while a draft is open returns 409. */
+ overwrite?: boolean;
+ /**
+ * The draft_updated_at of the staged draft this overwrite was confirmed against. A draft with a different stamp returns 409 instead of being overwritten. Omit to overwrite unconditionally.
+ * @nullable
+ */
+ expected_draft_updated_at?: string | null;
+ }
+
+ /**
+ * Only the workflow content fields this proposal changes. Approving merges them over the live content to build the staged draft, so unrelated parts of the workflow stay as they are. In `actions`, send each step you change with its `id` and only the fields you change; they merge into the live step, and a null field deletes it.
+ */
+ export type WorkflowProposalCreateContent = { [key: string]: unknown };
+
+ /**
+ * The metric numbers behind the proposal, so a human can judge it without re-deriving them.
+ */
+ export type WorkflowProposalCreateEvidence = { [key: string]: unknown };
+
+ export interface WorkflowProposalCreate {
+ /**
+ * Short summary of the proposed change.
+ * @maxLength 200
+ */
+ title: string;
+ /** Why this change is worth making, in prose a human reads. */
+ rationale: string;
+ /** Only the workflow content fields this proposal changes. Approving merges them over the live content to build the staged draft, so unrelated parts of the workflow stay as they are. In `actions`, send each step you change with its `id` and only the fields you change; they merge into the live step, and a null field deletes it. */
+ content: WorkflowProposalCreateContent;
+ /** The metric numbers behind the proposal, so a human can judge it without re-deriving them. */
+ evidence?: WorkflowProposalCreateEvidence;
+ /** Workflow version this was authored against. Required when the proposal changes actions, edges or variables: it is the snapshot approve compares against to tell whether someone edited the same steps since, and a defaulted version would read as current however long the producer took. Defaults to the current live version otherwise. */
+ base_version?: number;
+ /**
+ * The step this is about. Send it for a change to one step: both the evidence and the outcome then read that step's metrics, so a change to one email in a sequence is not measured against the rest. Leave it out only for a change that spans the workflow, such as its exit condition or a step being taken out, which is measured on the workflow's own numbers.
+ * @maxLength 200
+ * @nullable
+ */
+ step_id?: string | null;
+ /**
+ * Stable id of the producing agent run or finding. Posting the same one twice returns the existing proposal instead of creating a duplicate.
+ * @maxLength 200
+ * @nullable
+ */
+ source_id?: string | null;
+ }
+
+ export interface WorkflowProposalMetric {
+ /** What was measured, e.g. 'email open rate'. */
+ metric: string;
+ /**
+ * The rate over the window, or null when there was nothing to divide.
+ * @nullable
+ */
+ value: number | null;
+ /** Observations the rate was computed over. */
+ n: number;
+ /** True when n is too small for the rate to mean anything. Show it labelled, not as a finding. */
+ below_minimum_sample: boolean;
+ }
+
+ export interface WorkflowProposalVersionOutcome {
+ /** Workflow version these numbers belong to. */
+ version: number;
+ /** The metric the suggestion aimed at. */
+ target: WorkflowProposalMetric;
+ /** Click-through rate over the same window and denominator, since opens alone can move without clicks. */
+ click_through: WorkflowProposalMetric;
+ /** Counter-metrics over the same window, so a harmful win is visible. */
+ guardrails: WorkflowProposalMetric[];
+ }
+
+ export interface WorkflowProposalOutcome {
+ /** Relative window both sides were measured over. */
+ window: string;
+ /** The version the change was proposed against. */
+ before: WorkflowProposalVersionOutcome | null;
+ /** The version it went live as. Null until the proposal is applied. */
+ after: WorkflowProposalVersionOutcome | null;
+ /** Counter-metrics that cannot be read yet, named so their absence is not read as zero. */
+ unavailable_guardrails: string[];
+ }
+
export interface WorkflowRunActivityPoint {
/** GitHub Actions run id. */
run_id: number;
@@ -112487,6 +112642,38 @@ export namespace Schemas {
Week: 'week',
} as const;
+ export type HogFlowsProposalsListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number;
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number;
+ /**
+ * Only return proposals in this status (suggested, approved, rejected, applied).
+ */
+ status?: HogFlowsProposalsListStatus;
+ };
+
+ export type HogFlowsProposalsListStatus = typeof HogFlowsProposalsListStatus[keyof typeof HogFlowsProposalsListStatus];
+
+
+ export const HogFlowsProposalsListStatus = {
+ Applied: 'applied',
+ Approved: 'approved',
+ Rejected: 'rejected',
+ Suggested: 'suggested',
+ } as const;
+
+ export type HogFlowsProposalsOutcomeRetrieveParams = {
+ /**
+ * Relative window, e.g. -7d. Defaults to -7d.
+ */
+ window?: string;
+ };
+
export type HogFlowsRevisionsListParams = {
/**
* Number of results to return per page.