: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): opt a single workflow in to suggestions (#91795)
Daniel Marchuk649bb45e1789
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yamlindex d0f2fdbc3a86..438ef4a1980c 100644--- a/.semgrep/rules/security/idor-team-scoped-models.yaml+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml@@ -237,6 +237,7 @@ rules:|HealthIssue|HogFlow|HogFlowBatchJob+ |HogFlowOptimization|HogFlowRevision|HogFlowSchedule|HogFlowTemplate@@ -673,6 +674,7 @@ rules:|HealthIssue|HogFlow|HogFlowBatchJob+ |HogFlowOptimization|HogFlowRevision|HogFlowSchedule|HogFlowTemplatediff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessControlsLogic.ts b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessControlsLogic.tsindex af6d99b3eb07..89cc525e64b6 100644--- a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessControlsLogic.ts+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessControlsLogic.ts@@ -439,6 +439,7 @@ export interface accessControlsLogicActions {| 'health_issue'| 'heatmap'| 'hog_flow'+ | 'hog_flow_proposal'| 'hog_function'| 'ingestion_warning'| 'insight'@@ -617,6 +618,7 @@ export interface accessControlsLogicMeta {| 'health_issue'| 'heatmap'| 'hog_flow'+ | 'hog_flow_proposal'| 'hog_function'| 'ingestion_warning'| 'insight'@@ -772,6 +774,7 @@ export interface accessControlsLogicMeta {| 'health_issue'| 'heatmap'| 'hog_flow'+ | 'hog_flow_proposal'| 'hog_function'| 'ingestion_warning'| 'insight'@@ -899,6 +902,7 @@ export interface accessControlsLogicMeta {| 'health_issue'| 'heatmap'| 'hog_flow'+ | 'hog_flow_proposal'| 'hog_function'| 'ingestion_warning'| 'insight'diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessDetailLogic.ts b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessDetailLogic.tsindex 3128a86713f3..58568d556c89 100644--- a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessDetailLogic.ts+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessDetailLogic.ts@@ -264,6 +264,7 @@ export interface accessDetailLogicActions {| 'health_issue'| 'heatmap'| 'hog_flow'+ | 'hog_flow_proposal'| 'hog_function'| 'ingestion_warning'| 'insight'diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/addObjectOverrideModalLogic.ts b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/addObjectOverrideModalLogic.tsindex 2b690738143f..efd50094476c 100644--- a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/addObjectOverrideModalLogic.ts+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/addObjectOverrideModalLogic.ts@@ -110,6 +110,7 @@ export interface addObjectOverrideModalLogicActions {| 'health_issue'| 'heatmap'| 'hog_flow'+ | 'hog_flow_proposal'| 'hog_function'| 'ingestion_warning'| 'insight'@@ -235,6 +236,7 @@ export interface addObjectOverrideModalLogicActions {| 'health_issue'| 'heatmap'| 'hog_flow'+ | 'hog_flow_proposal'| 'hog_function'| 'ingestion_warning'| 'insight'@@ -381,6 +383,7 @@ export interface addObjectOverrideModalLogicActions {| 'health_issue'| 'heatmap'| 'hog_flow'+ | 'hog_flow_proposal'| 'hog_function'| 'ingestion_warning'| 'insight'@@ -511,6 +514,7 @@ export interface addObjectOverrideModalLogicActions {| 'health_issue'| 'heatmap'| 'hog_flow'+ | 'hog_flow_proposal'| 'hog_function'| 'ingestion_warning'| 'insight'@@ -640,6 +644,7 @@ export interface addObjectOverrideModalLogicActions {| 'health_issue'| 'heatmap'| 'hog_flow'+ | 'hog_flow_proposal'| 'hog_function'| 'ingestion_warning'| 'insight'@@ -790,6 +795,7 @@ export interface addObjectOverrideModalLogicMeta {| 'health_issue'| 'heatmap'| 'hog_flow'+ | 'hog_flow_proposal'| 'hog_function'| 'ingestion_warning'| 'insight'diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/groupedAccessControlRuleModalLogic.ts b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/groupedAccessControlRuleModalLogic.tsindex 9de1e1ca3f47..55069b397da5 100644--- a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/groupedAccessControlRuleModalLogic.ts+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/groupedAccessControlRuleModalLogic.ts@@ -73,6 +73,7 @@ export interface groupedAccessControlRuleModalLogicValues {| 'health_issue'| 'heatmap'| 'hog_flow'+ | 'hog_flow_proposal'| 'hog_function'| 'ingestion_warning'| 'insight'@@ -209,6 +210,7 @@ export interface groupedAccessControlRuleModalLogicValues {| 'health_issue'| 'heatmap'| 'hog_flow'+ | 'hog_flow_proposal'| 'hog_function'| 'ingestion_warning'| 'insight'@@ -332,6 +334,7 @@ export interface groupedAccessControlRuleModalLogicValues {| 'health_issue'| 'heatmap'| 'hog_flow'+ | 'hog_flow_proposal'| 'hog_function'| 'ingestion_warning'| 'insight'@@ -468,6 +471,7 @@ export interface groupedAccessControlRuleModalLogicValues {| 'health_issue'| 'heatmap'| 'hog_flow'+ | 'hog_flow_proposal'| 'hog_function'| 'ingestion_warning'| 'insight'@@ -604,6 +608,7 @@ export interface groupedAccessControlRuleModalLogicActions {| 'health_issue'| 'heatmap'| 'hog_flow'+ | 'hog_flow_proposal'| 'hog_function'| 'ingestion_warning'| 'insight'@@ -747,6 +752,7 @@ export interface groupedAccessControlRuleModalLogicActions {| 'health_issue'| 'heatmap'| 'hog_flow'+ | 'hog_flow_proposal'| 'hog_function'| 'ingestion_warning'| 'insight'@@ -870,6 +876,7 @@ export interface groupedAccessControlRuleModalLogicActions {| 'health_issue'| 'heatmap'| 'hog_flow'+ | 'hog_flow_proposal'| 'hog_function'| 'ingestion_warning'| 'insight'@@ -1032,6 +1039,7 @@ export interface groupedAccessControlRuleModalLogicMeta {| 'health_issue'| 'heatmap'| 'hog_flow'+ | 'hog_flow_proposal'| 'hog_function'| 'ingestion_warning'| 'insight'@@ -1157,6 +1165,7 @@ export interface groupedAccessControlRuleModalLogicMeta {| 'health_issue'| 'heatmap'| 'hog_flow'+ | 'hog_flow_proposal'| 'hog_function'| 'ingestion_warning'| 'insight'@@ -1281,6 +1290,7 @@ export interface groupedAccessControlRuleModalLogicMeta {| 'health_issue'| 'heatmap'| 'hog_flow'+ | 'hog_flow_proposal'| 'hog_function'| 'ingestion_warning'| 'insight'@@ -1405,6 +1415,7 @@ export interface groupedAccessControlRuleModalLogicMeta {| 'health_issue'| 'heatmap'| 'hog_flow'+ | 'hog_flow_proposal'| 'hog_function'| 'ingestion_warning'| 'insight'@@ -1530,6 +1541,7 @@ export interface groupedAccessControlRuleModalLogicMeta {| 'health_issue'| 'heatmap'| 'hog_flow'+ | 'hog_flow_proposal'| 'hog_function'| 'ingestion_warning'| 'insight'@@ -1654,6 +1666,7 @@ export interface groupedAccessControlRuleModalLogicMeta {| 'health_issue'| 'heatmap'| 'hog_flow'+ | 'hog_flow_proposal'| 'hog_function'| 'ingestion_warning'| 'insight'@@ -1789,6 +1802,7 @@ export interface groupedAccessControlRuleModalLogicMeta {| 'health_issue'| 'heatmap'| 'hog_flow'+ | 'hog_flow_proposal'| 'hog_function'| 'ingestion_warning'| 'insight'@@ -1913,6 +1927,7 @@ export interface groupedAccessControlRuleModalLogicMeta {| 'health_issue'| 'heatmap'| 'hog_flow'+ | 'hog_flow_proposal'| 'hog_function'| 'ingestion_warning'| 'insight'diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/accessControlLogic.ts b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/accessControlLogic.tsindex 19b669a43aa2..95f01b49a3ba 100644--- a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/accessControlLogic.ts+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/accessControlLogic.ts@@ -365,6 +365,7 @@ export interface accessControlLogicMeta {| 'health_issue'| 'heatmap'| 'hog_flow'+ | 'hog_flow_proposal'| 'hog_function'| 'ingestion_warning'| 'insight'@@ -593,6 +594,7 @@ export interface accessControlLogicMeta {| 'health_issue'| 'heatmap'| 'hog_flow'+ | 'hog_flow_proposal'| 'hog_function'| 'ingestion_warning'| 'insight'@@ -717,6 +719,7 @@ export interface accessControlLogicMeta {| 'health_issue'| 'heatmap'| 'hog_flow'+ | 'hog_flow_proposal'| 'hog_function'| 'ingestion_warning'| 'insight'diff --git a/frontend/src/lib/scopes.tsx b/frontend/src/lib/scopes.tsxindex 180b7a85c1a5..8200ec7d6887 100644--- a/frontend/src/lib/scopes.tsx+++ b/frontend/src/lib/scopes.tsx@@ -283,6 +283,8 @@ export const API_SCOPES_OMITTED_FROM_MODAL: Partial<Record<APIScopeObject, strinquery_performance: 'OAuth-hidden: staff-only, pasteable into a PAT but not advertised.',wizard_session: 'OAuth-hidden: pasteable into a PAT but not advertised.',wizard_run: 'OAuth-hidden: pasteable into a PAT but not advertised.',+ // A per-scout grant: the workflows scout holds it through its config, so a person never pastes it.+ hog_flow_proposal: 'Scout grant: held by the workflows scout through its config, not by a key.',// Umbrella access-control resource that `warehouse_view`/`warehouse_table` inherit from —// the granular scopes are offered instead, so keep the umbrella out of the modal.warehouse_objects: 'Umbrella resource: grant warehouse_view/warehouse_table instead.',@@ -570,6 +572,7 @@ export const API_SCOPE_GROUPS: APIScopeGroup[] = ['batch_import_support','clickhouse_test_cluster_perf','context_layer_internal',+ 'hog_flow_proposal','internal_run','mcp_builtin_agent','query_performance',diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex 07e3b2eff849..c4e468874040 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -5924,6 +5924,7 @@ export const API_SCOPE_OBJECTS = ['health_issue','heatmap','hog_flow',+ 'hog_flow_proposal','hog_function','ingestion_warning','insight',diff --git a/posthog/scopes.py b/posthog/scopes.pyindex c4f970fa3d41..610576dd88e9 100644--- a/posthog/scopes.py+++ b/posthog/scopes.py@@ -65,6 +65,9 @@ APIScopeObject = Literal["health_issue","heatmap","hog_flow",+ # Suggesting a change to a workflow, and nothing else. Separate from `hog_flow` so the scout can+ # propose without holding the scope that publishes, updates or test-sends a workflow. INTERNAL.+ "hog_flow_proposal","hog_function","ingestion_warning","insight",@@ -167,6 +170,10 @@ INTERNAL_API_SCOPE_OBJECTS: frozenset[APIScopeObject] = frozenset(# Grants Context Wiki writes only to write-enabled sandbox runs. Kept# separate from internal_run because read-only runs carry that marker."context_layer_internal",+ # Files a suggestion on a workflow, and nothing else. Programmatic-only so no personal key,+ # OAuth app or logged-in session can queue one: PostHog's own scout is the only producer, and+ # a person resolves suggestions rather than writing them.+ "hog_flow_proposal",# Narrows `internal_run`: the run behind this token was started by a person# pressing a button, not by one of PostHog's own schedulers. Both markers are# minted server-side, so neither can be self-granted; the LLM gateway metersdiff --git a/posthog/temporal/oauth.py b/posthog/temporal/oauth.pyindex 87e28b167686..33ad82e5ebd3 100644--- a/posthog/temporal/oauth.py+++ b/posthog/temporal/oauth.py@@ -239,6 +239,13 @@ SCOUT_USER_WRITE_SCOPES: list[str] = [# others meet. One scope object covers the whole surface, so the two# exclusions live in `products/replay_vision/backend/scout_writes.py`# instead: a scout cannot delete, and must cap what it creates or enables.+# hog_flow_proposal:write+# Queue a suggested change on a workflow whose owner opted in, for a+# person to approve or reject. Deliberately not `hog_flow:write`, which+# also publishes, updates and test-sends a workflow: this scope can put+# nothing in front of anyone. Creates only; a suggestion is resolved by+# a person. The workflows scout declares it in its SKILL.md+# (`scout-write-scopes`), so no other scout holds it unless granted.## `annotation:write` and `alert:write` exceed the "recoverable, project-scoped" bar the other# scopes meet. They stay in the v1 set that #94263 puts to the team, because narrowing the set is@@ -246,6 +253,13 @@ SCOUT_USER_WRITE_SCOPES: list[str] = [# reaches, or drop the scopes. `llm_skill:write` carries the same kind of open question: a scout# holding it can rewrite the skill body it runs from. That is accepted while the grant is a# deliberate per-scout choice a person makes, and the surfaces that offer it say so.+# Grantable although INTERNAL, which normally means "never on a token a person can obtain". A scout+# token is minted server-side from this allowlist and never through the consent flow, and the MCP+# server gates each tool on the token's own scopes rather than on what OAuth advertises, so the grant+# still reaches the run. Listed explicitly so a typo or a genuinely unreachable scope still fails+# `test_grantable_write_scopes_are_mcp_write_scopes`.+SCOUT_GRANTABLE_INTERNAL_SCOPES: frozenset[str] = frozenset({"hog_flow_proposal:write"})+SCOUT_GRANTABLE_WRITE_SCOPES: frozenset[str] = frozenset({"dashboard:write",@@ -256,6 +270,7 @@ SCOUT_GRANTABLE_WRITE_SCOPES: frozenset[str] = frozenset("warehouse_view:write","warehouse_table:write","replay_scanner:write",+ "hog_flow_proposal:write",})diff --git a/posthog/temporal/tests/test_oauth.py b/posthog/temporal/tests/test_oauth.pyindex 2f470792bad9..d21a77d3dfc9 100644--- a/posthog/temporal/tests/test_oauth.py+++ b/posthog/temporal/tests/test_oauth.py@@ -21,6 +21,7 @@ from posthog.temporal.oauth import (MCP_WRITE_SCOPES,POSTHOG_AI_APP_CLIENT_ID_DEV,RESEARCH_WITHHELD_SCOPES,+ SCOUT_GRANTABLE_INTERNAL_SCOPES,SCOUT_GRANTABLE_WRITE_SCOPES,SCOUT_INTERNAL_SCOPES,SCOUT_SCOPE_PRESETS,@@ -295,9 +296,9 @@ class TestResolveScopes(SimpleTestCase):assert resolve_scopes(decoded) == resolve_scopes(posture)def test_grantable_write_scopes_are_mcp_write_scopes(self) -> None:- # A typo or an internal scope in the allowlist would offer a person a switch that grants- # nothing, because the MCP server gates its tools on scopes it advertises.- assert SCOUT_GRANTABLE_WRITE_SCOPES <= set(MCP_WRITE_SCOPES)+ # A typo would offer a person a switch that grants nothing. An internal scope is allowed only+ # where it is listed as deliberately grantable, since those are minted server-side.+ assert SCOUT_GRANTABLE_WRITE_SCOPES <= set(MCP_WRITE_SCOPES) | SCOUT_GRANTABLE_INTERNAL_SCOPESdef test_custom_scopes(self) -> None:custom = ["feature_flag:read", "feature_flag:write"]diff --git a/products/replay_vision/frontend/generated/api.schemas.ts b/products/replay_vision/frontend/generated/api.schemas.tsindex 3e85b127320f..18347db8a79a 100644--- a/products/replay_vision/frontend/generated/api.schemas.ts+++ b/products/replay_vision/frontend/generated/api.schemas.ts@@ -2068,8 +2068,8 @@ export interface SignalScoutConfigOptionsApi {*/repositories?: string[]/**- * Extra write access granted to this one scout, as scope strings. The grantable set is `alert:write`, `annotation:write`, `dashboard:write`, `insight:write`, `llm_skill:write`, `replay_scanner:write`, `warehouse_table:write`, `warehouse_view:write`. Empty (the default) means the scout reads the project and writes only what every scout may write: notebooks, its findings, and its own memory. Each scope is project-wide and object-level, so a scout holding `dashboard:write` can update or delete any dashboard in the project, not only ones it made. Grant only what this scout maintains. Only the person the scout's runs act as (whoever authored it) or a project admin can set it, and a scoped API key must itself carry each scope it grants. A dry run (`emit=false`) never holds the grant. Applies from the scout's next run.- * @maxItems 8+ * Extra write access granted to this one scout, as scope strings. The grantable set is `alert:write`, `annotation:write`, `dashboard:write`, `hog_flow_proposal:write`, `insight:write`, `llm_skill:write`, `replay_scanner:write`, `warehouse_table:write`, `warehouse_view:write`. Empty (the default) means the scout reads the project and writes only what every scout may write: notebooks, its findings, and its own memory. Each scope is project-wide and object-level, so a scout holding `dashboard:write` can update or delete any dashboard in the project, not only ones it made. Grant only what this scout maintains. Only the person the scout's runs act as (whoever authored it) or a project admin can set it, and a scoped API key must itself carry each scope it grants. A dry run (`emit=false`) never holds the grant. Applies from the scout's next run.+ * @maxItems 9*/write_scopes?: string[]/** Whether this scout runs on its schedule. Defaults to true. */@@ -2299,8 +2299,8 @@ export interface SignalScoutConfigApi {*/repositories?: string[]/**- * Extra write access granted to this one scout, as scope strings. The grantable set is `alert:write`, `annotation:write`, `dashboard:write`, `insight:write`, `llm_skill:write`, `replay_scanner:write`, `warehouse_table:write`, `warehouse_view:write`. Empty (the default) means the scout reads the project and writes only what every scout may write: notebooks, its findings, and its own memory. Each scope is project-wide and object-level, so a scout holding `dashboard:write` can update or delete any dashboard in the project, not only ones it made. Grant only what this scout maintains. Only the person the scout's runs act as (whoever authored it) or a project admin can set it, and a scoped API key must itself carry each scope it grants. A dry run (`emit=false`) never holds the grant. Applies from the scout's next run.- * @maxItems 8+ * Extra write access granted to this one scout, as scope strings. The grantable set is `alert:write`, `annotation:write`, `dashboard:write`, `hog_flow_proposal:write`, `insight:write`, `llm_skill:write`, `replay_scanner:write`, `warehouse_table:write`, `warehouse_view:write`. Empty (the default) means the scout reads the project and writes only what every scout may write: notebooks, its findings, and its own memory. Each scope is project-wide and object-level, so a scout holding `dashboard:write` can update or delete any dashboard in the project, not only ones it made. Grant only what this scout maintains. Only the person the scout's runs act as (whoever authored it) or a project admin can set it, and a scoped API key must itself carry each scope it grants. A dry run (`emit=false`) never holds the grant. Applies from the scout's next run.+ * @maxItems 9*/readonly write_scopes: readonly string[]/**diff --git a/products/replay_vision/frontend/generated/api.zod.ts b/products/replay_vision/frontend/generated/api.zod.tsindex a4562bf3b44c..a2c5ffac2edb 100644--- a/products/replay_vision/frontend/generated/api.zod.ts+++ b/products/replay_vision/frontend/generated/api.zod.ts@@ -958,7 +958,7 @@ export const visionScannersScoutsCreateBodyConfigOneRepositoriesItemMax = 255export const visionScannersScoutsCreateBodyConfigOneRepositoriesMax = 10-export const visionScannersScoutsCreateBodyConfigOneWriteScopesMax = 8+export const visionScannersScoutsCreateBodyConfigOneWriteScopesMax = 9export const visionScannersScoutsCreateBodyConfigOneRunIntervalMinutesMin = 30export const visionScannersScoutsCreateBodyConfigOneRunIntervalMinutesMax = 43200@@ -1041,7 +1041,7 @@ export const VisionScannersScoutsCreateBody = /* @__PURE__ */ zod.max(visionScannersScoutsCreateBodyConfigOneWriteScopesMax).optional().describe(- "Extra write access granted to this one scout, as scope strings. The grantable set is `alert:write`, `annotation:write`, `dashboard:write`, `insight:write`, `llm_skill:write`, `replay_scanner:write`, `warehouse_table:write`, `warehouse_view:write`. Empty (the default) means the scout reads the project and writes only what every scout may write: notebooks, its findings, and its own memory. Each scope is project-wide and object-level, so a scout holding `dashboard:write` can update or delete any dashboard in the project, not only ones it made. Grant only what this scout maintains. Only the person the scout's runs act as (whoever authored it) or a project admin can set it, and a scoped API key must itself carry each scope it grants. A dry run (`emit=false`) never holds the grant. Applies from the scout's next run."+ "Extra write access granted to this one scout, as scope strings. The grantable set is `alert:write`, `annotation:write`, `dashboard:write`, `hog_flow_proposal:write`, `insight:write`, `llm_skill:write`, `replay_scanner:write`, `warehouse_table:write`, `warehouse_view:write`. Empty (the default) means the scout reads the project and writes only what every scout may write: notebooks, its findings, and its own memory. Each scope is project-wide and object-level, so a scout holding `dashboard:write` can update or delete any dashboard in the project, not only ones it made. Grant only what this scout maintains. Only the person the scout's runs act as (whoever authored it) or a project admin can set it, and a scoped API key must itself carry each scope it grants. A dry run (`emit=false`) never holds the grant. Applies from the scout's next run."),enabled: zod.boolean()diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.tsindex 01bcf0d178ac..2b90c81b5568 100644--- a/products/signals/frontend/generated/api.schemas.ts+++ b/products/signals/frontend/generated/api.schemas.ts@@ -3246,8 +3246,8 @@ export interface SignalScoutConfigOptionsApi {*/repositories?: string[]/**- * Extra write access granted to this one scout, as scope strings. The grantable set is `alert:write`, `annotation:write`, `dashboard:write`, `insight:write`, `llm_skill:write`, `replay_scanner:write`, `warehouse_table:write`, `warehouse_view:write`. Empty (the default) means the scout reads the project and writes only what every scout may write: notebooks, its findings, and its own memory. Each scope is project-wide and object-level, so a scout holding `dashboard:write` can update or delete any dashboard in the project, not only ones it made. Grant only what this scout maintains. Only the person the scout's runs act as (whoever authored it) or a project admin can set it, and a scoped API key must itself carry each scope it grants. A dry run (`emit=false`) never holds the grant. Applies from the scout's next run.- * @maxItems 8+ * Extra write access granted to this one scout, as scope strings. The grantable set is `alert:write`, `annotation:write`, `dashboard:write`, `hog_flow_proposal:write`, `insight:write`, `llm_skill:write`, `replay_scanner:write`, `warehouse_table:write`, `warehouse_view:write`. Empty (the default) means the scout reads the project and writes only what every scout may write: notebooks, its findings, and its own memory. Each scope is project-wide and object-level, so a scout holding `dashboard:write` can update or delete any dashboard in the project, not only ones it made. Grant only what this scout maintains. Only the person the scout's runs act as (whoever authored it) or a project admin can set it, and a scoped API key must itself carry each scope it grants. A dry run (`emit=false`) never holds the grant. Applies from the scout's next run.+ * @maxItems 9*/write_scopes?: string[]/** Whether this scout runs on its schedule. Defaults to true. */@@ -3546,8 +3546,8 @@ export interface SignalScoutConfigApi {*/repositories?: string[]/**- * Extra write access granted to this one scout, as scope strings. The grantable set is `alert:write`, `annotation:write`, `dashboard:write`, `insight:write`, `llm_skill:write`, `replay_scanner:write`, `warehouse_table:write`, `warehouse_view:write`. Empty (the default) means the scout reads the project and writes only what every scout may write: notebooks, its findings, and its own memory. Each scope is project-wide and object-level, so a scout holding `dashboard:write` can update or delete any dashboard in the project, not only ones it made. Grant only what this scout maintains. Only the person the scout's runs act as (whoever authored it) or a project admin can set it, and a scoped API key must itself carry each scope it grants. A dry run (`emit=false`) never holds the grant. Applies from the scout's next run.- * @maxItems 8+ * Extra write access granted to this one scout, as scope strings. The grantable set is `alert:write`, `annotation:write`, `dashboard:write`, `hog_flow_proposal:write`, `insight:write`, `llm_skill:write`, `replay_scanner:write`, `warehouse_table:write`, `warehouse_view:write`. Empty (the default) means the scout reads the project and writes only what every scout may write: notebooks, its findings, and its own memory. Each scope is project-wide and object-level, so a scout holding `dashboard:write` can update or delete any dashboard in the project, not only ones it made. Grant only what this scout maintains. Only the person the scout's runs act as (whoever authored it) or a project admin can set it, and a scoped API key must itself carry each scope it grants. A dry run (`emit=false`) never holds the grant. Applies from the scout's next run.+ * @maxItems 9*/readonly write_scopes: readonly string[]/**@@ -3668,8 +3668,8 @@ export interface SignalScoutConfigCreateApi {*/repositories?: string[]/**- * Extra write access granted to this one scout, as scope strings. The grantable set is `alert:write`, `annotation:write`, `dashboard:write`, `insight:write`, `llm_skill:write`, `replay_scanner:write`, `warehouse_table:write`, `warehouse_view:write`. Empty (the default) means the scout reads the project and writes only what every scout may write: notebooks, its findings, and its own memory. Each scope is project-wide and object-level, so a scout holding `dashboard:write` can update or delete any dashboard in the project, not only ones it made. Grant only what this scout maintains. Only the person the scout's runs act as (whoever authored it) or a project admin can set it, and a scoped API key must itself carry each scope it grants. A dry run (`emit=false`) never holds the grant. Applies from the scout's next run.- * @maxItems 8+ * Extra write access granted to this one scout, as scope strings. The grantable set is `alert:write`, `annotation:write`, `dashboard:write`, `hog_flow_proposal:write`, `insight:write`, `llm_skill:write`, `replay_scanner:write`, `warehouse_table:write`, `warehouse_view:write`. Empty (the default) means the scout reads the project and writes only what every scout may write: notebooks, its findings, and its own memory. Each scope is project-wide and object-level, so a scout holding `dashboard:write` can update or delete any dashboard in the project, not only ones it made. Grant only what this scout maintains. Only the person the scout's runs act as (whoever authored it) or a project admin can set it, and a scoped API key must itself carry each scope it grants. A dry run (`emit=false`) never holds the grant. Applies from the scout's next run.+ * @maxItems 9*/write_scopes?: string[]/** Whether this scout runs on its schedule. Defaults to true. */@@ -3809,8 +3809,8 @@ export interface PatchedSignalScoutConfigUpdateApi {*/repositories?: string[]/**- * Extra write access granted to this one scout, as scope strings. The grantable set is `alert:write`, `annotation:write`, `dashboard:write`, `insight:write`, `llm_skill:write`, `replay_scanner:write`, `warehouse_table:write`, `warehouse_view:write`. Empty (the default) means the scout reads the project and writes only what every scout may write: notebooks, its findings, and its own memory. Each scope is project-wide and object-level, so a scout holding `dashboard:write` can update or delete any dashboard in the project, not only ones it made. Grant only what this scout maintains. Only the person the scout's runs act as (whoever authored it) or a project admin can set it, and a scoped API key must itself carry each scope it grants. A dry run (`emit=false`) never holds the grant. Applies from the scout's next run.- * @maxItems 8+ * Extra write access granted to this one scout, as scope strings. The grantable set is `alert:write`, `annotation:write`, `dashboard:write`, `hog_flow_proposal:write`, `insight:write`, `llm_skill:write`, `replay_scanner:write`, `warehouse_table:write`, `warehouse_view:write`. Empty (the default) means the scout reads the project and writes only what every scout may write: notebooks, its findings, and its own memory. Each scope is project-wide and object-level, so a scout holding `dashboard:write` can update or delete any dashboard in the project, not only ones it made. Grant only what this scout maintains. Only the person the scout's runs act as (whoever authored it) or a project admin can set it, and a scoped API key must itself carry each scope it grants. A dry run (`emit=false`) never holds the grant. Applies from the scout's next run.+ * @maxItems 9*/write_scopes?: string[]}diff --git a/products/signals/frontend/generated/api.zod.ts b/products/signals/frontend/generated/api.zod.tsindex 31c61ddc50d9..709e857040f2 100644--- a/products/signals/frontend/generated/api.zod.ts+++ b/products/signals/frontend/generated/api.zod.ts@@ -623,7 +623,7 @@ export const signalsScoutCreateBodyConfigOneRepositoriesItemMax = 255export const signalsScoutCreateBodyConfigOneRepositoriesMax = 10-export const signalsScoutCreateBodyConfigOneWriteScopesMax = 8+export const signalsScoutCreateBodyConfigOneWriteScopesMax = 9export const signalsScoutCreateBodyConfigOneRunIntervalMinutesMin = 30export const signalsScoutCreateBodyConfigOneRunIntervalMinutesMax = 43200@@ -727,7 +727,7 @@ export const SignalsScoutCreateBody = /* @__PURE__ */ zod.max(signalsScoutCreateBodyConfigOneWriteScopesMax).optional().describe(- "Extra write access granted to this one scout, as scope strings. The grantable set is `alert:write`, `annotation:write`, `dashboard:write`, `insight:write`, `llm_skill:write`, `replay_scanner:write`, `warehouse_table:write`, `warehouse_view:write`. Empty (the default) means the scout reads the project and writes only what every scout may write: notebooks, its findings, and its own memory. Each scope is project-wide and object-level, so a scout holding `dashboard:write` can update or delete any dashboard in the project, not only ones it made. Grant only what this scout maintains. Only the person the scout's runs act as (whoever authored it) or a project admin can set it, and a scoped API key must itself carry each scope it grants. A dry run (`emit=false`) never holds the grant. Applies from the scout's next run."+ "Extra write access granted to this one scout, as scope strings. The grantable set is `alert:write`, `annotation:write`, `dashboard:write`, `hog_flow_proposal:write`, `insight:write`, `llm_skill:write`, `replay_scanner:write`, `warehouse_table:write`, `warehouse_view:write`. Empty (the default) means the scout reads the project and writes only what every scout may write: notebooks, its findings, and its own memory. Each scope is project-wide and object-level, so a scout holding `dashboard:write` can update or delete any dashboard in the project, not only ones it made. Grant only what this scout maintains. Only the person the scout's runs act as (whoever authored it) or a project admin can set it, and a scoped API key must itself carry each scope it grants. A dry run (`emit=false`) never holds the grant. Applies from the scout's next run."),enabled: zod.boolean()@@ -896,7 +896,7 @@ export const signalsScoutConfigCreateBodyRepositoriesItemMax = 255export const signalsScoutConfigCreateBodyRepositoriesMax = 10-export const signalsScoutConfigCreateBodyWriteScopesMax = 8+export const signalsScoutConfigCreateBodyWriteScopesMax = 9export const signalsScoutConfigCreateBodyRunIntervalMinutesMin = 30export const signalsScoutConfigCreateBodyRunIntervalMinutesMax = 43200@@ -958,7 +958,7 @@ export const SignalsScoutConfigCreateBody = /* @__PURE__ */ zod.max(signalsScoutConfigCreateBodyWriteScopesMax).optional().describe(- "Extra write access granted to this one scout, as scope strings. The grantable set is `alert:write`, `annotation:write`, `dashboard:write`, `insight:write`, `llm_skill:write`, `replay_scanner:write`, `warehouse_table:write`, `warehouse_view:write`. Empty (the default) means the scout reads the project and writes only what every scout may write: notebooks, its findings, and its own memory. Each scope is project-wide and object-level, so a scout holding `dashboard:write` can update or delete any dashboard in the project, not only ones it made. Grant only what this scout maintains. Only the person the scout's runs act as (whoever authored it) or a project admin can set it, and a scoped API key must itself carry each scope it grants. A dry run (`emit=false`) never holds the grant. Applies from the scout's next run."+ "Extra write access granted to this one scout, as scope strings. The grantable set is `alert:write`, `annotation:write`, `dashboard:write`, `hog_flow_proposal:write`, `insight:write`, `llm_skill:write`, `replay_scanner:write`, `warehouse_table:write`, `warehouse_view:write`. Empty (the default) means the scout reads the project and writes only what every scout may write: notebooks, its findings, and its own memory. Each scope is project-wide and object-level, so a scout holding `dashboard:write` can update or delete any dashboard in the project, not only ones it made. Grant only what this scout maintains. Only the person the scout's runs act as (whoever authored it) or a project admin can set it, and a scoped API key must itself carry each scope it grants. A dry run (`emit=false`) never holds the grant. Applies from the scout's next run."),enabled: zod.boolean().optional().describe('Whether this scout runs on its schedule. Defaults to true.'),emit: zod@@ -1103,7 +1103,7 @@ export const signalsScoutConfigUpdateBodyRepositoriesItemMax = 255export const signalsScoutConfigUpdateBodyRepositoriesMax = 10-export const signalsScoutConfigUpdateBodyWriteScopesMax = 8+export const signalsScoutConfigUpdateBodyWriteScopesMax = 9export const SignalsScoutConfigUpdateBody = /* @__PURE__ */ zod.object({@@ -1255,7 +1255,7 @@ export const SignalsScoutConfigUpdateBody = /* @__PURE__ */ zod.max(signalsScoutConfigUpdateBodyWriteScopesMax).optional().describe(- "Extra write access granted to this one scout, as scope strings. The grantable set is `alert:write`, `annotation:write`, `dashboard:write`, `insight:write`, `llm_skill:write`, `replay_scanner:write`, `warehouse_table:write`, `warehouse_view:write`. Empty (the default) means the scout reads the project and writes only what every scout may write: notebooks, its findings, and its own memory. Each scope is project-wide and object-level, so a scout holding `dashboard:write` can update or delete any dashboard in the project, not only ones it made. Grant only what this scout maintains. Only the person the scout's runs act as (whoever authored it) or a project admin can set it, and a scoped API key must itself carry each scope it grants. A dry run (`emit=false`) never holds the grant. Applies from the scout's next run."+ "Extra write access granted to this one scout, as scope strings. The grantable set is `alert:write`, `annotation:write`, `dashboard:write`, `hog_flow_proposal:write`, `insight:write`, `llm_skill:write`, `replay_scanner:write`, `warehouse_table:write`, `warehouse_view:write`. Empty (the default) means the scout reads the project and writes only what every scout may write: notebooks, its findings, and its own memory. Each scope is project-wide and object-level, so a scout holding `dashboard:write` can update or delete any dashboard in the project, not only ones it made. Grant only what this scout maintains. Only the person the scout's runs act as (whoever authored it) or a project admin can set it, and a scoped API key must itself carry each scope it grants. A dry run (`emit=false`) never holds the grant. Applies from the scout's next run."),}).describe('Editable display name, schedule, enablement, and emit posture for one scout config.')diff --git a/products/workflows/backend/migrations/0027_hogflowoptimization.py b/products/workflows/backend/migrations/0027_hogflowoptimization.pynew file mode 100644index 000000000000..413e17fc8373--- /dev/null+++ b/products/workflows/backend/migrations/0027_hogflowoptimization.py@@ -0,0 +1,58 @@+# Generated by Django 5.2.17 on 2026-09-29 09:31++import django.db.models.deletion+from django.db import migrations, models++import posthog.uuidt+++class Migration(migrations.Migration):+ dependencies = [+ ("posthog", "1386_taggeditem_drop_legacy_columns"),+ ("workflows", "0026_workflowproposal"),+ ]++ operations = [+ migrations.CreateModel(+ name="HogFlowOptimization",+ fields=[+ (+ "id",+ models.UUIDField(+ default=posthog.uuidt.uuid7,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ ("enabled", models.BooleanField(default=True)),+ (+ "created_at",+ models.DateTimeField(+ auto_now_add=True,+ help_text="When this workflow was first opted in.",+ ),+ ),+ (+ "hog_flow",+ models.OneToOneField(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="optimization",+ to="workflows.hogflow",+ ),+ ),+ (+ "team",+ models.ForeignKey(+ db_constraint=False,+ on_delete=django.db.models.deletion.CASCADE,+ related_name="+",+ to="posthog.team",+ ),+ ),+ ],+ options={+ "abstract": False,+ },+ ),+ ]diff --git a/products/workflows/backend/migrations/0028_workflowproposal_uuid7.py b/products/workflows/backend/migrations/0028_workflowproposal_uuid7.pynew file mode 100644index 000000000000..24d950e43ee6--- /dev/null+++ b/products/workflows/backend/migrations/0028_workflowproposal_uuid7.py@@ -0,0 +1,24 @@+# Generated by Django 5.2.17 on 2026-09-29 10:16++from django.db import migrations, models++import posthog.uuidt+++class Migration(migrations.Migration):+ dependencies = [+ ("workflows", "0027_hogflowoptimization"),+ ]++ operations = [+ migrations.AlterField(+ model_name="workflowproposal",+ name="id",+ field=models.UUIDField(+ default=posthog.uuidt.uuid7,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ ]diff --git a/products/workflows/backend/migrations/max_migration.txt b/products/workflows/backend/migrations/max_migration.txtindex e300e8f6ca1d..0ca55934617b 100644--- a/products/workflows/backend/migrations/max_migration.txt+++ b/products/workflows/backend/migrations/max_migration.txt@@ -1 +1 @@-0026_workflowproposal+0028_workflowproposal_uuid7diff --git a/products/workflows/backend/models/__init__.py b/products/workflows/backend/models/__init__.pyindex 6a5380dc753b..16d80dd740dc 100644--- a/products/workflows/backend/models/__init__.py+++ b/products/workflows/backend/models/__init__.py@@ -1,6 +1,7 @@from .hog_flow.hog_flow import HogFlowfrom .hog_flow.hog_flow_template import HogFlowTemplatefrom .hog_flow_batch_job import HogFlowBatchJob+from .hog_flow_optimization import HogFlowOptimizationfrom .hog_flow_revision import HogFlowRevisionfrom .hog_flow_schedule.hog_flow_schedule import HogFlowSchedulefrom .team_workflows_config import TeamWorkflowsConfig@@ -9,6 +10,7 @@ from .workflow_proposal import WorkflowProposal__all__ = ["HogFlow","HogFlowBatchJob",+ "HogFlowOptimization","HogFlowRevision","HogFlowSchedule","HogFlowTemplate",diff --git a/products/workflows/backend/models/hog_flow_optimization.py b/products/workflows/backend/models/hog_flow_optimization.pynew file mode 100644index 000000000000..fe23172ac33b--- /dev/null+++ b/products/workflows/backend/models/hog_flow_optimization.py@@ -0,0 +1,38 @@+from typing import Any++from django.db import models++from posthog.models.scoping.root_mixin import TeamScopedRootMixin+from posthog.models.utils import UUIDModel+++class HogFlowOptimization(TeamScopedRootMixin, UUIDModel):+ """One row per workflow whose owner asked PostHog to suggest improvements to it.++ `enabled` is the opt-in: no row, or a disabled one, means nothing reads the workflow, so a+ producer costs nothing for workflows nobody asked about. Turning it off keeps the row, so+ "tried it and turned it off" stays answerable - that is the question a rollout has to answer,+ and a deleted row cannot.++ Who flipped it and when is in the workflow's activity log, next to the rest of that workflow's+ history, rather than as a pair of columns here that could only remember the last flip. Cadence+ and "when did it last look" belong to whoever schedules the producer, a Signals scout today.++ Behind the `self-optimising-workflows` flag.+ """++ # db_constraint=False on team: a real FK to a hot table takes a parent-table lock on creation;+ # enforcement stays app-level, as it does on WorkflowProposal.+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False, related_name="+")+ hog_flow = models.OneToOneField("workflows.HogFlow", on_delete=models.CASCADE, related_name="optimization")++ enabled = models.BooleanField(default=True)+ created_at = models.DateTimeField(auto_now_add=True, help_text="When this workflow was first opted in.")++ def save(self, *args: Any, **kwargs: Any) -> None:+ # Mirrors the workflow's team, as WorkflowProposal does.+ self.team_id = self.hog_flow.team_id+ super().save(*args, **kwargs)++ def __str__(self) -> str:+ return f"HogFlowOptimization {self.hog_flow_id} ({'on' if self.enabled else 'off'})"diff --git a/products/workflows/backend/models/workflow_proposal.py b/products/workflows/backend/models/workflow_proposal.pyindex 9ab1081afa54..a4ea79362713 100644--- a/products/workflows/backend/models/workflow_proposal.py+++ b/products/workflows/backend/models/workflow_proposal.py@@ -3,10 +3,10 @@ from typing import Anyfrom django.db import modelsfrom posthog.models.scoping.root_mixin import TeamScopedRootMixin-from posthog.models.utils import UUIDTModel+from posthog.models.utils import UUIDModel-class WorkflowProposal(TeamScopedRootMixin, UUIDTModel):+class WorkflowProposal(TeamScopedRootMixin, UUIDModel):"""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 adiff --git a/products/workflows/backend/presentation/views/hog_flow.py b/products/workflows/backend/presentation/views/hog_flow.pyindex 761eb003f2df..acb9569cc20d 100644--- a/products/workflows/backend/presentation/views/hog_flow.py+++ b/products/workflows/backend/presentation/views/hog_flow.py@@ -25,7 +25,7 @@ from django.utils.dateparse import parse_datetimeimport requestsimport structlogimport posthoganalytics-from django_filters import BaseInFilter, CharFilter, FilterSet+from django_filters import BaseInFilter, BooleanFilter, CharFilter, FilterSetfrom django_filters.rest_framework import DjangoFilterBackendfrom drf_spectacular.types import OpenApiTypesfrom drf_spectacular.utils import (@@ -150,6 +150,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_optimization import HogFlowOptimizationfrom products.workflows.backend.models.hog_flow_revision import HogFlowRevisionfrom products.workflows.backend.models.hog_flow_schedule import SCHEDULED_TRIGGER_TYPES, HogFlowSchedulefrom products.workflows.backend.models.team_workflows_config import TeamWorkflowsConfig@@ -3947,6 +3948,12 @@ class WorkflowProposalEvidenceField(serializers.JSONField):pass+class HogFlowOptimizationSerializer(serializers.Serializer):+ enabled = serializers.BooleanField(+ help_text="Whether PostHog may read this workflow's metrics and suggest changes to it."+ )++class WorkflowProposalSerializer(serializers.ModelSerializer):resolved_by = UserBasicSerializer(read_only=True, allow_null=True)content = WorkflowProposalContentField(read_only=True)@@ -4193,6 +4200,15 @@ class ProposalNotRunnableError(exceptions.APIException):super().__init__(detail)+class WorkflowNotOptimisedError(exceptions.APIException):+ status_code = status.HTTP_409_CONFLICT+ default_detail = (+ "This workflow is not set up for suggestions. Turn on 'Suggest improvements' on the workflow "+ "before proposing a change to it."+ )+ default_code = "workflow_not_optimized"++class ProposalOutOfDateError(exceptions.APIException):status_code = status.HTTP_409_CONFLICTdefault_detail = (@@ -4524,12 +4540,24 @@ def filter_by_broadcast_status(queryset: QuerySet, statuses: set[str]) -> QuerySclass HogFlowFilterSet(FilterSet):+ # A producer's work list, so an agent need not read every workflow to find the few it may look at.+ optimization_enabled = BooleanFilter(+ method="filter_optimization_enabled",+ label="Only workflows someone turned suggestions on for.",+ )+class Meta:model = HogFlow# `created_by` is filtered by uuid in safely_get_queryset (the list UI's member picker keys on# uuid, not pk), so it's deliberately not an exact-match field here.fields = ["id", "created_at", "updated_at", "status", "origin_product"]+ def filter_optimization_enabled(self, queryset, name: str, value: bool):+ # Off keeps its row, so "on" is a row still enabled. Archived workflows drop out: nothing runs there.+ if not value:+ return queryset.exclude(optimization__enabled=True)+ return queryset.filter(optimization__enabled=True).exclude(status=HogFlow.State.ARCHIVED)+class HogFlowPagination(LimitOffsetPagination):default_limit = 100@@ -4739,6 +4767,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 == "optimization":+ # Reading the opt-in is workflow-read; flipping it decides whether an agent may read the workflow, so it is a write.+ if request.method in ("GET", "HEAD", "OPTIONS"):+ return ["hog_flow:read"]+ return ["hog_flow:write"]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"):@@ -5899,10 +5932,22 @@ class HogFlowViewSet(param_serializer.is_valid(raise_exception=True)params = param_serializer.validated_data+ source_id = params.get("source_id") or None++ # A retry names the suggestion it already made, which is still in someone's queue whatever the switch says now.+ retry_of = (+ WorkflowProposal.objects.filter(hog_flow=instance, source_id=source_id).first() if source_id else None+ )+ if retry_of:+ return Response(WorkflowProposalSerializer(retry_of).data, status=status.HTTP_200_OK)++ # Reading the queue stays open while the flag is on; the workflow's opt-in only gates producing a new one.+ if not HogFlowOptimization.objects.filter(hog_flow=instance, enabled=True).exists():+ raise WorkflowNotOptimisedError()+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 Noneif "actions" in content or "edges" in content:merged = merge_proposal_content(live_content, content)@@ -5921,11 +5966,6 @@ class HogFlowViewSet(})- 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"],@@ -6168,6 +6208,57 @@ class HogFlowViewSet(self._report_workflow_action("hog_flow_proposal_rejected", instance, {"proposal_id": str(locked_proposal.id)})return Response(WorkflowProposalSerializer(locked_proposal).data)+ @extend_schema(request=HogFlowOptimizationSerializer, responses={200: HogFlowOptimizationSerializer})+ @action(detail=True, methods=["GET", "POST"], url_path="optimization", filter_backends=[])+ def optimization(self, request: Request, *args, **kwargs):+ """Whether PostHog may look at this workflow and suggest changes to it.++ Turning it off stops a producer reading the workflow. Suggestions already made are left+ alone: someone still has them to resolve.+ """+ self._require_self_optimising_enabled()+ instance = self.get_object()++ row = HogFlowOptimization.objects.filter(hog_flow=instance).first()++ if request.method == "POST":+ param_serializer = HogFlowOptimizationSerializer(data=request.data)+ param_serializer.is_valid(raise_exception=True)+ enabled = param_serializer.validated_data["enabled"]+ if row is None:+ # Turning it off for a workflow nobody turned on is a no-op, not a row saying "no".+ changed = enabled+ if enabled:+ # get_or_create rather than create: two first-time enables race, and the loser of+ # the one-to-one constraint would answer 500 for a workflow that is now on.+ # nosemgrep: idor-lookup-without-team - team scope is enforced by TeamScopedManager+ row, created = HogFlowOptimization.objects.get_or_create(+ hog_flow=instance, defaults={"enabled": True}+ )+ changed = created or not row.enabled+ if not created and not row.enabled:+ row.enabled = True+ row.save(update_fields=["enabled"])+ else:+ # Off keeps the row: how many tried this and stopped is a rollout question.+ changed = row.enabled != enabled+ if changed:+ row.enabled = enabled+ row.save(update_fields=["enabled"])++ if changed:+ log_activity_from_viewset(+ self,+ instance,+ activity="optimization_enabled" if enabled else "optimization_disabled",+ name=instance.name,+ )+ self._report_workflow_action(+ "hog_flow_optimization_enabled" if enabled else "hog_flow_optimization_disabled", instance+ )++ return Response(HogFlowOptimizationSerializer({"enabled": row is not None and row.enabled}).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/tests/api/test_workflow_proposals.py b/products/workflows/backend/tests/api/test_workflow_proposals.pyindex c92db32ef7a4..e464660a3895 100644--- a/products/workflows/backend/tests/api/test_workflow_proposals.py+++ b/products/workflows/backend/tests/api/test_workflow_proposals.py@@ -13,6 +13,7 @@ from posthog.models.utils import generate_random_token_personal, hash_key_valuefrom products.cdp.backend.api.test.test_hog_function_templates import MOCK_NODE_TEMPLATESfrom products.workflows.backend.models.hog_flow.hog_flow import HogFlow+from products.workflows.backend.models.hog_flow_optimization import HogFlowOptimizationfrom products.workflows.backend.models.workflow_proposal import WorkflowProposalfrom products.workflows.backend.presentation.views.hog_flow import DRAFT_CONTENT_FIELDS@@ -46,6 +47,12 @@ class TestWorkflowProposals(APIBaseTest):super().setUp()sync_template_to_db(webhook_template)+ def _optimize(self, flow_id: str) -> None:+ response = self.client.post(+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/optimization", {"enabled": True}, format="json"+ )+ assert response.status_code == 200, response.json()+def _create_active_flow(self) -> str:create = self.client.post(f"/api/projects/{self.team.id}/hog_flows",@@ -55,6 +62,7 @@ class TestWorkflowProposals(APIBaseTest):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()+ self._optimize(flow_id)return flow_iddef _propose(self, flow_id: str, **overrides) -> dict:@@ -373,6 +381,140 @@ class TestWorkflowProposals(APIBaseTest):assert draft["exit_condition"] == "exit_only_at_end"assert {action["name"] for action in draft["actions"]} >= {"renamed"}+ def test_a_workflow_nobody_opted_in_is_not_suggested_against(self, _mock_flag):+ flow_id = self._create_active_flow()+ self.client.post(+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/optimization", {"enabled": False}, format="json"+ )++ refused = self.client.post(+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/proposals/",+ {+ "title": "x",+ "rationale": "y",+ "content": {"actions": [_trigger_action(), _webhook_action()]},+ "evidence": {+ "metric": "email open rate",+ "current_value": 0.1,+ "unit": "rate",+ "n": 100,+ "guardrails": [],+ },+ "base_version": 1,+ },+ format="json",+ )+ assert refused.status_code == 409, refused.json()+ assert refused.json()["code"] == "workflow_not_optimized"+ assert WorkflowProposal.objects.for_team(self.team.id).count() == 0++ def test_a_retry_after_opt_out_returns_the_suggestion_it_already_made(self, _mock_flag):+ flow_id = self._create_active_flow()+ self.client.post(+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/optimization", {"enabled": True}, format="json"+ )+ first = self._propose(flow_id, source_id="run-1")+ self.client.post(+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/optimization", {"enabled": False}, format="json"+ )++ again = self.client.post(+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/proposals/",+ {+ "title": "Point the webhook somewhere that answers",+ "rationale": "The same finding, sent again after a failed response.",+ "content": {"actions": [_trigger_action(), _webhook_action(url="https://proposed.example.com")]},+ "evidence": {+ "metric": "failure rate",+ "current_value": 1.0,+ "unit": "rate",+ "n": 240,+ "guardrails": [],+ },+ "base_version": 1,+ "source_id": "run-1",+ },+ 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++ def test_two_first_time_enables_do_not_collide(self, _mock_flag):+ flow_id = self._create_active_flow()+ HogFlowOptimization.objects.for_team(self.team.id).filter(hog_flow_id=flow_id).delete()+ url = f"/api/projects/{self.team.id}/hog_flows/{flow_id}/optimization"++ # The second request stands in for one that read "no row" before the first one wrote.+ first = self.client.post(url, {"enabled": True}, format="json")+ second = self.client.post(url, {"enabled": True}, format="json")++ assert (first.status_code, second.status_code) == (200, 200), second.json()+ assert HogFlowOptimization.objects.for_team(self.team.id).filter(hog_flow_id=flow_id).count() == 1++ def test_turning_the_workflow_off_keeps_the_suggestions_already_made(self, _mock_flag):+ flow_id = self._create_active_flow()+ proposal = self._propose(flow_id)++ off = self.client.post(+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/optimization", {"enabled": False}, format="json"+ )+ assert off.status_code == 200, off.json()+ assert off.json()["enabled"] is False+ assert HogFlowOptimization.objects.for_team(self.team.id).get(hog_flow_id=flow_id).enabled is False++ listed = self.client.get(f"/api/projects/{self.team.id}/hog_flows/{flow_id}/proposals/?status=suggested")+ assert listed.status_code == 200, listed.json()+ assert [row["id"] for row in listed.json()["results"]] == [proposal["id"]]+ rejected = self.client.post(+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/proposals/{proposal['id']}/reject/", {}+ )+ assert rejected.status_code == 200, rejected.json()++ def test_the_toggle_lands_in_the_workflow_history(self, _mock_flag):+ flow_id = self._create_active_flow()+ url = f"/api/projects/{self.team.id}/hog_flows/{flow_id}/optimization"+ self.client.post(url, {"enabled": False}, format="json")+ self.client.post(url, {"enabled": False}, format="json")++ entries = ActivityLog.objects.filter(scope="HogFlow", item_id=flow_id).order_by("created_at")+ activities = [entry.activity for entry in entries]+ assert activities.count("optimization_enabled") == 1+ assert activities.count("optimization_disabled") == 1, "a repeat of the same state logs nothing"+ disabled_entry = entries.filter(activity="optimization_disabled").first()+ assert disabled_entry is not None+ assert disabled_entry.user == self.user++ def test_turning_it_back_on_reuses_the_row(self, _mock_flag):+ flow_id = self._create_active_flow()+ url = f"/api/projects/{self.team.id}/hog_flows/{flow_id}/optimization"+ self.client.post(url, {"enabled": False}, format="json")++ back_on = self.client.post(url, {"enabled": True}, format="json")++ assert back_on.status_code == 200, back_on.json()+ assert back_on.json()["enabled"] is True+ rows = HogFlowOptimization.objects.for_team(self.team.id).filter(hog_flow_id=flow_id)+ assert rows.count() == 1+ row = rows.first()+ assert row is not None+ assert row.enabled is True++ def test_the_list_can_be_narrowed_to_workflows_with_suggestions_on(self, _mock_flag):+ opted_in = self._create_active_flow()+ untouched = self._create_active_flow()+ self.client.post(+ f"/api/projects/{self.team.id}/hog_flows/{untouched}/optimization", {"enabled": False}, format="json"+ )++ archived = self._create_active_flow()+ self.client.patch(f"/api/projects/{self.team.id}/hog_flows/{archived}", {"status": "archived"})++ listed = self.client.get(f"/api/projects/{self.team.id}/hog_flows?optimization_enabled=true")++ assert listed.status_code == 200, listed.json()+ assert [row["id"] for row in listed.json()["results"]] == [opted_in]+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")diff --git a/products/workflows/frontend/Workflows/WorkflowSceneHeader.tsx b/products/workflows/frontend/Workflows/WorkflowSceneHeader.tsxindex 0f7549dfb84f..28151b5c3d60 100644--- a/products/workflows/frontend/Workflows/WorkflowSceneHeader.tsx+++ b/products/workflows/frontend/Workflows/WorkflowSceneHeader.tsx@@ -24,6 +24,8 @@ import { ScenePanel, ScenePanelActionsSection, ScenePanelDivider } from '~/layouimport { AccessControlLevel, AccessControlResourceType } from '~/types'import { HogFlowManualTriggerButton } from './hogflows/HogFlowManualTriggerButton'+import { WorkflowSuggestionsMenuItem } from './suggestions/WorkflowSuggestionsMenuItem'+import { WorkflowSuggestionsPanelToggle } from './suggestions/WorkflowSuggestionsPanelToggle'import { SaveAsTemplateModal } from './templates/SaveAsTemplateModal'import { workflowTemplateLogic } from './templates/workflowTemplateLogic'import { workflowLogic } from './workflowLogic'@@ -64,6 +66,7 @@ export const WorkflowSceneHeader = (props: WorkflowSceneLogicProps = {}): JSX.Elconst isManualWorkflow = ['manual', 'batch'].includes(workflow?.trigger?.type || '')const { featureFlags } = useValues(featureFlagLogic)const sceneMenuBarEnabled = !!featureFlags[FEATURE_FLAGS.SCENE_MENU_BAR]+ const selfOptimisingEnabled = !!featureFlags[FEATURE_FLAGS.SELF_OPTIMISING_WORKFLOWS]const [displayStatus, setDisplayStatus] = useState(workflow?.status)const [isTransitioning, setIsTransitioning] = useState(false)const prevStatusRef = useRef(workflow?.status)@@ -184,6 +187,12 @@ export const WorkflowSceneHeader = (props: WorkflowSceneLogicProps = {}): JSX.El<IconClock />Version history</SceneMenuBarItem>+ {selfOptimisingEnabled && (+ <>+ <SceneMenuBarSeparator />+ <WorkflowSuggestionsMenuItem id={props.id!} />+ </>+ )}</SceneMenuBarMenu></SceneMenuBar>)}@@ -232,6 +241,14 @@ export const WorkflowSceneHeader = (props: WorkflowSceneLogicProps = {}): JSX.El</AccessControlAction><LemonDivider vertical /><ScenePanel>+ {selfOptimisingEnabled && (+ <>+ <ScenePanelActionsSection>+ <WorkflowSuggestionsPanelToggle id={props.id!} />+ </ScenePanelActionsSection>+ <ScenePanelDivider />+ </>+ )}<ScenePanelActionsSection><ButtonPrimitivemenuItemdiff --git a/products/workflows/frontend/Workflows/misc/workflowActivityDescriber.tsx b/products/workflows/frontend/Workflows/misc/workflowActivityDescriber.tsxindex 89cff9840462..0716e758367f 100644--- a/products/workflows/frontend/Workflows/misc/workflowActivityDescriber.tsx+++ b/products/workflows/frontend/Workflows/misc/workflowActivityDescriber.tsx@@ -216,6 +216,23 @@ export function workflowActivityDescriber(logItem: ActivityLogItem, asNotificati}}+ if (logItem.activity == 'optimization_enabled' || logItem.activity == 'optimization_disabled') {+ return {+ summary: activityLogSummary(+ logItem,+ logItem.activity == 'optimization_enabled' ? 'Turned on suggestions' : 'Turned off suggestions',+ nameOrLinkToWorkflow(logItem.item_id, logItem.detail.name)+ ),+ description: (+ <>+ <ActivityLogUserName logItem={logItem} />{' '}+ {logItem.activity == 'optimization_enabled' ? 'turned on' : 'turned off'} suggestions for the{' '}+ {objectNoun}: {nameOrLinkToWorkflow(logItem?.item_id, logItem?.detail.name)}+ </>+ ),+ }+ }+if (logItem.activity == 'proposal_approved') {return {summary: activityLogSummary(diff --git a/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestions.tsx b/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestions.tsxindex 74f8610cd1da..2df1f3ae963e 100644--- a/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestions.tsx+++ b/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestions.tsx@@ -6,24 +6,73 @@ import { WorkflowAppliedOutcome } from './WorkflowAppliedOutcome'import { workflowProposalsLogic } from './workflowProposalsLogic'import { WorkflowSuggestionCard } from './WorkflowSuggestionCard'-export function WorkflowSuggestions({ id }: { id: string }): JSX.Element {- const { pendingProposals, appliedProposals, outcomes, proposalsResponse, proposalsResponseLoading } = useValues(- workflowProposalsLogic({ id })+function SuggestionsOffNotice(): JSX.Element {+ return (+ <div className="flex flex-col gap-2">+ <h3 className="mb-0">Suggestions are off for this workflow</h3>+ <p className="mb-0 text-secondary">+ Turn on "Suggest improvements" in the workflow menu to have PostHog read how this workflow performs and+ suggest changes. Only the workflows you turn on are read.+ </p>+ </div>+ )+}++function SuggestionsUnreadableNotice(): JSX.Element {+ return (+ <div className="flex flex-col gap-2">+ <h3 className="mb-0">Could not read this workflow's suggestion setting</h3>+ <p className="mb-0 text-secondary">+ Reload the page to try again. Nothing changed: whatever the setting was, it still is.+ </p>+ </div>)+}++export function WorkflowSuggestions({ id }: { id: string }): JSX.Element {+ const {+ pendingProposals,+ appliedProposals,+ outcomes,+ optimizationEnabled,+ optimization,+ optimizationLoading,+ optimizationUnreadable,+ proposalsResponse,+ proposalsResponseLoading,+ } = useValues(workflowProposalsLogic({ id }))const measuredApplied = appliedProposals.filter((proposal) => outcomes[proposal.id]?.after)+ if (optimization === null && optimizationLoading) {+ return <Spinner />+ }++ const nothingFiled = pendingProposals.length === 0 && measuredApplied.length === 0+ // A failed read leaves the setting unknown, so it cannot stand in for "off".+ const notice = optimizationUnreadable ? (+ <SuggestionsUnreadableNotice />+ ) : !optimizationEnabled ? (+ <SuggestionsOffNotice />+ ) : null++ if (notice && nothingFiled) {+ return notice+ }+return (<div className="flex flex-col gap-4">+ {/* Off, or unreadable, still leaves what was already filed for someone to resolve. */}+ {notice}<div className="flex flex-col gap-2"><h3 className="mb-0">Waiting for you</h3>{proposalsResponse === null && proposalsResponseLoading ? (<Spinner />) : pendingProposals.length === 0 ? (<p className="mb-0 text-secondary">- Nothing to review. PostHog reads this workflow's metrics and files a suggestion here when it- finds a change worth making. Nothing reaches anyone until you approve a suggestion and publish- it.+ Nothing to review. PostHog reads this workflow's metrics on a schedule and files a suggestion+ here when it finds a change worth making. Nothing reaches anyone until you approve a suggestion+ and publish it.</p>) : (pendingProposals.map((proposal) => (diff --git a/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestionsMenuItem.tsx b/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestionsMenuItem.tsxnew file mode 100644index 000000000000..9bb6428f2c36--- /dev/null+++ b/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestionsMenuItem.tsx@@ -0,0 +1,35 @@+import { useActions, useValues } from 'kea'++import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'++import { SceneMenuBarCheckboxItem } from '~/layout/scenes/components/SceneMenuBar'+import { AccessControlLevel, AccessControlResourceType } from '~/types'++import { workflowLogic } from '../workflowLogic'+import { workflowProposalsLogic } from './workflowProposalsLogic'++export function WorkflowSuggestionsMenuItem({ id }: { id: string }): JSX.Element {+ const { optimizationEnabled, optimizationLoading, optimizationUnreadable } = useValues(+ workflowProposalsLogic({ id })+ )+ const { setOptimizationEnabled } = useActions(workflowProposalsLogic({ id }))+ const { workflowUserAccessLevel } = useValues(workflowLogic({ id }))++ // A viewer cannot flip it, so the item is inert instead of a request that ends in an error toast.+ const accessDisabledReason = getAccessControlDisabledReason(+ AccessControlResourceType.Workflow,+ AccessControlLevel.Editor,+ workflowUserAccessLevel ?? undefined+ )++ return (+ <SceneMenuBarCheckboxItem+ checked={optimizationEnabled}+ disabled={optimizationLoading || optimizationUnreadable || !!accessDisabledReason}+ onCheckedChange={(checked) => setOptimizationEnabled(checked)}+ data-attr="workflow-menubar-suggest-improvements"+ >+ Suggest improvements+ </SceneMenuBarCheckboxItem>+ )+}diff --git a/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestionsPanelToggle.tsx b/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestionsPanelToggle.tsxnew file mode 100644index 000000000000..c45583520804--- /dev/null+++ b/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestionsPanelToggle.tsx@@ -0,0 +1,46 @@+import { useActions, useValues } from 'kea'++import { LemonSwitch } from '@posthog/lemon-ui'++import { AccessControlAction } from 'lib/components/AccessControlAction'++import { AccessControlLevel, AccessControlResourceType } from '~/types'++import { workflowLogic } from '../workflowLogic'+import { workflowProposalsLogic } from './workflowProposalsLogic'++export function WorkflowSuggestionsPanelToggle({ id }: { id: string }): JSX.Element {+ const { optimizationEnabled, optimizationLoading, optimizationUnreadable } = useValues(+ workflowProposalsLogic({ id })+ )+ const { setOptimizationEnabled } = useActions(workflowProposalsLogic({ id }))+ const { workflowUserAccessLevel } = useValues(workflowLogic({ id }))++ return (+ <AccessControlAction+ resourceType={AccessControlResourceType.Workflow}+ minAccessLevel={AccessControlLevel.Editor}+ userAccessLevel={workflowUserAccessLevel ?? undefined}+ >+ {({ disabledReason }) => (+ <LemonSwitch+ id="workflow-self-optimization"+ data-attr="workflow-suggest-improvements"+ className="px-2 py-1"+ checked={optimizationEnabled}+ onChange={(checked) => setOptimizationEnabled(checked)}+ // A failed read must not show "off" for a workflow that may be on.+ disabled={optimizationLoading || optimizationUnreadable || !!disabledReason}+ tooltip={+ disabledReason ??+ (optimizationUnreadable+ ? 'Could not read whether suggestions are on for this workflow. Reload the page to try again.'+ : 'PostHog reads how this workflow performs and suggests changes for you to review. Nothing reaches anyone until you approve a suggestion and publish it.')+ }+ fullWidth+ label="Suggest improvements"+ />+ )}+ </AccessControlAction>+ )+}diff --git a/products/workflows/frontend/Workflows/suggestions/workflowProposalsLogic.ts b/products/workflows/frontend/Workflows/suggestions/workflowProposalsLogic.tsindex 6f73749f4ba5..9ead1c6e7292 100644--- a/products/workflows/frontend/Workflows/suggestions/workflowProposalsLogic.ts+++ b/products/workflows/frontend/Workflows/suggestions/workflowProposalsLogic.ts@@ -8,11 +8,14 @@ import { teamLogic } from 'scenes/teamLogic'import {hogFlowsProposalsApproveCreate,+ hogFlowsOptimizationCreate,+ hogFlowsOptimizationRetrieve,hogFlowsProposalsList,hogFlowsProposalsOutcomeRetrieve,hogFlowsProposalsRejectCreate,} from '../../generated/api'import type {+ HogFlowOptimizationApi,PaginatedWorkflowProposalListApi,WorkflowProposalApi,WorkflowProposalOutcomeApi,@@ -40,6 +43,10 @@ export interface workflowProposalsLogicValues {approveDisabledReason: string | undefinedlastSeenDraftStamp: string | nulllastSeenVersion: number | null+ optimization: HogFlowOptimizationApi | null+ optimizationEnabled: boolean+ optimizationLoading: boolean+ optimizationUnreadable: booleanoutcomes: Record<string, WorkflowProposalOutcomeApi>pendingProposals: WorkflowProposalApi[]proposalsResponse: PaginatedWorkflowProposalListApi | null@@ -78,6 +85,21 @@ export interface workflowProposalsLogicActions {appliedResponse: PaginatedWorkflowProposalListApipayload?: any}+ loadOptimization: () => any+ loadOptimizationFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadOptimizationSuccess: (+ optimization: HogFlowOptimizationApi | null,+ payload?: any+ ) => {+ optimization: HogFlowOptimizationApi | null+ payload?: any+ }loadOutcome: (proposalId: string) => {proposalId: string}@@ -109,6 +131,30 @@ export interface workflowProposalsLogicActions {draftStamp: string | nullversion: number | null}+ setOptimizationEnabled: (enabled: boolean) => {+ enabled: boolean+ }+ setOptimizationEnabledFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ setOptimizationEnabledSuccess: (+ optimization: HogFlowOptimizationApi,+ payload?: {+ enabled: boolean+ }+ ) => {+ optimization: HogFlowOptimizationApi+ payload?: {+ enabled: boolean+ }+ }+ setOptimizationUnreadable: (unreadable: boolean) => {+ unreadable: boolean+ }setOutcome: (proposalId: string,outcome: WorkflowProposalOutcomeApi@@ -130,6 +176,7 @@ export interface workflowProposalsLogicMeta {key: string__keaTypeGenInternalSelectorTypes: {appliedProposals: (appliedResponse: PaginatedWorkflowProposalListApi | null) => WorkflowProposalApi[]+ optimizationEnabled: (optimization: HogFlowOptimizationApi | null) => booleanpendingProposals: (proposalsResponse: PaginatedWorkflowProposalListApi | null) => WorkflowProposalApi[]approveDisabledReason: (hasUnsavedChanges: boolean, showDraftActions: boolean) => string | undefined}@@ -169,6 +216,8 @@ export const workflowProposalsLogic = kea<workflowProposalsLogicType>([}),loadOutcome: (proposalId: string) => ({ proposalId }),setLastSeen: (version: number | null, draftStamp: string | null) => ({ version, draftStamp }),+ setOptimizationUnreadable: (unreadable: boolean) => ({ unreadable }),+ setOptimizationEnabled: (enabled: boolean) => ({ enabled }),setOutcome: (proposalId: string, outcome: WorkflowProposalOutcomeApi) => ({ proposalId, outcome }),}),reducers({@@ -198,6 +247,15 @@ export const workflowProposalsLogic = kea<workflowProposalsLogicType>([setResolvingId: (_, { action }) => action,},],+ // A failed read must not read as "off".+ optimizationUnreadable: [+ false,+ {+ setOptimizationUnreadable: (_, { unreadable }) => unreadable,+ loadOptimizationSuccess: () => false,+ setOptimizationEnabledSuccess: () => false,+ },+ ],lastSeenVersion: [null as number | null,{@@ -222,7 +280,7 @@ export const workflowProposalsLogic = kea<workflowProposalsLogicType>([},],}),- loaders(({ props, values }) => ({+ loaders(({ actions, props, values }) => ({appliedResponse: [null as PaginatedWorkflowProposalListApi | null,{@@ -242,6 +300,26 @@ export const workflowProposalsLogic = kea<workflowProposalsLogicType>([},},],+ optimization: [+ null as HogFlowOptimizationApi | null,+ {+ loadOptimization: async () => {+ try {+ return await hogFlowsOptimizationRetrieve(String(values.currentTeamIdStrict), props.id)+ } catch (error) {+ // 404 is the flag being off, which the panel already reads as "nothing here".+ if (error instanceof ApiError && error.status === 404) {+ return null+ }+ actions.setOptimizationUnreadable(true)+ throw error+ }+ },+ setOptimizationEnabled: async ({ enabled }) => {+ return await hogFlowsOptimizationCreate(String(values.currentTeamIdStrict), props.id, { enabled })+ },+ },+ ],proposalsResponse: [null as PaginatedWorkflowProposalListApi | null,{@@ -266,6 +344,10 @@ export const workflowProposalsLogic = kea<workflowProposalsLogicType>([(s) => [s.appliedResponse],(response: PaginatedWorkflowProposalListApi | null): WorkflowProposalApi[] => response?.results ?? [],],+ optimizationEnabled: [+ (s) => [s.optimization],+ (optimization: HogFlowOptimizationApi | null): boolean => !!optimization?.enabled,+ ],pendingProposals: [(s) => [s.proposalsResponse],(response: PaginatedWorkflowProposalListApi | null): WorkflowProposalApi[] => response?.results ?? [],@@ -427,5 +509,6 @@ export const workflowProposalsLogic = kea<workflowProposalsLogicType>([actions.setLastSeen(values.originalWorkflow?.version ?? null, values.originalWorkflow?.draft_updated_at ?? null)actions.loadProposals()actions.loadApplied()+ actions.loadOptimization()}),])diff --git a/products/workflows/frontend/generated/api.schemas.ts b/products/workflows/frontend/generated/api.schemas.tsindex 5cf2a02da114..df6d8423633f 100644--- a/products/workflows/frontend/generated/api.schemas.ts+++ b/products/workflows/frontend/generated/api.schemas.ts@@ -1187,6 +1187,11 @@ export interface AppMetricsTotalsResponseApi {totals: AppMetricsTotalsResponseApiTotals}+export interface HogFlowOptimizationApi {+ /** Whether PostHog may read this workflow's metrics and suggest changes to it. */+ enabled: boolean+}+/*** * `suggested` - Suggested* * `approved` - Approved@@ -1971,6 +1976,10 @@ export type HogFlowsListParams = {* The initial index from which to return the results.*/offset?: number+ /**+ * Only workflows someone turned suggestions on for.+ */+ optimization_enabled?: boolean/*** Filter to workflows owned by a product surface, e.g. `loops` for Desktop loops.*/diff --git a/products/workflows/frontend/generated/api.ts b/products/workflows/frontend/generated/api.tsindex cd4561803511..c6b15b8d499e 100644--- a/products/workflows/frontend/generated/api.ts+++ b/products/workflows/frontend/generated/api.ts@@ -18,6 +18,7 @@ import type {HogFlowBatchJobApi,HogFlowBatchJobCancelResponseApi,HogFlowInvocationApi,+ HogFlowOptimizationApi,HogFlowPublishRequestApi,HogFlowPublishResponseApi,HogFlowRevisionApi,@@ -745,6 +746,51 @@ export const hogFlowsMetricsTotalsRetrieve = async (})}+export const getHogFlowsOptimizationRetrieveUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/hog_flows/${id}/optimization/`+}++/**+ * Whether PostHog may look at this workflow and suggest changes to it.+ *+ * Turning it off stops a producer reading the workflow. Suggestions already made are left+ * alone: someone still has them to resolve.+ */+export const hogFlowsOptimizationRetrieve = async (+ projectId: string,+ id: string,+ options?: RequestInit+): Promise<HogFlowOptimizationApi> => {+ return apiMutator<HogFlowOptimizationApi>(getHogFlowsOptimizationRetrieveUrl(projectId, id), {+ ...options,+ method: 'GET',+ })+}++export const getHogFlowsOptimizationCreateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/hog_flows/${id}/optimization/`+}++/**+ * Whether PostHog may look at this workflow and suggest changes to it.+ *+ * Turning it off stops a producer reading the workflow. Suggestions already made are left+ * alone: someone still has them to resolve.+ */+export const hogFlowsOptimizationCreate = async (+ projectId: string,+ id: string,+ hogFlowOptimizationApi: HogFlowOptimizationApi,+ options?: RequestInit+): Promise<HogFlowOptimizationApi> => {+ return apiMutator<HogFlowOptimizationApi>(getHogFlowsOptimizationCreateUrl(projectId, id), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(hogFlowOptimizationApi),+ })+}+export const getHogFlowsProposalsListUrl = (projectId: string, id: string, params?: HogFlowsProposalsListParams) => {const normalizedParams = new URLSearchParams()diff --git a/products/workflows/frontend/generated/api.zod.ts b/products/workflows/frontend/generated/api.zod.tsindex b3ee79d823a0..50a49117f244 100644--- a/products/workflows/frontend/generated/api.zod.ts+++ b/products/workflows/frontend/generated/api.zod.ts@@ -2430,6 +2430,16 @@ export const HogFlowsInvocationsCancelCreateBody = /* @__PURE__ */ zod}).describe('Cancel in-flight invocations of a workflow. Provide exactly one selector.')+/**+ * Whether PostHog may look at this workflow and suggest changes to it.+ *+ * Turning it off stops a producer reading the workflow. Suggestions already made are left+ * alone: someone still has them to resolve.+ */+export const HogFlowsOptimizationCreateBody = /* @__PURE__ */ zod.object({+ enabled: zod.boolean().describe("Whether PostHog may read this workflow's metrics and suggest changes to it."),+})+/*** Agent-authored changes to this workflow, awaiting a human's decision.*diff --git a/products/workflows/mcp/tools.yaml b/products/workflows/mcp/tools.yamlindex 8786d91b2ed1..403dba8b2b09 100644--- a/products/workflows/mcp/tools.yaml+++ b/products/workflows/mcp/tools.yaml@@ -99,6 +99,12 @@ tools:hog-flows-metrics-totals-retrieve:operation: hog_flows_metrics_totals_retrieveenabled: false+ hog-flows-optimization-create:+ operation: hog_flows_optimization_create+ enabled: false+ hog-flows-optimization-retrieve:+ operation: hog_flows_optimization_retrieve+ enabled: falsehog-flows-partial-update:operation: hog_flows_partial_updateenabled: falsediff --git a/pyproject.toml b/pyproject.tomlindex 9812d61000d9..a4492672c9b3 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -742,6 +742,7 @@ ignore_imports = ["products.workflows.backend.presentation.views.hog_flow -> products.workflows.backend.metrics","products.workflows.backend.presentation.views.hog_flow -> products.workflows.backend.models.hog_flow.hog_flow","products.workflows.backend.presentation.views.hog_flow -> products.workflows.backend.models.hog_flow_batch_job",+ "products.workflows.backend.presentation.views.hog_flow -> products.workflows.backend.models.hog_flow_optimization","products.workflows.backend.presentation.views.hog_flow -> products.workflows.backend.models.hog_flow_revision","products.workflows.backend.presentation.views.hog_flow -> products.workflows.backend.models.hog_flow_schedule","products.workflows.backend.presentation.views.hog_flow -> products.workflows.backend.models.team_workflows_config",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex f904d80bdedc..6482175af08d 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -50983,6 +50983,11 @@ export namespace Schemas {readonly last_run: HogFlowLastRun | null;}+ export interface HogFlowOptimization {+ /** Whether PostHog may read this workflow's metrics and suggest changes to it. */+ enabled: boolean;+ }+export interface HogFlowPublishImpactMoveTarget {/** Id of the surviving step runs will continue at. */action_id: string;@@ -78904,8 +78909,8 @@ export namespace Schemas {*/repositories?: string[];/**- * Extra write access granted to this one scout, as scope strings. The grantable set is `alert:write`, `annotation:write`, `dashboard:write`, `insight:write`, `llm_skill:write`, `replay_scanner:write`, `warehouse_table:write`, `warehouse_view:write`. Empty (the default) means the scout reads the project and writes only what every scout may write: notebooks, its findings, and its own memory. Each scope is project-wide and object-level, so a scout holding `dashboard:write` can update or delete any dashboard in the project, not only ones it made. Grant only what this scout maintains. Only the person the scout's runs act as (whoever authored it) or a project admin can set it, and a scoped API key must itself carry each scope it grants. A dry run (`emit=false`) never holds the grant. Applies from the scout's next run.- * @maxItems 8+ * Extra write access granted to this one scout, as scope strings. The grantable set is `alert:write`, `annotation:write`, `dashboard:write`, `hog_flow_proposal:write`, `insight:write`, `llm_skill:write`, `replay_scanner:write`, `warehouse_table:write`, `warehouse_view:write`. Empty (the default) means the scout reads the project and writes only what every scout may write: notebooks, its findings, and its own memory. Each scope is project-wide and object-level, so a scout holding `dashboard:write` can update or delete any dashboard in the project, not only ones it made. Grant only what this scout maintains. Only the person the scout's runs act as (whoever authored it) or a project admin can set it, and a scoped API key must itself carry each scope it grants. A dry run (`emit=false`) never holds the grant. Applies from the scout's next run.+ * @maxItems 9*/write_scopes?: string[];}@@ -90595,8 +90600,8 @@ export namespace Schemas {*/repositories?: string[];/**- * Extra write access granted to this one scout, as scope strings. The grantable set is `alert:write`, `annotation:write`, `dashboard:write`, `insight:write`, `llm_skill:write`, `replay_scanner:write`, `warehouse_table:write`, `warehouse_view:write`. Empty (the default) means the scout reads the project and writes only what every scout may write: notebooks, its findings, and its own memory. Each scope is project-wide and object-level, so a scout holding `dashboard:write` can update or delete any dashboard in the project, not only ones it made. Grant only what this scout maintains. Only the person the scout's runs act as (whoever authored it) or a project admin can set it, and a scoped API key must itself carry each scope it grants. A dry run (`emit=false`) never holds the grant. Applies from the scout's next run.- * @maxItems 8+ * Extra write access granted to this one scout, as scope strings. The grantable set is `alert:write`, `annotation:write`, `dashboard:write`, `hog_flow_proposal:write`, `insight:write`, `llm_skill:write`, `replay_scanner:write`, `warehouse_table:write`, `warehouse_view:write`. Empty (the default) means the scout reads the project and writes only what every scout may write: notebooks, its findings, and its own memory. Each scope is project-wide and object-level, so a scout holding `dashboard:write` can update or delete any dashboard in the project, not only ones it made. Grant only what this scout maintains. Only the person the scout's runs act as (whoever authored it) or a project admin can set it, and a scoped API key must itself carry each scope it grants. A dry run (`emit=false`) never holds the grant. Applies from the scout's next run.+ * @maxItems 9*/write_scopes?: string[];/** Whether this scout runs on its schedule. Defaults to true. */@@ -90828,8 +90833,8 @@ export namespace Schemas {*/repositories?: string[];/**- * Extra write access granted to this one scout, as scope strings. The grantable set is `alert:write`, `annotation:write`, `dashboard:write`, `insight:write`, `llm_skill:write`, `replay_scanner:write`, `warehouse_table:write`, `warehouse_view:write`. Empty (the default) means the scout reads the project and writes only what every scout may write: notebooks, its findings, and its own memory. Each scope is project-wide and object-level, so a scout holding `dashboard:write` can update or delete any dashboard in the project, not only ones it made. Grant only what this scout maintains. Only the person the scout's runs act as (whoever authored it) or a project admin can set it, and a scoped API key must itself carry each scope it grants. A dry run (`emit=false`) never holds the grant. Applies from the scout's next run.- * @maxItems 8+ * Extra write access granted to this one scout, as scope strings. The grantable set is `alert:write`, `annotation:write`, `dashboard:write`, `hog_flow_proposal:write`, `insight:write`, `llm_skill:write`, `replay_scanner:write`, `warehouse_table:write`, `warehouse_view:write`. Empty (the default) means the scout reads the project and writes only what every scout may write: notebooks, its findings, and its own memory. Each scope is project-wide and object-level, so a scout holding `dashboard:write` can update or delete any dashboard in the project, not only ones it made. Grant only what this scout maintains. Only the person the scout's runs act as (whoever authored it) or a project admin can set it, and a scoped API key must itself carry each scope it grants. A dry run (`emit=false`) never holds the grant. Applies from the scout's next run.+ * @maxItems 9*/readonly write_scopes: readonly string[];/**@@ -92878,8 +92883,8 @@ export namespace Schemas {*/repositories?: string[];/**- * Extra write access granted to this one scout, as scope strings. The grantable set is `alert:write`, `annotation:write`, `dashboard:write`, `insight:write`, `llm_skill:write`, `replay_scanner:write`, `warehouse_table:write`, `warehouse_view:write`. Empty (the default) means the scout reads the project and writes only what every scout may write: notebooks, its findings, and its own memory. Each scope is project-wide and object-level, so a scout holding `dashboard:write` can update or delete any dashboard in the project, not only ones it made. Grant only what this scout maintains. Only the person the scout's runs act as (whoever authored it) or a project admin can set it, and a scoped API key must itself carry each scope it grants. A dry run (`emit=false`) never holds the grant. Applies from the scout's next run.- * @maxItems 8+ * Extra write access granted to this one scout, as scope strings. The grantable set is `alert:write`, `annotation:write`, `dashboard:write`, `hog_flow_proposal:write`, `insight:write`, `llm_skill:write`, `replay_scanner:write`, `warehouse_table:write`, `warehouse_view:write`. Empty (the default) means the scout reads the project and writes only what every scout may write: notebooks, its findings, and its own memory. Each scope is project-wide and object-level, so a scout holding `dashboard:write` can update or delete any dashboard in the project, not only ones it made. Grant only what this scout maintains. Only the person the scout's runs act as (whoever authored it) or a project admin can set it, and a scoped API key must itself carry each scope it grants. A dry run (`emit=false`) never holds the grant. Applies from the scout's next run.+ * @maxItems 9*/write_scopes?: string[];/** Whether this scout runs on its schedule. Defaults to true. */@@ -114904,6 +114909,10 @@ export namespace Schemas {* The initial index from which to return the results.*/offset?: number;+ /**+ * Only workflows someone turned suggestions on for.+ */+ optimization_enabled?: boolean;/*** Filter to workflows owned by a product surface, e.g. `loops` for Desktop loops.*/diff --git a/services/mcp/src/generated/replay_vision/api.ts b/services/mcp/src/generated/replay_vision/api.tsindex 7a6276fd6cb4..a15748b79e72 100644--- a/services/mcp/src/generated/replay_vision/api.ts+++ b/services/mcp/src/generated/replay_vision/api.ts@@ -1674,7 +1674,7 @@ export const visionScannersScoutsCreateBodyConfigOneRepositoriesItemMax = 255export const visionScannersScoutsCreateBodyConfigOneRepositoriesMax = 10-export const visionScannersScoutsCreateBodyConfigOneWriteScopesMax = 8+export const visionScannersScoutsCreateBodyConfigOneWriteScopesMax = 9export const visionScannersScoutsCreateBodyConfigOneRunIntervalMinutesMin = 30export const visionScannersScoutsCreateBodyConfigOneRunIntervalMinutesMax = 43200@@ -1757,7 +1757,7 @@ export const VisionScannersScoutsCreateBody = () => zod.max(visionScannersScoutsCreateBodyConfigOneWriteScopesMax).optional().describe(- "Extra write access granted to this one scout, as scope strings. The grantable set is `alert:write`, `annotation:write`, `dashboard:write`, `insight:write`, `llm_skill:write`, `replay_scanner:write`, `warehouse_table:write`, `warehouse_view:write`. Empty (the default) means the scout reads the project and writes only what every scout may write: notebooks, its findings, and its own memory. Each scope is project-wide and object-level, so a scout holding `dashboard:write` can update or delete any dashboard in the project, not only ones it made. Grant only what this scout maintains. Only the person the scout's runs act as (whoever authored it) or a project admin can set it, and a scoped API key must itself carry each scope it grants. A dry run (`emit=false`) never holds the grant. Applies from the scout's next run."+ "Extra write access granted to this one scout, as scope strings. The grantable set is `alert:write`, `annotation:write`, `dashboard:write`, `hog_flow_proposal:write`, `insight:write`, `llm_skill:write`, `replay_scanner:write`, `warehouse_table:write`, `warehouse_view:write`. Empty (the default) means the scout reads the project and writes only what every scout may write: notebooks, its findings, and its own memory. Each scope is project-wide and object-level, so a scout holding `dashboard:write` can update or delete any dashboard in the project, not only ones it made. Grant only what this scout maintains. Only the person the scout's runs act as (whoever authored it) or a project admin can set it, and a scoped API key must itself carry each scope it grants. A dry run (`emit=false`) never holds the grant. Applies from the scout's next run."),enabled: zod.boolean()diff --git a/services/mcp/src/generated/signals/api.ts b/services/mcp/src/generated/signals/api.tsindex eb516be5676c..7195bf84e954 100644--- a/services/mcp/src/generated/signals/api.ts+++ b/services/mcp/src/generated/signals/api.ts@@ -658,7 +658,7 @@ export const signalsScoutCreateBodyConfigOneRepositoriesItemMax = 255export const signalsScoutCreateBodyConfigOneRepositoriesMax = 10-export const signalsScoutCreateBodyConfigOneWriteScopesMax = 8+export const signalsScoutCreateBodyConfigOneWriteScopesMax = 9export const signalsScoutCreateBodyConfigOneRunIntervalMinutesMin = 30export const signalsScoutCreateBodyConfigOneRunIntervalMinutesMax = 43200@@ -760,7 +760,7 @@ export const SignalsScoutCreateBody = () => zod.max(signalsScoutCreateBodyConfigOneWriteScopesMax).optional().describe(- "Extra write access granted to this one scout, as scope strings. The grantable set is `alert:write`, `annotation:write`, `dashboard:write`, `insight:write`, `llm_skill:write`, `replay_scanner:write`, `warehouse_table:write`, `warehouse_view:write`. Empty (the default) means the scout reads the project and writes only what every scout may write: notebooks, its findings, and its own memory. Each scope is project-wide and object-level, so a scout holding `dashboard:write` can update or delete any dashboard in the project, not only ones it made. Grant only what this scout maintains. Only the person the scout's runs act as (whoever authored it) or a project admin can set it, and a scoped API key must itself carry each scope it grants. A dry run (`emit=false`) never holds the grant. Applies from the scout's next run."+ "Extra write access granted to this one scout, as scope strings. The grantable set is `alert:write`, `annotation:write`, `dashboard:write`, `hog_flow_proposal:write`, `insight:write`, `llm_skill:write`, `replay_scanner:write`, `warehouse_table:write`, `warehouse_view:write`. Empty (the default) means the scout reads the project and writes only what every scout may write: notebooks, its findings, and its own memory. Each scope is project-wide and object-level, so a scout holding `dashboard:write` can update or delete any dashboard in the project, not only ones it made. Grant only what this scout maintains. Only the person the scout's runs act as (whoever authored it) or a project admin can set it, and a scoped API key must itself carry each scope it grants. A dry run (`emit=false`) never holds the grant. Applies from the scout's next run."),enabled: zod.boolean()@@ -926,7 +926,7 @@ export const signalsScoutConfigCreateBodyRepositoriesItemMax = 255export const signalsScoutConfigCreateBodyRepositoriesMax = 10-export const signalsScoutConfigCreateBodyWriteScopesMax = 8+export const signalsScoutConfigCreateBodyWriteScopesMax = 9export const signalsScoutConfigCreateBodyRunIntervalMinutesMin = 30export const signalsScoutConfigCreateBodyRunIntervalMinutesMax = 43200@@ -988,7 +988,7 @@ export const SignalsScoutConfigCreateBody = () => zod.max(signalsScoutConfigCreateBodyWriteScopesMax).optional().describe(- "Extra write access granted to this one scout, as scope strings. The grantable set is `alert:write`, `annotation:write`, `dashboard:write`, `insight:write`, `llm_skill:write`, `replay_scanner:write`, `warehouse_table:write`, `warehouse_view:write`. Empty (the default) means the scout reads the project and writes only what every scout may write: notebooks, its findings, and its own memory. Each scope is project-wide and object-level, so a scout holding `dashboard:write` can update or delete any dashboard in the project, not only ones it made. Grant only what this scout maintains. Only the person the scout's runs act as (whoever authored it) or a project admin can set it, and a scoped API key must itself carry each scope it grants. A dry run (`emit=false`) never holds the grant. Applies from the scout's next run."+ "Extra write access granted to this one scout, as scope strings. The grantable set is `alert:write`, `annotation:write`, `dashboard:write`, `hog_flow_proposal:write`, `insight:write`, `llm_skill:write`, `replay_scanner:write`, `warehouse_table:write`, `warehouse_view:write`. Empty (the default) means the scout reads the project and writes only what every scout may write: notebooks, its findings, and its own memory. Each scope is project-wide and object-level, so a scout holding `dashboard:write` can update or delete any dashboard in the project, not only ones it made. Grant only what this scout maintains. Only the person the scout's runs act as (whoever authored it) or a project admin can set it, and a scoped API key must itself carry each scope it grants. A dry run (`emit=false`) never holds the grant. Applies from the scout's next run."),enabled: zod.boolean().optional().describe('Whether this scout runs on its schedule. Defaults to true.'),emit: zod@@ -1142,7 +1142,7 @@ export const signalsScoutConfigUpdateBodyRepositoriesItemMax = 255export const signalsScoutConfigUpdateBodyRepositoriesMax = 10-export const signalsScoutConfigUpdateBodyWriteScopesMax = 8+export const signalsScoutConfigUpdateBodyWriteScopesMax = 9export const SignalsScoutConfigUpdateBody = () => zod.object({@@ -1294,7 +1294,7 @@ export const SignalsScoutConfigUpdateBody = () => zod.max(signalsScoutConfigUpdateBodyWriteScopesMax).optional().describe(- "Extra write access granted to this one scout, as scope strings. The grantable set is `alert:write`, `annotation:write`, `dashboard:write`, `insight:write`, `llm_skill:write`, `replay_scanner:write`, `warehouse_table:write`, `warehouse_view:write`. Empty (the default) means the scout reads the project and writes only what every scout may write: notebooks, its findings, and its own memory. Each scope is project-wide and object-level, so a scout holding `dashboard:write` can update or delete any dashboard in the project, not only ones it made. Grant only what this scout maintains. Only the person the scout's runs act as (whoever authored it) or a project admin can set it, and a scoped API key must itself carry each scope it grants. A dry run (`emit=false`) never holds the grant. Applies from the scout's next run."+ "Extra write access granted to this one scout, as scope strings. The grantable set is `alert:write`, `annotation:write`, `dashboard:write`, `hog_flow_proposal:write`, `insight:write`, `llm_skill:write`, `replay_scanner:write`, `warehouse_table:write`, `warehouse_view:write`. Empty (the default) means the scout reads the project and writes only what every scout may write: notebooks, its findings, and its own memory. Each scope is project-wide and object-level, so a scout holding `dashboard:write` can update or delete any dashboard in the project, not only ones it made. Grant only what this scout maintains. Only the person the scout's runs act as (whoever authored it) or a project admin can set it, and a scoped API key must itself carry each scope it grants. A dry run (`emit=false`) never holds the grant. Applies from the scout's next run."),}).describe('Editable display name, schedule, enablement, and emit posture for one scout config.')diff --git a/services/mcp/src/generated/workflows/api.ts b/services/mcp/src/generated/workflows/api.tsindex a3e00b45722f..29781f888be7 100644--- a/services/mcp/src/generated/workflows/api.ts+++ b/services/mcp/src/generated/workflows/api.ts@@ -34,6 +34,7 @@ export const HogFlowsListQueryParams = () => zod.object({id: zod.string().optional(),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.'),+ optimization_enabled: zod.boolean().optional().describe('Only workflows someone turned suggestions on for.'),origin_product: zod.enum(['broadcasts', 'loops']).optional()diff --git a/services/mcp/src/tools/generated/workflows.ts b/services/mcp/src/tools/generated/workflows.tsindex 39c01ab3dfa1..b250985c0124 100644--- a/services/mcp/src/tools/generated/workflows.ts+++ b/services/mcp/src/tools/generated/workflows.ts@@ -243,6 +243,7 @@ const workflowsList = (): ToolBase<id: params.id,limit: params.limit,offset: params.offset,+ optimization_enabled: params.optimization_enabled,origin_product: params.origin_product,search: params.search,status: params.status,diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-config-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-config-create.jsonindex 7a231a7f3538..2a9a7a535471 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-config-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-config-create.json@@ -178,11 +178,11 @@"type": "array"},"write_scopes": {- "description": "Extra write access granted to this one scout, as scope strings. The grantable set is `alert:write`, `annotation:write`, `dashboard:write`, `insight:write`, `llm_skill:write`, `replay_scanner:write`, `warehouse_table:write`, `warehouse_view:write`. Empty (the default) means the scout reads the project and writes only what every scout may write: notebooks, its findings, and its own memory. Each scope is project-wide and object-level, so a scout holding `dashboard:write` can update or delete any dashboard in the project, not only ones it made. Grant only what this scout maintains. Only the person the scout's runs act as (whoever authored it) or a project admin can set it, and a scoped API key must itself carry each scope it grants. A dry run (`emit=false`) never holds the grant. Applies from the scout's next run.",+ "description": "Extra write access granted to this one scout, as scope strings. The grantable set is `alert:write`, `annotation:write`, `dashboard:write`, `hog_flow_proposal:write`, `insight:write`, `llm_skill:write`, `replay_scanner:write`, `warehouse_table:write`, `warehouse_view:write`. Empty (the default) means the scout reads the project and writes only what every scout may write: notebooks, its findings, and its own memory. Each scope is project-wide and object-level, so a scout holding `dashboard:write` can update or delete any dashboard in the project, not only ones it made. Grant only what this scout maintains. Only the person the scout's runs act as (whoever authored it) or a project admin can set it, and a scoped API key must itself carry each scope it grants. A dry run (`emit=false`) never holds the grant. Applies from the scout's next run.","items": {"type": "string"},- "maxItems": 8,+ "maxItems": 9,"type": "array"}},diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-config-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-config-update.jsonindex 062749823898..b49d0018f5a6 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-config-update.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-config-update.json@@ -175,11 +175,11 @@"type": "array"},"write_scopes": {- "description": "Extra write access granted to this one scout, as scope strings. The grantable set is `alert:write`, `annotation:write`, `dashboard:write`, `insight:write`, `llm_skill:write`, `replay_scanner:write`, `warehouse_table:write`, `warehouse_view:write`. Empty (the default) means the scout reads the project and writes only what every scout may write: notebooks, its findings, and its own memory. Each scope is project-wide and object-level, so a scout holding `dashboard:write` can update or delete any dashboard in the project, not only ones it made. Grant only what this scout maintains. Only the person the scout's runs act as (whoever authored it) or a project admin can set it, and a scoped API key must itself carry each scope it grants. A dry run (`emit=false`) never holds the grant. Applies from the scout's next run.",+ "description": "Extra write access granted to this one scout, as scope strings. The grantable set is `alert:write`, `annotation:write`, `dashboard:write`, `hog_flow_proposal:write`, `insight:write`, `llm_skill:write`, `replay_scanner:write`, `warehouse_table:write`, `warehouse_view:write`. Empty (the default) means the scout reads the project and writes only what every scout may write: notebooks, its findings, and its own memory. Each scope is project-wide and object-level, so a scout holding `dashboard:write` can update or delete any dashboard in the project, not only ones it made. Grant only what this scout maintains. Only the person the scout's runs act as (whoever authored it) or a project admin can set it, and a scoped API key must itself carry each scope it grants. A dry run (`emit=false`) never holds the grant. Applies from the scout's next run.","items": {"type": "string"},- "maxItems": 8,+ "maxItems": 9,"type": "array"}},diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-create.jsonindex 34222566bbff..a41edee409e4 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-create.json@@ -175,11 +175,11 @@"type": "array"},"write_scopes": {- "description": "Extra write access granted to this one scout, as scope strings. The grantable set is `alert:write`, `annotation:write`, `dashboard:write`, `insight:write`, `llm_skill:write`, `replay_scanner:write`, `warehouse_table:write`, `warehouse_view:write`. Empty (the default) means the scout reads the project and writes only what every scout may write: notebooks, its findings, and its own memory. Each scope is project-wide and object-level, so a scout holding `dashboard:write` can update or delete any dashboard in the project, not only ones it made. Grant only what this scout maintains. Only the person the scout's runs act as (whoever authored it) or a project admin can set it, and a scoped API key must itself carry each scope it grants. A dry run (`emit=false`) never holds the grant. Applies from the scout's next run.",+ "description": "Extra write access granted to this one scout, as scope strings. The grantable set is `alert:write`, `annotation:write`, `dashboard:write`, `hog_flow_proposal:write`, `insight:write`, `llm_skill:write`, `replay_scanner:write`, `warehouse_table:write`, `warehouse_view:write`. Empty (the default) means the scout reads the project and writes only what every scout may write: notebooks, its findings, and its own memory. Each scope is project-wide and object-level, so a scout holding `dashboard:write` can update or delete any dashboard in the project, not only ones it made. Grant only what this scout maintains. Only the person the scout's runs act as (whoever authored it) or a project admin can set it, and a scoped API key must itself carry each scope it grants. A dry run (`emit=false`) never holds the grant. Applies from the scout's next run.","items": {"type": "string"},- "maxItems": 8,+ "maxItems": 9,"type": "array"}},diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-config-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-config-create.jsonindex 7a231a7f3538..2a9a7a535471 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-config-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-config-create.json@@ -178,11 +178,11 @@"type": "array"},"write_scopes": {- "description": "Extra write access granted to this one scout, as scope strings. The grantable set is `alert:write`, `annotation:write`, `dashboard:write`, `insight:write`, `llm_skill:write`, `replay_scanner:write`, `warehouse_table:write`, `warehouse_view:write`. Empty (the default) means the scout reads the project and writes only what every scout may write: notebooks, its findings, and its own memory. Each scope is project-wide and object-level, so a scout holding `dashboard:write` can update or delete any dashboard in the project, not only ones it made. Grant only what this scout maintains. Only the person the scout's runs act as (whoever authored it) or a project admin can set it, and a scoped API key must itself carry each scope it grants. A dry run (`emit=false`) never holds the grant. Applies from the scout's next run.",+ "description": "Extra write access granted to this one scout, as scope strings. The grantable set is `alert:write`, `annotation:write`, `dashboard:write`, `hog_flow_proposal:write`, `insight:write`, `llm_skill:write`, `replay_scanner:write`, `warehouse_table:write`, `warehouse_view:write`. Empty (the default) means the scout reads the project and writes only what every scout may write: notebooks, its findings, and its own memory. Each scope is project-wide and object-level, so a scout holding `dashboard:write` can update or delete any dashboard in the project, not only ones it made. Grant only what this scout maintains. Only the person the scout's runs act as (whoever authored it) or a project admin can set it, and a scoped API key must itself carry each scope it grants. A dry run (`emit=false`) never holds the grant. Applies from the scout's next run.","items": {"type": "string"},- "maxItems": 8,+ "maxItems": 9,"type": "array"}},diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-config-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-config-update.jsonindex 062749823898..b49d0018f5a6 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-config-update.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-config-update.json@@ -175,11 +175,11 @@"type": "array"},"write_scopes": {- "description": "Extra write access granted to this one scout, as scope strings. The grantable set is `alert:write`, `annotation:write`, `dashboard:write`, `insight:write`, `llm_skill:write`, `replay_scanner:write`, `warehouse_table:write`, `warehouse_view:write`. Empty (the default) means the scout reads the project and writes only what every scout may write: notebooks, its findings, and its own memory. Each scope is project-wide and object-level, so a scout holding `dashboard:write` can update or delete any dashboard in the project, not only ones it made. Grant only what this scout maintains. Only the person the scout's runs act as (whoever authored it) or a project admin can set it, and a scoped API key must itself carry each scope it grants. A dry run (`emit=false`) never holds the grant. Applies from the scout's next run.",+ "description": "Extra write access granted to this one scout, as scope strings. The grantable set is `alert:write`, `annotation:write`, `dashboard:write`, `hog_flow_proposal:write`, `insight:write`, `llm_skill:write`, `replay_scanner:write`, `warehouse_table:write`, `warehouse_view:write`. Empty (the default) means the scout reads the project and writes only what every scout may write: notebooks, its findings, and its own memory. Each scope is project-wide and object-level, so a scout holding `dashboard:write` can update or delete any dashboard in the project, not only ones it made. Grant only what this scout maintains. Only the person the scout's runs act as (whoever authored it) or a project admin can set it, and a scoped API key must itself carry each scope it grants. A dry run (`emit=false`) never holds the grant. Applies from the scout's next run.","items": {"type": "string"},- "maxItems": 8,+ "maxItems": 9,"type": "array"}},diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-scouts-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-scouts-create.jsonindex 1687e98c33c6..9bc3660a3c10 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-scouts-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-scouts-create.json@@ -174,11 +174,11 @@"type": "array"},"write_scopes": {- "description": "Extra write access granted to this one scout, as scope strings. The grantable set is `alert:write`, `annotation:write`, `dashboard:write`, `insight:write`, `llm_skill:write`, `replay_scanner:write`, `warehouse_table:write`, `warehouse_view:write`. Empty (the default) means the scout reads the project and writes only what every scout may write: notebooks, its findings, and its own memory. Each scope is project-wide and object-level, so a scout holding `dashboard:write` can update or delete any dashboard in the project, not only ones it made. Grant only what this scout maintains. Only the person the scout's runs act as (whoever authored it) or a project admin can set it, and a scoped API key must itself carry each scope it grants. A dry run (`emit=false`) never holds the grant. Applies from the scout's next run.",+ "description": "Extra write access granted to this one scout, as scope strings. The grantable set is `alert:write`, `annotation:write`, `dashboard:write`, `hog_flow_proposal:write`, `insight:write`, `llm_skill:write`, `replay_scanner:write`, `warehouse_table:write`, `warehouse_view:write`. Empty (the default) means the scout reads the project and writes only what every scout may write: notebooks, its findings, and its own memory. Each scope is project-wide and object-level, so a scout holding `dashboard:write` can update or delete any dashboard in the project, not only ones it made. Grant only what this scout maintains. Only the person the scout's runs act as (whoever authored it) or a project admin can set it, and a scoped API key must itself carry each scope it grants. A dry run (`emit=false`) never holds the grant. Applies from the scout's next run.","items": {"type": "string"},- "maxItems": 8,+ "maxItems": 9,"type": "array"}},diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-list.jsonindex 1e089f0ac4db..9ad63f6ffeed 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-list.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-list.json@@ -29,6 +29,10 @@"description": "The initial index from which to return the results.","type": "number"},+ "optimization_enabled": {+ "description": "Only workflows someone turned suggestions on for.",+ "type": "boolean"+ },"origin_product": {"description": "Filter to workflows owned by a product surface, e.g. `loops` for Desktop loops.","enum": ["broadcasts", "loops"],