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): revision history with restore-to-draft rollback (#72573)

Harley Alexanderc68548e2b5a2
diff --git a/products/posthog_ai/frontend/policy/toolPolicy.ts b/products/posthog_ai/frontend/policy/toolPolicy.ts
index fc53a626d716..c7f1f5c142f7 100644
--- a/products/posthog_ai/frontend/policy/toolPolicy.ts
+++ b/products/posthog_ai/frontend/policy/toolPolicy.ts
@@ -51,6 +51,7 @@ const POSTHOG_DESTRUCTIVE_SUB_TOOLS = new Set([
'visual-review-runs-finalize-create',
'workflows-discard-draft',
'workflows-publish',
+ 'workflows-restore-revision',
'workflows-test-run',
])
diff --git a/products/tasks/backend/constants.py b/products/tasks/backend/constants.py
index ab3bc3bdc16a..16a7e56d03c7 100644
--- a/products/tasks/backend/constants.py
+++ b/products/tasks/backend/constants.py
@@ -98,6 +98,7 @@ POSTHOG_EXEC_DESTRUCTIVE_SUB_TOOLS: tuple[str, ...] = (
"visual-review-runs-finalize-create",
"workflows-discard-draft",
"workflows-publish",
+ "workflows-restore-revision",
"workflows-test-run",
)
diff --git a/products/workflows/backend/api/hog_flow.py b/products/workflows/backend/api/hog_flow.py
index ee3d5be900b9..229bff5893f9 100644
--- a/products/workflows/backend/api/hog_flow.py
+++ b/products/workflows/backend/api/hog_flow.py
@@ -92,6 +92,7 @@ from products.workflows.backend.models.hog_flow.hog_flow import (
HogFlow,
)
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.services.batch_audience import (
PERSON_BATCH_SIZE as WORKFLOWS_PERSON_BATCH_SIZE,
@@ -139,6 +140,18 @@ DRAFT_CONTENT_FIELDS = (
"variables",
)
+
+def snapshot_flow_content(flow: HogFlow) -> dict:
+ snapshot = {field: getattr(flow, field) for field in DRAFT_CONTENT_FIELDS}
+ # The model's legacy default for actions/edges is `{}`, but the API shape is a list — normalize
+ # so re-validation of a snapshot (draft publish, revision restore) doesn't choke on a
+ # never-edited column.
+ for field in ("actions", "edges"):
+ if not snapshot[field]:
+ snapshot[field] = []
+ return snapshot
+
+
# A batch audience is a one-time snapshot of everyone matching the conditions at run time, so each
# condition must resolve to a concrete set of persons/groups. Feature flag evaluation is dynamic
# (rollout %, distinct_id hashing, super-conditions, holdouts) and has no such fixed membership, so a
@@ -1516,6 +1529,33 @@ class HogFlowPublishResponseSerializer(serializers.Serializer):
)
+class HogFlowRevisionBasicSerializer(serializers.ModelSerializer):
+ # allow_null: the first tracked write bootstraps a snapshot of the pre-existing live content,
+ # which has no author.
+ created_by = UserBasicSerializer(read_only=True, allow_null=True)
+
+ class Meta:
+ model = HogFlowRevision
+ fields = ["version", "created_at", "created_by"]
+ read_only_fields = fields
+
+
+class HogFlowRevisionSerializer(HogFlowRevisionBasicSerializer):
+ class Meta(HogFlowRevisionBasicSerializer.Meta):
+ fields = [*HogFlowRevisionBasicSerializer.Meta.fields, "content"]
+ read_only_fields = fields
+
+
+class HogFlowRevisionRestoreRequestSerializer(serializers.Serializer):
+ overwrite = serializers.BooleanField(
+ default=False,
+ help_text=(
+ "Replace the open staged draft with this revision's content. Without it, restoring while "
+ "a draft is open returns 409."
+ ),
+ )
+
+
class CommaSeparatedListFilter(BaseInFilter, CharFilter):
pass
@@ -1541,6 +1581,18 @@ class StaleWorkflowUpdateError(exceptions.APIException):
default_code = "stale_update"
+class DraftExistsError(exceptions.APIException):
+ status_code = status.HTTP_409_CONFLICT
+ default_detail = (
+ "This workflow has an open draft. Publish or discard it first, or pass overwrite=true to "
+ "replace it with the restored revision."
+ )
+ default_code = "draft_exists"
+
+
+REVISIONS_DISABLED_MESSAGE = "Revision history isn't enabled for this project yet."
+
+
# The confirm token makes the publish preview structurally unskippable: only the preview mints it,
# and it signs the exact draft it previewed — so a valid token proves the caller saw the impact
# summary for the draft being published. Short max-age keeps the previewed counts fresh.
@@ -1573,6 +1625,8 @@ class HogFlowViewSet(
"user_blast_radius",
"assets",
"asset_content",
+ "revisions",
+ "revision_detail",
]
scope_object_write_actions = [
"create",
@@ -1586,6 +1640,7 @@ class HogFlowViewSet(
"graph",
"publish",
"discard_draft",
+ "restore_revision",
]
queryset = HogFlow.objects.all()
pagination_class = HogFlowPagination
@@ -1770,6 +1825,9 @@ class HogFlowViewSet(
# injects derived fields like 'trigger' and 'billable_action_types' which would otherwise make every
# status-only PATCH look like a mixed edit.
route_to_draft = False
+ # Resolved once, before the write transaction: the flag check can hit the network and must
+ # not extend the select_for_update row-lock hold (same rule as _maybe_reschedule_timing_edits).
+ revisions_enabled = use_workflows_revisions(self.team)
if self._is_mcp_request(self.request):
keys = set(self.request.data.keys())
has_status = "status" in keys
@@ -1787,11 +1845,10 @@ class HogFlowViewSet(
# team; otherwise active workflows stay read-only via MCP. Status-only PATCHes (lifecycle
# tools) pass through either way, and metadata-only edits apply live once the flag is on.
if serializer.instance.status == HogFlow.State.ACTIVE and has_non_status:
- if not use_workflows_revisions(self.team):
+ if not revisions_enabled:
raise exceptions.ValidationError(MCP_ACTIVE_EDIT_REJECTION)
route_to_draft = bool(keys & set(DRAFT_CONTENT_FIELDS))
- # TODO(team-workflows): Atomically increment version, insert new object instead of default update behavior
instance_id = serializer.instance.id
# Optimistic concurrency: a client may send the `updated_at` it last loaded as `base_updated_at`.
@@ -1837,11 +1894,21 @@ class HogFlowViewSet(
serializer.validated_data.update(remaining)
serializer.save()
else:
+ bump = False
if before_update is not None:
self._refresh_action_redirects(
- serializer.instance, before_update, serializer.validated_data.get("actions")
+ serializer.instance,
+ before_update,
+ serializer.validated_data.get("actions"),
+ enabled=revisions_enabled,
+ )
+ bump = self._stage_revision_bump(
+ serializer.instance, before_update, serializer.validated_data, enabled=revisions_enabled
)
serializer.save()
+ if bump:
+ assert before_update is not None
+ self._append_revisions(serializer.instance, before_update)
if not route_to_draft:
self._maybe_reschedule_timing_edits(before_update, serializer.instance)
@@ -1874,30 +1941,66 @@ class HogFlowViewSet(
except Exception as e:
logger.warning("Failed to capture hog_flow_activated event", error=str(e))
- def _refresh_action_redirects(self, target: HogFlow, old: HogFlow, new_actions: Optional[list]) -> None:
+ def _refresh_action_redirects(
+ self, target: HogFlow, old: HogFlow, new_actions: Optional[list], enabled: bool
+ ) -> None:
# Skip-forward for deleted steps: refresh the redirect map whenever a live graph write is about
# to land, while both the old graph (`old`, the locked pre-write row) and the new actions are in
# hand. Must run before serializer.save() so the map persists in the same write, transaction,
- # and worker reload as the graph it describes. Flag-gated with the rest of the revisions cycle.
+ # and worker reload as the graph it describes. Flag-gated with the rest of the revisions cycle;
+ # `enabled` is the caller's pre-transaction flag evaluation so no network call runs under the lock.
# No status gate: disabling a flow doesn't purge its parked runs (the worker only cancels them
# if they wake while the flow is still disabled), so a step deleted during a disable/re-enable
# window needs its redirect recorded just like one deleted live.
- if new_actions is None or not use_workflows_revisions(self.team):
+ if new_actions is None or not enabled:
return
target.action_redirects = compute_action_redirects(
old.actions or [], old.edges or [], new_actions, old.action_redirects
)
+ def _stage_revision_bump(self, instance: HogFlow, before: HogFlow, validated_data: dict, enabled: bool) -> bool:
+ # Revision history: only live-content changes get a version. Compared pre-save so the bumped
+ # version lands in the same UPDATE (and worker reload) as the content it describes. The
+ # serializer injects derived fields (trigger, billable_action_types) into every validated
+ # payload, so a status/metadata-only write compares equal here and stays unversioned.
+ # `enabled` is the caller's pre-transaction flag evaluation — the flag check can hit the
+ # network and must not run under the select_for_update lock.
+ if not enabled:
+ return False
+ old_content = snapshot_flow_content(before)
+ new_content = {
+ **old_content,
+ **{field: validated_data[field] for field in DRAFT_CONTENT_FIELDS if field in validated_data},
+ }
+ if new_content == old_content:
+ return False
+ instance.version = (before.version or 0) + 1
+ return True
+
+ def _append_revisions(self, instance: HogFlow, before: HogFlow) -> None:
+ # Must run inside the same transaction as the content write it snapshots. On the first
+ # tracked write, also snapshot the outgoing live content so the state before any tracked
+ # change is always available to roll back to (there's no backfill).
+ if not HogFlowRevision.objects.filter(hog_flow=instance).exists():
+ HogFlowRevision.objects.create(
+ team_id=self.team_id,
+ hog_flow=instance,
+ version=before.version,
+ content=snapshot_flow_content(before),
+ created_by=None,
+ )
+ HogFlowRevision.objects.create(
+ team_id=self.team_id,
+ hog_flow=instance,
+ version=instance.version,
+ content=snapshot_flow_content(instance),
+ created_by=self.request.user if self.request.user.is_authenticated else None,
+ )
+
def _write_draft(self, instance: HogFlow, locked: HogFlow, validated_data: dict) -> None:
# The draft is always a full content snapshot (live config as the base, staged draft on top,
# this edit's validated fields last) so publish is a plain copy with no merge logic.
- snapshot = {field: getattr(locked, field) for field in DRAFT_CONTENT_FIELDS}
- # The model's legacy default for actions/edges is `{}`, but the API shape is a list — normalize
- # so publish's re-validation doesn't choke on a snapshot of a never-edited column.
- for field in ("actions", "edges"):
- if not snapshot[field]:
- snapshot[field] = []
- draft = {**snapshot, **(locked.draft or {})}
+ draft = {**snapshot_flow_content(locked), **(locked.draft or {})}
for field in DRAFT_CONTENT_FIELDS:
if field in validated_data:
draft[field] = validated_data[field]
@@ -1918,13 +2021,17 @@ class HogFlowViewSet(
# Authorize + team-scope via the normal lookup, then re-read FOR UPDATE inside the transaction.
instance = self.get_object()
+ # Resolved before the write transaction: the flag check can hit the network and must not
+ # extend the select_for_update row-lock hold.
+ revisions_enabled = use_workflows_revisions(self.team)
+
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)
route_to_draft = False
if self._is_mcp_request(request) and locked.status == HogFlow.State.ACTIVE:
- if not use_workflows_revisions(self.team):
+ if not revisions_enabled:
raise exceptions.ValidationError(MCP_ACTIVE_EDIT_REJECTION)
route_to_draft = True
@@ -1949,9 +2056,16 @@ class HogFlowViewSet(
if route_to_draft:
self._write_draft(locked, locked, serializer.validated_data)
else:
- self._refresh_action_redirects(locked, before_update, serializer.validated_data.get("actions"))
+ self._refresh_action_redirects(
+ locked, before_update, serializer.validated_data.get("actions"), enabled=revisions_enabled
+ )
+ bump = self._stage_revision_bump(
+ locked, before_update, serializer.validated_data, enabled=revisions_enabled
+ )
# save() mutates and returns `locked` in place, so it's the saved HogFlow from here on.
serializer.save()
+ if bump:
+ self._append_revisions(locked, before_update)
if not route_to_draft:
self._maybe_reschedule_timing_edits(before_update, locked)
@@ -2104,8 +2218,15 @@ class HogFlowViewSet(
# recompiles bytecode — a stored blob is never trusted to be execution-ready.
serializer = self.get_serializer(locked, data=dict(locked.draft), partial=True)
serializer.is_valid(raise_exception=True)
- self._refresh_action_redirects(locked, before_update, serializer.validated_data.get("actions"))
+ # enabled=True: the flag was already checked (and required) at the top of this method,
+ # before the transaction — re-evaluating it here would put a network call under the lock.
+ self._refresh_action_redirects(
+ locked, before_update, serializer.validated_data.get("actions"), enabled=True
+ )
+ bump = self._stage_revision_bump(locked, before_update, serializer.validated_data, enabled=True)
serializer.save()
+ if bump:
+ self._append_revisions(locked, before_update)
locked.draft = None
locked.draft_updated_at = None
locked.save(update_fields=["draft", "draft_updated_at"])
@@ -2147,6 +2268,73 @@ class HogFlowViewSet(
return Response(self.get_serializer(locked).data)
+ @extend_schema(responses={200: HogFlowRevisionBasicSerializer(many=True)})
+ # filter_backends=[]: don't inherit the viewset's HogFlow filterset — its fields would be
+ # advertised as query params in the generated contract but silently ignored here.
+ @action(detail=True, methods=["GET"], filter_backends=[])
+ def revisions(self, request: Request, *args, **kwargs):
+ # Version history: one snapshot per live-content change, newest first. Content is fetched
+ # per-version via the detail endpoint — the list stays light.
+ if not use_workflows_revisions(self.team):
+ raise exceptions.ValidationError(REVISIONS_DISABLED_MESSAGE)
+ instance = self.get_object()
+ queryset = HogFlowRevision.objects.filter(hog_flow=instance).order_by("-version").select_related("created_by")
+ page = self.paginate_queryset(queryset)
+ return self.get_paginated_response(HogFlowRevisionBasicSerializer(page, many=True).data)
+
+ @extend_schema(
+ parameters=[OpenApiParameter("version", int, OpenApiParameter.PATH, description="Workflow version to fetch.")],
+ responses={200: HogFlowRevisionSerializer},
+ )
+ @action(detail=True, methods=["GET"], url_path=r"revisions/(?P<version>\d+)")
+ def revision_detail(self, request: Request, version: Optional[str] = None, *args, **kwargs):
+ if not use_workflows_revisions(self.team):
+ raise exceptions.ValidationError(REVISIONS_DISABLED_MESSAGE)
+ instance = self.get_object()
+ try:
+ revision = HogFlowRevision.objects.get(hog_flow=instance, version=int(version or 0))
+ except HogFlowRevision.DoesNotExist:
+ raise exceptions.NotFound("No such revision for this workflow.")
+ return Response(HogFlowRevisionSerializer(revision).data)
+
+ @extend_schema(
+ parameters=[
+ OpenApiParameter("version", int, OpenApiParameter.PATH, description="Workflow version to restore.")
+ ],
+ request=HogFlowRevisionRestoreRequestSerializer,
+ responses={200: HogFlowSerializer},
+ )
+ @action(detail=True, methods=["POST"], url_path=r"revisions/(?P<version>\d+)/restore")
+ def restore_revision(self, request: Request, version: Optional[str] = None, *args, **kwargs):
+ # Rollback (or roll-forward) = copy the revision's content into the draft, then go through
+ # the normal publish preview + confirm. Nothing here touches the live config, so the impact
+ # of the rollback is always previewed and confirmed like any other publish.
+ if not use_workflows_revisions(self.team):
+ raise exceptions.ValidationError(REVISIONS_DISABLED_MESSAGE)
+ param_serializer = HogFlowRevisionRestoreRequestSerializer(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)
+ try:
+ revision = HogFlowRevision.objects.get(hog_flow_id=locked.pk, version=int(version or 0))
+ except HogFlowRevision.DoesNotExist:
+ raise exceptions.NotFound("No such revision for this workflow.")
+ if locked.draft and not param_serializer.validated_data["overwrite"]:
+ raise DraftExistsError()
+ # nosemgrep: idor-lookup-without-team (re-fetch of already-authorized instance for activity logging)
+ before_update = HogFlow.objects.get(pk=instance.pk)
+ locked.draft = dict(revision.content)
+ locked.draft_updated_at = timezone.now()
+ locked.save(update_fields=["draft", "draft_updated_at"])
+
+ log_activity_from_viewset(self, locked, name=locked.name, previous=before_update)
+ self._emit_resource_edited(locked)
+
+ return Response(self.get_serializer(locked).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_hog_flow_revisions.py b/products/workflows/backend/api/test/test_hog_flow_revisions.py
new file mode 100644
index 000000000000..865e05faa5d8
--- /dev/null
+++ b/products/workflows/backend/api/test/test_hog_flow_revisions.py
@@ -0,0 +1,311 @@
+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 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.hog_flow_revision import HogFlowRevision
+
+webhook_template = MOCK_NODE_TEMPLATES[0]
+
+FLAG_PATH = "products.workflows.backend.api.hog_flow.use_workflows_revisions"
+
+
+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}}},
+ }
+
+
+class TestHogFlowRevisions(APIBaseTest):
+ def setUp(self):
+ super().setUp()
+ sync_template_to_db(webhook_template)
+
+ def _create_active_flow(self) -> str:
+ hog_flow = {"name": "Test Flow", "actions": [_trigger_action(), _webhook_action()]}
+ create = self.client.post(f"/api/projects/{self.team.id}/hog_flows", hog_flow)
+ 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 _create_active_three_step_flow(self) -> str:
+ hog_flow = {
+ "name": "Revision Flow",
+ "actions": [_trigger_action(), _webhook_action("action_1"), _webhook_action("action_2")],
+ "edges": [
+ {"from": "trigger_node", "to": "action_1", "type": "continue"},
+ {"from": "action_1", "to": "action_2", "type": "continue"},
+ ],
+ }
+ create = self.client.post(f"/api/projects/{self.team.id}/hog_flows", hog_flow)
+ 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 _live_edit(self, flow_id: str, url: str = "https://changed.example.com"):
+ return self.client.patch(
+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}",
+ {"actions": [_trigger_action(), _webhook_action(url=url)]},
+ )
+
+ def _stage_draft(self, flow_id: str, url: str = "https://changed.example.com"):
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}",
+ {"actions": [_trigger_action(), _webhook_action(url=url)]},
+ HTTP_X_POSTHOG_CLIENT="mcp",
+ )
+ assert response.status_code == 200, 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 _list_revisions(self, flow_id: str) -> list[dict]:
+ # Assert through the endpoint, not the ORM, so these exercise its team scoping, ordering
+ # (newest-first), and serialization (content omitted). Requires the flag on for a 200.
+ response = self.client.get(f"/api/projects/{self.team.id}/hog_flows/{flow_id}/revisions")
+ assert response.status_code == 200, response.json()
+ return response.json()["results"]
+
+ def _revision_content(self, flow_id: str, version: int) -> dict:
+ response = self.client.get(f"/api/projects/{self.team.id}/hog_flows/{flow_id}/revisions/{version}")
+ assert response.status_code == 200, response.json()
+ return response.json()["content"]
+
+ # ── Appending on live-content writes ─────────────────────────────
+
+ @patch(FLAG_PATH, return_value=True)
+ def test_publish_appends_revision_and_bumps_version(self, _flag):
+ flow_id = self._create_active_flow()
+ self._stage_draft(flow_id)
+ published = self._publish(flow_id)
+ assert published.json()["workflow"]["version"] == 2
+
+ revisions = self._list_revisions(flow_id)
+ # Newest-first: v2 (this user's publish) then the v1 bootstrap snapshot (no author)
+ assert [r["version"] for r in revisions] == [2, 1]
+ assert revisions[0]["created_by"]["id"] == self.user.id
+ assert revisions[1]["created_by"] is None
+ # First write also snapshots the outgoing live content, so there's always a state to roll back to
+ v1_urls = [
+ a["config"]["inputs"]["url"]["value"]
+ for a in self._revision_content(flow_id, 1)["actions"]
+ if a["type"] == "function"
+ ]
+ assert v1_urls == ["https://example.com"]
+ v2_content = self._revision_content(flow_id, 2)
+ v2_urls = [a["config"]["inputs"]["url"]["value"] for a in v2_content["actions"] if a["type"] == "function"]
+ assert v2_urls == ["https://changed.example.com"]
+ # Content is exactly the draft-cycle content fields — no system bookkeeping
+ assert set(v2_content.keys()) == set(DRAFT_CONTENT_FIELDS)
+
+ @patch(FLAG_PATH, return_value=True)
+ def test_web_live_edit_appends_revision(self, _flag):
+ flow_id = self._create_active_flow()
+ response = self._live_edit(flow_id)
+ assert response.status_code == 200, response.json()
+ assert response.json()["version"] == 2
+ assert [r["version"] for r in self._list_revisions(flow_id)] == [2, 1]
+
+ @patch(FLAG_PATH, return_value=True)
+ def test_graph_live_edit_appends_revision(self, _flag):
+ flow_id = self._create_active_three_step_flow()
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/graph",
+ {"operations": [{"op": "remove_action", "id": "action_1"}]},
+ )
+ assert response.status_code == 200, response.json()
+ assert response.json()["version"] == 2
+ assert [r["version"] for r in self._list_revisions(flow_id)] == [2, 1]
+ assert "action_1" not in [a["id"] for a in self._revision_content(flow_id, 2)["actions"]]
+
+ @parameterized.expand(
+ [
+ ("draft_staging", {"actions": [_trigger_action(), _webhook_action(url="https://d.example.com")]}, "mcp"),
+ ("metadata_only", {"name": "Renamed"}, None),
+ ("status_only", {"status": "draft"}, None),
+ ]
+ )
+ def test_non_content_writes_do_not_append_revisions(self, _name, payload, client_header):
+ flow_id = self._create_active_flow()
+ with patch(FLAG_PATH, return_value=True):
+ extra = {"HTTP_X_POSTHOG_CLIENT": client_header} if client_header else {}
+ response = self.client.patch(f"/api/projects/{self.team.id}/hog_flows/{flow_id}", payload, **extra)
+ assert response.status_code == 200, response.json()
+ assert self._list_revisions(flow_id) == []
+ assert response.json()["version"] == 1
+
+ @patch(FLAG_PATH, return_value=True)
+ def test_no_op_live_edit_does_not_append_revision(self, _flag):
+ # Two identical saves in a row: the first may change stored shape (create vs update
+ # serializer defaults differ), but the second must not append a junk revision.
+ flow_id = self._create_active_flow()
+ first = self.client.patch(
+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}",
+ {"actions": [_trigger_action(), _webhook_action()]},
+ )
+ assert first.status_code == 200, first.json()
+ revisions_after_first = [r["version"] for r in self._list_revisions(flow_id)]
+
+ second = self.client.patch(
+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}",
+ {"actions": [_trigger_action(), _webhook_action()]},
+ )
+ assert second.status_code == 200, second.json()
+ assert [r["version"] for r in self._list_revisions(flow_id)] == revisions_after_first
+
+ @patch(FLAG_PATH, return_value=False)
+ def test_flag_off_appends_no_revisions(self, _flag):
+ flow_id = self._create_active_flow()
+ response = self._live_edit(flow_id)
+ assert response.status_code == 200, response.json()
+ assert response.json()["version"] == 1
+ # Flag off: the list endpoint is rejected (see test_flag_off_rejects_revision_endpoints), so
+ # assert directly that nothing was persisted.
+ assert not HogFlowRevision.objects.for_team(self.team.id).filter(hog_flow_id=flow_id).exists()
+
+ # ── Listing and fetching ─────────────────────────────────────────
+
+ @patch(FLAG_PATH, return_value=True)
+ def test_list_and_retrieve_revisions(self, _flag):
+ flow_id = self._create_active_flow()
+ self._live_edit(flow_id)
+
+ response = self.client.get(f"/api/projects/{self.team.id}/hog_flows/{flow_id}/revisions")
+ assert response.status_code == 200, response.json()
+ results = response.json()["results"]
+ assert [r["version"] for r in results] == [2, 1]
+ assert results[0]["created_by"]["id"] == self.user.id
+ assert results[1]["created_by"] is None, "the bootstrap snapshot has no author and must serialize as null"
+ assert "content" not in results[0]
+
+ detail = self.client.get(f"/api/projects/{self.team.id}/hog_flows/{flow_id}/revisions/1")
+ assert detail.status_code == 200, detail.json()
+ urls = [
+ a["config"]["inputs"]["url"]["value"]
+ for a in detail.json()["content"]["actions"]
+ if a["type"] == "function"
+ ]
+ assert urls == ["https://example.com"]
+
+ @patch(FLAG_PATH, return_value=True)
+ def test_retrieve_missing_revision_404s(self, _flag):
+ flow_id = self._create_active_flow()
+ response = self.client.get(f"/api/projects/{self.team.id}/hog_flows/{flow_id}/revisions/99")
+ assert response.status_code == 404, response.json()
+
+ # ── Restore (rollback) ───────────────────────────────────────────
+
+ @patch(FLAG_PATH, return_value=True)
+ def test_restore_copies_revision_into_draft_without_touching_live(self, _flag):
+ flow_id = self._create_active_flow()
+ self._live_edit(flow_id)
+ live_actions = HogFlow.objects.get(pk=flow_id).actions
+
+ response = self.client.post(f"/api/projects/{self.team.id}/hog_flows/{flow_id}/revisions/1/restore", {})
+ assert response.status_code == 200, response.json()
+
+ flow = HogFlow.objects.get(pk=flow_id)
+ assert flow.actions == live_actions
+ assert flow.draft is not None
+ assert flow.draft_updated_at is not None
+ draft_urls = [a["config"]["inputs"]["url"]["value"] for a in flow.draft["actions"] if a["type"] == "function"]
+ assert draft_urls == ["https://example.com"]
+
+ @patch(FLAG_PATH, return_value=True)
+ def test_rollback_round_trip_restores_live_and_prunes_redirects(self, _flag):
+ # Publish v2 deleting a step (parked runs get a redirect), then roll back to v1: the step
+ # comes back, its redirect entry is pruned, and the rollback is recorded as a new revision.
+ flow_id = self._create_active_three_step_flow()
+ self._stage_draft_delete_action_1(flow_id)
+ self._publish(flow_id)
+ flow = HogFlow.objects.get(pk=flow_id)
+ assert flow.action_redirects == {"action_1": "action_2"}
+
+ restore = self.client.post(f"/api/projects/{self.team.id}/hog_flows/{flow_id}/revisions/1/restore", {})
+ assert restore.status_code == 200, restore.json()
+ self._publish(flow_id)
+
+ flow = HogFlow.objects.get(pk=flow_id)
+ assert "action_1" in [a["id"] for a in flow.actions]
+ assert flow.action_redirects is None, "re-adding the deleted step must prune its redirect entry"
+ assert flow.draft is None
+ assert [r["version"] for r in self._list_revisions(flow_id)] == [3, 2, 1]
+
+ def _stage_draft_delete_action_1(self, flow_id: str) -> None:
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}",
+ {
+ "actions": [_trigger_action(), _webhook_action("action_2")],
+ "edges": [{"from": "trigger_node", "to": "action_2", "type": "continue"}],
+ },
+ HTTP_X_POSTHOG_CLIENT="mcp",
+ )
+ assert response.status_code == 200, response.json()
+
+ @patch(FLAG_PATH, return_value=True)
+ def test_restore_with_open_draft_conflicts_unless_overwrite(self, _flag):
+ flow_id = self._create_active_flow()
+ self._live_edit(flow_id)
+ self._stage_draft(flow_id, url="https://staged.example.com")
+
+ conflict = self.client.post(f"/api/projects/{self.team.id}/hog_flows/{flow_id}/revisions/1/restore", {})
+ assert conflict.status_code == 409, conflict.json()
+ flow = HogFlow.objects.get(pk=flow_id)
+ assert flow.draft is not None
+ staged_urls = [a["config"]["inputs"]["url"]["value"] for a in flow.draft["actions"] if a["type"] == "function"]
+ assert staged_urls == ["https://staged.example.com"], "a rejected restore must not clobber the open draft"
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/revisions/1/restore", {"overwrite": True}
+ )
+ assert response.status_code == 200, response.json()
+ flow = HogFlow.objects.get(pk=flow_id)
+ assert flow.draft is not None
+ draft_urls = [a["config"]["inputs"]["url"]["value"] for a in flow.draft["actions"] if a["type"] == "function"]
+ assert draft_urls == ["https://example.com"]
+
+ @parameterized.expand([("list", "GET", "revisions"), ("restore", "POST", "revisions/1/restore")])
+ def test_flag_off_rejects_revision_endpoints(self, _name, method, path):
+ flow_id = self._create_active_flow()
+ with patch(FLAG_PATH, return_value=False):
+ response = getattr(self.client, method.lower())(
+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/{path}", {} if method == "POST" else None
+ )
+ assert response.status_code == 400, response.json()
diff --git a/products/workflows/frontend/generated/api.schemas.ts b/products/workflows/frontend/generated/api.schemas.ts
index 6871b0a7642d..3d1a459c533d 100644
--- a/products/workflows/frontend/generated/api.schemas.ts
+++ b/products/workflows/frontend/generated/api.schemas.ts
@@ -973,6 +973,36 @@ export interface HogInvocationRerunResponseApi {
skipped_count: number
}
+export interface HogFlowRevisionBasicApi {
+ /** Workflow version this snapshot was published as. */
+ readonly version: number
+ readonly created_at: string
+ readonly created_by: UserBasicApi | null
+}
+
+export interface PaginatedHogFlowRevisionBasicListApi {
+ count: number
+ /** @nullable */
+ next?: string | null
+ /** @nullable */
+ previous?: string | null
+ results: HogFlowRevisionBasicApi[]
+}
+
+export interface HogFlowRevisionApi {
+ /** Workflow version this snapshot was published as. */
+ readonly version: number
+ readonly created_at: string
+ readonly created_by: UserBasicApi | null
+ /** Full snapshot of the workflow's content fields (actions, edges, trigger, etc.) at this version. */
+ readonly content: unknown
+}
+
+export interface HogFlowRevisionRestoreRequestApi {
+ /** Replace the open staged draft with this revision's content. Without it, restoring while a draft is open returns 409. */
+ overwrite?: boolean
+}
+
export interface PatchedHogFlowScheduleApi {
readonly id?: string
/** iCalendar RRULE string (e.g. 'FREQ=DAILY;INTERVAL=1'). Must produce occurrences at most once per hour. */
@@ -1462,6 +1492,17 @@ export const HogFlowsMetricsTotalsRetrieveInterval = {
Week: 'week',
} as const
+export type HogFlowsRevisionsListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number
+}
+
export type HogFlowsMetricsGlobalRetrieveParams = {
/**
* Start of the window, matched on metric time. Relative ('-7d', '-24h') or ISO 8601. Defaults to -7d.
diff --git a/products/workflows/frontend/generated/api.ts b/products/workflows/frontend/generated/api.ts
index 9a4012c98ea4..67842f01c263 100644
--- a/products/workflows/frontend/generated/api.ts
+++ b/products/workflows/frontend/generated/api.ts
@@ -18,6 +18,8 @@ import type {
HogFlowInvocationApi,
HogFlowPublishRequestApi,
HogFlowPublishResponseApi,
+ HogFlowRevisionApi,
+ HogFlowRevisionRestoreRequestApi,
HogFlowScheduleApi,
HogFlowTemplateApi,
HogFlowTemplatesListParams,
@@ -30,12 +32,14 @@ import type {
HogFlowsMetricsGlobalRetrieveParams,
HogFlowsMetricsRetrieveParams,
HogFlowsMetricsTotalsRetrieveParams,
+ HogFlowsRevisionsListParams,
HogInvocationRerunRequestApi,
HogInvocationRerunResponseApi,
HogInvocationResultApi,
HogInvocationResultDetailApi,
MessageAssetApi,
PaginatedHogFlowMinimalListApi,
+ PaginatedHogFlowRevisionBasicListApi,
PaginatedHogFlowTemplateListApi,
PatchedHogFlowApi,
PatchedHogFlowGraphUpdateApi,
@@ -658,6 +662,69 @@ export const hogFlowsRerunCreate = async (
})
}
+export const getHogFlowsRevisionsListUrl = (projectId: string, id: string, params?: HogFlowsRevisionsListParams) => {
+ 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}/revisions/?${stringifiedParams}`
+ : `/api/projects/${projectId}/hog_flows/${id}/revisions/`
+}
+
+export const hogFlowsRevisionsList = async (
+ projectId: string,
+ id: string,
+ params?: HogFlowsRevisionsListParams,
+ options?: RequestInit
+): Promise<PaginatedHogFlowRevisionBasicListApi> => {
+ return apiMutator<PaginatedHogFlowRevisionBasicListApi>(getHogFlowsRevisionsListUrl(projectId, id, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getHogFlowsRevisionsRetrieveUrl = (projectId: string, id: string, version: number) => {
+ return `/api/projects/${projectId}/hog_flows/${id}/revisions/${version}/`
+}
+
+export const hogFlowsRevisionsRetrieve = async (
+ projectId: string,
+ id: string,
+ version: number,
+ options?: RequestInit
+): Promise<HogFlowRevisionApi> => {
+ return apiMutator<HogFlowRevisionApi>(getHogFlowsRevisionsRetrieveUrl(projectId, id, version), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getHogFlowsRevisionsRestoreCreateUrl = (projectId: string, id: string, version: number) => {
+ return `/api/projects/${projectId}/hog_flows/${id}/revisions/${version}/restore/`
+}
+
+export const hogFlowsRevisionsRestoreCreate = async (
+ projectId: string,
+ id: string,
+ version: number,
+ hogFlowRevisionRestoreRequestApi?: HogFlowRevisionRestoreRequestApi,
+ options?: RequestInit
+): Promise<HogFlowApi> => {
+ return apiMutator<HogFlowApi>(getHogFlowsRevisionsRestoreCreateUrl(projectId, id, version), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(hogFlowRevisionRestoreRequestApi),
+ })
+}
+
export const getHogFlowsSchedulesListUrl = (projectId: string, id: string) => {
return `/api/projects/${projectId}/hog_flows/${id}/schedules/`
}
diff --git a/products/workflows/frontend/generated/api.zod.ts b/products/workflows/frontend/generated/api.zod.ts
index f8049069d242..ec27ae072a86 100644
--- a/products/workflows/frontend/generated/api.zod.ts
+++ b/products/workflows/frontend/generated/api.zod.ts
@@ -2067,6 +2067,17 @@ export const HogFlowsRerunCreateBody = /* @__PURE__ */ zod
})
.describe('Rerun invocations of a hog function or hog flow from their stored payloads.')
+export const hogFlowsRevisionsRestoreCreateBodyOverwriteDefault = false
+
+export const HogFlowsRevisionsRestoreCreateBody = /* @__PURE__ */ zod.object({
+ overwrite: zod
+ .boolean()
+ .default(hogFlowsRevisionsRestoreCreateBodyOverwriteDefault)
+ .describe(
+ "Replace the open staged draft with this revision's content. Without it, restoring while a draft is open returns 409."
+ ),
+})
+
export const hogFlowsSchedulesCreateBodyTimezoneMax = 64
export const HogFlowsSchedulesCreateBody = /* @__PURE__ */ zod.object({
diff --git a/products/workflows/mcp/tools.yaml b/products/workflows/mcp/tools.yaml
index 44265f0a298d..6f5f125ffdcf 100644
--- a/products/workflows/mcp/tools.yaml
+++ b/products/workflows/mcp/tools.yaml
@@ -75,6 +75,15 @@ tools:
hog-flows-rerun-create:
operation: hog_flows_rerun_create
enabled: false
+ hog-flows-revisions-list:
+ operation: hog_flows_revisions_list
+ enabled: false
+ hog-flows-revisions-restore-create:
+ operation: hog_flows_revisions_restore_create
+ enabled: false
+ hog-flows-revisions-retrieve:
+ operation: hog_flows_revisions_retrieve
+ enabled: false
hog-flows-schedules-create:
operation: hog_flows_schedules_create
enabled: false
@@ -177,6 +186,20 @@ tools:
Get a single workflow invocation by invocation_id, including invocation_globals — the raw triggering payload
(event/person/groups) that the run executed against. Use after workflows-list-invocations to inspect exactly
what input produced a failure.
+ workflows-get-revision:
+ operation: hog_flows_revisions_retrieve
+ enabled: true
+ scopes:
+ - hog_flow:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ title: Get workflow revision
+ description: >
+ Get one revision of a workflow by version number, including its full content snapshot (actions, edges,
+ trigger, variables). Use to inspect what was live at that version before restoring it with
+ workflows-restore-revision.
workflows-global-stats:
operation: hog_flows_metrics_global_retrieve
enabled: true
@@ -242,6 +265,21 @@ tools:
failure view: filter status=failed to see who it failed for and why. Filter by distinct_id and time range.
Distinct from workflows-list-batch-jobs (the dispatch ledger, which has no per-person outcome) — drill from
a failed invocation into workflows-logs for the step-by-step trace.
+ workflows-list-revisions:
+ operation: hog_flows_revisions_list
+ enabled: true
+ scopes:
+ - hog_flow:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ list: true
+ title: List workflow revisions
+ description: >
+ List a workflow's revision history, newest first. Every live-content change (publish, direct edit) appends a
+ version; each entry shows version, when, and by whom. Fetch a version's content with workflows-get-revision;
+ roll back with workflows-restore-revision.
workflows-logs:
operation: hog_flows_logs_retrieve
enabled: true
@@ -300,6 +338,23 @@ tools:
draft changed since the preview and a 400 means the token expired — preview again and re-confirm either way.
Publish revalidates the draft fully and recompiles it, so an invalid draft is rejected with the reason and
the live config stays untouched. Test the draft first with workflows-test-run (use_draft=true).
+ workflows-restore-revision:
+ operation: hog_flows_revisions_restore_create
+ enabled: true
+ scopes:
+ - hog_flow:write
+ annotations:
+ readOnly: false
+ destructive: true
+ idempotent: true
+ title: Restore workflow revision
+ description: >
+ Roll a workflow back (or forward) by copying a revision's content into its staged draft — the live config is
+ untouched until you publish. Then run the normal cycle: test with workflows-test-run (use_draft=true),
+ preview with workflows-publish, confirm. The preview shows exactly what the rollback does to people
+ in-flight. A 409 means a draft is already open — publish or discard it, or pass overwrite=true to replace
+ it. Note what a rollback can't undo: runs that already moved on while the newer version was live keep their
+ positions.
workflows-stats:
operation: hog_flows_metrics_retrieve
enabled: true
diff --git a/products/workflows/skills/building-workflows/SKILL.md b/products/workflows/skills/building-workflows/SKILL.md
index 71eb327e1715..6864650a9c36 100644
--- a/products/workflows/skills/building-workflows/SKILL.md
+++ b/products/workflows/skills/building-workflows/SKILL.md
@@ -45,6 +45,12 @@ Editing an active workflow stages a **draft** instead of changing what's running
In-flight runs follow the live config: once published, people mid-flow continue from their current step on the new version. Steps they already passed don't re-run; people parked on a step the publish deletes skip forward to its next surviving step (or exit at a dead end), exactly as the impact preview reported.
+### Rolling back
+
+Every live-content change appends a snapshot to the workflow's revision history. `workflows-list-revisions` lists versions (newest first); `workflows-get-revision` returns one version's full content. To roll back (or forward), `workflows-restore-revision` copies that version's content into the draft — it never touches the live config — then the normal publish cycle applies: test with `use_draft=true`, preview, confirm. The preview shows exactly what the rollback does to people in-flight, same as any publish.
+
+A restore returns 409 when a draft is already open; publish or discard it, or pass `overwrite=true` to replace it. Two things a rollback cannot undo: runs that already moved or exited while the newer version was live keep their positions (their side effects happened), and a publish that shortened a delay may have pulled parked wake times earlier — rolling back doesn't push them later again.
+
If an edit is rejected with "editing an active workflow isn't supported", draft editing isn't enabled for this project yet — then a live change means recreating the workflow as a new draft (`workflows-create`), testing it, and enabling it as a replacement.
## What the server owns, never send it
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 2f3beff90ecb..1fa31db6fb24 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -10153,6 +10153,20 @@
"readOnlyHint": true
}
},
+ "workflows-get-revision": {
+ "description": "Get one revision of a workflow by version number, including its full content snapshot (actions, edges, trigger, variables). Use to inspect what was live at that version before restoring it with workflows-restore-revision.",
+ "category": "Workflows",
+ "feature": "workflows",
+ "summary": "Get workflow revision",
+ "title": "Get workflow revision",
+ "required_scopes": ["hog_flow:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
"workflows-global-stats": {
"description": "At-a-glance health across ALL workflows in one call: per-workflow succeeded/failed counts over a window (after/before, default last 7 days), sorted most-failing first. Start here when debugging — find which workflows are failing, then drill into those with workflows-list-invocations (who it failed for) → workflows-get-invocation (the triggering payload) → workflows-logs (the failing step). Avoids scanning every workflow one at a time. For a single workflow's time-series, use workflows-stats.",
"category": "Workflows",
@@ -10223,6 +10237,20 @@
"readOnlyHint": true
}
},
+ "workflows-list-revisions": {
+ "description": "List a workflow's revision history, newest first. Every live-content change (publish, direct edit) appends a version; each entry shows version, when, and by whom. Fetch a version's content with workflows-get-revision; roll back with workflows-restore-revision.",
+ "category": "Workflows",
+ "feature": "workflows",
+ "summary": "List workflow revisions",
+ "title": "List workflow revisions",
+ "required_scopes": ["hog_flow:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
"workflows-logs": {
"description": "Retrieve execution logs for a specific workflow by ID. Returns log entries with timestamp, level (DEBUG, LOG, INFO, WARN, ERROR), and message. Use to debug why a workflow is failing or not producing expected results. Supports filtering by log level, text search, time range (after/before), and pagination via limit.",
"category": "Workflows",
@@ -10279,6 +10307,20 @@
"readOnlyHint": false
}
},
+ "workflows-restore-revision": {
+ "description": "Roll a workflow back (or forward) by copying a revision's content into its staged draft — the live config is untouched until you publish. Then run the normal cycle: test with workflows-test-run (use_draft=true), preview with workflows-publish, confirm. The preview shows exactly what the rollback does to people in-flight. A 409 means a draft is already open — publish or discard it, or pass overwrite=true to replace it. Note what a rollback can't undo: runs that already moved on while the newer version was live keep their positions.",
+ "category": "Workflows",
+ "feature": "workflows",
+ "summary": "Restore workflow revision",
+ "title": "Restore workflow revision",
+ "required_scopes": ["hog_flow:write"],
+ "annotations": {
+ "destructiveHint": true,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ }
+ },
"workflows-show-email-template": {
"description": "Render an email template as an inline preview for the user. Call after creating or updating a template, and whenever the user asks to see one. The response carries the final rendered html — read it before describing the result. For fetching a template to edit it, use workflows-get-email-template.",
"category": "Workflows",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 3e3aba627f45..68fcce7b3007 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -10774,6 +10774,20 @@
"readOnlyHint": true
}
},
+ "workflows-get-revision": {
+ "description": "Get one revision of a workflow by version number, including its full content snapshot (actions, edges, trigger, variables). Use to inspect what was live at that version before restoring it with workflows-restore-revision.",
+ "category": "Workflows",
+ "feature": "workflows",
+ "summary": "Get workflow revision",
+ "title": "Get workflow revision",
+ "required_scopes": ["hog_flow:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
"workflows-global-stats": {
"description": "At-a-glance health across ALL workflows in one call: per-workflow succeeded/failed counts over a window (after/before, default last 7 days), sorted most-failing first. Start here when debugging — find which workflows are failing, then drill into those with workflows-list-invocations (who it failed for) → workflows-get-invocation (the triggering payload) → workflows-logs (the failing step). Avoids scanning every workflow one at a time. For a single workflow's time-series, use workflows-stats.",
"category": "Workflows",
@@ -10844,6 +10858,20 @@
"readOnlyHint": true
}
},
+ "workflows-list-revisions": {
+ "description": "List a workflow's revision history, newest first. Every live-content change (publish, direct edit) appends a version; each entry shows version, when, and by whom. Fetch a version's content with workflows-get-revision; roll back with workflows-restore-revision.",
+ "category": "Workflows",
+ "feature": "workflows",
+ "summary": "List workflow revisions",
+ "title": "List workflow revisions",
+ "required_scopes": ["hog_flow:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
"workflows-logs": {
"description": "Retrieve execution logs for a specific workflow by ID. Returns log entries with timestamp, level (DEBUG, LOG, INFO, WARN, ERROR), and message. Use to debug why a workflow is failing or not producing expected results. Supports filtering by log level, text search, time range (after/before), and pagination via limit.",
"category": "Workflows",
@@ -10900,6 +10928,20 @@
"readOnlyHint": false
}
},
+ "workflows-restore-revision": {
+ "description": "Roll a workflow back (or forward) by copying a revision's content into its staged draft — the live config is untouched until you publish. Then run the normal cycle: test with workflows-test-run (use_draft=true), preview with workflows-publish, confirm. The preview shows exactly what the rollback does to people in-flight. A 409 means a draft is already open — publish or discard it, or pass overwrite=true to replace it. Note what a rollback can't undo: runs that already moved on while the newer version was live keep their positions.",
+ "category": "Workflows",
+ "feature": "workflows",
+ "summary": "Restore workflow revision",
+ "title": "Restore workflow revision",
+ "required_scopes": ["hog_flow:write"],
+ "annotations": {
+ "destructiveHint": true,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ }
+ },
"workflows-run-batch": {
"description": "Broadcast a batch workflow to its matching users NOW — sends real messages/webhooks, not a test. Workflow must be enabled. STOP before calling: show the user the audience size from workflows-blast-radius and get their explicit confirmation in a separate turn — never size and fire in one step. Requires acknowledged_affected_count from workflows-blast-radius; rejects on drift or over the cap.",
"category": "Workflows",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 832c04af238a..407bfb4f1c4a 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -32729,6 +32729,27 @@ export namespace Schemas {
workflow?: HogFlow | null;
}
+ export interface HogFlowRevision {
+ /** Workflow version this snapshot was published as. */
+ readonly version: number;
+ readonly created_at: string;
+ readonly created_by: UserBasic | null;
+ /** Full snapshot of the workflow's content fields (actions, edges, trigger, etc.) at this version. */
+ readonly content: unknown;
+ }
+
+ export interface HogFlowRevisionBasic {
+ /** Workflow version this snapshot was published as. */
+ readonly version: number;
+ readonly created_at: string;
+ readonly created_by: UserBasic | null;
+ }
+
+ export interface HogFlowRevisionRestoreRequest {
+ /** Replace the open staged draft with this revision's content. Without it, restoring while a draft is open returns 409. */
+ overwrite?: boolean;
+ }
+
/**
* @nullable
*/
@@ -41180,6 +41201,15 @@ export namespace Schemas {
results: HogFlowMinimal[];
}
+ export interface PaginatedHogFlowRevisionBasicList {
+ count: number;
+ /** @nullable */
+ next?: string | null;
+ /** @nullable */
+ previous?: string | null;
+ results: HogFlowRevisionBasic[];
+ }
+
export interface PaginatedHogFlowTemplateList {
count: number;
/** @nullable */
@@ -75675,6 +75705,17 @@ export namespace Schemas {
Week: 'week',
} as const;
+ export type HogFlowsRevisionsListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number;
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number;
+ };
+
export type HogFlowsMetricsGlobalRetrieveParams = {
/**
* Start of the window, matched on metric time. Relative ('-7d', '-24h') or ISO 8601. Defaults to -7d.
diff --git a/services/mcp/src/generated/workflows/api.ts b/services/mcp/src/generated/workflows/api.ts
index d42cf56b4ae7..d7991374eabe 100644
--- a/services/mcp/src/generated/workflows/api.ts
+++ b/services/mcp/src/generated/workflows/api.ts
@@ -3,7 +3,7 @@
* MCP service uses these Zod schemas for generated tool handlers.
* To regenerate: hogli build:openapi
*
- * PostHog API - MCP 15 enabled ops
+ * PostHog API - MCP 18 enabled ops
* OpenAPI spec version: 1.0.0
*/
import * as zod from 'zod'
@@ -1017,6 +1017,51 @@ export const HogFlowsPublishCreateBody = /* @__PURE__ */ zod.object({
),
})
+export const HogFlowsRevisionsListParams = /* @__PURE__ */ zod.object({
+ id: zod.string().describe('A UUID string identifying this hog flow.'),
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."
+ ),
+})
+
+export const HogFlowsRevisionsListQueryParams = /* @__PURE__ */ zod.object({
+ limit: zod.number().optional().describe('Number of results to return per page.'),
+ offset: zod.number().optional().describe('The initial index from which to return the results.'),
+})
+
+export const HogFlowsRevisionsRetrieveParams = /* @__PURE__ */ zod.object({
+ id: zod.string().describe('A UUID string identifying this hog flow.'),
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."
+ ),
+ version: zod.number().describe('Workflow version to fetch.'),
+})
+
+export const HogFlowsRevisionsRestoreCreateParams = /* @__PURE__ */ zod.object({
+ id: zod.string().describe('A UUID string identifying this hog flow.'),
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."
+ ),
+ version: zod.number().describe('Workflow version to restore.'),
+})
+
+export const hogFlowsRevisionsRestoreCreateBodyOverwriteDefault = false
+
+export const HogFlowsRevisionsRestoreCreateBody = /* @__PURE__ */ zod.object({
+ overwrite: zod
+ .boolean()
+ .default(hogFlowsRevisionsRestoreCreateBodyOverwriteDefault)
+ .describe(
+ "Replace the open staged draft with this revision's content. Without it, restoring while a draft is open returns 409."
+ ),
+})
+
export const HogFlowsSchedulesPartialUpdateParams = /* @__PURE__ */ zod.object({
id: zod.string().describe('A UUID string identifying this hog flow.'),
project_id: zod
diff --git a/services/mcp/src/tools/generated/workflows.ts b/services/mcp/src/tools/generated/workflows.ts
index e064627115df..c3a031fba4c4 100644
--- a/services/mcp/src/tools/generated/workflows.ts
+++ b/services/mcp/src/tools/generated/workflows.ts
@@ -22,6 +22,11 @@ import {
HogFlowsPublishCreateBody,
HogFlowsPublishCreateParams,
HogFlowsRetrieveParams,
+ HogFlowsRevisionsListParams,
+ HogFlowsRevisionsListQueryParams,
+ HogFlowsRevisionsRestoreCreateBody,
+ HogFlowsRevisionsRestoreCreateParams,
+ HogFlowsRevisionsRetrieveParams,
HogFlowsSchedulesPartialUpdateBody,
HogFlowsSchedulesPartialUpdateParams,
} from '@/generated/workflows/api'
@@ -125,6 +130,21 @@ const workflowsGetInvocation = (): ToolBase<
},
})
+const WorkflowsGetRevisionSchema = HogFlowsRevisionsRetrieveParams.omit({ project_id: true })
+
+const workflowsGetRevision = (): ToolBase<typeof WorkflowsGetRevisionSchema, Schemas.HogFlowRevision> => ({
+ name: 'workflows-get-revision',
+ schema: WorkflowsGetRevisionSchema,
+ handler: async (context: Context, params: z.infer<typeof WorkflowsGetRevisionSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.HogFlowRevision>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/hog_flows/${encodeURIComponent(String(params.id))}/revisions/${encodeURIComponent(String(params.version))}/`,
+ })
+ return result
+ },
+})
+
const WorkflowsGlobalStatsSchema = HogFlowsMetricsGlobalRetrieveQueryParams
const workflowsGlobalStats = (): ToolBase<
@@ -217,6 +237,30 @@ const workflowsListInvocations = (): ToolBase<
},
})
+const WorkflowsListRevisionsSchema = HogFlowsRevisionsListParams.omit({ project_id: true }).extend(
+ HogFlowsRevisionsListQueryParams.shape
+)
+
+const workflowsListRevisions = (): ToolBase<
+ typeof WorkflowsListRevisionsSchema,
+ WithPostHogUrl<Schemas.PaginatedHogFlowRevisionBasicList>
+> => ({
+ name: 'workflows-list-revisions',
+ schema: WorkflowsListRevisionsSchema,
+ handler: async (context: Context, params: z.infer<typeof WorkflowsListRevisionsSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.PaginatedHogFlowRevisionBasicList>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/hog_flows/${encodeURIComponent(String(params.id))}/revisions/`,
+ query: {
+ limit: params.limit,
+ offset: params.offset,
+ },
+ })
+ return await withPostHogUrl(context, result, '/workflows')
+ },
+})
+
const WorkflowsLogsSchema = HogFlowsLogsRetrieveParams.omit({ project_id: true }).extend(
HogFlowsLogsRetrieveQueryParams.shape
)
@@ -285,6 +329,28 @@ const workflowsPublish = (): ToolBase<typeof WorkflowsPublishSchema, Schemas.Hog
},
})
+const WorkflowsRestoreRevisionSchema = HogFlowsRevisionsRestoreCreateParams.omit({ project_id: true }).extend(
+ HogFlowsRevisionsRestoreCreateBody.shape
+)
+
+const workflowsRestoreRevision = (): ToolBase<typeof WorkflowsRestoreRevisionSchema, Schemas.HogFlow> => ({
+ name: 'workflows-restore-revision',
+ schema: WorkflowsRestoreRevisionSchema,
+ handler: async (context: Context, params: z.infer<typeof WorkflowsRestoreRevisionSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const body: Record<string, unknown> = {}
+ if (params.overwrite !== undefined) {
+ body['overwrite'] = params.overwrite
+ }
+ const result = await context.api.request<Schemas.HogFlow>({
+ method: 'POST',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/hog_flows/${encodeURIComponent(String(params.id))}/revisions/${encodeURIComponent(String(params.version))}/restore/`,
+ body,
+ })
+ return result
+ },
+})
+
const WorkflowsStatsSchema = HogFlowsMetricsRetrieveParams.omit({ project_id: true }).extend(
HogFlowsMetricsRetrieveQueryParams.shape
)
@@ -422,13 +488,16 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
'workflows-discard-draft': workflowsDiscardDraft,
'workflows-get': workflowsGet,
'workflows-get-invocation': workflowsGetInvocation,
+ 'workflows-get-revision': workflowsGetRevision,
'workflows-global-stats': workflowsGlobalStats,
'workflows-list': workflowsList,
'workflows-list-batch-jobs': workflowsListBatchJobs,
'workflows-list-invocations': workflowsListInvocations,
+ 'workflows-list-revisions': workflowsListRevisions,
'workflows-logs': workflowsLogs,
'workflows-patch-graph': workflowsPatchGraph,
'workflows-publish': workflowsPublish,
+ 'workflows-restore-revision': workflowsRestoreRevision,
'workflows-stats': workflowsStats,
'workflows-test-run': workflowsTestRun,
'workflows-update': workflowsUpdate,
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-get-revision.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-get-revision.json
new file mode 100644
index 000000000000..f134c73d0ac3
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-get-revision.json
@@ -0,0 +1,15 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "id": {
+ "description": "A UUID string identifying this hog flow.",
+ "type": "string"
+ },
+ "version": {
+ "description": "Workflow version to fetch.",
+ "type": "number"
+ }
+ },
+ "required": ["id", "version"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-list-revisions.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-list-revisions.json
new file mode 100644
index 000000000000..42d84da8dd75
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-list-revisions.json
@@ -0,0 +1,19 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "id": {
+ "description": "A UUID string identifying this hog flow.",
+ "type": "string"
+ },
+ "limit": {
+ "description": "Number of results to return per page.",
+ "type": "number"
+ },
+ "offset": {
+ "description": "The initial index from which to return the results.",
+ "type": "number"
+ }
+ },
+ "required": ["id"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-restore-revision.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-restore-revision.json
new file mode 100644
index 000000000000..09fac72f3553
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-restore-revision.json
@@ -0,0 +1,20 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "id": {
+ "description": "A UUID string identifying this hog flow.",
+ "type": "string"
+ },
+ "overwrite": {
+ "default": false,
+ "description": "Replace the open staged draft with this revision's content. Without it, restoring while a draft is open returns 409.",
+ "type": "boolean"
+ },
+ "version": {
+ "description": "Workflow version to restore.",
+ "type": "number"
+ }
+ },
+ "required": ["id", "version"],
+ "type": "object"
+}