: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
refactor(tasks): use the integrations SDK (#124994)
Tom Owerse35bdfa0e7c8
diff --git a/posthog/hogql/database/schema/test/test_persons.py b/posthog/hogql/database/schema/test/test_persons.pyindex d4dc933d8400..e13c00c2828b 100644--- a/posthog/hogql/database/schema/test/test_persons.py+++ b/posthog/hogql/database/schema/test/test_persons.py@@ -2,6 +2,7 @@ from datetime import datetimefrom posthog.test.base import (APIBaseTest,+ ClickhouseDestroyTablesMixin,ClickhouseTestMixin,_create_event,_create_person,@@ -254,7 +255,8 @@ def _persons_semi_join(clickhouse: str) -> str:return sql[sql.rindex("FROM events", 0, end) : end]-class TestPersonIdPushdown(ClickhouseTestMixin, APIBaseTest):+class TestPersonIdPushdown(ClickhouseDestroyTablesMixin, ClickhouseTestMixin, APIBaseTest):+ # The no_where case reads every event of the team, so rows left by earlier tests break it.FIXTURE = [("in_window_paid", "paid_in_window", "paid", IN_WINDOW),("in_window_free", "free_in_window", "free", IN_WINDOW),diff --git a/posthog/integrations/model_access_baseline.txt b/posthog/integrations/model_access_baseline.txtindex 3f6019eb152d..add3f7a70e61 100644--- a/posthog/integrations/model_access_baseline.txt+++ b/posthog/integrations/model_access_baseline.txt@@ -64,35 +64,17 @@ products/slack_app/backend/temporal/activities/messaging.py 1products/slack_app/backend/temporal/activities/onboarding.py 2products/subscriptions/backend/models/subscription.py 1products/subscriptions/backend/temporal/activities.py 2-products/tasks/backend/facade/api.py 15-products/tasks/backend/github_repository_access.py 2-products/tasks/backend/logic/pull_request_titles.py 2-products/tasks/backend/logic/repo_selection/agent.py 3-products/tasks/backend/logic/services/comment_slack_dm.py 2-products/tasks/backend/logic/services/dev_sandbox_context.py 2+products/tasks/backend/facade/api.py 5products/tasks/backend/logic/services/pr_reconciliation.py 1-products/tasks/backend/logic/services/workflow_tasks.py 3-products/tasks/backend/logic/task_review.py 3-products/tasks/backend/max_tools.py 4-products/tasks/backend/models.py 5-products/tasks/backend/presentation/serializers.py 6-products/tasks/backend/repository_readiness.py 2-products/tasks/backend/repository_resolver.py 4-products/tasks/backend/temporal/build_image/activities.py 2-products/tasks/backend/temporal/create_snapshot/activities/create_sandbox.py 2-products/tasks/backend/temporal/create_snapshot/activities/get_snapshot_context.py 2-products/tasks/backend/temporal/create_snapshot/utils.py 2+products/tasks/backend/logic/task_review.py 1+products/tasks/backend/models.py 4products/tasks/backend/temporal/process_task/activities/create_sandbox_from_snapshot.py 1-products/tasks/backend/temporal/process_task/activities/feature_flags.py 2-products/tasks/backend/temporal/process_task/activities/get_pr_context.py 2products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py 1products/tasks/backend/temporal/process_task/activities/provision_sandbox.py 1products/tasks/backend/temporal/process_task/activities/refresh_sandbox_credentials.py 1products/tasks/backend/temporal/process_task/activities/send_followup_to_sandbox.py 1-products/tasks/backend/temporal/process_task/activities/start_agent_server.py 2products/tasks/backend/temporal/process_task/sandbox_credentials.py 1-products/tasks/backend/temporal/process_task/utils.py 3-products/tasks/scripts/run_agent_in_docker.py 2+products/tasks/backend/temporal/process_task/utils.py 2products/warehouse_sources/backend/models/external_data_destination.py 1products/warehouse_sources/backend/temporal/data_imports/sources/custom/source.py 1products/workflows/backend/management/commands/delete_stale_ses_identity.py 2diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex 5ed5d335255b..2056ae81e45c 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -56,11 +56,11 @@ from posthog.clickhouse.query_tagging import tag_queriesfrom posthog.dataclasses import frozenfrom posthog.event_usage import groupsfrom posthog.ingress.contracts import WebhookDelivery+from posthog.integrations import IntegrationManager, IntegrationNotFound, IntegrationRecordfrom posthog.models import Team, Userfrom posthog.models.activity_logging.activity_log import Change, Detail, log_activityfrom posthog.models.activity_logging.model_activity import get_was_impersonatedfrom posthog.models.comment.comment import CANVAS_COMMENT_SCOPES-from posthog.models.integration import Integrationfrom posthog.models.integration.codex import CodexAccessGrant, CodexAuthError, CodexReauthRequired, CodexUserIntegrationfrom posthog.models.oauth import OAuthAccessToken, OAuthRefreshTokenfrom posthog.temporal.oauth import CONTEXT_LAYER_INTERNAL_SCOPE@@ -6363,10 +6363,10 @@ def user_has_usable_personal_github(user_id: int) -> bool:def _ensure_task_team_github_integration(task: Task) -> bool:if task.github_integration_id is not None:return True- github_integration = Integration.objects.filter(team_id=task.team_id, kind="github").first()+ github_integration = IntegrationManager.github.oauth.find(task.team_id)if github_integration is None:return False- task.github_integration = github_integration+ task.github_integration_id = github_integration.idtask.save(update_fields=["github_integration", "updated_at"])return True@@ -7969,7 +7969,7 @@ def create_task(validated_data["created_by"] = User.objects.get(id=user_id)if validated_data.get("repository") and not validated_data.get("github_integration"):- default_integration = Integration.objects.filter(team=team, kind="github").first()+ default_integration = IntegrationManager.github.oauth.find(team.id)if default_integration:validated_data["github_integration"] = default_integration@@ -8185,10 +8185,10 @@ def create_task(if signal_report is not None:integration_id = _report_task_github_integration_id(team, code_access_allowed=True)default_integration = (- Integration.objects.filter(id=integration_id).first() if integration_id is not None else None+ _team_github_integration_or_none(team.id, integration_id) if integration_id is not None else None)else:- default_integration = Integration.objects.filter(team=team, kind="github").first()+ default_integration = IntegrationManager.github.oauth.find(team.id)if default_integration:validated_data["github_integration"] = default_integration@@ -8250,13 +8250,16 @@ def create_task(if validated_data.get("repository")else None)- if integration_id is None:+ pilot_integration = (+ _team_github_integration_or_none(team_id, integration_id) if integration_id is not None else None+ )+ if pilot_integration is None:raise ValidationError({"repository": "Connect or repair GitHub access to the selected repository before creating a pull request."})- validated_data["github_integration"] = Integration.objects.get(team_id=team_id, id=integration_id)+ validated_data["github_integration"] = pilot_integrationlogger.info("Creating task with data: %s", validated_data)with transaction.atomic():@@ -8676,8 +8679,11 @@ def resolve_team_github_integration_id(team_id: int, github_integration_id: int)no serializer team context. Returns ``None`` for any id that doesn't belong to the team —the caller treats that as "skip warming" (the submit later falls through to a cold create+run)."""- exists = Integration.objects.filter(id=github_integration_id, team_id=team_id, kind="github").exists()- return github_integration_id if exists else None+ try:+ IntegrationManager.github.oauth.get(team_id, github_integration_id)+ except IntegrationNotFound:+ return None+ return github_integration_iddef can_mint_readonly_github_token(team_id: int) -> bool:@@ -9072,6 +9078,13 @@ def _activate_warm_run(observe_prewarmed_activated(run)+def _team_github_integration_or_none(team_id: int, integration_id: int) -> IntegrationRecord | None:+ try:+ return IntegrationManager.github.oauth.get(team_id, integration_id)+ except IntegrationNotFound:+ return None++def _report_task_github_integration_id(team: Team, *, code_access_allowed: bool) -> int | None:if not code_access_allowed:return None@@ -9081,7 +9094,7 @@ def _report_task_github_integration_id(team: Team, *, code_access_allowed: bool)if github_optional_pilot_enabled(team.id):return readonly_github_integration_id(team.id)- integration = Integration.objects.filter(team=team, kind="github").first()+ integration = IntegrationManager.github.oauth.find(team.id)return integration.id if integration is not None else None@@ -9199,9 +9212,10 @@ def warm_task_sandbox(github_integration_id = _report_task_github_integration_id(team, code_access_allowed=code_access_allowed)github_integration = Noneif github_integration_id is not None:- github_integration = Integration.objects.filter(- id=github_integration_id, team_id=team_id, kind="github"- ).first()+ try:+ github_integration = IntegrationManager.github.oauth.get(team_id, github_integration_id)+ except IntegrationNotFound:+ github_integration = None# An integration id that does not resolve to this team's GitHub integration is never warmed on, and# a repository cannot be cloned without one. An integration without a repository is fine: the# create path stores that pair too, and reuse matches on the integration id.@@ -9271,7 +9285,7 @@ def warm_task_sandbox()# `_build_task` resolves the team's first GitHub integration; a warm must instead hold the# one the caller asked for, because warm reuse matches on the integration id.- task.github_integration = github_integration+ task.github_integration_id = github_integration.id if github_integration is not None else Nonetask.save(update_fields=["github_integration", "updated_at"])assert task.created_by is not None # create_without_run always sets created_by from user_id@@ -10274,11 +10288,7 @@ def resolve_slack_thread_context(# per-conversation queue workflow, so derive its handle anyway. Only possible# when the team maps to a single Slack workspace — with several, the guess# could point at another workspace's workflow.- workspace_ids = list(- Integration.objects.filter(team_id=team_id, kind="slack")- .values_list("integration_id", flat=True)- .distinct()[:2]- )+ workspace_ids = list({row.integration_id for row in IntegrationManager.slack.oauth.list(team_id)})workspace_id = workspace_ids[0] if len(workspace_ids) == 1 else Nonequeue_workflow_id = _slack_queue_workflow_id(workspace_id, channel, thread_ts)return contracts.SlackThreadContextResult(@@ -10806,7 +10816,7 @@ def update_channel(*,can_manage_shared_auto_archive: bool,name: str | None = None,- github_integration: Integration | None = None,+ github_integration: IntegrationRecord | None = None,repositories: list[str] | None = None,auto_archive_after_days: int | None | _AutoArchiveUnchanged = _AUTO_ARCHIVE_UNCHANGED,channel_type: str | None = None,@@ -10840,7 +10850,9 @@ def update_channel(update_fields.append("name")if repositories is not None:channel.repositories = repositories- channel.github_integration = github_integration if repositories else None+ channel.github_integration_id = (+ github_integration.id if repositories and github_integration is not None else None+ )update_fields.extend(["repositories", "github_integration"])if not isinstance(auto_archive_after_days, _AutoArchiveUnchanged):channel.auto_archive_after_days = auto_archive_after_daysdiff --git a/products/tasks/backend/github_repository_access.py b/products/tasks/backend/github_repository_access.pyindex 6164e7f28b63..a27f51d32a85 100644--- a/products/tasks/backend/github_repository_access.py+++ b/products/tasks/backend/github_repository_access.py@@ -2,7 +2,8 @@ import loggingfrom collections.abc import Iterablefrom posthog.egress.limiter.policies import Priority-from posthog.models.integration import GitHubIntegration, Integration+from posthog.integrations import IntegrationManager+from posthog.models.integration import GitHubIntegrationlogger = logging.getLogger(__name__)@@ -11,7 +12,7 @@ def inaccessible_repositories_via_integration(team_id: int, integration_id: int, full_names: Iterable[str]) -> list[str]:names = list(full_names)- integration = Integration.objects.filter(team_id=team_id, kind="github", id=integration_id).first()+ integration = IntegrationManager.github.oauth.get_many(team_id, [integration_id]).get(integration_id)if integration is None:return namestry:diff --git a/products/tasks/backend/logic/pull_request_titles.py b/products/tasks/backend/logic/pull_request_titles.pyindex d3cbb102e7d1..f058a77d554f 100644--- a/products/tasks/backend/logic/pull_request_titles.py+++ b/products/tasks/backend/logic/pull_request_titles.py@@ -6,8 +6,9 @@ import structlogfrom posthog.egress.github.transport import GitHubEgressBudgetExhausted, GitHubRateLimitErrorfrom posthog.egress.limiter.policies import Priority+from posthog.integrations import IntegrationManagerfrom posthog.models.github_integration_base import GitHubIntegrationError, PullRequestRef-from posthog.models.integration import GitHubIntegration, Integration+from posthog.models.integration import GitHubIntegrationfrom posthog.models.user_integration import UserGitHubIntegrationfrom products.tasks.backend.models import Task, TaskRun@@ -61,7 +62,9 @@ def _github_for_task(task: Task, team_id: int, user_id: int) -> GitHubIntegratioreturn UserGitHubIntegration(user_integration, source="tasks", priority=Priority.NORMAL)if not task.github_integration_id:return None- integration = Integration.objects.filter(team_id=team_id, kind="github", id=task.github_integration_id).first()+ integration = IntegrationManager.github.oauth.get_many(team_id, [task.github_integration_id]).get(+ task.github_integration_id+ )if integration is None:return Nonegithub = GitHubIntegration(integration, source="tasks", priority=Priority.NORMAL)diff --git a/products/tasks/backend/logic/repo_selection/agent.py b/products/tasks/backend/logic/repo_selection/agent.pyindex 7d9b128f1e6c..070a1652af66 100644--- a/products/tasks/backend/logic/repo_selection/agent.py+++ b/products/tasks/backend/logic/repo_selection/agent.py@@ -6,11 +6,12 @@ import loggingfrom collections.abc import Callable, Iterable, Mappingfrom typing import TYPE_CHECKING-from django.db.models import Case, IntegerField, Q, Value, When+from django.db.models import Case, IntegerField, Value, Whenfrom posthog.egress.limiter.policies import Priority+from posthog.integrations import IntegrationManager, IntegrationRecordfrom posthog.models.github_integration_base import INSTALLATION_UNAVAILABLE_SINCE_CONFIG_KEY, GitHubIntegrationBase-from posthog.models.integration import ERROR_TOKEN_REFRESH_FAILED, GitHubIntegration, Integration+from posthog.models.integration import ERROR_TOKEN_REFRESH_FAILED, GitHubIntegrationfrom posthog.models.integration_repository_cache import GitHubRepositoryFullCachefrom posthog.models.organization import OrganizationMembershipfrom posthog.models.repo_routing_rule import RepoRoutingRule@@ -118,6 +119,11 @@ def _first_user_github_integration(user_ids: Iterable[int]) -> UserIntegration |)+def _account_type_sort_key(row: IntegrationRecord) -> tuple[bool, str]:+ account_type = (row.config.get("account") or {}).get("type")+ return (account_type is None, account_type or "")++def resolve_team_github_integration(team_id: int, team: Team | None = None, requester_user_id: int | None = None, team_only: bool = False) -> GitHubIntegrationBase | None:@@ -141,21 +147,36 @@ def resolve_team_github_integration(source's repository names are shown to other team members, or when the work runs under theteam installation's bot identity — a personal connection is a cross-account leak there."""- integration = (- Integration.objects.filter(team_id=team_id, kind="github")- # Skip integrations whose installation has been synced and confirmed empty (0 repos)- .exclude(repository_cache=[], repository_cache_updated_at__isnull=False)- # Skip installs whose token refresh is permanently failing (uninstalled/suspended on- # GitHub's side): re-selecting one makes repo discovery storm GitHub with doomed refreshes.- .exclude(errors=ERROR_TOKEN_REFRESH_FAILED)- .exclude(config__has_key=INSTALLATION_UNAVAILABLE_SINCE_CONFIG_KEY)- # Prioritize orgs vs users (alphabetically), then oldest first- .order_by("config__account__type", "created_at", "id")- .first()+ candidates = sorted(+ (+ row+ for row in IntegrationManager.github.oauth.list(team_id)+ # Skip installs whose token refresh is permanently failing (uninstalled/suspended on+ # GitHub's side): re-selecting one makes repo discovery storm GitHub with doomed refreshes.+ if row.errors != ERROR_TOKEN_REFRESH_FAILED and INSTALLATION_UNAVAILABLE_SINCE_CONFIG_KEY not in row.config+ ),+ # Prioritize orgs vs users (alphabetically), then oldest first. `list` is already oldest+ # first and `sorted` is stable.+ key=_account_type_sort_key,+ )+ # Skip integrations whose installation has been synced and confirmed empty (0 repos). The SDK+ # defers the repository cache, so check it only until the first match.+ github = next(+ (+ adapter+ for adapter in (+ GitHubIntegration(row, source="repo_selection", priority=Priority.CRITICAL) for row in candidates+ )+ if not (+ adapter.integration.repository_cache_updated_at is not None+ and adapter.integration.repository_cache == []+ )+ ),+ None,)# Prefer the first GitHub integration from the team- if integration is not None:- return GitHubIntegration(integration, source="repo_selection", priority=Priority.CRITICAL)+ if github is not None:+ return githubif team_only:return None@@ -181,10 +202,9 @@ def resolve_team_github_integration(async def _github_reconnect_required(team_id: int) -> bool:- if (- await Integration.objects.filter(team_id=team_id, kind="github")- .filter(Q(errors=ERROR_TOKEN_REFRESH_FAILED) | Q(config__has_key=INSTALLATION_UNAVAILABLE_SINCE_CONFIG_KEY))- .aexists()+ if any(+ row.errors == ERROR_TOKEN_REFRESH_FAILED or INSTALLATION_UNAVAILABLE_SINCE_CONFIG_KEY in row.config+ for row in await IntegrationManager.github.oauth.alist(team_id)):return Truediff --git a/products/tasks/backend/logic/services/comment_slack_dm.py b/products/tasks/backend/logic/services/comment_slack_dm.pyindex 230c012e0064..2aa899367b00 100644--- a/products/tasks/backend/logic/services/comment_slack_dm.py+++ b/products/tasks/backend/logic/services/comment_slack_dm.py@@ -21,9 +21,10 @@ import structlogfrom posthog.comment.access import task_comment_target_is_accessiblefrom posthog.comment.formatting import rich_content_to_slack_payloadfrom posthog.dataclasses import frozen+from posthog.integrations import IntegrationManager, IntegrationRecordfrom posthog.models.comment import Commentfrom posthog.models.comment.comment import CANVAS_COMMENT_SCOPES-from posthog.models.integration import Integration, SlackIntegration+from posthog.models.integration import SlackIntegrationfrom posthog.models.organization import OrganizationMembershipfrom posthog.models.team import Teamfrom posthog.models.user import NOTIFICATION_DEFAULTS, User@@ -84,11 +85,9 @@ def send_comment_slack_dms(if not wanted:return _skip(comment_id, "no_enabled_recipient")- integrations = list(- Integration.objects.filter(team_id=team_id, kind=Integration.IntegrationKind.SLACK)- .exclude(integration_id__isnull=True)- .exclude(integration_id="")- .order_by("id")+ integrations = sorted(+ (row for row in IntegrationManager.slack.oauth.list(team_id) if row.integration_id),+ key=lambda row: row.id,)if not integrations:return _skip(comment_id, "no_slack_integration")@@ -115,7 +114,7 @@ def send_comment_slack_dms(integration_by_workspace = {integration.integration_id: integration for integration in integrations}slack_clients: dict[int, SlackIntegration] = {}- def slack_for(integration: Integration) -> SlackIntegration:+ def slack_for(integration: IntegrationRecord) -> SlackIntegration:if integration.id not in slack_clients:slack_clients[integration.id] = SlackIntegration(integration)return slack_clients[integration.id]@@ -161,7 +160,7 @@ def send_comment_slack_dms(slack = slack_for(integration)slack_user_id = _linked_slack_user_id(user_id=user_id, integration=integration)else:- email_destination_integration: Integration | None = None+ email_destination_integration: IntegrationRecord | None = Noneemail_destination_slack: SlackIntegration | None = Noneambiguous_email_destination = Falsefor candidate in integrations:@@ -266,7 +265,7 @@ def _recipients_wanting_dms(*, team_id: int, comment: Comment, recipients: Mappireturn wanted-def _linked_slack_user_id(*, user_id: int, integration: Integration) -> str | None:+def _linked_slack_user_id(*, user_id: int, integration: IntegrationRecord) -> str | None:link = (UserIntegration.objects.filter(user_id=user_id,@@ -280,8 +279,8 @@ def _linked_slack_user_id(*, user_id: int, integration: Integration) -> str | Nodef _linked_integration_for_recipient(- *, user_id: int, integration_by_workspace: Mapping[str | None, Integration]-) -> Integration | None:+ *, user_id: int, integration_by_workspace: Mapping[str | None, IntegrationRecord]+) -> IntegrationRecord | None:linked_workspaces = (UserIntegration.objects.filter(user_id=user_id, kind=UserIntegration.IntegrationKind.SLACK).order_by("-created_at")@@ -293,7 +292,7 @@ def _linked_integration_for_recipient(return None-def _slack_user_id_by_email(*, email: str, integration: Integration, slack: SlackIntegration) -> str | None:+def _slack_user_id_by_email(*, email: str, integration: IntegrationRecord, slack: SlackIntegration) -> str | None:"""Match a PostHog email against the workspace's own Slack directory.This is what makes the feature work without every person linking an account first. It asks the@@ -320,7 +319,7 @@ def _slack_user_id_by_email(*, email: str, integration: Integration, slack: Slacdef _mention_resolver(*,organization_id: str | UUID,- integration: Integration,+ integration: IntegrationRecord,slack: SlackIntegration,cache: dict[tuple[int, str], str | None],lookup_allowances: dict[int, int],diff --git a/products/tasks/backend/logic/services/dev_sandbox_context.py b/products/tasks/backend/logic/services/dev_sandbox_context.pyindex 5b09c5056a14..575f543ef952 100644--- a/products/tasks/backend/logic/services/dev_sandbox_context.py+++ b/products/tasks/backend/logic/services/dev_sandbox_context.py@@ -1,6 +1,6 @@from __future__ import annotations-from posthog.models.integration import Integration+from posthog.integrations import IntegrationManagerfrom posthog.models.organization import OrganizationMembershipfrom posthog.models.team.team import Team@@ -20,7 +20,7 @@ def resolve_sandbox_context_for_local_dev(repository: str) -> CustomPromptSandboraise RuntimeError(f"No users in organization '{team.organization.name}' (team {team.id})")user = membership.user# Validate the integration exists upfront so we fail early with a clear message.- gh = Integration.objects.filter(team=team, kind="github").first()+ gh = IntegrationManager.github.oauth.find(team.id)if not gh:raise RuntimeError(f"No GitHub integration found for team {team.id}. "diff --git a/products/tasks/backend/logic/services/workflow_tasks.py b/products/tasks/backend/logic/services/workflow_tasks.pyindex 11a186a6b60c..8a78fa158767 100644--- a/products/tasks/backend/logic/services/workflow_tasks.py+++ b/products/tasks/backend/logic/services/workflow_tasks.py@@ -17,8 +17,9 @@ from django.utils import timezone as django_timezoneimport structlogfrom posthog.dataclasses import frozen+from posthog.integrations import IntegrationManager, IntegrationRecordfrom posthog.models import User-from posthog.models.integration import Integration, SlackIntegration+from posthog.models.integration import SlackIntegrationfrom posthog.models.team.team import Teamfrom posthog.temporal.oauth import PosthogMcpScopes@@ -602,7 +603,7 @@ def _trimmed_event(event: dict[str, Any]) -> dict[str, Any]:class _SlackBinding:"""A slack_context resolved against the team's Slack integrations, ready to bind."""- integration: Integration+ integration: IntegrationRecordthread_context: SlackThreadContext@@ -610,11 +611,9 @@ def _resolve_slack_binding(team_id: int, ctx: contracts.WorkflowTaskSlackContext"""Team-scoped on purpose: the team filter is what stops a token binding another team's threads."""if ctx is None:return None- integration = Integration.objects.filter(id=ctx.integration_id, team_id=team_id, kind="slack").first()+ integration = IntegrationManager.slack.oauth.get_many(team_id, [ctx.integration_id]).get(ctx.integration_id)if integration is None and ctx.slack_team_id:- integration = Integration.objects.filter(- team_id=team_id, kind="slack", integration_id=ctx.slack_team_id- ).first()+ integration = IntegrationManager.slack.oauth.find(team_id, external_id=ctx.slack_team_id)if integration is None:logger.warning("workflow_task_slack_bind_no_integration",@@ -650,7 +649,7 @@ def _resolve_slack_binding(team_id: int, ctx: contracts.WorkflowTaskSlackContext)-def _may_speak_in_channel(integration: Integration, ctx: contracts.WorkflowTaskSlackContext) -> bool:+def _may_speak_in_channel(integration: IntegrationRecord, ctx: contracts.WorkflowTaskSlackContext) -> bool:"""Whether the task is allowed to reply in this channel at all.An externally shared channel has members from another Slack workspace, so PostHog stays@@ -699,7 +698,7 @@ def _acknowledge_trigger_message(binding: _SlackBinding) -> None:transaction.on_commit(_react)-def _thread_has_a_live_run(integration: Integration, ctx: contracts.WorkflowTaskSlackContext) -> bool:+def _thread_has_a_live_run(integration: IntegrationRecord, ctx: contracts.WorkflowTaskSlackContext) -> bool:"""Whether another agent already owns this thread's reply channel.Checked before the binding is built, not just before the row is written: the same@@ -708,7 +707,7 @@ def _thread_has_a_live_run(integration: Integration, ctx: contracts.WorkflowTask"""existing = (SlackThreadTaskMapping.objects.select_related("task_run")- .filter(integration=integration, channel=ctx.channel, thread_ts=ctx.thread_ts)+ .filter(integration_id=integration.id, channel=ctx.channel, thread_ts=ctx.thread_ts).first())return existing is not None and existing.task_run is not None and existing.task_run.status in ACTIVE_RUN_STATUSES@@ -724,7 +723,7 @@ def _bind_slack_thread(*, team: Team, task: Task, binding: _SlackBinding) -> Nonif run is None:returnSlackThreadTaskMapping.objects.update_or_create(- integration=binding.integration,+ integration_id=binding.integration.id,channel=thread.channel,thread_ts=thread.thread_ts,defaults={diff --git a/products/tasks/backend/logic/task_review.py b/products/tasks/backend/logic/task_review.pyindex 23e33a5a45cd..bb6e5a1a52cd 100644--- a/products/tasks/backend/logic/task_review.py+++ b/products/tasks/backend/logic/task_review.py@@ -1,7 +1,8 @@from rest_framework.exceptions import NotFound, PermissionDenied, ValidationErrorfrom posthog.egress.limiter.policies import Priority-from posthog.models.integration import GitHubIntegration, Integration+from posthog.integrations import IntegrationManager+from posthog.models.integration import GitHubIntegrationfrom posthog.models.user_integration import UserGitHubIntegrationfrom products.tasks.backend.models import Task@@ -28,8 +29,13 @@ def task_review(team_id: int, task_id: str, user_id: int, page: int) -> dict:if user_integration is not None and user_integration.user_id == user_id:github = UserGitHubIntegration(user_integration, source="tasks", priority=Priority.CRITICAL)else:- integrations = Integration.objects.filter(team_id=team_id, kind="github")- integration = integrations.filter(id=task.github_integration_id).first() if task.github_integration_id else None+ integration = (+ IntegrationManager.github.oauth.get_many(team_id, [task.github_integration_id]).get(+ task.github_integration_id+ )+ if task.github_integration_id+ else None+ )if integration is None:raise ValidationError("Connect GitHub in PostHog to load the review.")github = GitHubIntegration(integration, source="tasks", priority=Priority.CRITICAL)diff --git a/products/tasks/backend/max_tools.py b/products/tasks/backend/max_tools.pyindex e5486e497a3b..036194ba9df4 100644--- a/products/tasks/backend/max_tools.py+++ b/products/tasks/backend/max_tools.py@@ -6,6 +6,7 @@ from asgiref.sync import async_to_sync, sync_to_asyncfrom pydantic import BaseModel, Fieldfrom posthog.egress.limiter.policies import Priority+from posthog.integrations import IntegrationManagerfrom posthog.storage import object_storagefrom ee.hogai.tool import MaxTool@@ -72,14 +73,12 @@ By default, the task will be created and immediately executed. Set run=false toasync def _arun_impl(self, title: str, description: str, repository: str, run: bool = True) -> tuple[str, dict[str, Any]]:- from posthog.models.integration import Integration-slack_thread_context = (self._config.get("configurable") or {}).get("slack_thread_context")@sync_to_async@transaction.atomicdef create_task_and_maybe_run():- github_integration = Integration.objects.filter(team=self._team, kind="github").first()+ github_integration = IntegrationManager.github.oauth.find(self._team.id)task = Task.objects.create(team=self._team,@@ -89,7 +88,7 @@ By default, the task will be created and immediately executed. Set run=false todescription=description,origin_product=Task.OriginProduct.USER_CREATED,repository=repository,- github_integration=github_integration,+ github_integration_id=github_integration.id if github_integration is not None else None,)task_run = None@@ -551,11 +550,11 @@ Use this tool when the user wants to:args_schema: type[BaseModel] = ListRepositoriesArgsasync def _arun_impl(self, search: str | None = None) -> tuple[str, dict[str, Any]]:- from posthog.models.integration import GitHubIntegration, Integration+ from posthog.models.integration import GitHubIntegration@sync_to_asyncdef get_repositories():- integrations = Integration.objects.filter(team=self._team, kind="github")+ integrations = IntegrationManager.github.oauth.list(self._team.id)all_repos: list[dict[str, str]] = []diff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.pyindex 0655210ba011..e07a4bd2118b 100644--- a/products/tasks/backend/models.py+++ b/products/tasks/backend/models.py@@ -30,6 +30,7 @@ import posthoganalyticsfrom posthog.event_usage import groupsfrom posthog.helpers.encrypted_fields import EncryptedJSONStringField+from posthog.integrations import IntegrationManagerfrom posthog.models.github_integration_base import INSTALLATION_UNAVAILABLE_SINCE_CONFIG_KEYfrom posthog.models.integration import ERROR_TOKEN_REFRESH_FAILED, Integrationfrom posthog.models.scoping.root_mixin import TeamScopedRootMixin@@ -1325,12 +1326,16 @@ class Task(Taggable, DeletedMetaFields, models.Model):github_resolution_allowed = Task._github_resolution_allowed(origin_product, has_repository=bool(repository))github_integration = Noneif github_resolution_allowed:- github_integration = (- Integration.objects.filter(team=team, kind="github")- .exclude(errors=ERROR_TOKEN_REFRESH_FAILED)- .exclude(config__has_key=INSTALLATION_UNAVAILABLE_SINCE_CONFIG_KEY)- .first()+ github_integration = next(+ (+ row+ for row in IntegrationManager.github.oauth.list(team.id)+ if row.errors != ERROR_TOKEN_REFRESH_FAILED+ and INSTALLATION_UNAVAILABLE_SINCE_CONFIG_KEY not in row.config+ ),+ None,)+ github_integration_id = github_integration.id if github_integration is not None else Nonegithub_user_integration = Nonetask_stub = Task(team=team,@@ -1338,7 +1343,7 @@ class Task(Taggable, DeletedMetaFields, models.Model):client_provenance=client_provenance,created_by=created_by,repository=repository,- github_integration=github_integration,+ github_integration_id=github_integration_id,runtime=runtime,)authorship_mode = (@@ -1407,7 +1412,7 @@ class Task(Taggable, DeletedMetaFields, models.Model):profile=profile_key,client_provenance=client_provenance,created_by=created_by,- github_integration=github_integration,+ github_integration_id=github_integration_id,github_user_integration=github_user_integration,repository=repository,repositories=resolved_repositories,diff --git a/products/tasks/backend/presentation/serializers.py b/products/tasks/backend/presentation/serializers.pyindex 0d4a43bba5f2..89af6c00623e 100644--- a/products/tasks/backend/presentation/serializers.py+++ b/products/tasks/backend/presentation/serializers.py@@ -20,7 +20,7 @@ from rest_framework_dataclasses.serializers import DataclassSerializerfrom posthog.api.fields import JSONTolerantListField, RepeatedOrCommaSeparatedListFieldfrom posthog.api.scoped_related_fields import TeamScopedPrimaryKeyRelatedFieldfrom posthog.event_usage import groups-from posthog.models.integration import Integration+from posthog.integrations.fields import IntegrationReferenceFieldfrom posthog.models.user_integration import UserIntegrationfrom posthog.oauth_provenance import get_oauth_client_id, is_interactive_desktop_grantfrom posthog.object_tags.kinds import OBJECT_KINDS@@ -798,8 +798,8 @@ class TaskWriteSerializer(serializers.Serializer):max_length=10,help_text="GitHub repositories available to this task, each in `organization/repo` format.",)- github_integration = serializers.PrimaryKeyRelatedField( # nosemgrep: unscoped-primary-key-related-field- queryset=Integration.objects.filter(kind="github"),+ github_integration = IntegrationReferenceField(+ kinds=["github"],required=False,allow_null=True,help_text="GitHub integration for this task.",@@ -815,7 +815,7 @@ class TaskWriteSerializer(serializers.Serializer):# (team scope is enforced by validate_signal_report below). Bound lazily in __init__ so# importing this module never touches the signals model.signal_report = serializers.PrimaryKeyRelatedField( # nosemgrep: unscoped-primary-key-related-field- queryset=Integration.objects.none(),+ queryset=UserIntegration.objects.none(), # placeholder, replaced in __init__required=False,allow_null=True,help_text="Signal report this task implements, when created from a report.",@@ -940,7 +940,7 @@ class TaskWriteSerializer(serializers.Serializer):),)channel = TeamScopedPrimaryKeyRelatedField( # nosemgrep: unscoped-primary-key-related-field- queryset=Integration.objects.none(),+ queryset=UserIntegration.objects.none(), # placeholder, replaced in __init__required=False,allow_null=True,help_text="Channel this task is owned by (the channel it was kicked off in).",@@ -972,12 +972,6 @@ class TaskWriteSerializer(serializers.Serializer):raise serializers.ValidationError("Space not found")return value- def validate_github_integration(self, value):- """Validate that the GitHub integration belongs to the same team"""- if value and value.team_id != self.context["team"].id:- raise serializers.ValidationError("Integration must belong to the same team")- return value-def validate_github_user_integration(self, value):"""Validate that the GitHub user integration belongs to the authenticated user."""request = self.context.get("request")@@ -2635,8 +2629,8 @@ class ChannelUpdateSerializer(serializers.Serializer):required=False,help_text="Channel name, rendered as #<name>. Normalized to lowercase-dashed.",)- github_integration = TeamScopedPrimaryKeyRelatedField(- queryset=Integration.objects.filter(kind="github"),+ github_integration = IntegrationReferenceField(+ kinds=["github"],required=False,allow_null=True,help_text="Team GitHub integration used for repositories linked to this channel.",@@ -2668,11 +2662,6 @@ class ChannelUpdateSerializer(serializers.Serializer):raise serializers.ValidationError("That name is reserved for a default space. Pick another name.")return value- def validate_github_integration(self, value):- if value is not None and value.team_id != self.context["team_id"]:- raise serializers.ValidationError("GitHub integration must belong to this project")- return value-def validate_repositories(self, value: list[str]) -> list[str]:repositories = [TaskWriteSerializer().validate_repository(repository) for repository in value]if len(set(repositories)) != len(repositories):@@ -4146,7 +4135,7 @@ class WarmTaskRequestSerializer(serializers.Serializer):),)signal_report = serializers.PrimaryKeyRelatedField( # nosemgrep: unscoped-primary-key-related-field- queryset=Integration.objects.none(),+ queryset=UserIntegration.objects.none(), # placeholder, replaced in __init__required=False,default=None,allow_null=True,diff --git a/products/tasks/backend/repository_readiness.py b/products/tasks/backend/repository_readiness.pyindex a088edbe8fda..a03b92f6147e 100644--- a/products/tasks/backend/repository_readiness.py+++ b/products/tasks/backend/repository_readiness.py@@ -11,7 +11,8 @@ from django.utils import timezoneimport requestsfrom posthog.egress.limiter.policies import Priority-from posthog.models.integration import GitHubIntegration, Integration+from posthog.integrations import IntegrationManager, IntegrationRecord+from posthog.models.integration import GitHubIntegrationfrom products.error_tracking.backend.facade import api as error_tracking_apifrom products.event_definitions.backend.models.event_definition import EventDefinition@@ -115,12 +116,11 @@ def _cache_key(*, team_id: int, integration_id: int, repository: str, window_day)-def _refresh_installation_token(integration: Integration) -> None:+def _refresh_installation_token(integration: IntegrationRecord) -> None:github = GitHubIntegration(integration, source="tasks", priority=Priority.CRITICAL)try:if github.access_token_expired():github.refresh_access_token()- integration.refresh_from_db(fields=["config", "sensitive_config"])except Exception:logger.warning("repository_readiness.refresh_token_failed", exc_info=True)return@@ -232,7 +232,7 @@ def _fetch_file_content(github: GitHubIntegration, repository: str, path: str, rreturn None-def _scan_repository(integration: Integration, repository: str) -> tuple[RepositoryScanEvidence, list[str]]:+def _scan_repository(integration: IntegrationRecord, repository: str) -> tuple[RepositoryScanEvidence, list[str]]:github = GitHubIntegration(integration, source="tasks", priority=Priority.CRITICAL)tree_paths, default_branch = _fetch_repository_tree(github, repository)@@ -374,7 +374,7 @@ def compute_repository_readiness(repository = _normalize_repo_key(repository)window_days = min(max(window_days, 1), MAX_WINDOW_DAYS)- integration = Integration.objects.filter(team=team, kind="github").first()+ integration = IntegrationManager.github.oauth.find(team.id)if not integration:not_ready = _capability_state("GitHub integration is not connected.", "needs_setup")return {diff --git a/products/tasks/backend/repository_resolver.py b/products/tasks/backend/repository_resolver.pydeleted file mode 100644index 1ceb4a31a896..000000000000--- a/products/tasks/backend/repository_resolver.py+++ /dev/null@@ -1,288 +0,0 @@-"""-Repository resolution helpers for the multi-repository issue tracker system.-"""--import fnmatch-from typing import Any, Optional--from django.apps import apps--from posthog.egress.limiter.policies import Priority-from posthog.models.integration import GitHubIntegration, Integration---class RepositoryContext:- """Context object for a resolved repository"""-- def __init__(self, integration: Integration, repository: str, organization: str, is_primary: bool = False):- self.integration = integration- self.repository = repository- self.organization = organization- self.is_primary = is_primary- self.github_integration = GitHubIntegration(integration, source="tasks", priority=Priority.CRITICAL)-- @property- def full_name(self) -> str:- return f"{self.organization}/{self.repository}"-- def to_dict(self) -> dict[str, Any]:- return {- "org": self.organization,- "repo": self.repository,- "integration_id": self.integration.id,- "full_name": self.full_name,- "is_primary": self.is_primary,- }---async def resolve_repositories_for_issue(issue) -> list[RepositoryContext]:- """- Resolves the actual repositories the agent can work with for an issue.-- Args:- issue: Issue model instance-- Returns:- List of RepositoryContext objects- """- Task = apps.get_model("tasks", "Task")-- if issue.repository_scope == Task.RepositoryScope.SINGLE: # type: ignore[attr-defined] # Task has no RepositoryScope; nothing calls this module- return await resolve_single_repository(issue)-- elif issue.repository_scope == Task.RepositoryScope.MULTIPLE: # type: ignore[attr-defined] # Task has no RepositoryScope; nothing calls this module- return await resolve_multiple_repositories(issue)-- elif issue.repository_scope == Task.RepositoryScope.SMART_SELECT: # type: ignore[attr-defined] # Task has no RepositoryScope; nothing calls this module- return await resolve_smart_select_repositories(issue)-- # Fallback to legacy behavior- return await resolve_legacy_repository(issue)---async def resolve_single_repository(issue) -> list[RepositoryContext]:- """Resolve a single repository for the issue"""- config = issue.repository_config- integration = issue.github_integration-- if not integration:- # Fallback to team's first GitHub integration- integration = await _get_team_github_integration(issue.team_id)- if not integration:- return []-- org = config.get("organization")- repo = config.get("repository")-- if not org or not repo:- # If not configured, use the first available repository- github = GitHubIntegration(integration, source="tasks", priority=Priority.CRITICAL)- repositories = await github.list_all_cached_repositories_async()- if repositories:- org = github.organization()- repo = repositories[0]["name"]- else:- return []-- return [RepositoryContext(integration=integration, repository=repo, organization=org, is_primary=True)]---async def resolve_multiple_repositories(issue) -> list[RepositoryContext]:- """Resolve multiple repositories for the issue"""- repositories_config = issue.repository_config.get("repositories", [])- resolved_repos = []-- for repo_config in repositories_config:- integration_id = repo_config.get("integration_id")- org = repo_config.get("org")- repo = repo_config.get("repo")- is_primary = repo_config.get("is_primary", False)-- if not integration_id or not org or not repo:- continue-- try:- integration = await Integration.objects.aget(id=integration_id, kind="github")- resolved_repos.append(- RepositoryContext(integration=integration, repository=repo, organization=org, is_primary=is_primary)- )- except Integration.DoesNotExist:- continue-- return resolved_repos---async def resolve_smart_select_repositories(issue) -> list[RepositoryContext]:- """- AI-driven repository selection with constraints.- This will be called when the agent needs to dynamically select repositories.- """- constraints = issue.repository_config.get("constraints", {})-- # Get all available repositories from allowed integrations- available_repos = []- allowed_integrations = await _get_allowed_integrations_for_smart_select(issue, constraints)-- for integration in allowed_integrations:- github = GitHubIntegration(integration, source="tasks", priority=Priority.CRITICAL)- try:- repos = await github.list_all_cached_repositories_async()- org = github.organization()-- for repo in repos:- repo_name = repo["name"]- if await _meets_smart_select_constraints(org, repo_name, constraints):- available_repos.append(- RepositoryContext(integration=integration, repository=repo_name, organization=org)- )- except Exception:- continue-- # For now, return available repositories- # In future iterations, this will include AI analysis- max_repos = int(constraints.get("max_repositories", 5))- selected_repos = available_repos[:max_repos]-- # Mark first as primary- if selected_repos:- selected_repos[0].is_primary = True-- # Update issue config with selected repositories- await _update_issue_selected_repositories(issue, selected_repos)-- return selected_repos---async def resolve_legacy_repository(issue) -> list[RepositoryContext]:- """Fallback to legacy single repository behavior"""- integration = issue.legacy_github_integration- if not integration:- return []-- github = GitHubIntegration(integration, source="tasks", priority=Priority.CRITICAL)- repositories, _ = await github.list_cached_repositories_async()-- if not repositories:- return []-- return [- RepositoryContext(- integration=integration,- repository=repositories[0]["name"],- organization=github.organization(),- is_primary=True,- )- ]---async def validate_repository_access(issue, org: str, repo: str) -> bool:- """- Validate that an issue can access a specific repository based on its scoping configuration.-- Args:- issue: Issue model instance- org: Organization name- repo: Repository name-- Returns:- True if access is allowed, False otherwise- """- return issue.can_access_repository(org, repo)---async def get_primary_repository(issue) -> Optional[RepositoryContext]:- """Get the primary repository for an issue"""- repositories = await resolve_repositories_for_issue(issue)-- # Look for explicitly marked primary repository- for repo in repositories:- if repo.is_primary:- return repo-- # Default to first repository- return repositories[0] if repositories else None---async def _get_team_github_integration(team_id: int) -> Optional[Integration]:- """Get the team's first GitHub integration"""- try:- return await Integration.objects.filter(team_id=team_id, kind="github").afirst()- except Integration.DoesNotExist:- return None---async def _get_allowed_integrations_for_smart_select(issue, constraints: dict) -> list[Integration]:- """Get allowed integrations based on smart select constraints"""- allowed_orgs = constraints.get("organizations", [])-- integrations = []- async for integration in Integration.objects.filter(team_id=issue.team_id, kind="github"):- github = GitHubIntegration(integration, source="tasks", priority=Priority.CRITICAL)- org = github.organization()-- # If organizations are specified, only include matching ones- if allowed_orgs and org not in allowed_orgs:- continue-- integrations.append(integration)-- return integrations---async def _meets_smart_select_constraints(org: str, repo: str, constraints: dict) -> bool:- """Check if a repository meets smart select constraints"""- allowed_repos = constraints.get("repositories", [])-- if allowed_repos:- repo_full_name = f"{org}/{repo}"- # Support wildcard patterns like "PostHog/*" or "*-api"- if not any(fnmatch.fnmatch(repo_full_name, pattern) for pattern in allowed_repos):- return False-- return True---async def _update_issue_selected_repositories(issue, selected_repos: list[RepositoryContext]) -> None:- """Update issue configuration with selected repositories"""- Task = apps.get_model("tasks", "Task")-- available_repositories = [repo.to_dict() for repo in selected_repos]-- # Update the issue's repository config- issue.repository_config = {**issue.repository_config, "available_repositories": available_repositories}-- await Task.objects.filter(id=issue.id).aupdate(repository_config=issue.repository_config) # type: ignore[misc] # Task has no repository_config; nothing calls this module---# Smart selection AI helpers (placeholder for future implementation)-async def ai_select_repositories(- issue, available_repositories: list[RepositoryContext], max_count: int, preferences: dict-) -> list[RepositoryContext]:- """- Use AI to analyze issue and select most relevant repositories.- This is a placeholder for future AI implementation.- """- # For now, use simple heuristics- selected = []-- # Prefer repositories with keywords matching the issue- issue_keywords = issue.title.lower().split() + issue.description.lower().split()-- for repo in available_repositories:- score: float = 0.0- repo_name = repo.repository.lower()-- # Score based on keyword matches- for keyword in issue_keywords:- if keyword in repo_name:- score += 1-- # Prefer recently active repositories (placeholder)- if preferences.get("prefer_recent_activity", False):- score += 0.5-- selected.append((repo, score))-- # Sort by score and take top repositories- selected.sort(key=lambda x: x[1], reverse=True)- return [repo for repo, _ in selected[:max_count]]diff --git a/products/tasks/backend/temporal/build_image/activities.py b/products/tasks/backend/temporal/build_image/activities.pyindex 9ab70e5b932c..02d215cd10d8 100644--- a/products/tasks/backend/temporal/build_image/activities.py+++ b/products/tasks/backend/temporal/build_image/activities.py@@ -11,6 +11,7 @@ from temporalio import activityif TYPE_CHECKING:import modal+from posthog.integrations import IntegrationManagerfrom posthog.temporal.common.utils import asyncifyfrom posthog.temporal.oauth import create_oauth_access_token_for_user@@ -195,15 +196,13 @@ def _sanitized_build_log(raw: str) -> str:def _resolve_build_github_token(team_id: int) -> str | None:- from posthog.models.integration import Integration # noqa: PLC0415-from products.tasks.backend.temporal.create_snapshot.utils import get_github_token # noqa: PLC0415- integration = Integration.objects.filter(team_id=team_id, kind="github").first()+ integration = IntegrationManager.github.oauth.find(team_id)if integration is None:return Nonetry:- return get_github_token(integration.id)+ return get_github_token(team_id, integration.id)except Exception as e:logger.warning("custom_image_build_github_token_failed", extra={"team_id": team_id, "error": str(e)})return Nonediff --git a/products/tasks/backend/temporal/create_snapshot/activities/clone_repository.py b/products/tasks/backend/temporal/create_snapshot/activities/clone_repository.pyindex d258a4ecf9eb..4ab301c284c9 100644--- a/products/tasks/backend/temporal/create_snapshot/activities/clone_repository.py+++ b/products/tasks/backend/temporal/create_snapshot/activities/clone_repository.py@@ -29,7 +29,7 @@ def clone_repository(input: CloneRepositoryInput) -> str:**ctx.to_log_context(),):try:- github_token = get_github_token(ctx.github_integration_id)+ github_token = get_github_token(ctx.team_id, ctx.github_integration_id)except Exception as e:raise GitHubAuthenticationError(f"Failed to get GitHub token for integration {ctx.github_integration_id}",diff --git a/products/tasks/backend/temporal/create_snapshot/activities/create_sandbox.py b/products/tasks/backend/temporal/create_snapshot/activities/create_sandbox.pyindex 12978e2995a5..177183a3b55e 100644--- a/products/tasks/backend/temporal/create_snapshot/activities/create_sandbox.py+++ b/products/tasks/backend/temporal/create_snapshot/activities/create_sandbox.py@@ -2,7 +2,8 @@ from dataclasses import dataclassfrom temporalio import activity-from posthog.models import Integration+from posthog.integrations import IntegrationManager+from posthog.models.user import Userfrom posthog.temporal.common.utils import asyncifyfrom products.tasks.backend.logic.services.sandbox import Sandbox, SandboxConfig, SandboxTemplate@@ -35,8 +36,9 @@ def create_sandbox(input: CreateSandboxInput) -> CreateSandboxOutput:):github_token = get_github_token(ctx.github_integration_id) or ""- integration = Integration.objects.select_related("created_by").get(id=ctx.github_integration_id)- access_token = create_oauth_access_token_for_user(integration.created_by, ctx.team_id)+ integration = IntegrationManager.github.oauth.get(ctx.team_id, ctx.github_integration_id)+ user = User.objects.filter(id=integration.created_by_id).first()+ access_token = create_oauth_access_token_for_user(user, ctx.team_id)environment_variables = {"GITHUB_TOKEN": github_token,diff --git a/products/tasks/backend/temporal/create_snapshot/activities/get_snapshot_context.py b/products/tasks/backend/temporal/create_snapshot/activities/get_snapshot_context.pyindex bc17a5075d01..71be0249479f 100644--- a/products/tasks/backend/temporal/create_snapshot/activities/get_snapshot_context.py+++ b/products/tasks/backend/temporal/create_snapshot/activities/get_snapshot_context.py@@ -2,7 +2,7 @@ from dataclasses import dataclassfrom temporalio import activity-from posthog.models.integration import Integration+from posthog.integrations import IntegrationManager, IntegrationNotFoundfrom posthog.temporal.common.utils import asyncifyfrom products.tasks.backend.exceptions import TaskInvalidStateError@@ -40,8 +40,8 @@ def get_snapshot_context(input: GetSnapshotContextInput) -> SnapshotContext:)try:- Integration.objects.get(id=input.github_integration_id)- except Integration.DoesNotExist as e:+ IntegrationManager.github.oauth.get(input.team_id, input.github_integration_id)+ except IntegrationNotFound as e:raise TaskInvalidStateError(f"Integration {input.github_integration_id} not found",{"github_integration_id": input.github_integration_id},diff --git a/products/tasks/backend/temporal/create_snapshot/utils.py b/products/tasks/backend/temporal/create_snapshot/utils.pyindex f7929428349a..f150986e20ec 100644--- a/products/tasks/backend/temporal/create_snapshot/utils.py+++ b/products/tasks/backend/temporal/create_snapshot/utils.py@@ -1,11 +1,12 @@from typing import Optionalfrom posthog.egress.limiter.policies import Priority-from posthog.models.integration import GitHubIntegration, Integration+from posthog.integrations import IntegrationManager+from posthog.models.integration import GitHubIntegration-def get_github_token(github_integration_id: int) -> Optional[str]:- integration = Integration.objects.get(id=github_integration_id)+def get_github_token(team_id: int, github_integration_id: int) -> Optional[str]:+ integration = IntegrationManager.github.oauth.get(team_id, github_integration_id)github_integration = GitHubIntegration(integration, source="tasks_sandbox", priority=Priority.CRITICAL)if github_integration.access_token_expired():diff --git a/products/tasks/backend/temporal/process_task/activities/feature_flags.py b/products/tasks/backend/temporal/process_task/activities/feature_flags.pyindex e01cbed808bd..b32ef78d0cef 100644--- a/products/tasks/backend/temporal/process_task/activities/feature_flags.py+++ b/products/tasks/backend/temporal/process_task/activities/feature_flags.py@@ -3,6 +3,7 @@ from typing import Anyfrom temporalio import activity+from posthog.integrations import IntegrationManager, IntegrationNotFoundfrom posthog.temporal.common.logger import get_loggerfrom posthog.temporal.common.utils import close_db_connections@@ -25,24 +26,23 @@ def is_slack_app_agent_design_enabled_for_task_activity() -> bool:"""Flag check + persist to TaskRun.state so out-of-workflow callers (e.g.forward_pending_message) can read the decision without re-evaluating."""- from posthog.models.integration import Integration-from products.slack_app.backend.feature_flags import is_slack_app_agent_design_enabledfrom products.tasks.backend.models import TaskRun+ run = TaskRun.objects.select_related("task__created_by").filter(id=input.run_id).first()try:- integration = Integration.objects.select_related("team", "team__organization").get(id=input.integration_id)- except Integration.DoesNotExist:+ if run is None:+ raise IntegrationNotFound(f"No task run {input.run_id}")+ integration = IntegrationManager.slack.oauth.get(run.team_id, input.integration_id)+ except IntegrationNotFound:logger.warning("slack_app_agent_design_integration_missing", integration_id=input.integration_id)enabled = Falseelse:# The run's creator is the person the decision is about, so the gate resolves the# flag against them and an internal rollout can name people by email or cohort the# way every other one does. None when the run has no creator on record.- creator_distinct_id = (- TaskRun.objects.filter(id=input.run_id).values_list("task__created_by__distinct_id", flat=True).first()- )- enabled = is_slack_app_agent_design_enabled(integration, creator_distinct_id)+ creator = run.task.created_by+ enabled = is_slack_app_agent_design_enabled(integration, creator.distinct_id if creator else None)def _persist(state: dict[str, Any]) -> None:state[AGENT_DESIGN_STATE_KEY] = enableddiff --git a/products/tasks/backend/temporal/process_task/activities/get_pr_babysit_snapshot.py b/products/tasks/backend/temporal/process_task/activities/get_pr_babysit_snapshot.pyindex 5a1dc024c0d7..3d4e38fe8c84 100644--- a/products/tasks/backend/temporal/process_task/activities/get_pr_babysit_snapshot.py+++ b/products/tasks/backend/temporal/process_task/activities/get_pr_babysit_snapshot.py@@ -5,6 +5,7 @@ from django.core.exceptions import ObjectDoesNotExistfrom temporalio import activityfrom posthog.egress.github.transport import GitHubEgressBudgetExhausted, GitHubRateLimitError+from posthog.integrations import IntegrationNotFoundfrom posthog.models.integration import GitHubIntegrationfrom posthog.models.user_integration import UserGitHubIntegrationfrom posthog.temporal.common.utils import close_db_connections@@ -52,10 +53,10 @@ def get_pr_babysit_snapshot(input: GetPrBabysitSnapshotInput) -> PRSnapshot | Notry:github_integration: GitHubIntegration | UserGitHubIntegrationif ctx.github_integration_id:- github_integration = get_github_integration(ctx.github_integration_id)+ github_integration = get_github_integration(ctx.team_id, ctx.github_integration_id)else:github_integration = get_user_github_integration(str(ctx.github_user_integration_id))- except ObjectDoesNotExist:+ except (ObjectDoesNotExist, IntegrationNotFound):activity.logger.warning("get_pr_babysit_snapshot_github_integration_not_found",extra={diff --git a/products/tasks/backend/temporal/process_task/activities/get_pr_context.py b/products/tasks/backend/temporal/process_task/activities/get_pr_context.pyindex 892eeb092905..ec8f4e34ecfa 100644--- a/products/tasks/backend/temporal/process_task/activities/get_pr_context.py+++ b/products/tasks/backend/temporal/process_task/activities/get_pr_context.py@@ -8,7 +8,7 @@ from temporalio import activityfrom posthog.egress.github.transport import GitHubEgressBudgetExhausted, GitHubRateLimitErrorfrom posthog.egress.limiter.policies import Priority-from posthog.models import Integration+from posthog.integrations import IntegrationManager, IntegrationNotFoundfrom posthog.models.integration import GitHubIntegrationfrom posthog.models.user_integration import UserGitHubIntegration, UserIntegrationfrom posthog.temporal.common.utils import close_db_connections@@ -94,8 +94,8 @@ def merge_queue_push_would_eject(github_integration: GitHubIntegration | UserGitreturn state is not None and state.push_would_eject-def get_github_integration(github_integration_id: int) -> GitHubIntegration:- integration = Integration.objects.get(id=github_integration_id)+def get_github_integration(team_id: int, github_integration_id: int) -> GitHubIntegration:+ integration = IntegrationManager.github.oauth.get(team_id, github_integration_id)github_integration = GitHubIntegration(integration, source="tasks_sandbox", priority=Priority.CRITICAL)if github_integration.access_token_expired():@@ -135,10 +135,10 @@ def get_pr_context(input: GetPrContextInput) -> GetPrContextOutput | None:try:github_integration: GitHubIntegration | UserGitHubIntegrationif ctx.github_integration_id:- github_integration = get_github_integration(ctx.github_integration_id)+ github_integration = get_github_integration(ctx.team_id, ctx.github_integration_id)else:github_integration = get_user_github_integration(str(ctx.github_user_integration_id))- except ObjectDoesNotExist:+ except (ObjectDoesNotExist, IntegrationNotFound):activity.logger.warning("get_pr_context_github_integration_not_found",extra={diff --git a/products/tasks/backend/temporal/process_task/activities/mark_pr_ready.py b/products/tasks/backend/temporal/process_task/activities/mark_pr_ready.pyindex 8418631f385a..a770d8e35091 100644--- a/products/tasks/backend/temporal/process_task/activities/mark_pr_ready.py+++ b/products/tasks/backend/temporal/process_task/activities/mark_pr_ready.py@@ -62,7 +62,7 @@ def mark_pr_ready(input: MarkPrReadyInput) -> bool:return Falsegithub = (- get_github_integration(context.github_integration_id)+ get_github_integration(context.team_id, context.github_integration_id)if context.github_integration_idelse get_user_github_integration(str(context.github_user_integration_id)))diff --git a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.pyindex 5550d0e0ccdc..bef359ee903c 100644--- a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py+++ b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py@@ -1325,7 +1325,7 @@ def _installation_behind_sandbox_token(ctx: TaskProcessingContext) -> GitHubIntereturn Noneif get_pr_authorship_mode(_load_task(ctx), ctx.state) != PrAuthorshipMode.BOT:return None- return resolve_installation_github_integration(ctx.github_integration_id)+ return resolve_installation_github_integration(ctx.team_id, ctx.github_integration_id)def _is_repository_access_denied_clone_error(result: ExecutionResult) -> bool:diff --git a/products/tasks/backend/temporal/process_task/activities/start_agent_server.py b/products/tasks/backend/temporal/process_task/activities/start_agent_server.pyindex ce67fc4b731f..a1caf13874e0 100644--- a/products/tasks/backend/temporal/process_task/activities/start_agent_server.py+++ b/products/tasks/backend/temporal/process_task/activities/start_agent_server.py@@ -15,7 +15,7 @@ from temporalio import activityfrom posthog.dataclasses import frozenfrom posthog.egress.limiter.policies import Priority-from posthog.models import Integration+from posthog.integrations import IntegrationManagerfrom posthog.models.integration import GitHubIntegrationfrom posthog.models.user_integration import UserGitHubIntegration, UserIntegrationfrom posthog.temporal.common.activity_context import current_activity_attempt@@ -153,7 +153,7 @@ def _resolve_protected_base_branch(ctx: TaskProcessingContext) -> str | None:integration: GitHubIntegration | UserGitHubIntegrationif ctx.github_integration_id:integration = GitHubIntegration(- Integration.objects.get(id=ctx.github_integration_id),+ IntegrationManager.github.oauth.get(ctx.team_id, ctx.github_integration_id),source="tasks_sandbox",priority=Priority.CRITICAL,)diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_get_pr_context.py b/products/tasks/backend/temporal/process_task/activities/tests/test_get_pr_context.pyindex 4574dc365292..696813cbeb28 100644--- a/products/tasks/backend/temporal/process_task/activities/tests/test_get_pr_context.py+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_get_pr_context.py@@ -9,6 +9,8 @@ from django.core.exceptions import ObjectDoesNotExistfrom parameterized import parameterizedfrom posthog.egress.github.transport import GitHubEgressBudgetExhausted, GitHubRateLimitError+from posthog.integrations import IntegrationNotFound+from posthog.models.team.team import Teamfrom products.tasks.backend.exceptions import GitHubRateLimitedError, ProcessTaskTransientErrorfrom products.tasks.backend.temporal.process_task.activities.get_pr_context import (@@ -369,7 +371,7 @@ class TestGetGithubIntegration:wrapped.access_token_expired.return_value = TrueMockGitHubIntegration.return_value = wrapped- result = get_github_integration(github_integration.id)+ result = get_github_integration(github_integration.team_id, github_integration.id)assert result is wrappedwrapped.access_token_expired.assert_called_once()@@ -382,14 +384,19 @@ class TestGetGithubIntegration:wrapped.access_token_expired.return_value = FalseMockGitHubIntegration.return_value = wrapped- result = get_github_integration(github_integration.id)+ result = get_github_integration(github_integration.team_id, github_integration.id)assert result is wrappedwrapped.refresh_access_token.assert_not_called()@pytest.mark.django_db- def test_raises_when_integration_not_found(self):- from posthog.models import Integration-- with pytest.raises(Integration.DoesNotExist):- get_github_integration(999999999)+ @pytest.mark.parametrize("case", ["missing_id", "other_team"])+ def test_raises_when_integration_not_found(self, github_integration, case):+ if case == "missing_id":+ team_id, integration_id = github_integration.team_id, 999999999+ else:+ other_team = Team.objects.create(organization=github_integration.team.organization, name="Other team")+ team_id, integration_id = other_team.id, github_integration.id++ with pytest.raises(IntegrationNotFound):+ get_github_integration(team_id, integration_id)diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_mark_pr_ready.py b/products/tasks/backend/temporal/process_task/activities/tests/test_mark_pr_ready.pyindex 39d8e5fb2ae2..548eabd7ffe5 100644--- a/products/tasks/backend/temporal/process_task/activities/tests/test_mark_pr_ready.py+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_mark_pr_ready.py@@ -92,7 +92,7 @@ def test_activity_rechecks_run_and_pr_before_requesting_review(monkeypatch, changithub.get_pull_request_babysit_snapshot.side_effect = RuntimeError("unavailable")github.get_pull_request_babysit_snapshot.return_value = rawmonkeypatch.setattr(ready_module.posthoganalytics, "feature_enabled", lambda *args, **kwargs: change != "disabled")- monkeypatch.setattr(ready_module, "get_github_integration", lambda _: github)+ monkeypatch.setattr(ready_module, "get_github_integration", lambda *_: github)with patch.object(ready_module.TaskRun.objects, "filter") as find_run:find_run.return_value.first.side_effect = [run, late_run]assert mark_pr_ready(MarkPrReadyInput(context=context, snapshot=snapshot)) is requesteddiff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_slack_agent_design_flag_activity.py b/products/tasks/backend/temporal/process_task/activities/tests/test_slack_agent_design_flag_activity.pynew file mode 100644index 000000000000..2b336222efeb--- /dev/null+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_slack_agent_design_flag_activity.py@@ -0,0 +1,67 @@+import uuid++from posthog.test.base import BaseTest+from unittest.mock import patch++from parameterized import parameterized++from posthog.models.integration import Integration+from posthog.models.organization import Organization+from posthog.models.team.team import Team++from products.tasks.backend.models import Task, TaskRun+from products.tasks.backend.temporal.process_task.activities.feature_flags import (+ AGENT_DESIGN_STATE_KEY,+ IsSlackAppAgentDesignEnabledForTaskActivityInput,+ is_slack_app_agent_design_enabled_for_task_activity,+)+++class TestIsSlackAppAgentDesignEnabledForTaskActivity(BaseTest):+ def setUp(self) -> None:+ super().setUp()+ self.task = Task.objects.create(+ team=self.team,+ title="Slack task",+ description="From Slack",+ origin_product=Task.OriginProduct.SLACK,+ created_by=self.user,+ )+ self.task_run = TaskRun.objects.create(task=self.task, team=self.team)+ other_org = Organization.objects.create(name="Other org")+ self.other_team = Team.objects.create(organization=other_org, name="Other team")++ def _slack_integration(self, team: Team) -> Integration:+ return Integration.objects.create(team=team, kind="slack", integration_id="T123", config={})++ @parameterized.expand(+ [+ ("same_team", "same_team", True, True),+ ("other_team", "other_team", True, False),+ ("missing_run", "same_team", False, False),+ ]+ )+ def test_evaluates_only_for_the_run_team(+ self, _name: str, integration_team: str, run_exists: bool, expected: bool+ ) -> None:+ integration = self._slack_integration(self.team if integration_team == "same_team" else self.other_team)+ run_id = str(self.task_run.id) if run_exists else str(uuid.uuid4())++ with patch(+ "products.slack_app.backend.feature_flags.posthoganalytics.feature_enabled", return_value=True+ ) as feature_enabled:+ enabled = is_slack_app_agent_design_enabled_for_task_activity(+ IsSlackAppAgentDesignEnabledForTaskActivityInput(integration_id=integration.id, run_id=run_id)+ )++ assert enabled is expected+ if expected:+ feature_enabled.assert_called_once()+ args, kwargs = feature_enabled.call_args+ assert args[1] == self.user.distinct_id+ assert kwargs["groups"] == {"organization": str(self.team.organization_id)}+ else:+ feature_enabled.assert_not_called()+ if run_exists:+ self.task_run.refresh_from_db()+ assert self.task_run.state[AGENT_DESIGN_STATE_KEY] is expecteddiff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.py b/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.pyindex c099df0ad183..4a32345ad14f 100644--- a/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.py+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.py@@ -699,7 +699,7 @@ def _mock_github_integration(mocker, pr_base: str | None):integration.access_token_expired.return_value = Falseintegration.get_open_pr_base_for_head.return_value = pr_basemocker.patch(- "products.tasks.backend.temporal.process_task.activities.start_agent_server.Integration.objects.get",+ "products.tasks.backend.temporal.process_task.activities.start_agent_server.IntegrationManager.github.oauth.get",return_value=mocker.Mock(),)mocker.patch(@@ -803,7 +803,7 @@ def test_resolve_protected_base_branch_for_stacked_run(mocker, stack_base_branchdef test_resolve_protected_base_skips_lookup_without_repository(mocker) -> None:get = mocker.patch(- "products.tasks.backend.temporal.process_task.activities.start_agent_server.Integration.objects.get",+ "products.tasks.backend.temporal.process_task.activities.start_agent_server.IntegrationManager.github.oauth.get",)context = _context(github_integration_id=42, repository=None, branch="some-branch")assert _resolve_protected_base_branch(context) is None@@ -860,7 +860,7 @@ def test_prepare_launch_resolves_protected_base_branch_alongside_preparation(prefix = "products.tasks.backend.temporal.process_task.activities.start_agent_server"_mock_prepare_launch_dependencies(mocker)if lookup_error is not None:- mocker.patch(f"{prefix}.Integration.objects.get", side_effect=lookup_error)+ mocker.patch(f"{prefix}.IntegrationManager.github.oauth.get", side_effect=lookup_error)else:integration = _mock_github_integration(mocker, pr_base=pr_base)if lookup_hangs:@@ -880,7 +880,7 @@ def test_prepare_launch_resolves_protected_base_branch_alongside_preparation(def test_resolve_protected_base_falls_back_to_branch_on_error(mocker) -> None:mocker.patch(- "products.tasks.backend.temporal.process_task.activities.start_agent_server.Integration.objects.get",+ "products.tasks.backend.temporal.process_task.activities.start_agent_server.IntegrationManager.github.oauth.get",side_effect=RuntimeError("boom"),)context = _context(github_integration_id=42, repository="PostHog/posthog", branch="posthog-code/fix")diff --git a/products/tasks/backend/temporal/process_task/utils.py b/products/tasks/backend/temporal/process_task/utils.pyindex 4f38edf0d2a7..269f9491ecd6 100644--- a/products/tasks/backend/temporal/process_task/utils.py+++ b/products/tasks/backend/temporal/process_task/utils.py@@ -16,6 +16,7 @@ from pydantic import BaseModelfrom posthog.dataclasses import frozenfrom posthog.egress.limiter.policies import Priorityfrom posthog.enums import LabeledStrEnum+from posthog.integrations import IntegrationManagerfrom posthog.llm.gateway_client import GatewayNotConfiguredError, ensure_scout_trial_capture_readyfrom posthog.models.github_integration_base import GitHubIntegrationBase, GitHubIntegrationErrorfrom posthog.models.integration import GitHubIntegration, Integration@@ -1031,8 +1032,8 @@ def installation_confirms_repository_denied(github_integration: GitHubIntegratioreturn response.status_code in (403, 404)-def resolve_installation_github_integration(github_integration_id: int) -> GitHubIntegration | None:- integration = Integration.objects.filter(id=github_integration_id, kind="github").first()+def resolve_installation_github_integration(team_id: int, github_integration_id: int) -> GitHubIntegration | None:+ integration = IntegrationManager.github.oauth.get_many(team_id, [github_integration_id]).get(github_integration_id)if integration is None:return Nonereturn GitHubIntegration(integration, source="tasks_sandbox", priority=Priority.CRITICAL)diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.pyindex 12389644fb21..d2db6be5e668 100644--- a/products/tasks/backend/tests/test_api.py+++ b/products/tasks/backend/tests/test_api.py@@ -2824,6 +2824,27 @@ class TestTaskAPI(BaseTaskAPITest):self.assertEqual(response.status_code, status.HTTP_201_CREATED)+ @parameterized.expand([("empty_string",), ("other_team",)])+ def test_create_task_github_integration_reference(self, case: str) -> None:+ github_integration: int | str = ""+ if case == "other_team":+ other_team = Team.objects.create(organization=self.organization, name="Other team")+ github_integration = Integration.objects.create(team=other_team, kind="github", integration_id="999").id++ response = self.client.post(+ "/api/projects/@current/tasks/",+ {"title": "New Task", "description": "New Description", "github_integration": github_integration},+ format="json",+ )++ if case == "empty_string":+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)+ self.assertIsNone(Task.objects.get(id=response.json()["id"]).github_integration_id)+ else:+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertEqual(response.json()["attr"], "github_integration")+ self.assertFalse(Task.objects.filter(title="New Task").exists())+def test_create_task_defaults_origin_product(self):response = self.client.post("/api/projects/@current/tasks/",diff --git a/products/tasks/backend/tests/test_repository_readiness.py b/products/tasks/backend/tests/test_repository_readiness.pyindex 2e6197483ccf..2cba0a8378b8 100644--- a/products/tasks/backend/tests/test_repository_readiness.py+++ b/products/tasks/backend/tests/test_repository_readiness.py@@ -208,12 +208,12 @@ class TestComputeRepositoryReadiness(TestCase):assert result["cacheAgeSeconds"] == 0@patch("products.tasks.backend.repository_readiness._refresh_installation_token")- @patch("products.tasks.backend.repository_readiness.Integration")+ @patch("products.tasks.backend.repository_readiness.IntegrationManager")def test_no_access_token_returns_unknown(self, mock_integration_cls: MagicMock, mock_refresh: MagicMock) -> None:integration = MagicMock()integration.id = 1integration.sensitive_config = {}- mock_integration_cls.objects.filter.return_value.first.return_value = integration+ mock_integration_cls.github.oauth.find.return_value = integrationresult = compute_repository_readiness(team=self.team, repository="org/repo")assert result["overall"] == "unknown"@@ -223,12 +223,12 @@ class TestComputeRepositoryReadiness(TestCase):integration.id = 1integration.kind = "github"integration.sensitive_config = {"access_token": "ghp_test"}- mock_integration_cls.objects.filter.return_value.first.return_value = integration+ mock_integration_cls.github.oauth.find.return_value = integrationreturn integration@patch("products.tasks.backend.repository_readiness._scan_repository")@patch("products.tasks.backend.repository_readiness._refresh_installation_token")- @patch("products.tasks.backend.repository_readiness.Integration")+ @patch("products.tasks.backend.repository_readiness.IntegrationManager")def test_scan_failure_graceful_degradation(self,mock_integration_cls: MagicMock,@@ -248,7 +248,7 @@ class TestComputeRepositoryReadiness(TestCase):@patch("products.tasks.backend.repository_readiness._scan_repository")@patch("products.tasks.backend.repository_readiness._refresh_installation_token")- @patch("products.tasks.backend.repository_readiness.Integration")+ @patch("products.tasks.backend.repository_readiness.IntegrationManager")def test_cache_hit_returns_cache_age(self,mock_integration_cls: MagicMock,@@ -265,7 +265,7 @@ class TestComputeRepositoryReadiness(TestCase):@patch("products.tasks.backend.repository_readiness._scan_repository")@patch("products.tasks.backend.repository_readiness._refresh_installation_token")- @patch("products.tasks.backend.repository_readiness.Integration")+ @patch("products.tasks.backend.repository_readiness.IntegrationManager")def test_refresh_bypasses_cache(self,mock_integration_cls: MagicMock,@@ -282,7 +282,7 @@ class TestComputeRepositoryReadiness(TestCase):@patch("products.tasks.backend.repository_readiness._scan_repository")@patch("products.tasks.backend.repository_readiness._refresh_installation_token")- @patch("products.tasks.backend.repository_readiness.Integration")+ @patch("products.tasks.backend.repository_readiness.IntegrationManager")def test_detected_state_when_code_found_but_settings_off(self,mock_integration_cls: MagicMock,@@ -315,7 +315,7 @@ class TestComputeRepositoryReadiness(TestCase):@patch("products.tasks.backend.repository_readiness._scan_repository")@patch("products.tasks.backend.repository_readiness._refresh_installation_token")- @patch("products.tasks.backend.repository_readiness.Integration")+ @patch("products.tasks.backend.repository_readiness.IntegrationManager")def test_waiting_for_data_when_code_found_and_settings_on(self,mock_integration_cls: MagicMock,@@ -345,7 +345,7 @@ class TestComputeRepositoryReadiness(TestCase):@patch("products.tasks.backend.repository_readiness._scan_repository")@patch("products.tasks.backend.repository_readiness._refresh_installation_token")- @patch("products.tasks.backend.repository_readiness.Integration")+ @patch("products.tasks.backend.repository_readiness.IntegrationManager")def test_needs_setup_when_no_code_evidence(self,mock_integration_cls: MagicMock,@@ -367,7 +367,7 @@ class TestComputeRepositoryReadiness(TestCase):@patch("products.tasks.backend.repository_readiness._fetch_file_content")@patch("products.tasks.backend.repository_readiness._fetch_repository_tree")@patch("products.tasks.backend.repository_readiness._refresh_installation_token")- @patch("products.tasks.backend.repository_readiness.Integration")+ @patch("products.tasks.backend.repository_readiness.IntegrationManager")def test_time_budget_exceeded_returns_partial_results(self,mock_integration_cls: MagicMock,diff --git a/products/tasks/scripts/run_agent_in_docker.py b/products/tasks/scripts/run_agent_in_docker.pyindex 13df4201c0f7..459a720d17e9 100755--- a/products/tasks/scripts/run_agent_in_docker.py+++ b/products/tasks/scripts/run_agent_in_docker.py@@ -25,7 +25,8 @@ django.setup()from django.db import transactionfrom posthog.accessible_teams import AccessibleTeams-from posthog.models import Integration, PersonalAPIKey, Team, User+from posthog.integrations import IntegrationManager+from posthog.models import PersonalAPIKey, Team, Userfrom posthog.personal_api_key_minting import mint_personal_api_keyfrom products.feature_flags.backend.models.feature_flag import FeatureFlag@@ -60,9 +61,11 @@ def create_test_task(repository=None):feature_flag.active = Truefeature_flag.save()- github_integration, _ = Integration.objects.get_or_create(- team=team, kind="github", defaults={"config": {"organization": org, "repositories": [repo]}}- )+ github_integration = IntegrationManager.github.oauth.find(team.id)+ if github_integration is None:+ github_integration = IntegrationManager.github.oauth.create(+ team.id, external_id=None, config={"organization": org, "repositories": [repo]}+ )github_token = (github_integration.sensitive_config.get("access_token") if github_integration.sensitive_config else None@@ -75,7 +78,7 @@ def create_test_task(repository=None):title="Add a joke to the README.md file",description="Add a joke to the README.md file",origin_product=Task.OriginProduct.USER_CREATED,- github_integration=github_integration,+ github_integration_id=github_integration.id,repository=repository,)