: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
fix(tasks): let a goal-space setup run reach every tool it needs (#105809)
Peter Kirkhamdb58f2c56923
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex 04430616900c..cea532f47a73 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -9832,23 +9832,29 @@ def start_space_setup(raise contracts.SpaceSetupInProgressError("Space setup is already running. Open its task to see progress.")repository = request.repository or (channel.repositories[0] if channel.repositories else None)request = replace(request, repository=repository)- task = Task.create_and_run(- team=team,- title=space_setup_task_title(channel.name, request),- description=build_space_setup_prompt(- team_id=team.id, channel_id=str(channel.id), channel_name=channel.name, request=request- ),- origin_product=Task.OriginProduct.SPACE_SETUP,- user_id=user_id,- channel=channel,- create_pr=False,- posthog_mcp_scopes=[*contracts.SPACE_SETUP_SCOPES, CONTEXT_LAYER_INTERNAL_SCOPE],- runtime_adapter=SPACE_SETUP_RUNTIME_ADAPTER,- model=SPACE_SETUP_MODEL,- reasoning_effort=SPACE_SETUP_REASONING_EFFORT,- initial_permission_mode="auto",- client_provenance=client_provenance,- )+ try:+ task = Task.create_and_run(+ team=team,+ title=space_setup_task_title(channel.name, request),+ description=build_space_setup_prompt(+ team_id=team.id, channel_id=str(channel.id), channel_name=channel.name, request=request+ ),+ origin_product=Task.OriginProduct.SPACE_SETUP,+ user_id=user_id,+ channel=channel,+ repository=repository,+ create_pr=False,+ posthog_mcp_scopes=[*contracts.SPACE_SETUP_SCOPES, CONTEXT_LAYER_INTERNAL_SCOPE],+ runtime_adapter=SPACE_SETUP_RUNTIME_ADAPTER,+ model=SPACE_SETUP_MODEL,+ reasoning_effort=SPACE_SETUP_REASONING_EFFORT,+ initial_permission_mode="auto",+ client_provenance=client_provenance,+ )+ except ValueError as e:+ raise SpaceSetupUnavailableError(+ f"Goal setup could not start: {e}. Connect the GitHub integration that owns the repository, then retry setup."+ ) from eChannelContextGeneration.objects.update_or_create(channel_id=channel.id, defaults={"team_id": team.id, "task_id": task.id})diff --git a/products/tasks/backend/facade/contracts.py b/products/tasks/backend/facade/contracts.pyindex 24a7ca04398b..6d300e9456ca 100644--- a/products/tasks/backend/facade/contracts.py+++ b/products/tasks/backend/facade/contracts.py@@ -665,6 +665,10 @@ SPACE_SETUP_SCOPES = ("task:write","canvas:write","hog_flow:write",+ # workflows-schedule-create and workflows-test-run require these beside hog_flow:write.+ "person:read",+ "group:read",+ "integration:read","query:read","data_catalog:read","insight:read",diff --git a/products/tasks/backend/logic/services/test_space_setup.py b/products/tasks/backend/logic/services/test_space_setup.pyindex b952ea67d44c..314cf023d5b1 100644--- a/products/tasks/backend/logic/services/test_space_setup.py+++ b/products/tasks/backend/logic/services/test_space_setup.py@@ -1,12 +1,20 @@import reimport jsonfrom datetime import date+from pathlib import Pathfrom django.test import SimpleTestCasefrom parameterized import parameterized-from products.tasks.backend.facade.contracts import SpaceFeatureRequest, SpaceGoalRequest, SpaceSetupRequest+from posthog.temporal.oauth import CONTEXT_LAYER_INTERNAL_SCOPE, INTERNAL_SCOPES++from products.tasks.backend.facade.contracts import (+ SPACE_SETUP_SCOPES,+ SpaceFeatureRequest,+ SpaceGoalRequest,+ SpaceSetupRequest,+)from products.tasks.backend.logic.services.space_setup import (DEFAULT_AUTONOMY,GOAL_LOOP_BRIEFS,@@ -133,3 +141,34 @@ class TestChannelSetupWriteSerializer(SimpleTestCase):goal=SpaceGoalRequest(statement="Grow activation", target="20%", period="week", direction="at_least"),repository=None,)+++class TestSpaceSetupScopes(SimpleTestCase):+ def test_every_tool_the_setup_steps_name_is_callable_with_the_setup_scopes(self):+ definitions = json.loads(+ (Path(__file__).parents[5] / "services" / "mcp" / "schema" / "tool-definitions-all.json").read_text()+ )+ prompt = build_space_setup_prompt(+ team_id=1,+ channel_id=CHANNEL_ID,+ channel_name="scopes",+ request=SpaceSetupRequest(+ kind="goal", goal=SpaceGoalRequest(statement="Move one metric"), repository="posthog/posthog"+ ),+ )+ setup_steps = prompt.split("## Loop graph", 1)[0]+ named_tools = {name for name in re.findall(r"`([a-z]+(?:-[a-z]+)+)`", setup_steps) if name in definitions}+ assert {"canvas-create", "workflows-schedule-create", "workflows-test-run", "metric-list"} <= named_tools++ granted = {*SPACE_SETUP_SCOPES, *INTERNAL_SCOPES, CONTEXT_LAYER_INTERNAL_SCOPE}+ missing = {+ name: sorted(+ scope for scope in definitions[name].get("required_scopes", []) if not _granted(granted, scope)+ )+ for name in sorted(named_tools)+ }+ assert {name: scopes for name, scopes in missing.items() if scopes} == {}+++def _granted(granted: set[str], required: str) -> bool:+ return required in granted or (required.endswith(":read") and required.replace(":read", ":write") in granted)diff --git a/products/tasks/backend/temporal/client.py b/products/tasks/backend/temporal/client.pyindex 46bbcf9d65ba..85b8b1acb17a 100644--- a/products/tasks/backend/temporal/client.py+++ b/products/tasks/backend/temporal/client.py@@ -39,6 +39,7 @@ from products.tasks.backend.temporal.constants import (STEERING_PROTOCOL_QUERY_TIMEOUT,STEERING_PROTOCOL_VERSION,)+from products.tasks.backend.temporal.oauth import dispatched_run_scopesfrom products.tasks.backend.temporal.process_task.workflow import PendingFollowup, ProcessTaskInputfrom products.tasks.backend.temporal.slack_relay.activities import RelaySlackMessageInput@@ -457,41 +458,6 @@ def execute_task_processing_workflow()-def _resolve_mcp_scopes(task_run: TaskRun) -> PosthogMcpScopes:- """Best-effort scope posture for the reconciler when ``pending_dispatch`` didn't carry- ``posthog_mcp_scopes`` (pre-reconciler rows, or the bootstrap/start path). Mirrors- ``_trigger_task_processing_workflow``: full scopes unless the run_source is scoped down.-- Signals scout runs are the exception. Their posture (``signal_scout_internal:*`` +- ``signal_scout_report:write``) is carried by neither ``"full"`` nor ``"read_only"``, so a scout- re-dispatched on this fallback with a generic posture loses every ``signals-scout-*`` tool — they- drop out of the MCP catalog and surface to the agent as "Unknown tool", burning the whole run- (it investigates, then can't emit a report, write scratchpad, or build its profile). Pin- scout-origin runs to the most-capable scout posture so a reconciled scout stays fully functional.- Over-granting the report scope to a non-report scout is harmless: the report endpoints- independently gate on the skill's ``allowed_tools`` opt-in.- """- from products.tasks.backend.temporal.process_task.utils import ( # noqa: PLC0415 — avoid an import cycle- mcp_scopes_for_run_source,- parse_run_state,- )-- if task_run.task.origin_product == Task.OriginProduct.SIGNALS_SCOUT:- return "signals_scout_reports"- # The suggestion scan only reads; a reconciled run must not inherit the generic full posture.- if task_run.task.origin_product == Task.OriginProduct.SIGNALS_SCOUT_SUGGESTIONS:- return "read_only"-- # Loop-fired runs persist their real scopes in pending_dispatch; a row missing it must- # degrade to read_only, never escalate to the full write surface the generic fallback- # below grants (loop runs carry no run_source).- if task_run.task.origin_product == Task.OriginProduct.LOOP:- return "read_only"-- run_source = parse_run_state(task_run.state).run_source- return mcp_scopes_for_run_source(run_source)--def redispatch_orphaned_task_run(run_id: str) -> str:"""Re-dispatch a run stuck in QUEUED whose create-time on_commit dispatch never fired.@@ -545,7 +511,7 @@ def redispatch_orphaned_task_run(run_id: str) -> str:run_id=run_id,create_pr=dispatch_params.get("create_pr", default_create_pr),slack_thread_context=dispatch_params.get("slack_thread_context"),- posthog_mcp_scopes=dispatch_params.get("posthog_mcp_scopes") or _resolve_mcp_scopes(task_run),+ posthog_mcp_scopes=dispatched_run_scopes(task, task_run.state),)# A loop run's skill bundles are seeded by the same on_commit callback whose lossdiff --git a/products/tasks/backend/temporal/oauth.py b/products/tasks/backend/temporal/oauth.pyindex 337b882ad1fd..daf31cbc415d 100644--- a/products/tasks/backend/temporal/oauth.py+++ b/products/tasks/backend/temporal/oauth.py@@ -40,6 +40,7 @@ __all__ = ["create_oauth_access_token_for_run","create_oauth_access_token_for_user","create_wizard_oauth_access_token",+ "dispatched_run_scopes",]# Loop CRUD MCP tools must never be reachable from inside a loop-fired run, regardless of the@@ -112,27 +113,71 @@ def _scopes_for_loop_fired_run(scopes: PosthogMcpScopes) -> list[str]:return [scope for scope in resolved if scope not in LOOP_FIRED_RUN_EXCLUDED_SCOPES]+def _scopes_from_state_value(raw: object) -> PosthogMcpScopes | None:+ """A scope posture as run state holds it after a JSON round trip, or None when it is not one."""+ if isinstance(raw, list) and all(isinstance(scope, str) for scope in raw):+ return cast(list[str], list(raw))+ if isinstance(raw, str) and raw in get_args(McpScopePreset):+ return cast(McpScopePreset, raw)+ if isinstance(raw, dict):+ # `resolve_scopes` reads a posture defensively, so an unknown preset or an extra scope+ # outside the grantable allowlist cannot widen it.+ return cast(ScoutScopePosture, raw)+ return None+++def default_run_scopes(origin_product: str, state: dict[str, Any] | None) -> PosthogMcpScopes:+ """The scopes dispatch grants a run whose state records none: full unless the run source+ is scoped down, mirroring ``_trigger_task_processing_workflow``.++ Signals scout runs are the exception. Their posture (``signal_scout_internal:*`` ++ ``signal_scout_report:write``) is carried by neither ``"full"`` nor ``"read_only"``, so a scout+ on a generic posture loses every ``signals-scout-*`` tool and burns the whole run. Pin+ scout-origin runs to the most-capable scout posture; over-granting the report scope to a+ non-report scout is harmless because the report endpoints gate on the skill's opt-in. The+ suggestion scan only reads. Loop runs persist their real scopes in ``pending_dispatch`` and+ carry no run source, so a loop row without them degrades to ``read_only``.+ """+ from products.tasks.backend.temporal.process_task.utils import ( # noqa: PLC0415 — keeps temporalio off the import path+ mcp_scopes_for_run_source,+ parse_run_state,+ )++ if origin_product == Task.OriginProduct.SIGNALS_SCOUT:+ return "signals_scout_reports"+ if origin_product in (Task.OriginProduct.SIGNALS_SCOUT_SUGGESTIONS, Task.OriginProduct.LOOP):+ return "read_only"+ return mcp_scopes_for_run_source(parse_run_state(state).run_source)+++def dispatched_run_scopes(task: Task, state: dict[str, Any] | None) -> PosthogMcpScopes:+ """The scopes the run was dispatched with: what ``pending_dispatch`` recorded at creation,+ else what dispatch grants a run that recorded none (``default_run_scopes``).++ The launch activities receive this value on their input; the provisioning activities do+ not, and the token they place in the sandbox environment must carry the same grant as the+ MCP session, or a shell fallback runs with less than the run was given. A recorded value+ that does not parse fails closed to ``read_only``.+ """+ pending = (state or {}).get("pending_dispatch")+ raw = pending.get("posthog_mcp_scopes") if isinstance(pending, dict) else None+ if raw is None:+ return default_run_scopes(task.origin_product, state)+ scopes = _scopes_from_state_value(raw)+ return scopes if scopes is not None else "read_only"++def _workflow_run_scopes(requested: PosthogMcpScopes, state: dict[str, Any] | None) -> list[str]:"""Scopes for a workflow-fired run: the request intersected with the run's snapshottedchoice (neither side can widen the other), minus the automation-editing scopes loop- runs also strip."""+ runs also strip. A snapshot that does not parse narrows to ``read_only`` rather than+ dropping the leg that stops a widened request."""resolved = set(resolve_scopes(requested, include_internal_scopes=True))connectors = ((state or {}).get("config_snapshot") or {}).get("connectors")raw = connectors.get("posthog_mcp_scopes") if isinstance(connectors, dict) else None- snapshot: PosthogMcpScopes | None = None- if isinstance(raw, list):- snapshot = [str(scope) for scope in raw]- elif isinstance(raw, str) and raw in get_args(McpScopePreset):- snapshot = cast(McpScopePreset, raw)- elif isinstance(raw, dict):- # A snapshotted scout posture. Passed through unchecked because `resolve_scopes` reads- # it defensively: an unrecognized preset resolves to `read_only`, and the extra write- # scopes are intersected with the grantable allowlist there. Skipping the dict instead- # would drop the snapshot leg of the intersection, which is the half that stops a- # widened request from taking effect.- snapshot = cast(ScoutScopePosture, raw)- if snapshot is not None:- resolved &= set(resolve_scopes(snapshot, include_internal_scopes=True))+ if raw is not None:+ snapshot = _scopes_from_state_value(raw)+ resolved &= set(resolve_scopes("read_only" if snapshot is None else snapshot, include_internal_scopes=True))return sorted(scope for scope in resolved if scope not in LOOP_FIRED_RUN_EXCLUDED_SCOPES)@@ -198,7 +243,7 @@ def create_oauth_access_token_for_run(task: Task,state: dict[str, Any] | None,*,- scopes: PosthogMcpScopes = "read_only",+ scopes: PosthogMcpScopes | None = None,) -> str:"""Mint the sandbox OAuth token for a run, resolving the acting user from run state.@@ -208,7 +253,11 @@ def create_oauth_access_token_for_run(hand — passing ``user``/``allow_task_creator_fallback`` separately makes it possibleto mint creator credentials for a Slack run by omitting one kwarg. Loop-fired runs(``loop_id`` in run state) get ``loop:write`` stripped from the granted scopes here.+ ``scopes`` defaults to what the run was dispatched with (``dispatched_run_scopes``), so+ a caller without the value on its activity input still mints the run's own grant."""+ if scopes is None:+ scopes = dispatched_run_scopes(task, state)with transaction.atomic():locked_task = (Task.objects.select_for_update(of=("self",))diff --git a/products/tasks/backend/temporal/tests/test_oauth.py b/products/tasks/backend/temporal/tests/test_oauth.pyindex b555da7e585f..54f9e31f67b1 100644--- a/products/tasks/backend/temporal/tests/test_oauth.py+++ b/products/tasks/backend/temporal/tests/test_oauth.py@@ -2,6 +2,7 @@ import pytestfrom unittest.mock import MagicMock, patchfrom posthog.models import Organization, Team+from posthog.models.organization import OrganizationMembershipfrom posthog.models.user import Userfrom posthog.temporal.oauth import PosthogMcpScopes@@ -521,6 +522,64 @@ def test_workflow_run_scopes_never_exceed_request_or_snapshot(assert granted <= set(resolve_scopes(snapshot, include_internal_scopes=True))+ ("origin_product", "state", "requested", "granted"),+ [+ (Task.OriginProduct.SPACE_SETUP, {"pending_dispatch": {"posthog_mcp_scopes": "full"}}, None, "full"),+ (+ Task.OriginProduct.SPACE_SETUP,+ {"pending_dispatch": {"posthog_mcp_scopes": ["canvas:write", "task:read"]}},+ None,+ ["canvas:write", "task:read"],+ ),+ (+ Task.OriginProduct.SPACE_SETUP,+ {"pending_dispatch": {"posthog_mcp_scopes": "not-a-preset"}},+ None,+ "read_only",+ ),+ (+ Task.OriginProduct.SPACE_SETUP,+ {"pending_dispatch": {"posthog_mcp_scopes": ["canvas:write", None]}},+ None,+ "read_only",+ ),+ (+ Task.OriginProduct.SPACE_SETUP,+ {"pending_dispatch": {"posthog_mcp_scopes": "full"}},+ "read_only",+ "read_only",+ ),+ # No recorded dispatch: the run-source policy dispatch itself applies.+ (Task.OriginProduct.USER_CREATED, {}, None, "full"),+ (Task.OriginProduct.USER_CREATED, {"run_source": "agent"}, None, "read_only"),+ (Task.OriginProduct.LOOP, {}, None, "read_only"),+ (Task.OriginProduct.SIGNALS_SCOUT, {}, None, "signals_scout_reports"),+ ],+)+@patch("products.tasks.backend.temporal.oauth._create_oauth_access_token_for_user", return_value="token")+def test_run_token_defaults_to_the_dispatched_scopes(+ mock_create: MagicMock,+ origin_product: str,+ state: dict,+ requested: PosthogMcpScopes | None,+ granted: PosthogMcpScopes,+) -> None:+ organization = Organization.objects.create(name="dispatch-scope-org")+ team = Team.objects.create(organization=organization, name="dispatch-scope-team")+ owner = User.objects.create(email="[email protected]")+ OrganizationMembership.objects.create(organization=organization, user=owner)+ task = Task.objects.create(team=team, title="Run", created_by=owner, origin_product=origin_product)++ if requested is None:+ create_oauth_access_token_for_run(task, state)+ else:+ create_oauth_access_token_for_run(task, state, scopes=requested)++ assert mock_create.call_args.kwargs["scopes"] == granted++@pytest.mark.django_db@patch("products.tasks.backend.temporal.oauth._create_oauth_access_token_for_user", return_value="token")def test_workflow_fired_run_excludes_loop_write_scope(mock_create: MagicMock) -> None:diff --git a/products/tasks/backend/tests/test_channel_extras.py b/products/tasks/backend/tests/test_channel_extras.pyindex 3f62e0e21ad3..6a74a7c8bd0b 100644--- a/products/tasks/backend/tests/test_channel_extras.py+++ b/products/tasks/backend/tests/test_channel_extras.py@@ -10,7 +10,7 @@ from parameterized import parameterizedfrom rest_framework import statusfrom rest_framework.test import APIClient-from posthog.models import PersonalAPIKey+from posthog.models import Integration, PersonalAPIKeyfrom posthog.models.oauth import OAuthAccessToken, OAuthApplicationfrom posthog.models.personal_api_key import hash_key_valuefrom posthog.models.scoping import team_scope@@ -175,6 +175,7 @@ class TestChannelSetup(ChannelExtrasBaseTest):with team_scope(self.team.id):self.channel.repositories = ["posthog/posthog"]self.channel.save(update_fields=["repositories"])+ Integration.objects.create(team=self.team, kind="github", integration_id="12345", config={})response = self.client.post(f"{self.base}/setup/", self.GOAL_BODY, format="json")@@ -185,6 +186,7 @@ class TestChannelSetup(ChannelExtrasBaseTest):assert task.created_by_id == self.user.idassert "Increase the weekly activation rate" in task.descriptionassert "posthog/posthog" in task.description+ assert task.repository == "posthog/posthog"assert f"team_id: {self.team.id}" in task.descriptionrun = TaskRun.objects.get(task=task)assert run.state["model"] == "gpt-5.6-sol"@@ -200,6 +202,18 @@ class TestChannelSetup(ChannelExtrasBaseTest):assert feed.payload["kind"] == "goal"assert feed.payload["task_id"] == str(task.id)+ @patch("products.cdp.backend.facade.api.is_hog_function_template_available", return_value=True)+ def test_goal_setup_without_a_github_integration_is_refused_not_a_server_error(self, _template):+ with team_scope(self.team.id):+ self.channel.repositories = ["posthog/posthog"]+ self.channel.save(update_fields=["repositories"])++ response = self.client.post(f"{self.base}/setup/", self.GOAL_BODY, format="json")++ assert response.status_code == status.HTTP_503_SERVICE_UNAVAILABLE, response.json()+ assert "GitHub integration" in response.json()["detail"]+ assert not Task.objects.filter(channel=self.channel).exists()+@parameterized.expand([("not_started",), ("queued",), ("in_progress",)])@patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")def test_active_setup_is_not_duplicated_after_context_publication(self, run_status, _workflow):