: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(workflows): add the workflow proposal model (#91708)
Daniel Marchukb1b13f9f2fa3
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yamlindex cbb95a3477f1..7a8b9018500c 100644--- a/.semgrep/rules/security/idor-team-scoped-models.yaml+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml@@ -426,6 +426,7 @@ rules:|WizardRunArtifact|WizardSession|WizardWorker+ |WorkflowProposal)$- focus-metavariable: $SINKpattern-sanitizers:@@ -840,6 +841,7 @@ rules:|WizardRunArtifact|WizardSession|WizardWorker+ |WorkflowProposal)$# Exclude when team filter is present- pattern-not: $M.objects. ... .$METHOD2(..., team__project_id=$T, ...)diff --git a/posthog/models/activity_logging/activity_log.py b/posthog/models/activity_logging/activity_log.pyindex 9524a2b78ec2..cd2f47dc4021 100644--- a/posthog/models/activity_logging/activity_log.py+++ b/posthog/models/activity_logging/activity_log.py@@ -315,6 +315,9 @@ field_with_masked_contents: dict[AuditableScope, list[str]] = {# `before` against the stripped `after`, leaking the secret. Record that actions changed, never# the contents — the per-version content audit lives in the revisions feature instead."actions",+ # Reverse FK into WorkflowProposal's fail-closed manager, and a suggestion filed or resolved+ # is not a workflow edit.+ "proposals",],"OrganizationDomain": ["_scim_bearer_token",@@ -884,6 +887,8 @@ field_exclusions: dict[AuditableScope, list[str]] = {# Reads through UserFacetSettings' own fail-closed TeamScopedManager, which has no# ambient team scope at signal-handling time (same reason Loop excludes triggers/fires)."facet_settings",+ # Same fail-closed manager, on the WorkflowProposal relation a user can resolve.+ "resolved_workflow_proposals",],"AlertConfiguration": ["last_checked_at",diff --git a/products/model_crossing_uses_baseline.txt b/products/model_crossing_uses_baseline.txtindex 5c298847d07d..9fac39e6a924 100644--- a/products/model_crossing_uses_baseline.txt+++ b/products/model_crossing_uses_baseline.txt@@ -428,6 +428,7 @@ posthog.Team workflows.HogFlowRevision.team reverse-accessor(hogflowrevision_setposthog.Team workflows.HogFlowSchedule.team reverse-accessor(hogflowschedule_set) 1posthog.Team workflows.HogFlowTemplate.team reverse-accessor(hogflowtemplate_set) 1posthog.Team workflows.TeamWorkflowsConfig.team reverse-accessor(teamworkflowsconfig) 1+posthog.Team workflows.WorkflowProposal.team reverse-accessor(workflowproposal_set) 1posthog.User access_control.AccessControl.created_by reverse-accessor(accesscontrol_set) 1posthog.User access_control.OrganizationResourceAccess.created_by reverse-accessor(organizationresourceaccess_set) 1posthog.User access_control.Role.created_by reverse-accessor(roles) 1@@ -535,6 +536,7 @@ posthog.User workflows.HogFlow.created_by reverse-accessor(hogflow_set) 1posthog.User workflows.HogFlowBatchJob.created_by reverse-accessor(hogflowbatchjob_set) 1posthog.User workflows.HogFlowRevision.created_by reverse-accessor(hogflowrevision_set) 1posthog.User workflows.HogFlowTemplate.created_by reverse-accessor(hogflowtemplate_set) 1+posthog.User workflows.WorkflowProposal.resolved_by reverse-accessor(resolved_workflow_proposals) 1product_analytics.Insight alerts.AlertConfiguration.insight reverse-accessor(alertconfiguration_set) 1product_analytics.Insight dashboards.Dashboard.insights reverse-accessor(dashboards) 1product_analytics.Insight dashboards.DashboardTile.insight reverse-accessor(dashboard_tiles) 1diff --git a/products/workflows/backend/migrations/0026_workflowproposal.py b/products/workflows/backend/migrations/0026_workflowproposal.pynew file mode 100644index 000000000000..44809f79074c--- /dev/null+++ b/products/workflows/backend/migrations/0026_workflowproposal.py@@ -0,0 +1,152 @@+# Generated by Django 5.2.14 on 2026-08-13 10:13++import django.db.models.deletion+from django.conf import settings+from django.db import migrations, models++import posthog.uuidt+++class Migration(migrations.Migration):+ dependencies = [+ ("posthog", "1300_identityproviderconfig_saml_relay_state_unique"),+ ("workflows", "0025_hogflow_email_sending_paused_by"),+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),+ ]++ operations = [+ migrations.CreateModel(+ name="WorkflowProposal",+ fields=[+ (+ "id",+ models.UUIDField(+ default=posthog.uuidt.UUIDT,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ (+ "title",+ models.CharField(+ help_text="Short summary of the proposed change.",+ max_length=200,+ ),+ ),+ (+ "rationale",+ models.TextField(help_text="Why the producer thinks this change is worth making."),+ ),+ (+ "content",+ models.JSONField(+ help_text="The proposed change as a partial workflow content snapshot: only the content fields it changes, and within `actions` only the steps it changes, each carrying its `id` and only the fields that change. Approving merges it over the live content to build the staged draft."+ ),+ ),+ (+ "step_id",+ models.CharField(+ blank=True,+ help_text=(+ "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."+ ),+ max_length=200,+ null=True,+ ),+ ),+ (+ "base_version",+ models.IntegerField(+ help_text="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."+ ),+ ),+ (+ "evidence",+ models.JSONField(+ blank=True,+ default=dict,+ help_text="The numbers behind the proposal: the metric, its current and target value, the window, and the query that produced them.",+ ),+ ),+ (+ "status",+ models.CharField(+ choices=[+ ("suggested", "Suggested"),+ ("approved", "Approved"),+ ("rejected", "Rejected"),+ ("applied", "Applied"),+ ],+ default="suggested",+ max_length=20,+ ),+ ),+ (+ "source_id",+ models.CharField(+ blank=True,+ help_text="Stable id of the producing agent run or finding, e.g. 'run:<run id>:finding:<finding id>'.",+ max_length=200,+ null=True,+ ),+ ),+ ("created_at", models.DateTimeField(auto_now_add=True)),+ ("resolved_at", models.DateTimeField(blank=True, null=True)),+ (+ "applied_version",+ models.IntegerField(+ blank=True,+ help_text="Workflow version the approved change went live as.",+ null=True,+ ),+ ),+ (+ "hog_flow",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="proposals",+ to="workflows.hogflow",+ ),+ ),+ (+ "resolved_by",+ models.ForeignKey(+ blank=True,+ db_constraint=False,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ related_name="resolved_workflow_proposals",+ to=settings.AUTH_USER_MODEL,+ ),+ ),+ (+ "team",+ models.ForeignKey(+ db_constraint=False,+ on_delete=django.db.models.deletion.CASCADE,+ to="posthog.team",+ ),+ ),+ ],+ options={+ "indexes": [+ models.Index(+ fields=["team", "hog_flow", "status"],+ name="workflow_proposal_status_idx",+ )+ ],+ "constraints": [+ models.UniqueConstraint(+ condition=models.Q(("source_id__isnull", False), models.Q(("source_id", ""), _negated=True)),+ fields=("hog_flow", "source_id"),+ name="unique_workflow_proposal_source",+ )+ ],+ },+ ),+ ]diff --git a/products/workflows/backend/migrations/max_migration.txt b/products/workflows/backend/migrations/max_migration.txtindex 4aa215fa754c..e300e8f6ca1d 100644--- a/products/workflows/backend/migrations/max_migration.txt+++ b/products/workflows/backend/migrations/max_migration.txt@@ -1 +1 @@-0025_hogflow_email_sending_paused_by+0026_workflowproposaldiff --git a/products/workflows/backend/models/__init__.py b/products/workflows/backend/models/__init__.pyindex 0d93b4114cf0..6a5380dc753b 100644--- a/products/workflows/backend/models/__init__.py+++ b/products/workflows/backend/models/__init__.py@@ -4,6 +4,7 @@ from .hog_flow_batch_job import HogFlowBatchJobfrom .hog_flow_revision import HogFlowRevisionfrom .hog_flow_schedule.hog_flow_schedule import HogFlowSchedulefrom .team_workflows_config import TeamWorkflowsConfig+from .workflow_proposal import WorkflowProposal__all__ = ["HogFlow",@@ -12,4 +13,5 @@ __all__ = ["HogFlowSchedule","HogFlowTemplate","TeamWorkflowsConfig",+ "WorkflowProposal",]diff --git a/products/workflows/backend/models/workflow_proposal.py b/products/workflows/backend/models/workflow_proposal.pynew file mode 100644index 000000000000..9ab1081afa54--- /dev/null+++ b/products/workflows/backend/models/workflow_proposal.py@@ -0,0 +1,111 @@+from typing import Any++from django.db import models++from posthog.models.scoping.root_mixin import TeamScopedRootMixin+from posthog.models.utils import UUIDTModel+++class WorkflowProposal(TeamScopedRootMixin, UUIDTModel):+ """A change to a workflow that an agent proposes and a human resolves.++ Approving one stages its content into the workflow's `draft` — the same move as restoring a+ revision — so nothing here can reach the live config without a human publishing it.++ Behind the `self-optimising-workflows` flag. Only PostHog's own scout files one, so the row+ records no author; `source_id` names the run or finding it came from, so a retry lands on the+ row it already made.+ """++ class Status(models.TextChoices):+ SUGGESTED = "suggested", "Suggested"+ APPROVED = "approved", "Approved"+ REJECTED = "rejected", "Rejected"+ APPLIED = "applied", "Applied"++ OPEN_STATUSES = (Status.SUGGESTED,)++ class Meta:+ constraints = [+ # An MCP retry or a re-emitted finding resolves to the same proposal instead of stacking+ # duplicates in a human's queue. Only fenced when the producer named itself; a blank+ # name is no name, so blanks never collide with each other.+ models.UniqueConstraint(+ fields=["hog_flow", "source_id"],+ condition=models.Q(source_id__isnull=False) & ~models.Q(source_id=""),+ name="unique_workflow_proposal_source",+ ),+ ]+ indexes = [+ models.Index(fields=["team", "hog_flow", "status"], name="workflow_proposal_status_idx"),+ ]++ # db_constraint=False on team/resolved_by: a real FK constraint to a hot table+ # (posthog_team, posthog_user) takes a parent-table lock on creation; enforcement stays app-level.+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False)+ hog_flow = models.ForeignKey("workflows.HogFlow", on_delete=models.CASCADE, related_name="proposals")++ title = models.CharField(max_length=200, help_text="Short summary of the proposed change.")+ rationale = models.TextField(help_text="Why the producer thinks this change is worth making.")+ content = models.JSONField(+ help_text=(+ "The proposed change as a partial workflow content snapshot: only the content fields it "+ "changes, and within `actions` only the steps it changes, each carrying its `id` and only "+ "the fields that change. Approving merges it over the live content to build the staged draft."+ )+ )+ step_id = models.CharField(+ max_length=200,+ null=True,+ blank=True,+ help_text=(+ "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."+ ),+ )+ base_version = models.IntegerField(+ help_text=(+ "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."+ )+ )+ evidence = models.JSONField(+ default=dict,+ blank=True,+ help_text=(+ "The numbers behind the proposal: the metric, its current and target value, the window, and "+ "the query that produced them."+ ),+ )++ status = models.CharField(max_length=20, choices=Status, default=Status.SUGGESTED)+ source_id = models.CharField(+ max_length=200,+ null=True,+ blank=True,+ help_text="Stable id of the producing agent run or finding, e.g. 'run:<run id>:finding:<finding id>'.",+ )++ created_at = models.DateTimeField(auto_now_add=True)+ resolved_at = models.DateTimeField(null=True, blank=True)+ resolved_by = models.ForeignKey(+ "posthog.User",+ on_delete=models.SET_NULL,+ null=True,+ blank=True,+ db_constraint=False,+ related_name="resolved_workflow_proposals",+ )+ applied_version = models.IntegerField(+ null=True, blank=True, help_text="Workflow version the approved change went live as."+ )++ def save(self, *args: Any, **kwargs: Any) -> None:+ # Mirrors the workflow's team, as HogFlowRevision does: fail-closed reads filter on this row's team_id.+ self.team_id = self.hog_flow.team_id+ super().save(*args, **kwargs)++ def __str__(self) -> str:+ return f"WorkflowProposal {self.hog_flow_id} ({self.status}): {self.title}"diff --git a/products/workflows/backend/test/test_workflow_proposal_model.py b/products/workflows/backend/test/test_workflow_proposal_model.pynew file mode 100644index 000000000000..d16264775f40--- /dev/null+++ b/products/workflows/backend/test/test_workflow_proposal_model.py@@ -0,0 +1,33 @@+from posthog.test.base import BaseTest++from django.db import IntegrityError, transaction++from products.workflows.backend.models import HogFlow+from products.workflows.backend.models.workflow_proposal import WorkflowProposal+++class TestWorkflowProposalSourceFence(BaseTest):+ def setUp(self):+ super().setUp()+ self.flow = HogFlow.objects.create(team=self.team, name="Fenced flow")++ def _file(self, source_id: str | None) -> WorkflowProposal:+ return WorkflowProposal.objects.for_team(self.team.pk).create(+ team=self.team,+ hog_flow=self.flow,+ title="Shorten the subject",+ rationale="Opens are low.",+ content={"exit_condition": "exit_only_at_end"},+ base_version=1,+ source_id=source_id,+ )++ def test_a_named_source_is_filed_once_per_workflow(self):+ self._file("run:1:finding:1")+ with transaction.atomic(), self.assertRaises(IntegrityError):+ self._file("run:1:finding:1")++ def test_unnamed_sources_do_not_collide(self):+ for source_id in ("", "", None, None):+ self._file(source_id)+ assert WorkflowProposal.objects.for_team(self.team.pk).filter(hog_flow=self.flow).count() == 4