Skip to content

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

fix(signals): give entitled ask ai runs a repo and github credentials (#95498)

posthog[bot]7def8a678824
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.py
index cebde22a3edc..77f96c76b8ea 100644
--- a/products/tasks/backend/facade/api.py
+++ b/products/tasks/backend/facade/api.py
@@ -862,10 +862,13 @@ def task_exempt_from_code_access(task_id: str | UUID, team_id: int) -> bool:
also serve the generally-available Inbox, whose tasks must run without the waitlist. Only
server-verifiable Inbox shapes qualify:
- - ``SIGNAL_REPORT`` linked to a report in this team and repo-less (Inbox "Discuss").
- Reports are minted by scouts and the link is team-scoped by the write serializer, so a
- caller can't forge one. Acting on a report is entitled through self-driving
- (`product-autonomy`). Repository-backed report tasks require Desktop access.
+ - ``SIGNAL_REPORT`` linked to a report in this team, repo-less, and carrying no GitHub
+ integration (the Inbox "Discuss" fallback). Reports are minted by scouts and the link is
+ team-scoped by the write serializer, so a caller can't forge one. Acting on a report is
+ entitled through self-driving (`product-autonomy`). A report task that resolved a
+ repository, or that carries the team integration for a repo-less discussion, is not
+ exempt, because `create_task` only gives it either after the gate passed. Re-checking
+ here costs the caller nothing.
- ``SIGNALS_CHAT`` (Inbox scout chat), reserved for server-side creation by the signals
scout-chat endpoint; the write serializer rejects it from API callers. Only while
repo-less: chat tasks are minted without repositories, and attaching one via update
@@ -5672,13 +5675,16 @@ def compute_repository_readiness(team_id: int, *, repository: str, window_days:
return _compute(team=team, repository=repository, window_days=window_days, refresh=refresh)
-def _capture_no_repo_selection_override(*, team: Team, report_id: str, resolved_repository: str | None) -> None:
+def _capture_no_repo_selection_override(
+ *, team: Team, report_id: str, resolved_repository: str | None, relationship: str | None
+) -> None:
"""Record a person starting work on a report whose scout chose no repository.
The count tells the signals team how often the scouts' `NO_REPO` default disagrees with what a
person wanted, and `resolved_repository` separates a recovery from a cascade that also found
- nothing. Keyed on the team, like the other scout events. Best-effort: a capture failure must
- never fail the task creation."""
+ nothing. `relationship` separates a "Create PR" override from an Ask AI one, which start from
+ different intents. Keyed on the team, like the other scout events. Best-effort: a capture
+ failure must never fail the task creation."""
try:
posthoganalytics.capture(
distinct_id=str(team.uuid),
@@ -5687,6 +5693,7 @@ def _capture_no_repo_selection_override(*, team: Team, report_id: str, resolved_
"report_id": report_id,
"team_id": team.id,
"resolved_repository": resolved_repository,
+ "relationship": relationship,
},
groups=groups(team=team),
)
@@ -5700,6 +5707,7 @@ def create_task(
*,
validated_data: dict,
client_provenance: TaskClientProvenance | None = None,
+ code_access_allowed: bool = False,
) -> contracts.TaskDetailDTO:
"""Create a task, mirroring ``TaskSerializer.create`` byte-for-byte.
@@ -5707,6 +5715,11 @@ def create_task(
``resolve_user_github_integration_for_task`` so no internal/other-product import leaks into
presentation. ``validated_data`` carries the validated write fields (integrations already
resolved to instances by the write serializer's PK fields).
+
+ ``code_access_allowed`` is the caller's Desktop-access outcome, which only the request layer can
+ evaluate. It upgrades a report discussion from the repo-less exempt shape to a full cloud task:
+ a resolved repository and the team's GitHub credential. Defaults to ``False`` so a caller that
+ never ran the gate creates the exempt shape.
"""
from posthog.models import Team # noqa: PLC0415
@@ -5873,17 +5886,17 @@ def create_task(
signal_report_task_relationship = validated_data.pop("signal_report_task_relationship", None)
# Inbox "Create PR" doesn't pre-select a repo, so resolve one here rather than creating a
- # report-linked task that can never open a PR. Only "implementation" (Create PR) and legacy
- # clients (no relationship) resolve one: "Discuss" (and any other non-implementation label)
- # must stay repo-less to keep the code-access exemption (`task_exempt_from_code_access`).
- # Giving a discussion a repository would 403 a caller without Desktop access on the very click
- # this path exists to unblock.
+ # report-linked task that can never open a PR. "Implementation" (Create PR) and legacy clients
+ # (no relationship) always resolve one. "Discuss" (and any other non-implementation label)
+ # resolves one only for a caller the Desktop gate passed: the run endpoint gates a
+ # repository-backed report task, so resolving for anyone else would 403 the very click this
+ # path exists to unblock (see `task_exempt_from_code_access`).
signal_report = validated_data.get("signal_report")
if (
signal_report is not None
and not validated_data.get("repository")
and validated_data.get("origin_product") == Task.OriginProduct.SIGNAL_REPORT
- and signal_report_task_relationship in (None, "implementation")
+ and (signal_report_task_relationship in (None, "implementation") or code_access_allowed)
):
from products.signals.backend.facade.api import ( # noqa: PLC0415 — cross-product read kept off the api import path
persisted_repo_selection,
@@ -5909,12 +5922,25 @@ def create_task(
)
if selection is not None:
_capture_no_repo_selection_override(
- team=team, report_id=str(signal_report.id), resolved_repository=resolved_repository
+ team=team,
+ report_id=str(signal_report.id),
+ resolved_repository=resolved_repository,
+ relationship=signal_report_task_relationship,
)
if resolved_repository:
validated_data["repository"] = resolved_repository
- if validated_data.get("repository") and not validated_data.get("github_integration"):
+ # The credential follows the entitlement, not the repository: an entitled report task carries
+ # the team's GitHub integration even when nothing resolved, so the agent can still clone what
+ # the conversation turns out to need. That is the shape a repo-less user-created task already
+ # has, and provisioning keys the token off the attached integration, so a task created without
+ # the gate stays credential-less.
+ entitled_report_task = (
+ code_access_allowed
+ and signal_report is not None
+ and validated_data.get("origin_product") == Task.OriginProduct.SIGNAL_REPORT
+ )
+ if (validated_data.get("repository") or entitled_report_task) and not validated_data.get("github_integration"):
default_integration = Integration.objects.filter(team=team, kind="github").first()
if default_integration:
validated_data["github_integration"] = default_integration
@@ -6010,7 +6036,9 @@ def update_task(
if task is None or not Task.objects.filter(id=task.id).filter(task_control_q(user_id)).exists():
return None
- # Repo is immutable for code-access-exempt tasks; a mutable repo reopens the gate (see task_exempt_from_code_access).
+ # Repo and credential are immutable for code-access-exempt tasks: a mutable repo reopens the
+ # gate (see task_exempt_from_code_access), and provisioning injects whatever integration is
+ # attached, so an attachable one would credential a run the create path left credential-less.
if task.origin_product in (Task.OriginProduct.SIGNALS_CHAT, Task.OriginProduct.SIGNAL_REPORT):
validated_data.pop("repository", None)
validated_data.pop("repositories", None)
diff --git a/products/tasks/backend/presentation/views/api.py b/products/tasks/backend/presentation/views/api.py
index febe2e080f4b..695208cc17e7 100644
--- a/products/tasks/backend/presentation/views/api.py
+++ b/products/tasks/backend/presentation/views/api.py
@@ -655,6 +655,21 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
validated_data = dict(serializer.validated_data)
relationship = validated_data.get("signal_report_task_relationship")
discussion_question = validated_data.pop("signal_report_discussion_question", None)
+
+ # Inbox "Discuss" runs repo-less so the generally-available Inbox never 403s a caller the
+ # Desktop gate refuses. An entitled caller gets the shape a normal cloud task has instead: a
+ # resolved repository and the team's GitHub credential, so the sandbox can clone a private
+ # repository and update the report's PR. Only the request layer can evaluate the gate, so it
+ # runs here and the outcome travels into the facade. A resolution error (503) counts as
+ # refused, which keeps the discussion starting repo-less.
+ code_access_allowed = False
+ if (
+ relationship not in (None, "implementation")
+ and validated_data.get("signal_report") is not None
+ and validated_data.get("origin_product") == tasks_facade.TaskOriginProduct.SIGNAL_REPORT
+ ):
+ code_access_allowed = code_access_required_response(request, self.organization) is None
+
from products.signals.backend.facade.api import ( # noqa: PLC0415 — keeps the signals stack off this module's import path
ReportTaskCapExceeded,
)
@@ -665,6 +680,7 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
self._user_id(),
validated_data=validated_data,
client_provenance=get_task_client_provenance(request),
+ code_access_allowed=code_access_allowed,
)
except ComputeBillingLimitExceeded as error:
return compute_quota_limit_response(error.reason)
diff --git a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py
index 84acd48b8885..bd06c1ddea17 100644
--- a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py
+++ b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py
@@ -347,12 +347,18 @@ def _resolve_sandbox_github_token(
) -> str:
"""Decide which GitHub credential (if any) a fresh sandbox gets.
- A repo-less run that requested read-only access is resolved FIRST: _build_task attaches the
- team's GitHub integration to every task, so has_github_credentials is true whenever the team
- has GitHub connected at all — resolved the other way around, the write-capable installation
- token would reach a run that asked for read-only. The read-only mint is best-effort (empty
- string on failure, never the full token); the full credential path keeps its raise-on-failure
- contract for repo-backed runs that can't work without credentials.
+ A repo-less run that requested read-only access is resolved FIRST: a task whose team has GitHub
+ connected can carry the team integration, so has_github_credentials is true for it. Resolved the
+ other way around, the write-capable installation token would reach a run that asked for
+ read-only. The read-only mint is best-effort (empty string on failure, never the full token);
+ the full credential path keeps its raise-on-failure contract for repo-backed runs that can't
+ work without credentials.
+
+ Everything else follows the attached integration, including a repo-less signals run: a scout or
+ scout-chat task never gets one (`github_resolution_allowed` in `Task._build_task` refuses to
+ resolve one, and `update_task` keeps it unattachable afterwards), while a report discussion gets
+ one only after the create-time Desktop gate passed. So a repo-less run with no integration
+ stays credential-less, and an entitled discussion can clone a private repository and push.
"""
if ctx.github_read_access and not has_repo:
github_token = get_readonly_github_token(ctx.team_id) or ""
@@ -365,9 +371,6 @@ def _resolve_sandbox_github_token(
)
return github_token
- if not has_repo and task.origin_product in (Task.OriginProduct.SIGNALS_CHAT, Task.OriginProduct.SIGNAL_REPORT):
- return ""
-
should_inject_github_token = ctx.has_github_credentials and (
has_repo or ctx.github_user_integration_id is not None or ctx.github_integration_id is not None
)
diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.py
index f54530df324b..202e0937628a 100644
--- a/products/tasks/backend/tests/test_api.py
+++ b/products/tasks/backend/tests/test_api.py
@@ -1874,10 +1874,19 @@ class TestTaskAPI(BaseTaskAPITest):
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
self.assertEqual(response.json()["repository"], expected_repository)
- def test_discussion_from_no_repo_report_stays_repo_less_and_exempt(self):
- # A "Discuss" kickoff must not resolve a repository, even on a one-repo team with a NO_REPO
- # selection artefact. A repository-backed report task loses the code-access exemption, so a
- # caller without Desktop access would 403 on the discussion — the dead-end this path removes.
+ @parameterized.expand(
+ [
+ ("allowed", tasks_access.DesktopAccessDecision.ALLOWED, "acme/web"),
+ ("refused", tasks_access.DesktopAccessDecision.STARTUP_PLAN, None),
+ ("unresolvable", DesktopAccessResolutionError("cannot verify"), None),
+ ]
+ )
+ def test_discussion_repository_and_credential_follow_the_desktop_gate(self, _name, decision, expected_repository):
+ # A "Discuss" kickoff is repo-less and credential-less for a caller the gate refuses, so the
+ # generally-available Inbox never 403s on the click this path exists to unblock. An
+ # unverifiable gate degrades to that same shape rather than failing the click. An entitled
+ # caller gets a repository and the team credential instead, which is what lets the sandbox
+ # clone a private repository and update the report's pull request.
from products.signals.backend.models import SignalReport, SignalReportArtefact
Integration.objects.create(
@@ -1897,6 +1906,48 @@ class TestTaskAPI(BaseTaskAPITest):
content=RepoSelectionResult(repository=None, reason="test").model_dump_json(),
)
+ gate = {"side_effect": decision} if isinstance(decision, Exception) else {"return_value": decision}
+ with patch("products.tasks.backend.logic.services.code_usage_gate.get_desktop_access_decision", **gate):
+ response = self.client.post(
+ "/api/projects/@current/tasks/",
+ {
+ "title": "Discuss report",
+ "description": "Let's discuss this report",
+ "origin_product": "signal_report",
+ "signal_report": str(report.id),
+ "signal_report_task_relationship": "discussion",
+ },
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)
+ data = response.json()
+ self.assertEqual(data["repository"], expected_repository)
+ entitled = expected_repository is not None
+ task = Task.objects.get(id=data["id"])
+ self.assertEqual(task.github_integration is not None, entitled)
+ self.assertEqual(tasks_facade.task_exempt_from_code_access(data["id"], self.team.id), not entitled)
+
+ def test_entitled_discussion_with_no_resolvable_repository_still_carries_the_credential(self):
+ # Ambiguous repositories resolve to nothing, and a discussion that stopped there used to
+ # start credential-less, so the agent could not clone the private repository it names mid
+ # conversation. The credential follows the entitlement, not the repository.
+ from products.signals.backend.models import SignalReport
+
+ Integration.objects.create(
+ team=self.team,
+ kind="github",
+ integration_id="gh-ambiguous",
+ config={"installation_id": "gh-ambiguous"},
+ sensitive_config={},
+ repository_cache=[
+ {"full_name": "acme/web", "name": "web", "id": 1},
+ {"full_name": "acme/api", "name": "api", "id": 2},
+ ],
+ repository_cache_updated_at=django_timezone.now(),
+ )
+ report = SignalReport.objects.create(team=self.team)
+
response = self.client.post(
"/api/projects/@current/tasks/",
{
@@ -1910,8 +1961,11 @@ class TestTaskAPI(BaseTaskAPITest):
)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
- self.assertIsNone(response.json()["repository"])
- self.assertTrue(tasks_facade.task_exempt_from_code_access(response.json()["id"], self.team.id))
+ data = response.json()
+ self.assertIsNone(data["repository"])
+ task = Task.objects.get(id=data["id"])
+ self.assertIsNotNone(task.github_integration)
+ self.assertFalse(tasks_facade.task_exempt_from_code_access(data["id"], self.team.id))
def test_create_task_with_signal_report_discussion_records_artefact_without_gate_row(self):
from products.signals.backend.models import SignalReport, SignalReportTask
diff --git a/products/tasks/backend/tests/test_sandbox_utils.py b/products/tasks/backend/tests/test_sandbox_utils.py
index 48934f0544f1..09c0b5497641 100644
--- a/products/tasks/backend/tests/test_sandbox_utils.py
+++ b/products/tasks/backend/tests/test_sandbox_utils.py
@@ -122,6 +122,44 @@ def test_readonly_request_takes_priority_over_full_credential_path(
mock_full.assert_not_called()
+ "github_integration_id, expected",
+ [(5, "FULL_TOKEN"), (None, "")],
+ ids=["entitled_discussion_gets_the_team_credential", "unentitled_discussion_stays_credential_less"],
+)
+@patch("products.tasks.backend.temporal.process_task.activities.provision_sandbox.emit_agent_log")
+@patch("products.tasks.backend.temporal.process_task.activities.provision_sandbox.get_sandbox_github_token")
+def test_repo_less_report_run_follows_the_integration_the_create_path_attached(
+ mock_full: MagicMock, _mock_log: MagicMock, github_integration_id: int | None, expected: str
+) -> None:
+ # Ask AI on a report runs repo-less, and it used to get no credential whatever it carried, so
+ # it could not clone a private repository or push. The attached integration is the signal now:
+ # the create path attaches one only after the Desktop gate passed, and a scout or scout-chat
+ # task never gets one at all.
+ from products.tasks.backend.models import Task # noqa: PLC0415 — model import kept off this module's import path
+ from products.tasks.backend.temporal.process_task.activities.provision_sandbox import ( # noqa: PLC0415 — activities import the workflow stack; keep it off this module's import path
+ _resolve_sandbox_github_token,
+ )
+
+ mock_full.return_value = "FULL_TOKEN"
+ task = Task(origin_product=Task.OriginProduct.SIGNAL_REPORT)
+ ctx = TaskProcessingContext(
+ task_id="t",
+ run_id="r",
+ team_id=1,
+ team_uuid="u",
+ organization_id="o",
+ github_integration_id=github_integration_id,
+ repository=None,
+ distinct_id="d",
+ state={},
+ )
+
+ token = _resolve_sandbox_github_token(ctx, task=task, actor_user=None, repository=None, has_repo=False)
+
+ assert token == expected
+
+
@patch("products.tasks.backend.temporal.process_task.activities.provision_sandbox.emit_agent_log")
@patch("products.tasks.backend.temporal.process_task.activities.provision_sandbox.get_sandbox_github_token")
def test_reauthorization_required_surfaces_as_credential_unavailable(