:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(tasks): support multiple repositories for tasks and spaces (#76447)
Shy Alter339beefc473a
diff --git a/ee/hogai/api/tests/test_serializers.py b/ee/hogai/api/tests/test_serializers.pyindex 13fa9c939f06..902776ffa5eb 100644--- a/ee/hogai/api/tests/test_serializers.py+++ b/ee/hogai/api/tests/test_serializers.py@@ -345,6 +345,7 @@ class TestConversationSerializerTaskField(APIBaseTest):origin_product=Task.OriginProduct.POSTHOG_AI,runtime=Task.Runtime.ACP,repository=None,+ repositories=[],github_integration=None,github_user_integration=None,signal_report=None,diff --git a/posthog/management/migration_analysis/atomic_false_acknowledged_migrations.txt b/posthog/management/migration_analysis/atomic_false_acknowledged_migrations.txtindex f0072e15432a..5baac068442e 100644--- a/posthog/management/migration_analysis/atomic_false_acknowledged_migrations.txt+++ b/posthog/management/migration_analysis/atomic_false_acknowledged_migrations.txt@@ -16,3 +16,4 @@# posthog.1234_backfill_something_in_batchesposthog.1264_delete_revenue_analytics_user_product_listproduct_analytics.0004_delete_revenue_analytics_insights+tasks.0079_backfill_task_repositoriesdiff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex 8e03114e61d1..cc43924c1a0b 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -28,7 +28,7 @@ from uuid import UUID, uuid4from django.conf import settingsfrom django.core.exceptions import ValidationError as DjangoValidationErrorfrom django.db import IntegrityError, transaction-from django.db.models import CharField, Count, Exists, F, Min, OuterRef, Q, QuerySet, Subquery+from django.db.models import CharField, Count, Exists, F, Func, Min, OuterRef, Q, QuerySet, Subqueryfrom django.db.models.fields.json import KeyTextTransformfrom django.utils import timezone as django_timezone@@ -48,6 +48,9 @@ from products.tasks.backend.constants import (is_blocked_sandbox_env_key,)from products.tasks.backend.error_telemetry import truncate_error_message+from products.tasks.backend.github_repository_access import (+ inaccessible_repositories_via_integration as _inaccessible_repositories_via_integration,+)from products.tasks.backend.logic.services.image_builder import (ensure_image_builder_task,is_custom_images_enabled,@@ -73,6 +76,7 @@ from products.tasks.backend.models import (TaskThreadMessage,TaskThreadMessageMention,)+from products.tasks.backend.pr_urls import merge_pr_outputfrom products.tasks.backend.prompts import build_wizard_pr_agent_prompt, generate_wizard_head_branchfrom products.tasks.backend.visibility import task_control_q, task_run_visibility_q, task_visibility_q@@ -414,6 +418,7 @@ def _task_detail_to_dto(origin_product=task.origin_product,runtime=task.runtime,repository=task.repository,+ repositories=task.repositories or ([task.repository] if task.repository else []),github_integration=task.github_integration_id,github_user_integration=task.github_user_integration_id,signal_report=task.signal_report_id,@@ -1829,6 +1834,8 @@ _PROTECTED_RUN_STATE_KEYS = frozenset({"github_credential_source","pr_authorship_mode",+ "repositories",+ "verified_pr_urls","sandbox_id","sandbox_cpu_cores","sandbox_memory_gb",@@ -2189,7 +2196,8 @@ def update_task_run(existing_output = run.output if isinstance(run.output, dict) else {}# Same attested-key policy as set_task_run_output — this PATCH surface is# caller-controlled too, so it can't be a back door to output.pr_merged.- setattr(run, key, _apply_caller_output(existing_output, value, {**existing_output, **value}))+ merged_output = merge_pr_output(existing_output, value)+ setattr(run, key, _apply_caller_output(existing_output, value, merged_output))update_fields.add(key)continueif key == "state_remove_keys":@@ -2303,9 +2311,7 @@ def set_task_run_output(# Preserve PR facts a webhook may have written concurrently: this assignment is wholesale,# so a bare `= output` would drop output.pr_url recorded out of band.existing = run.output if isinstance(run.output, dict) else {}- merged = {**output}- if not merged.get("pr_url") and existing.get("pr_url"):- merged["pr_url"] = existing["pr_url"]+ merged = merge_pr_output(existing, output)run.output = _apply_caller_output(existing, output, merged)run.save(update_fields=["output", "updated_at"])if task.json_schema:@@ -4003,18 +4009,27 @@ def list_tasks(team_id: int, user_id: int | None, *, filters: dict) -> list[contreturn _tasks_to_dtos(_list_tasks_queryset(team_id, user_id, filters=filters), team_id)+def inaccessible_repositories_via_integration(team_id: int, integration_id: int, repositories: list[str]) -> list[str]:+ return _inaccessible_repositories_via_integration(team_id, integration_id, repositories)++def list_task_repositories(team_id: int, user_id: int | None) -> list[str]:"""Distinct repositories used by non-deleted, non-internal visible tasks for the team."""- repositories = (- Task.objects.filter(team_id=team_id, deleted=False, internal=False)- .filter(task_visibility_q(user_id))+ tasks = Task.objects.filter(team_id=team_id, deleted=False, internal=False).filter(task_visibility_q(user_id))+ plural = (+ tasks.exclude(repositories=[])+ .annotate(repository_name=Func(F("repositories"), function="unnest", output_field=CharField()))+ .values_list("repository_name", flat=True)+ .distinct()+ )+ legacy = (+ tasks.filter(repositories=[]).exclude(repository__isnull=True)- .exclude(repository__exact="")+ .exclude(repository="").values_list("repository", flat=True).distinct()- .order_by("repository"))- return [repo for repo in repositories if repo is not None]+ return sorted(set(plural) | {repository for repository in legacy if repository})def get_task_summaries(team_id: int, user_id: int | None, *, ids: list) -> list[contracts.TaskSummaryDTO]:@@ -4098,6 +4113,15 @@ def create_task(team_id: int, user_id: int | None, *, validated_data: dict) -> cpending_user_message = (validated_data.pop("pending_user_message", None) or "").strip() or Nonepending_user_artifact_ids = validated_data.pop("pending_user_artifact_ids", None) or []warm_auto_publish = validated_data.pop("auto_publish", None)+ channel = validated_data.get("channel")+ if channel is not None and "repositories" not in validated_data and "repository" not in validated_data:+ validated_data["repositories"] = channel.repositories+ validated_data["github_integration"] = channel.github_integration+ if "repositories" in validated_data:+ repositories = validated_data["repositories"]+ validated_data["repository"] = repositories[0] if repositories else None+ elif "repository" in validated_data:+ validated_data["repositories"] = [validated_data["repository"]] if validated_data["repository"] else []if user_id is not None:validated_data["created_by"] = User.objects.get(id=user_id)@@ -4106,6 +4130,7 @@ def create_task(team_id: int, user_id: int | None, *, validated_data: dict) -> cwarm_branch_providedand validated_data["origin_product"] == Task.OriginProduct.USER_CREATEDand validated_data.get("repository")+ and len(validated_data.get("repositories", [])) <= 1and user_id is not None):warm_run = _find_idling_warm_run(@@ -4272,6 +4297,14 @@ def update_task(validated_data.pop("signal_report_task_relationship", None)validated_data.pop("origin_product", None)validated_data.pop("branch", None)+ if "repositories" in validated_data:+ repositories = validated_data["repositories"]+ validated_data["repository"] = repositories[0] if repositories else None+ elif "repository" in validated_data:+ if len(task.repositories) <= 1:+ validated_data["repositories"] = [validated_data["repository"]] if validated_data["repository"] else []+ else:+ validated_data.pop("repository")if "title" in validated_data and "title_manually_set" not in validated_data:validated_data["title_manually_set"] = Trueif "archived" in validated_data and validated_data["archived"] != task.archived:@@ -5336,6 +5369,8 @@ def _channel_to_dto(channel: Channel) -> contracts.ChannelDTO:id=channel.id,name=channel.name,channel_type=channel.channel_type,+ github_integration=channel.github_integration_id,+ repositories=channel.repositories,created_at=channel.created_at,created_by=_user_basic_info(channel.created_by if channel.created_by_id else None),)@@ -5430,20 +5465,41 @@ def resolve_channel(team_id: int, user_id: int | None, *, name: str) -> contractreturn _channel_to_dto(channel)-def rename_channel(channel_id: str | UUID, team_id: int, *, name: str) -> contracts.ChannelDTO | str:- """Rename a public channel. Returns the DTO, or an error kind: ``not_found`` /- ``invalid_name`` / ``personal`` / ``name_taken``."""+def update_channel(+ channel_id: str | UUID,+ team_id: int,+ user_id: int | None,+ *,+ name: str | None = None,+ github_integration: Integration | None = None,+ repositories: list[str] | None = None,+) -> contracts.ChannelDTO | str:+ """Update a channel, keeping repository configuration creator-owned."""channel = Channel.objects.filter(id=channel_id, team_id=team_id, deleted=False).first()if channel is None:return "not_found"if channel.channel_type == Channel.ChannelType.PERSONAL:- return "personal"- normalized = normalize_channel_name(name)- if not normalized:- return "invalid_name"- channel.name = normalized+ if channel.created_by_id != user_id:+ return "not_found"+ if name is not None:+ return "personal"+ elif repositories is not None and channel.created_by_id != user_id:+ return "not_found"+ update_fields: list[str] = []+ if name is not None:+ normalized = normalize_channel_name(name)+ if not normalized:+ return "invalid_name"+ channel.name = normalized+ update_fields.append("name")+ if repositories is not None:+ channel.repositories = repositories+ channel.github_integration = github_integration if repositories else None+ update_fields.extend(["repositories", "github_integration"])+ if not update_fields:+ return _channel_to_dto(channel)try:- channel.save(update_fields=["name", "updated_at"])+ channel.save(update_fields=[*update_fields, "updated_at"])except IntegrityError:return "name_taken"return _channel_to_dto(channel)diff --git a/products/tasks/backend/facade/contracts.py b/products/tasks/backend/facade/contracts.pyindex 0b008a68d5d0..d37e96157cc6 100644--- a/products/tasks/backend/facade/contracts.py+++ b/products/tasks/backend/facade/contracts.py@@ -152,6 +152,7 @@ class TaskDetailDTO:origin_product: strruntime: strrepository: str | None+ repositories: list[str]github_integration: int | Nonegithub_user_integration: UUID | Nonesignal_report: UUID | None@@ -175,6 +176,8 @@ class ChannelDTO:id: UUIDname: strchannel_type: str+ github_integration: int | None+ repositories: list[str]created_at: datetimecreated_by: "TaskUserBasicInfo | None" = Nonediff --git a/products/tasks/backend/facade/loops.py b/products/tasks/backend/facade/loops.pyindex 6952d4ed05db..7ad2491fa5e1 100644--- a/products/tasks/backend/facade/loops.py+++ b/products/tasks/backend/facade/loops.py@@ -35,7 +35,7 @@ from pydantic.dataclasses import dataclassfrom posthog.models import Userfrom posthog.models.file_system.file_system import FileSystem-from posthog.models.integration import GitHubIntegration, Integration+from posthog.models.integration import Integrationfrom posthog.models.organization import OrganizationMembershipfrom posthog.models.scoping import team_scopefrom posthog.models.team.team import Team@@ -43,6 +43,7 @@ from posthog.rbac.user_access_control import AccessControlLevel, UserAccessContrfrom products.mcp_store.backend.facade.api import get_active_installationsfrom products.tasks.backend import loop_service+from products.tasks.backend.github_repository_access import inaccessible_repositories_via_integrationfrom products.tasks.backend.logic.services import loop_runsfrom products.tasks.backend.loop_lifecycle import (pause_loops_for_deactivated_user,@@ -646,20 +647,7 @@ def repository_accessible_via_integration(team_id: int, integration_id: int, fulaccept only an exact match against the resulting list. A missing/invalidated cache is a normalstate, so treating it as permissive would leave the cross-project boundary bypassable; if thelist can't be resolved (refresh error, no snapshot) we reject rather than authorize."""- integration = Integration.objects.filter(team_id=team_id, kind="github", id=integration_id).first()- if integration is None:- return False- normalized = full_name.strip().lower()- try:- repositories = GitHubIntegration(integration).list_all_cached_repositories()- except Exception:- logger.warning(- "loop_repository_access_check_unavailable",- exc_info=True,- extra={"team_id": team_id, "integration_id": integration_id},- )- return False- return any(isinstance(repo, dict) and str(repo.get("full_name", "")).lower() == normalized for repo in repositories)+ return not inaccessible_repositories_via_integration(team_id, integration_id, [full_name])def _desktop_node_exists(team_id: int, node_id: str, *, node_type: str) -> bool:diff --git a/products/tasks/backend/github_repository_access.py b/products/tasks/backend/github_repository_access.pynew file mode 100644index 000000000000..587539bd4853--- /dev/null+++ b/products/tasks/backend/github_repository_access.py@@ -0,0 +1,26 @@+import logging+from collections.abc import Iterable++from posthog.models.integration import GitHubIntegration, Integration++logger = logging.getLogger(__name__)+++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()+ if integration is None:+ return names+ try:+ repositories = GitHubIntegration(integration).list_all_cached_repositories()+ except Exception:+ logger.warning(+ "github_repository_access_check_unavailable",+ exc_info=True,+ extra={"team_id": team_id, "integration_id": integration_id},+ )+ return names+ accessible = {str(repo.get("full_name", "")).lower() for repo in repositories if isinstance(repo, dict)}+ return [full_name for full_name in names if full_name.strip().lower() not in accessible]diff --git a/products/tasks/backend/migrations/0078_task_repositories.py b/products/tasks/backend/migrations/0078_task_repositories.pynew file mode 100644index 000000000000..d1c81ff0146f--- /dev/null+++ b/products/tasks/backend/migrations/0078_task_repositories.py@@ -0,0 +1,21 @@+from django.contrib.postgres.fields import ArrayField+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [("tasks", "0077_taskartifact_export_asset_id")]++ operations = [+ migrations.AddField(+ model_name="task",+ name="repositories",+ field=ArrayField(+ base_field=models.CharField(max_length=255),+ default=list,+ db_default=[],+ blank=True,+ size=None,+ help_text="GitHub repositories available to this task",+ ),+ ),+ ]diff --git a/products/tasks/backend/migrations/0079_backfill_task_repositories.py b/products/tasks/backend/migrations/0079_backfill_task_repositories.pynew file mode 100644index 000000000000..0137b2bf441f--- /dev/null+++ b/products/tasks/backend/migrations/0079_backfill_task_repositories.py@@ -0,0 +1,28 @@+from django.db import migrations+++def backfill_task_repositories(apps, schema_editor):+ while True:+ with schema_editor.connection.cursor() as cursor:+ cursor.execute(+ """+ UPDATE posthog_task+ SET repositories = ARRAY[LOWER(repository)]+ WHERE id IN (+ SELECT id+ FROM posthog_task+ WHERE repositories = '{}' AND repository IS NOT NULL AND repository <> ''+ LIMIT 10000+ )+ """+ )+ if cursor.rowcount == 0:+ return+++class Migration(migrations.Migration):+ atomic = False++ dependencies = [("tasks", "0078_task_repositories")]++ operations = [migrations.RunPython(backfill_task_repositories, migrations.RunPython.noop)]diff --git a/products/tasks/backend/migrations/0080_channel_repository_configuration.py b/products/tasks/backend/migrations/0080_channel_repository_configuration.pynew file mode 100644index 000000000000..b9c4f9a40377--- /dev/null+++ b/products/tasks/backend/migrations/0080_channel_repository_configuration.py@@ -0,0 +1,37 @@+import django.db.models.deletion+from django.contrib.postgres.fields import ArrayField+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("posthog", "1280_alter_integration_kind"),+ ("tasks", "0079_backfill_task_repositories"),+ ]++ operations = [+ migrations.AddField(+ model_name="channel",+ name="github_integration",+ field=models.ForeignKey(+ blank=True,+ limit_choices_to={"kind": "github"},+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ related_name="+",+ to="posthog.integration",+ ),+ ),+ migrations.AddField(+ model_name="channel",+ name="repositories",+ field=ArrayField(+ base_field=models.CharField(max_length=255),+ blank=True,+ db_default=[],+ default=list,+ help_text="GitHub repositories inherited by new tasks in this channel",+ size=None,+ ),+ ),+ ]diff --git a/products/tasks/backend/migrations/max_migration.txt b/products/tasks/backend/migrations/max_migration.txtindex d439c4d16f3a..f44f3bbe89c0 100644--- a/products/tasks/backend/migrations/max_migration.txt+++ b/products/tasks/backend/migrations/max_migration.txt@@ -1 +1 @@-0077_taskartifact_export_asset_id+0080_channel_repository_configurationdiff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.pyindex ccfc3683c117..e6a912279003 100644--- a/products/tasks/backend/models.py+++ b/products/tasks/backend/models.py@@ -89,6 +89,21 @@ class Channel(TeamScopedRootMixin):created_by = models.ForeignKey("posthog.User", on_delete=models.SET_NULL, null=True, blank=True, related_name="+", db_constraint=False)+ github_integration = models.ForeignKey(+ "posthog.Integration",+ on_delete=models.SET_NULL,+ null=True,+ blank=True,+ related_name="+",+ limit_choices_to={"kind": "github"},+ )+ repositories = ArrayField(+ models.CharField(max_length=255),+ default=list,+ db_default=[],+ blank=True,+ help_text="GitHub repositories inherited by new tasks in this channel",+ )deleted = models.BooleanField(default=False)created_at = models.DateTimeField(default=django_timezone.now)updated_at = models.DateTimeField(auto_now=True)@@ -189,6 +204,13 @@ class Task(FileSystemSyncMixin, DeletedMetaFields, models.Model):repository = models.CharField(max_length=255, null=True, blank=True) # Format is organization/repo, for example posthog/posthog-js+ repositories = ArrayField(+ models.CharField(max_length=255),+ default=list,+ db_default=[],+ blank=True,+ help_text="GitHub repositories available to this task",+ )# Channel this task was kicked off in. Legacy tasks (and tasks from non-channel# surfaces) stay NULL. SET_NULL so deleting a channel never deletes its tasks.@@ -347,6 +369,7 @@ class Task(FileSystemSyncMixin, DeletedMetaFields, models.Model):"description": self.description[:500] if self.description else "","origin_product": self.origin_product,"repository": self.repository,+ "repositories": self.repositories or ([self.repository] if self.repository else []),}if properties:all_properties.update(properties)@@ -402,6 +425,7 @@ class Task(FileSystemSyncMixin, DeletedMetaFields, models.Model):state: dict = {} if self.runtime == Task.Runtime.PI else {"mode": mode}if extra_state:state.update({k: v for k, v in extra_state.items() if k != "mode"})+ state.setdefault("repositories", self.repositories or ([self.repository] if self.repository else []))# Pin the stream-routing decision once so every reader/writer agrees for this run's life.if "use_dedicated_stream" not in state:distinct_id = (self.created_by.distinct_id if self.created_by else None) or f"team_{self.team_id}"@@ -2038,6 +2062,9 @@ class TaskRun(models.Model):"run_id": str(self.id),"team_id": self.team_id,"repository": self.task.repository,+ "repositories": (self.state or {}).get("repositories")+ or self.task.repositories+ or ([self.task.repository] if self.task.repository else []),"origin_product": self.task.origin_product,"title": self.task.title,"signal_report_id": str(self.task.signal_report_id) if self.task.signal_report_id else None,diff --git a/products/tasks/backend/pr_urls.py b/products/tasks/backend/pr_urls.pynew file mode 100644index 000000000000..26a4faf017b9--- /dev/null+++ b/products/tasks/backend/pr_urls.py@@ -0,0 +1,21 @@+def read_pr_urls(output: object) -> list[str]:+ if not isinstance(output, dict):+ return []++ raw_urls = output.get("pr_urls")+ urls: list[object] = raw_urls if isinstance(raw_urls, list) else []+ pr_url = output.get("pr_url")+ candidates = [*urls, pr_url]+ return list(dict.fromkeys(url for url in candidates if isinstance(url, str) and url))+++def merge_pr_output(existing: object, incoming: dict) -> dict:+ current = existing if isinstance(existing, dict) else {}+ merged = {**current, **incoming}+ urls = list(dict.fromkeys([*read_pr_urls(incoming), *read_pr_urls(current)]))+ if not urls:+ return merged++ primary = incoming.get("pr_url") or current.get("pr_url") or urls[0]+ ordered = [primary, *(url for url in urls if url != primary)]+ return {**merged, "pr_url": primary, "pr_urls": ordered}diff --git a/products/tasks/backend/presentation/serializers.py b/products/tasks/backend/presentation/serializers.pyindex 13fea70e05f5..384d4308e576 100644--- a/products/tasks/backend/presentation/serializers.py+++ b/products/tasks/backend/presentation/serializers.py@@ -376,6 +376,7 @@ class TaskSerializer(DataclassSerializer):"origin_product","runtime","repository",+ "repositories","github_integration","github_user_integration","signal_report",@@ -430,6 +431,12 @@ class TaskWriteSerializer(serializers.Serializer):allow_null=True,help_text="Target GitHub repository in `organization/repo` format (e.g. `posthog/posthog-js`).",)+ repositories = serializers.ListField(+ child=serializers.CharField(max_length=255),+ required=False,+ 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-fieldqueryset=Integration.objects.filter(kind="github"),required=False,@@ -632,6 +639,12 @@ class TaskWriteSerializer(serializers.Serializer):return value.lower()+ def validate_repositories(self, value: list[str]) -> list[str]:+ repositories = [self.validate_repository(repository) for repository in value]+ if len(set(repositories)) != len(repositories):+ raise serializers.ValidationError("Repositories must be unique")+ return repositories+def validate_signal_report(self, value):if value and value.team_id != self.context["team"].id:raise serializers.ValidationError("Signal report must belong to the same team")@@ -647,6 +660,28 @@ class TaskWriteSerializer(serializers.Serializer):return normalizeddef validate(self, attrs: dict) -> dict:+ if "repository" in attrs and "repositories" in attrs:+ legacy = attrs["repository"] or None+ repositories = attrs["repositories"]+ if legacy != (repositories[0] if repositories else None):+ raise serializers.ValidationError({"repositories": "Conflicts with repository"})+ repositories = attrs.get("repositories")+ plural_repositories = repositories+ if repositories is None and "repository" in attrs:+ repositories = [attrs["repository"]] if attrs["repository"] else []+ if plural_repositories and attrs.get("github_integration") is None:+ instance_integration = getattr(self.instance, "github_integration", None)+ if instance_integration is None:+ raise serializers.ValidationError({"github_integration": "Required when repositories are configured"})+ integration = attrs.get("github_integration") or getattr(self.instance, "github_integration", None)+ if repositories and integration:+ inaccessible = tasks_facade.inaccessible_repositories_via_integration(+ self.context["team"].id, integration.id, repositories+ )+ if inaccessible:+ raise serializers.ValidationError(+ {"repositories": f"Not accessible via the selected GitHub integration: {', '.join(inaccessible)}"}+ )if "runtime" in self.initial_data and "runtime" not in self.fields:raise serializers.ValidationError({"runtime": "Runtime cannot be changed after task creation."})@@ -1414,7 +1449,15 @@ class ChannelSerializer(DataclassSerializer):class Meta:dataclass = ChannelDTO- fields = ["id", "name", "channel_type", "created_at", "created_by"]+ fields = [+ "id",+ "name",+ "channel_type",+ "github_integration",+ "repositories",+ "created_at",+ "created_by",+ ]class ChannelWriteSerializer(serializers.Serializer):@@ -1425,6 +1468,56 @@ class ChannelWriteSerializer(serializers.Serializer):)+class ChannelUpdateSerializer(serializers.Serializer):+ name = serializers.CharField(+ max_length=128,+ required=False,+ help_text="Channel name, rendered as #<name>. Normalized to lowercase-dashed.",+ )+ github_integration = TeamScopedPrimaryKeyRelatedField(+ queryset=Integration.objects.filter(kind="github"),+ required=False,+ allow_null=True,+ help_text="Team GitHub integration used for repositories linked to this channel.",+ )+ repositories = serializers.ListField(+ child=serializers.CharField(max_length=255),+ required=False,+ max_length=10,+ help_text="GitHub repositories inherited by new tasks in this channel.",+ )++ 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):+ raise serializers.ValidationError("Repositories must be unique")+ return repositories++ def validate(self, attrs: dict) -> dict:+ repositories = attrs.get("repositories")+ integration = attrs.get("github_integration")+ if repositories is None:+ if "github_integration" in attrs:+ raise serializers.ValidationError({"repositories": "Required when changing the GitHub integration"})+ return attrs+ if repositories and integration is None:+ raise serializers.ValidationError({"github_integration": "Required when repositories are configured"})+ if repositories and integration:+ inaccessible = tasks_facade.inaccessible_repositories_via_integration(+ self.context["team_id"], integration.id, repositories+ )+ if inaccessible:+ raise serializers.ValidationError(+ {"repositories": f"Not accessible via the selected GitHub integration: {', '.join(inaccessible)}"}+ )+ return attrs++class TaskThreadMessageSerializer(DataclassSerializer):"""Response shape for one message in a task's thread."""diff --git a/products/tasks/backend/presentation/views/channels_api.py b/products/tasks/backend/presentation/views/channels_api.pyindex deea7f7f75e9..0c14b9246c4a 100644--- a/products/tasks/backend/presentation/views/channels_api.py+++ b/products/tasks/backend/presentation/views/channels_api.py@@ -20,6 +20,7 @@ from products.tasks.backend.presentation.serializers import (ChannelFeedMessageSerializer,ChannelFeedMessageWriteSerializer,ChannelSerializer,+ ChannelUpdateSerializer,ChannelWriteSerializer,TaskActivityMarkReadResponseSerializer,TaskActivityMarkReadSerializer,@@ -76,14 +77,14 @@ class ChannelViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):return Response(ChannelSerializer(channel).data)@extend_schema(- request=ChannelWriteSerializer,+ request=ChannelUpdateSerializer,responses={200: ChannelSerializer},summary="Rename a public channel",)def partial_update(self, request, pk=None, **kwargs):- serializer = ChannelWriteSerializer(data=request.data)+ serializer = ChannelUpdateSerializer(data=request.data, context={"team_id": self.team_id}, partial=True)serializer.is_valid(raise_exception=True)- result = tasks_facade.rename_channel(pk, self.team_id, name=serializer.validated_data["name"])+ result = tasks_facade.update_channel(pk, self.team_id, self._user_id(), **serializer.validated_data)if result == "not_found":raise NotFound()if result == "personal":diff --git a/products/tasks/backend/temporal/execute_sandbox/workflow.py b/products/tasks/backend/temporal/execute_sandbox/workflow.pyindex fbc2b62daedb..8fc1ff6b5e8f 100644--- a/products/tasks/backend/temporal/execute_sandbox/workflow.py+++ b/products/tasks/backend/temporal/execute_sandbox/workflow.py@@ -1095,28 +1095,38 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):can_clone_without_integration = is_public_sandbox_repo(prepared.repository)has_clone_credentials = self.context.has_github_credentials or can_clone_without_integration- will_clone = bool(prepared.repository and not used_snapshot and has_clone_credentials)- will_checkout = bool(prepared.repository and prepared.branch and has_clone_credentials)+ repositories_to_clone = [] if used_snapshot or not has_clone_credentials else self.context.repositories+ will_clone = bool(repositories_to_clone)+ checkout_repository = self.context.repositories[0] if len(self.context.repositories) == 1 else None+ will_checkout = bool(checkout_repository and prepared.branch and has_clone_credentials)if will_clone:await self._emit_progress("clone", "in_progress", "Cloning repository", "setup")- await workflow.execute_activity(- clone_repository_in_sandbox,- CloneRepositoryInSandboxInput(- context=self.context,- sandbox_id=created.sandbox_id,- repository=prepared.repository,- github_token=prepared.github_token,- shallow_clone=prepared.shallow_clone,- ),- start_to_close_timeout=timedelta(minutes=5),- retry_policy=RetryPolicy(maximum_attempts=3),+ await asyncio.gather(+ *(+ workflow.execute_activity(+ clone_repository_in_sandbox,+ CloneRepositoryInSandboxInput(+ context=self.context,+ sandbox_id=created.sandbox_id,+ repository=repository,+ github_token=prepared.github_token,+ shallow_clone=prepared.shallow_clone,+ ),+ start_to_close_timeout=timedelta(minutes=5),+ retry_policy=RetryPolicy(maximum_attempts=3),+ )+ for repository in repositories_to_clone+ ))- await self._emit_progress("clone", "completed", "Cloned repository", "setup")+ clone_label = "Cloned repository" if len(repositories_to_clone) == 1 else "Cloned repositories"+ await self._emit_progress("clone", "completed", clone_label, "setup")state = self.context.state or {}is_resume = bool(state.get("resume_from_run_id") or state.get("handoff_resumed"))if will_checkout and not is_resume:+ assert checkout_repository is not None+ assert prepared.branch is not Nonebranch_label_active = f"Checking out branch {prepared.branch}"branch_label_done = f"Checked out branch {prepared.branch}"await self._emit_progress("checkout", "in_progress", branch_label_active, "setup")@@ -1125,7 +1135,7 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):CheckoutBranchInSandboxInput(context=self.context,sandbox_id=created.sandbox_id,- repository=prepared.repository,+ repository=checkout_repository,branch=prepared.branch,github_token=prepared.github_token,shallow_clone=prepared.shallow_clone,diff --git a/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py b/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.pyindex 386ae0b3caa5..300f9138eba9 100644--- a/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py+++ b/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py@@ -125,6 +125,13 @@ class TaskProcessingContext:def has_github_credentials(self) -> bool:return self.github_integration_id is not None or self.github_user_integration_id is not None+ @property+ def repositories(self) -> list[str]:+ repositories = (self.state or {}).get("repositories")+ if isinstance(repositories, list) and all(isinstance(repository, str) for repository in repositories):+ return repositories+ return [self.repository] if self.repository else []+@propertydef github_read_access(self) -> bool:"""Repo-less run that asked for a read-only GitHub token (see Task.create_and_run)."""@@ -798,12 +805,15 @@ def get_task_processing_context(input: GetTaskProcessingContextInput) -> TaskPro"falling back to the environment or default base image",)+ repositories = state.get("repositories")+ run_repository = repositories[0] if isinstance(repositories, list) and repositories else task.repository+log_with_activity_context("Task processing context created",task_id=str(task.id),run_id=run_id,team_id=task.team_id,- repository=task.repository,+ repository=run_repository,origin_product=task.origin_product,environment=task_run.environment,distinct_id=distinct_id,@@ -965,7 +975,7 @@ def get_task_processing_context(input: GetTaskProcessingContextInput) -> TaskProorganization_id=str(task.team.organization_id),github_integration_id=task.github_integration_id,github_user_integration_id=user_github_integration_id,- repository=task.repository,+ repository=run_repository,distinct_id=distinct_id,origin_product=task.origin_product,task_runtime=task.runtime,diff --git a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.pyindex 8a18ac21198d..12bd8747056f 100644--- a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py+++ b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py@@ -432,7 +432,7 @@ def prepare_sandbox_for_repository(input: PrepareSandboxForRepositoryInput) -> P"prepare_sandbox_for_repository",**ctx.to_log_context(),):- has_repo = ctx.repository is not None+ has_repo = bool(ctx.repositories)repository = ctx.repositorysnapshot = None@@ -443,9 +443,8 @@ def prepare_sandbox_for_repository(input: PrepareSandboxForRepositoryInput) -> P# Repo-setup snapshots come from default-base sandboxes; restoring one would silently# drop the custom base image. Resume snapshots were taken from this task's own sandbox.if has_repo and ctx.github_integration_id is not None and not ctx.custom_image_name:- assert repository is not Nonewith StepTimer("snapshot_lookup") as snapshot_lookup_timer:- snapshot = SandboxSnapshot.get_latest_snapshot_with_repos(ctx.github_integration_id, [repository])+ snapshot = SandboxSnapshot.get_latest_snapshot_with_repos(ctx.github_integration_id, ctx.repositories)used_snapshot = snapshot is not Nonesnapshot_lookup_timer.set_used_snapshot(used_snapshot)if snapshot is not None:@@ -464,8 +463,9 @@ def prepare_sandbox_for_repository(input: PrepareSandboxForRepositoryInput) -> Pshallow_clone = task.origin_product != Task.OriginProduct.SIGNAL_REPORTactor_user = get_task_run_credential_user(task, ctx.state)+ credential_repository = repository or (ctx.repositories[0] if ctx.repositories else None)github_token = _resolve_sandbox_github_token(- ctx, task=task, actor_user=actor_user, repository=repository, has_repo=has_repo+ ctx, task=task, actor_user=actor_user, repository=credential_repository, has_repo=has_repo)try: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 4626866cbec8..148f3d61104d 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@@ -109,26 +109,26 @@ def _ensure_repository_on_disk(ctx: TaskProcessingContext, sandbox: SandboxBase)repeated 5-minute attempts surfacing as a misleading "Failed to start agent server". Checkthe directory upfront and fail non-retryably with the actual reason instead."""- if not ctx.repository:+ if not ctx.repositories:return- repo_path = sandbox_repo_path(ctx.repository)- result = sandbox.execute(f"test -d {shlex.quote(repo_path)}", timeout_seconds=10)- if result.exit_code == 0:- return- raise SandboxMissingRepositoryError(- f"Repository {ctx.repository} is not present in the sandbox at {repo_path} — it was never "- "cloned (no snapshot restored and no usable GitHub credentials for this task)",- {- "task_id": ctx.task_id,- "run_id": ctx.run_id,- "sandbox_id": sandbox.id,- "repository": ctx.repository,- "repo_path": repo_path,- "github_integration_id": ctx.github_integration_id,- "github_user_integration_id": ctx.github_user_integration_id,- },- cause=RuntimeError(f"missing repository directory {repo_path}"),- )+ for repository in ctx.repositories:+ repo_path = sandbox_repo_path(repository)+ result = sandbox.execute(f"test -d {shlex.quote(repo_path)}", timeout_seconds=10)+ if result.exit_code != 0:+ raise SandboxMissingRepositoryError(+ f"Repository {repository} is not present in the sandbox at {repo_path} — it was never "+ "cloned (no snapshot restored and no usable GitHub credentials for this task)",+ {+ "task_id": ctx.task_id,+ "run_id": ctx.run_id,+ "sandbox_id": sandbox.id,+ "repository": repository,+ "repo_path": repo_path,+ "github_integration_id": ctx.github_integration_id,+ "github_user_integration_id": ctx.github_user_integration_id,+ },+ cause=RuntimeError(f"missing repository directory {repo_path}"),+ )@dataclass@@ -332,7 +332,7 @@ def _invoke_start_agent_server() -> None:try:sandbox.start_agent_server(- repository=ctx.repository,+ repository=ctx.repository if len(ctx.repositories) <= 1 else None,task_id=ctx.task_id,run_id=ctx.run_id,mode=ctx.mode,diff --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 030259e9ac91..4a3d91f9db68 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@@ -111,6 +111,24 @@ def test_ensure_repository_on_disk_passes_when_repo_present(mocker) -> None:assert sandbox_repo_path("PostHog/posthog") in sandbox.execute.call_args.args[0]+def test_ensure_every_repository_is_on_disk(mocker) -> None:+ sandbox = mocker.Mock()+ sandbox.execute.return_value = ExecutionResult(stdout="", stderr="", exit_code=0)++ _ensure_repository_on_disk(+ _context(+ repository="PostHog/posthog",+ state={"repositories": ["PostHog/posthog", "PostHog/posthog-js"]},+ ),+ sandbox,+ )++ assert [call.args[0] for call in sandbox.execute.call_args_list] == [+ f"test -d {sandbox_repo_path('PostHog/posthog')}",+ f"test -d {sandbox_repo_path('PostHog/posthog-js')}",+ ]++def test_ensure_repository_on_disk_fails_non_retryably_when_repo_missing(mocker) -> None:# Without this, a run whose repo was never cloned (no snapshot, no GitHub credentials) burns# repeated 5-minute health-check timeouts and fails with a misleading "Failed to start agentdiff --git a/products/tasks/backend/temporal/process_task/tests/test_workflow.py b/products/tasks/backend/temporal/process_task/tests/test_workflow.pyindex 6f552b702ed3..2863f388bd95 100644--- a/products/tasks/backend/temporal/process_task/tests/test_workflow.py+++ b/products/tasks/backend/temporal/process_task/tests/test_workflow.py@@ -1390,6 +1390,52 @@ class TestProcessTaskWorkflowUnit:assert inject_fresh_tokens_on_resume not in activity_calls+ async def test_get_sandbox_for_repository_clones_every_repository(self, monkeypatch):+ workflow = ProcessTaskWorkflow()+ workflow._context = _build_context(+ github_integration_id=123,+ state={"repositories": ["posthog/posthog", "posthog/code"]},+ )+ prepared = PrepareSandboxForRepositoryOutput(+ sandbox_name="sandbox-name",+ repository="posthog/posthog",+ github_token="ghs_token",+ branch=None,+ environment_variables={},+ snapshot_id=None,+ snapshot_external_id=None,+ used_snapshot=False,+ should_create_snapshot=True,+ shallow_clone=True,+ image_source="base_image",+ image_source_label="published sandbox base image",+ )+ created = CreateSandboxForRepositoryOutput(+ sandbox_id="sandbox-123",+ sandbox_url="https://sandbox.example",+ connect_token="connect-token",+ )+ cloned: list[str] = []++ async def fake_execute_activity(activity_fn, *args, **kwargs):+ if activity_fn is prepare_sandbox_for_repository:+ return prepared+ if activity_fn is create_sandbox_for_repository:+ return created+ if activity_fn is clone_repository_in_sandbox:+ cloned.append(args[0].repository)+ return None+ if activity_fn is emit_progress_activity:+ return None+ raise AssertionError(f"Unexpected activity call: {activity_fn}")++ monkeypatch.setattr(process_task_workflow_module.workflow, "execute_activity", fake_execute_activity)++ result = await workflow._get_sandbox_for_repository()++ assert cloned == ["posthog/posthog", "posthog/code"]+ assert result.clone_ms is None+@pytest.mark.parametrize("custom_image_name, expected_image_source, expected_image_source_label",[diff --git a/products/tasks/backend/temporal/process_task/workflow.py b/products/tasks/backend/temporal/process_task/workflow.pyindex 731b0dc15f05..c2f31312be09 100644--- a/products/tasks/backend/temporal/process_task/workflow.py+++ b/products/tasks/backend/temporal/process_task/workflow.py@@ -1264,8 +1264,10 @@ class ProcessTaskWorkflow(PostHogWorkflow):can_clone_without_integration = is_public_sandbox_repo(prepared.repository)has_clone_credentials = self.context.has_github_credentials or can_clone_without_integration- will_clone = bool(prepared.repository and not used_snapshot and has_clone_credentials)- will_checkout = bool(prepared.repository and prepared.branch and has_clone_credentials)+ repositories_to_clone = [] if used_snapshot or not has_clone_credentials else self.context.repositories+ will_clone = bool(repositories_to_clone)+ checkout_repository = self.context.repositories[0] if len(self.context.repositories) == 1 else None+ will_checkout = bool(checkout_repository and prepared.branch and has_clone_credentials)overlap = bool(self.context.overlap_clone_boot_enabled and will_clone)boot_path = "overlap" if overlap else "classic"@@ -1278,26 +1280,37 @@ class ProcessTaskWorkflow(PostHogWorkflow):clone_ms: int | None = Noneif will_clone:await self._emit_progress("clone", "in_progress", "Cloning repository", "setup")- clone_output = await workflow.execute_activity(- clone_repository_in_sandbox,- CloneRepositoryInSandboxInput(- context=self.context,- sandbox_id=created.sandbox_id,- repository=prepared.repository,- github_token=prepared.github_token,- shallow_clone=prepared.shallow_clone,- ),- start_to_close_timeout=timedelta(minutes=5),- retry_policy=RetryPolicy(maximum_attempts=3),+ clone_outputs = await asyncio.gather(+ *(+ workflow.execute_activity(+ clone_repository_in_sandbox,+ CloneRepositoryInSandboxInput(+ context=self.context,+ sandbox_id=created.sandbox_id,+ repository=repository,+ github_token=prepared.github_token,+ shallow_clone=prepared.shallow_clone,+ ),+ start_to_close_timeout=timedelta(minutes=5),+ retry_policy=RetryPolicy(maximum_attempts=3),+ )+ for repository in repositories_to_clone+ ))- # Pre-rollout histories (and mocked tests) recorded a null result here.- clone_ms = getattr(clone_output, "clone_ms", None)- await self._emit_progress("clone", "completed", "Cloned repository", "setup")+ clone_durations: list[int] = []+ for clone_output in clone_outputs:+ if (duration := getattr(clone_output, "clone_ms", None)) is not None:+ clone_durations.append(duration)+ clone_ms = sum(clone_durations) if clone_durations else None+ clone_label = "Cloned repository" if len(repositories_to_clone) == 1 else "Cloned repositories"+ await self._emit_progress("clone", "completed", clone_label, "setup")state = self.context.state or {}is_resume = bool(state.get("resume_from_run_id") or state.get("handoff_resumed"))checkout_ms: int | None = Noneif will_checkout and not is_resume:+ assert checkout_repository is not None+ assert prepared.branch is not Nonebranch_label_active = f"Checking out branch {prepared.branch}"branch_label_done = f"Checked out branch {prepared.branch}"await self._emit_progress("checkout", "in_progress", branch_label_active, "setup")@@ -1306,7 +1319,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):CheckoutBranchInSandboxInput(context=self.context,sandbox_id=created.sandbox_id,- repository=prepared.repository,+ repository=checkout_repository,branch=prepared.branch,github_token=prepared.github_token,shallow_clone=prepared.shallow_clone,diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.pyindex a24346f52461..3c5cd8d78ff6 100644--- a/products/tasks/backend/tests/test_api.py+++ b/products/tasks/backend/tests/test_api.py@@ -1313,8 +1313,83 @@ class TestTaskAPI(BaseTaskAPITest):self.assertEqual(data["title"], "New Task")self.assertEqual(data["description"], "New Description")self.assertEqual(data["repository"], "posthog/posthog")+ self.assertEqual(data["repositories"], ["posthog/posthog"])self.assertEqual(data["runtime"], Task.Runtime.ACP)+ @patch("products.tasks.backend.facade.api._find_idling_warm_run")+ def test_create_task_with_multiple_repositories(self, mock_find_warm_run):+ mock_find_warm_run.return_value = None+ integration = Integration.objects.create(+ team=self.team,+ kind="github",+ integration_id="123",+ repository_cache=[+ {"id": 1, "name": "posthog", "full_name": "posthog/posthog"},+ {"id": 2, "name": "code", "full_name": "posthog/code"},+ ],+ repository_cache_updated_at=django_timezone.now(),+ )++ response = self.client.post(+ "/api/projects/@current/tasks/",+ {+ "title": "Cross-repo task",+ "description": "Update both services",+ "github_integration": integration.id,+ "repositories": ["PostHog/PostHog", "PostHog/Code"],+ "branch": "main",+ },+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_201_CREATED)+ task = Task.objects.get(id=response.json()["id"])+ self.assertEqual(task.repositories, ["posthog/posthog", "posthog/code"])+ self.assertEqual(task.create_run().state["repositories"], task.repositories)+ mock_find_warm_run.assert_not_called()++ update = self.client.patch(+ f"/api/projects/@current/tasks/{task.id}/",+ {"repository": "posthog/posthog"},+ format="json",+ )+ self.assertEqual(update.status_code, status.HTTP_200_OK)+ task.refresh_from_db()+ self.assertEqual(task.repository, "posthog/posthog")+ self.assertEqual(task.repositories, ["posthog/posthog", "posthog/code"])++ def test_create_task_rejects_repository_outside_integration(self):+ integration = Integration.objects.create(+ team=self.team,+ kind="github",+ integration_id="123",+ repository_cache=[{"id": 1, "name": "posthog", "full_name": "posthog/posthog"}],+ repository_cache_updated_at=django_timezone.now(),+ )++ response = self.client.post(+ "/api/projects/@current/tasks/",+ {+ "title": "Invalid task",+ "github_integration": integration.id,+ "repositories": ["posthog/code"],+ },+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)++ response = self.client.post(+ "/api/projects/@current/tasks/",+ {+ "title": "Invalid legacy task",+ "github_integration": integration.id,+ "repository": "posthog/code",+ },+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+def test_create_task_with_pi_runtime(self):response = self.client.post("/api/projects/@current/tasks/",@@ -3943,6 +4018,7 @@ class TestTaskRepositoriesAction(BaseTaskAPITest):description="",origin_product=Task.OriginProduct.USER_CREATED,repository="posthog/posthog",+ repositories=["posthog/posthog", "posthog/code"],)# Duplicate of an existing repo should be collapsed.Task.objects.create(@@ -3966,7 +4042,7 @@ class TestTaskRepositoriesAction(BaseTaskAPITest):self.assertEqual(response.json(),- {"repositories": ["posthog/posthog", "posthog/posthog-js"]},+ {"repositories": ["posthog/code", "posthog/posthog", "posthog/posthog-js"]},)def test_excludes_soft_deleted_tasks(self):@@ -5333,14 +5409,37 @@ class TestTaskRunAPI(BaseTaskAPITest):self.assertEqual(response.status_code, status.HTTP_200_OK)run.refresh_from_db()+ assert isinstance(run.output, dict)self.assertEqual(run.output,{"head_branch": "posthog-code/update-readme","pr_url": "https://github.com/org/repo/pull/2",+ "pr_urls": ["https://github.com/org/repo/pull/2"],},)+ response = self.client.patch(+ f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/",+ {+ "output": {+ "pr_url": "https://github.com/org/repo/pull/2",+ "pr_urls": [+ "https://github.com/org/repo/pull/2",+ "https://github.com/org/other/pull/3",+ ],+ }+ },+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ run.refresh_from_db()+ self.assertEqual(+ run.output["pr_urls"],+ ["https://github.com/org/repo/pull/2", "https://github.com/org/other/pull/3"],+ )+def test_partial_update_does_not_restore_stale_state(self):task = self.create_task()run = TaskRun.objects.create(diff --git a/products/tasks/backend/tests/test_channels_api.py b/products/tasks/backend/tests/test_channels_api.pyindex 7cfd9bfd52b6..2a420493a155 100644--- a/products/tasks/backend/tests/test_channels_api.py+++ b/products/tasks/backend/tests/test_channels_api.py@@ -9,7 +9,7 @@ from parameterized import parameterizedfrom rest_framework import statusfrom rest_framework.test import APIClient-from posthog.models import Organization, OrganizationMembership, Team, User+from posthog.models import Integration, Organization, OrganizationMembership, Team, Userfrom products.tasks.backend.facade import api as tasks_facadefrom products.tasks.backend.models import Channel, ChannelFeedMessage, Task, TaskActivity, TaskRun, TaskThreadMessage@@ -84,6 +84,32 @@ class ChannelsAPITestCase(TestCase):delete = self.client.delete(f"{self._channels_url()}{personal.id}/")self.assertEqual(delete.status_code, status.HTTP_403_FORBIDDEN)+ @patch("posthog.models.integration.GitHubIntegration.list_all_cached_repositories")+ def test_cannot_configure_someone_elses_personal_channel_repositories(self, list_repositories):+ list_repositories.return_value = [{"full_name": "posthog/posthog"}]+ integration = Integration.objects.create(team=self.team, kind="github", integration_id="1", config={})+ self.client.get(self._channels_url())+ personal = Channel.objects.unscoped().get(team=self.team, channel_type=Channel.ChannelType.PERSONAL)++ other_client = APIClient()+ other_client.force_authenticate(self.other_user)+ sneaky = other_client.patch(+ f"{self._channels_url()}{personal.id}/",+ {"github_integration": integration.id, "repositories": ["posthog/posthog"]},+ format="json",+ )+ self.assertEqual(sneaky.status_code, status.HTTP_404_NOT_FOUND)+ personal.refresh_from_db()+ self.assertEqual(personal.repositories, [])++ owned = self.client.patch(+ f"{self._channels_url()}{personal.id}/",+ {"github_integration": integration.id, "repositories": ["posthog/posthog"]},+ format="json",+ )+ self.assertEqual(owned.status_code, status.HTTP_200_OK, owned.content)+ self.assertEqual(owned.json()["repositories"], ["posthog/posthog"])+def test_task_created_in_public_channel_is_team_visible(self):channel_id = self.client.post(self._channels_url(), {"name": "growth"}).json()["id"]created = self.client.post(@@ -98,6 +124,56 @@ class ChannelsAPITestCase(TestCase):listed = other_client.get(self._tasks_url(), {"channel": channel_id}).json()["results"]self.assertEqual([t["id"] for t in listed], [created.json()["id"]])+ @patch("posthog.models.integration.GitHubIntegration.list_all_cached_repositories")+ def test_new_tasks_inherit_channel_repositories(self, list_repositories):+ list_repositories.return_value = [+ {"full_name": "posthog/posthog"},+ {"full_name": "posthog/posthog-js"},+ ]+ integration = Integration.objects.create(team=self.team, kind="github", integration_id="1", config={})+ channel_id = self.client.post(self._channels_url(), {"name": "growth"}).json()["id"]+ configured = self.client.patch(+ f"{self._channels_url()}{channel_id}/",+ {+ "github_integration": integration.id,+ "repositories": ["posthog/posthog", "posthog/posthog-js"],+ },+ format="json",+ )+ self.assertEqual(configured.status_code, status.HTTP_200_OK, configured.content)++ created = self.client.post(+ self._tasks_url(),+ {"title": "Ship it", "description": "Do the thing", "channel": channel_id},+ )++ self.assertEqual(created.status_code, status.HTTP_201_CREATED, created.content)+ self.assertEqual(created.json()["repositories"], ["posthog/posthog", "posthog/posthog-js"])+ self.assertEqual(created.json()["github_integration"], integration.id)++ @patch("posthog.models.integration.GitHubIntegration.list_all_cached_repositories")+ def test_only_creator_can_configure_public_channel_repositories(self, list_repositories):+ list_repositories.return_value = [{"full_name": "posthog/posthog"}]+ integration = Integration.objects.create(team=self.team, kind="github", integration_id="1", config={})+ channel_id = self.client.post(self._channels_url(), {"name": "growth"}).json()["id"]++ other_client = APIClient()+ other_client.force_authenticate(self.other_user)+ response = other_client.patch(+ f"{self._channels_url()}{channel_id}/",+ {"github_integration": integration.id, "repositories": ["posthog/posthog"]},+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)+ channel = Channel.objects.unscoped().get(id=channel_id)+ self.assertEqual(channel.repositories, [])+ self.assertIsNone(channel.github_integration_id)++ renamed = other_client.patch(f"{self._channels_url()}{channel_id}/", {"name": "renamed"}, format="json")+ self.assertEqual(renamed.status_code, status.HTTP_200_OK, renamed.content)+ self.assertEqual(renamed.json()["name"], "renamed")+def test_public_channel_task_is_readable_but_not_controllable_by_teammates(self):channel_id = self.client.post(self._channels_url(), {"name": "growth"}).json()["id"]created = self.client.post(diff --git a/products/tasks/backend/tests/test_loops_api.py b/products/tasks/backend/tests/test_loops_api.pyindex ede7d4718a2d..2596b2096f44 100644--- a/products/tasks/backend/tests/test_loops_api.py+++ b/products/tasks/backend/tests/test_loops_api.py@@ -972,7 +972,7 @@ class LoopGithubTriggerValidationAPITest(LoopsAPITestCase):def setUp(self) -> None:super().setUp()self.integration = Integration.objects.create(team=self.team, kind="github", integration_id="1", config={})- mock_github = self._start_patch("products.tasks.backend.facade.loops.GitHubIntegration")+ mock_github = self._start_patch("products.tasks.backend.github_repository_access.GitHubIntegration")mock_github.return_value.list_all_cached_repositories.return_value = [{"full_name": "acme/repo"}]def _github_trigger(self, events: list, filters: dict | None = None) -> dict:@@ -1264,7 +1264,7 @@ class LoopInternalFacadeTest(LoopsAPITestCase):},)- @patch("products.tasks.backend.facade.loops.GitHubIntegration")+ @patch("products.tasks.backend.github_repository_access.GitHubIntegration")def test_repository_access_requires_an_exact_cache_match(self, mock_github):integration = Integration.objects.create(team=self.team, kind="github", integration_id="1", config={})mock_github.return_value.list_all_cached_repositories.return_value = [{"full_name": "acme/allowed"}]@@ -1274,7 +1274,7 @@ class LoopInternalFacadeTest(LoopsAPITestCase):)self.assertFalse(loops_facade.repository_accessible_via_integration(self.team.id, integration.id, "acme/other"))- @patch("products.tasks.backend.facade.loops.GitHubIntegration")+ @patch("products.tasks.backend.github_repository_access.GitHubIntegration")def test_repository_access_fails_closed_when_the_repo_list_is_unavailable(self, mock_github):# A cold or invalidated cache that can't be refreshed must reject, not authorize: otherwise a# member could point a loop at another project's private repo reachable by the shared install.diff --git a/products/tasks/backend/tests/test_webhooks.py b/products/tasks/backend/tests/test_webhooks.pyindex dbcbe16ad6dd..dfbe54141a05 100644--- a/products/tasks/backend/tests/test_webhooks.py+++ b/products/tasks/backend/tests/test_webhooks.py@@ -74,6 +74,7 @@ class TestGitHubPRWebhook(TestCase):task=cls.task,team=cls.team,status=TaskRun.Status.COMPLETED,+ state={"verified_pr_urls": ["https://github.com/posthog/posthog/pull/123"]},output={"pr_url": "https://github.com/posthog/posthog/pull/123"},)@@ -197,7 +198,16 @@ class TestGitHubPRWebhook(TestCase):self.assertEqual(response.status_code, 200)run.refresh_from_db()- self.assertEqual(run.output, {"pr_url": "https://github.com/posthog/posthog/pull/10"})+ self.assertEqual(+ run.output,+ {+ "pr_url": "https://github.com/posthog/posthog/pull/10",+ "pr_urls": [+ "https://github.com/posthog/posthog/pull/10",+ "https://github.com/posthog/posthog/pull/11",+ ],+ },+ )def _merged_pr_payload(self, pr_url: str) -> dict:return {@@ -227,7 +237,7 @@ class TestGitHubPRWebhook(TestCase):task=self.task,team=self.team,status=status,- state=state,+ state={**state, "verified_pr_urls": [pr_url]},output={"pr_url": pr_url, **extra_output},)@@ -251,14 +261,14 @@ class TestGitHubPRWebhook(TestCase):task=self.task,team=self.team,status=TaskRun.Status.IN_PROGRESS,- state={"wizard_config": {}},+ state={"wizard_config": {}, "verified_pr_urls": [pr_url]},output={"pr_url": pr_url},)terminal_run = TaskRun.objects.create(task=self.task,team=self.team,status=TaskRun.Status.FAILED,- state={"wizard_config": {}},+ state={"wizard_config": {}, "verified_pr_urls": [pr_url]},output={"pr_url": pr_url},)payload = {@@ -288,7 +298,7 @@ class TestGitHubPRWebhook(TestCase):task=self.task,team=self.team,status=TaskRun.Status.IN_PROGRESS,- state={"wizard_config": {}},+ state={"wizard_config": {}, "verified_pr_urls": [pr_url]},output={"pr_url": pr_url},)@@ -334,7 +344,7 @@ class TestGitHubPRWebhook(TestCase):team=self.team,status=status,environment=environment,- state=state,+ state={**state, "verified_pr_urls": [pr_url]},output={"pr_url": pr_url},)@@ -362,7 +372,7 @@ class TestGitHubPRWebhook(TestCase):task=self.task,team=self.team,status=TaskRun.Status.IN_PROGRESS,- state={"wizard_config": {}},+ state={"wizard_config": {}, "verified_pr_urls": [pr_url]},output={"pr_url": pr_url},)@@ -445,6 +455,7 @@ class TestGitHubPRWebhook(TestCase):run.refresh_from_db()assert run.output is not Noneself.assertEqual(run.output["pr_url"], pr_url)+ self.assertEqual(run.state["verified_pr_urls"], [pr_url])@patch("products.tasks.backend.facade.api.posthoganalytics.feature_enabled", return_value=True)@patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")@@ -563,6 +574,10 @@ class TestGitHubPRWebhook(TestCase):run.refresh_from_db()assert run.output is not Noneself.assertEqual(run.output["pr_url"], existing)+ self.assertEqual(+ run.output["pr_urls"],+ [existing, "https://github.com/posthog/posthog/pull/901"],+ )@patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")def test_invalid_signature_rejected(self, mock_get_secret):@@ -720,6 +735,7 @@ class TestGitHubPRWebhookResolvesSignalReports(TestCase):task=self.task,team=self.team,status=TaskRun.Status.COMPLETED,+ state={"verified_pr_urls": ["https://github.com/posthog/posthog/pull/42"]},output={"pr_url": "https://github.com/posthog/posthog/pull/42"},)self.report = SignalReport.objects.create(@@ -978,6 +994,7 @@ class TestFindTaskRun(TestCase):team=self.team,status=TaskRun.Status.COMPLETED,output={"pr_url": "https://github.com/posthog/posthog/pull/123"},+ state={"verified_pr_urls": ["https://github.com/posthog/posthog/pull/123"]},)result = find_task_run(pr_url="https://github.com/posthog/posthog/pull/123")self.assertEqual(result, task_run)@@ -991,6 +1008,7 @@ class TestFindTaskRun(TestCase):team=self.team,status=TaskRun.Status.IN_PROGRESS,output={"pr_url": pr_url},+ state={"verified_pr_urls": [pr_url]},)# Created later, so a purely newest-first lookup would wrongly pick this one.TaskRun.objects.create(@@ -998,6 +1016,7 @@ class TestFindTaskRun(TestCase):team=self.team,status=TaskRun.Status.COMPLETED,output={"pr_url": pr_url},+ state={"verified_pr_urls": [pr_url]},)self.assertEqual(find_task_run(pr_url=pr_url), active_run)@@ -1008,6 +1027,7 @@ class TestFindTaskRun(TestCase):team=self.team,status=TaskRun.Status.IN_PROGRESS,output={"pr_url": pr_url},+ state={"verified_pr_urls": [pr_url]},)self.assertIsNone(find_task_run(pr_url=pr_url, repository="acme/other"))@@ -1021,12 +1041,29 @@ class TestFindTaskRun(TestCase):result = find_task_run(branch="feature/my-branch", repository="posthog/posthog")self.assertEqual(result, task_run)+ def test_finds_multi_repository_run_from_snapshot(self):+ self.task.repositories = ["posthog/posthog", "posthog/code"]+ self.task.save(update_fields=["repositories"])+ task_run = self.task.create_run(branch="feature/my-branch")+ task_run.output = {"pr_urls": ["https://github.com/posthog/code/pull/123"]}+ task_run.state["verified_pr_urls"] = ["https://github.com/posthog/code/pull/123"]+ task_run.save(update_fields=["output", "state"])++ self.assertEqual(+ find_task_run(+ pr_url="https://github.com/posthog/code/pull/123",+ repository="posthog/code",+ ),+ task_run,+ )+def test_pr_url_takes_priority_over_branch(self):pr_run = TaskRun.objects.create(task=self.task,team=self.team,status=TaskRun.Status.COMPLETED,output={"pr_url": "https://github.com/posthog/posthog/pull/123"},+ state={"verified_pr_urls": ["https://github.com/posthog/posthog/pull/123"]},branch="feature/other-branch",)TaskRun.objects.create(@@ -1042,6 +1079,17 @@ class TestFindTaskRun(TestCase):)self.assertEqual(result, pr_run)+ def test_caller_reported_pr_url_is_not_trusted_for_lookup(self):+ pr_url = "https://github.com/posthog/posthog/pull/123"+ TaskRun.objects.create(+ task=self.task,+ team=self.team,+ status=TaskRun.Status.IN_PROGRESS,+ output={"pr_url": pr_url, "pr_urls": [pr_url]},+ )++ self.assertIsNone(find_task_run(pr_url=pr_url, repository="posthog/posthog"))+def test_falls_back_to_branch_when_pr_url_not_found(self):branch_run = TaskRun.objects.create(task=self.task,@@ -1166,6 +1214,7 @@ class TestGitHubWebhookFanout(TestCase):task=cls.task,team=cls.team,status=TaskRun.Status.COMPLETED,+ state={"verified_pr_urls": ["https://github.com/myorg/myrepo/pull/99"]},output={"pr_url": "https://github.com/myorg/myrepo/pull/99"},)cls.integration = Integration.objects.create(diff --git a/products/tasks/backend/webhooks.py b/products/tasks/backend/webhooks.pyindex 1c4dae8c0722..079000a45dfc 100644--- a/products/tasks/backend/webhooks.py+++ b/products/tasks/backend/webhooks.py@@ -3,7 +3,7 @@ import uuidimport hashlibfrom django.db import transaction-from django.db.models import Case, IntegerField, Value, When+from django.db.models import Case, IntegerField, Q, Value, Whenfrom django.http import HttpResponseimport structlog@@ -18,6 +18,7 @@ from products.signals.backend.models import InvalidStatusTransition, SignalReporfrom products.tasks.backend.facade.api import post_pr_created_thread_update, signal_workflow_completionfrom products.tasks.backend.facade.cancellation import cancel_task_runfrom products.tasks.backend.models import TaskRun+from products.tasks.backend.pr_urls import merge_pr_output, read_pr_urlsfrom products.tasks.backend.prompts import WIZARD_HEAD_BRANCH_PREFIXlogger = structlog.get_logger(__name__)@@ -27,6 +28,14 @@ TASK_RUN_SELECT_RELATED = ("task", "task__created_by", "team")_TERMINAL_RUN_STATUSES = (TaskRun.Status.COMPLETED, TaskRun.Status.FAILED, TaskRun.Status.CANCELLED)+def _run_repository_filter(repository: str) -> Q:+ normalized = repository.strip().lower()+ return Q(state__repositories__contains=[normalized]) | Q(+ state__repositories__isnull=True,+ task__repository__iexact=normalized,+ )++def find_task_run(pr_url: str | None = None,branch: str | None = None,@@ -39,9 +48,9 @@ def find_task_run(# original and its live resume can both claim the same PR URL. Scope to the# webhook's repo and prefer non-terminal runs so merge handling lands on the# run that can still act on it.- runs = TaskRun.objects.filter(output__pr_url=pr_url)+ runs = TaskRun.objects.filter(state__verified_pr_urls__contains=[pr_url])if repository:- runs = runs.filter(task__repository__iexact=repository)+ runs = runs.filter(_run_repository_filter(repository))# Declared type keeps mypy happy: the annotated queryset yields an AnnotatedWith# variant that must not leak into the plain-queryset legs below.task_run: TaskRun | None = (@@ -68,8 +77,8 @@ def find_task_run(# otherwise claim the run before the dedicated leg below is consulted.task_run = (TaskRun.objects.filter(+ _run_repository_filter(repository),branch=branch,- task__repository__iexact=repository,state__wizard_head_branch__isnull=True,).select_related(*TASK_RUN_SELECT_RELATED)@@ -85,8 +94,8 @@ def find_task_run(if branch.startswith(WIZARD_HEAD_BRANCH_PREFIX):task_run = (TaskRun.objects.filter(+ _run_repository_filter(repository),state__wizard_head_branch=branch,- task__repository__iexact=repository,task__deleted=False,).exclude(status__in=_TERMINAL_RUN_STATUSES)@@ -158,6 +167,9 @@ def handle_pull_request_event(payload: dict) -> HttpResponse:branch = pull_request.get("head", {}).get("ref")repository_full_name = (payload.get("repository") or {}).get("full_name")task_run = find_task_run(pr_url=pr_url, branch=branch, repository=repository_full_name)+ claimed_pr_urls = (+ read_pr_urls(task_run.output if isinstance(task_run.output, dict) else {}) if task_run is not None else []+ )logger.info("github_pr_webhook_processed",@@ -193,8 +205,7 @@ def handle_pull_request_event(payload: dict) -> HttpResponse:# Only trust the merge for the run that actually claims this PR URL. The pr_url backstop# above already covers branch-matched internal PRs, so requiring equality here keeps a# same-branch webhook for a different PR from marking this run's PR as merged.- run_output = task_run.output if isinstance(task_run.output, dict) else {}- if run_output.get("pr_url") == pr_url:+ if pr_url in claimed_pr_urls:_record_run_pr_merged(task_run)# Ungated on the pr_url match above: unlike the run-bookkeeping calls, this keys off# task_id (reports_for_task_filter), not output.pr_url, so the same-branch trust rule@@ -205,8 +216,7 @@ def handle_pull_request_event(payload: dict) -> HttpResponse:if task_run and action == "closed" and not merged:# Same trust rule as the merge branch: only the run that claims this PR URL.- run_output = task_run.output if isinstance(task_run.output, dict) else {}- if run_output.get("pr_url") == pr_url:+ if pr_url in claimed_pr_urls:_cancel_wizard_run_on_close(task_run)# Ungated for the same reason as the merge branch's resolve call: a closed-unmerged PR# archives (suppresses) its report so it leaves the inbox instead of lingering.@@ -226,8 +236,8 @@ def _record_run_pr_url(task_run: TaskRun, pr_url: str) -> None:``output.pr_url`` stays empty, so inbox notifications, the CI follow-up loop,and later webhook lookups never resolve the PR."""- recorded = _record_run_output_field(task_run, "pr_url", pr_url, "github_pr_webhook_record_pr_url_failed")- if not recorded and not TaskRun.objects.filter(id=task_run.id, output__pr_url=pr_url).exists():+ recorded = _append_run_pr_url(task_run, pr_url)+ if not recorded and pr_url not in read_pr_urls(task_run.output):returnpost_pr_created_thread_update(task_run, pr_url)if not recorded:@@ -246,6 +256,31 @@ def _record_run_pr_url(task_run: TaskRun, pr_url: str) -> None:logger.warning("github_pr_webhook_pr_events_failed", run_id=str(task_run.id), exc_info=True)+def _append_run_pr_url(task_run: TaskRun, pr_url: str) -> bool:+ try:+ with transaction.atomic():+ locked = TaskRun.objects.select_for_update().get(id=task_run.id)+ state = locked.state if isinstance(locked.state, dict) else {}+ existing_verified = state.get("verified_pr_urls")+ verified_pr_urls = list(+ dict.fromkeys([*(existing_verified if isinstance(existing_verified, list) else []), pr_url])+ )+ locked.state = {**state, "verified_pr_urls": verified_pr_urls}+ if pr_url in read_pr_urls(locked.output):+ locked.save(update_fields=["state", "updated_at"])+ task_run.state = locked.state+ task_run.output = locked.output+ return False+ locked.output = merge_pr_output(locked.output, {"pr_urls": [pr_url]})+ locked.save(update_fields=["state", "output", "updated_at"])+ task_run.state = locked.state+ task_run.output = locked.output+ return True+ except Exception:+ logger.warning("github_pr_webhook_record_pr_url_failed", run_id=str(task_run.id), exc_info=True)+ return False++def _record_run_pr_merged(task_run: TaskRun) -> None:"""Persist ``output.pr_merged`` when the run's PR is merged.diff --git a/products/tasks/frontend/generated/api.schemas.ts b/products/tasks/frontend/generated/api.schemas.tsindex 47fec8799a6a..a3c070185425 100644--- a/products/tasks/frontend/generated/api.schemas.ts+++ b/products/tasks/frontend/generated/api.schemas.ts@@ -1128,6 +1128,9 @@ export interface ChannelDTOApi {id: stringname: stringchannel_type: string+ /** @nullable */+ github_integration: number | null+ repositories: string[]created_at: stringcreated_by?: TaskUserBasicInfoApi | null}@@ -1203,15 +1206,23 @@ export interface ChannelFeedMessageWriteApi {created_at?: string}-/**- * Request body for creating (resolve-or-create) or renaming a public channel.- */-export interface PatchedChannelWriteApi {+export interface PatchedChannelUpdateApi {/*** Channel name, rendered as #<name>. Normalized to lowercase-dashed.* @maxLength 128*/name?: string+ /**+ * Team GitHub integration used for repositories linked to this channel.+ * @nullable+ */+ github_integration?: number | null+ /**+ * GitHub repositories inherited by new tasks in this channel.+ * @maxItems 10+ * @items.maxLength 255+ */+ repositories?: string[]}/**@@ -1411,6 +1422,7 @@ export interface TaskDetailDTOApi {readonly runtime: RuntimeEnumApi/** @nullable */repository: string | null+ repositories: string[]/** @nullable */github_integration: number | null/** @nullable */@@ -1532,6 +1544,12 @@ export interface TaskCreateApi {* @nullable*/repository?: string | null+ /**+ * GitHub repositories available to this task, each in `organization/repo` format.+ * @maxItems 10+ * @items.maxLength 255+ */+ repositories?: string[]/*** GitHub integration for this task.* @nullable@@ -1669,6 +1687,12 @@ export interface TaskWriteApi {* @nullable*/repository?: string | null+ /**+ * GitHub repositories available to this task, each in `organization/repo` format.+ * @maxItems 10+ * @items.maxLength 255+ */+ repositories?: string[]/*** GitHub integration for this task.* @nullable@@ -1791,6 +1815,12 @@ export interface PatchedTaskWriteApi {* @nullable*/repository?: string | null+ /**+ * GitHub repositories available to this task, each in `organization/repo` format.+ * @maxItems 10+ * @items.maxLength 255+ */+ repositories?: string[]/*** GitHub integration for this task.* @nullablediff --git a/products/tasks/frontend/generated/api.ts b/products/tasks/frontend/generated/api.tsindex 1b8f6eae7d87..77d0ee63cacf 100644--- a/products/tasks/frontend/generated/api.ts+++ b/products/tasks/frontend/generated/api.ts@@ -38,7 +38,7 @@ import type {PaginatedTaskRunDetailDTOListApi,PaginatedTaskSummaryDTOListApi,PaginatedTaskThreadMessageDTOListApi,- PatchedChannelWriteApi,+ PatchedChannelUpdateApi,PatchedLoopWriteApi,PatchedSandboxCustomImageUpdateApi,PatchedSandboxEnvironmentWriteApi,@@ -934,14 +934,14 @@ export const getTaskChannelsPartialUpdateUrl = (projectId: string, id: string) =export const taskChannelsPartialUpdate = async (projectId: string,id: string,- patchedChannelWriteApi?: PatchedChannelWriteApi,+ patchedChannelUpdateApi?: PatchedChannelUpdateApi,options?: RequestInit): Promise<ChannelDTOApi> => {return apiMutator<ChannelDTOApi>(getTaskChannelsPartialUpdateUrl(projectId, id), {...options,method: 'PATCH',headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(patchedChannelWriteApi),+ body: JSON.stringify(patchedChannelUpdateApi),})}diff --git a/products/tasks/frontend/generated/api.zod.ts b/products/tasks/frontend/generated/api.zod.tsindex 152d14ffda8e..37525ffd9c98 100644--- a/products/tasks/frontend/generated/api.zod.ts+++ b/products/tasks/frontend/generated/api.zod.ts@@ -1047,15 +1047,26 @@ export const TaskChannelsFeedCreateBody = /* @__PURE__ */ zod*/export const taskChannelsPartialUpdateBodyNameMax = 128-export const TaskChannelsPartialUpdateBody = /* @__PURE__ */ zod- .object({- name: zod- .string()- .max(taskChannelsPartialUpdateBodyNameMax)- .optional()- .describe('Channel name, rendered as #<name>. Normalized to lowercase-dashed.'),- })- .describe('Request body for creating (resolve-or-create) or renaming a public channel.')+export const taskChannelsPartialUpdateBodyRepositoriesItemMax = 255++export const taskChannelsPartialUpdateBodyRepositoriesMax = 10++export const TaskChannelsPartialUpdateBody = /* @__PURE__ */ zod.object({+ name: zod+ .string()+ .max(taskChannelsPartialUpdateBodyNameMax)+ .optional()+ .describe('Channel name, rendered as #<name>. Normalized to lowercase-dashed.'),+ github_integration: zod+ .number()+ .nullish()+ .describe('Team GitHub integration used for repositories linked to this channel.'),+ repositories: zod+ .array(zod.string().max(taskChannelsPartialUpdateBodyRepositoriesItemMax))+ .max(taskChannelsPartialUpdateBodyRepositoriesMax)+ .optional()+ .describe('GitHub repositories inherited by new tasks in this channel.'),+})/*** API for managing tasks within a project. Tasks represent units of work to be performed by an agent.@@ -1064,6 +1075,10 @@ export const tasksCreateBodyTitleMax = 255export const tasksCreateBodyRepositoryMax = 255+export const tasksCreateBodyRepositoriesItemMax = 255++export const tasksCreateBodyRepositoriesMax = 10+export const tasksCreateBodySignalReportTaskRelationshipMax = 200export const tasksCreateBodyBranchMax = 255@@ -1118,6 +1133,11 @@ export const TasksCreateBody = /* @__PURE__ */ zod.max(tasksCreateBodyRepositoryMax).nullish().describe('Target GitHub repository in `organization\/repo` format (e.g. `posthog\/posthog-js`).'),+ repositories: zod+ .array(zod.string().max(tasksCreateBodyRepositoriesItemMax))+ .max(tasksCreateBodyRepositoriesMax)+ .optional()+ .describe('GitHub repositories available to this task, each in `organization\/repo` format.'),github_integration: zod.number().nullish().describe('GitHub integration for this task.'),github_user_integration: zod.uuid()@@ -1219,6 +1239,10 @@ export const tasksUpdateBodyTitleMax = 255export const tasksUpdateBodyRepositoryMax = 255+export const tasksUpdateBodyRepositoriesItemMax = 255++export const tasksUpdateBodyRepositoriesMax = 10+export const tasksUpdateBodySignalReportTaskRelationshipMax = 200export const tasksUpdateBodyBranchMax = 255@@ -1273,6 +1297,11 @@ export const TasksUpdateBody = /* @__PURE__ */ zod.max(tasksUpdateBodyRepositoryMax).nullish().describe('Target GitHub repository in `organization\/repo` format (e.g. `posthog\/posthog-js`).'),+ repositories: zod+ .array(zod.string().max(tasksUpdateBodyRepositoriesItemMax))+ .max(tasksUpdateBodyRepositoriesMax)+ .optional()+ .describe('GitHub repositories available to this task, each in `organization\/repo` format.'),github_integration: zod.number().nullish().describe('GitHub integration for this task.'),github_user_integration: zod.uuid()@@ -1359,6 +1388,10 @@ export const tasksPartialUpdateBodyTitleMax = 255export const tasksPartialUpdateBodyRepositoryMax = 255+export const tasksPartialUpdateBodyRepositoriesItemMax = 255++export const tasksPartialUpdateBodyRepositoriesMax = 10+export const tasksPartialUpdateBodySignalReportTaskRelationshipMax = 200export const tasksPartialUpdateBodyBranchMax = 255@@ -1413,6 +1446,11 @@ export const TasksPartialUpdateBody = /* @__PURE__ */ zod.max(tasksPartialUpdateBodyRepositoryMax).nullish().describe('Target GitHub repository in `organization\/repo` format (e.g. `posthog\/posthog-js`).'),+ repositories: zod+ .array(zod.string().max(tasksPartialUpdateBodyRepositoriesItemMax))+ .max(tasksPartialUpdateBodyRepositoriesMax)+ .optional()+ .describe('GitHub repositories available to this task, each in `organization\/repo` format.'),github_integration: zod.number().nullish().describe('GitHub integration for this task.'),github_user_integration: zod.uuid()diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 347cf0cfa844..7053c7ebdb52 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -13530,6 +13530,9 @@ export namespace Schemas {id: string;name: string;channel_type: string;+ /** @nullable */+ github_integration: number | null;+ repositories: string[];created_at: string;created_by?: TaskUserBasicInfo | null;}@@ -47527,6 +47530,7 @@ export namespace Schemas {readonly runtime: RuntimeEnum;/** @nullable */repository: string | null;+ repositories: string[];/** @nullable */github_integration: number | null;/** @nullable */@@ -49396,15 +49400,23 @@ export namespace Schemas {expected_current_version_id?: string | null;}- /**- * Request body for creating (resolve-or-create) or renaming a public channel.- */- export interface PatchedChannelWrite {+ export interface PatchedChannelUpdate {/*** Channel name, rendered as #<name>. Normalized to lowercase-dashed.* @maxLength 128*/name?: string;+ /**+ * Team GitHub integration used for repositories linked to this channel.+ * @nullable+ */+ github_integration?: number | null;+ /**+ * GitHub repositories inherited by new tasks in this channel.+ * @maxItems 10+ * @items.maxLength 255+ */+ repositories?: string[];}export interface PatchedClusteringJob {@@ -55670,6 +55682,12 @@ export namespace Schemas {* @nullable*/repository?: string | null;+ /**+ * GitHub repositories available to this task, each in `organization/repo` format.+ * @maxItems 10+ * @items.maxLength 255+ */+ repositories?: string[];/*** GitHub integration for this task.* @nullable@@ -70463,6 +70481,12 @@ export namespace Schemas {* @nullable*/repository?: string | null;+ /**+ * GitHub repositories available to this task, each in `organization/repo` format.+ * @maxItems 10+ * @items.maxLength 255+ */+ repositories?: string[];/*** GitHub integration for this task.* @nullable@@ -71544,6 +71568,12 @@ export namespace Schemas {* @nullable*/repository?: string | null;+ /**+ * GitHub repositories available to this task, each in `organization/repo` format.+ * @maxItems 10+ * @items.maxLength 255+ */+ repositories?: string[];/*** GitHub integration for this task.* @nullablediff --git a/services/mcp/src/generated/tasks/api.ts b/services/mcp/src/generated/tasks/api.tsindex 8342310f1ef2..9b33590fc6de 100644--- a/services/mcp/src/generated/tasks/api.ts+++ b/services/mcp/src/generated/tasks/api.ts@@ -818,6 +818,10 @@ export const tasksCreateBodyTitleMax = 255export const tasksCreateBodyRepositoryMax = 255+export const tasksCreateBodyRepositoriesItemMax = 255++export const tasksCreateBodyRepositoriesMax = 10+export const tasksCreateBodySignalReportTaskRelationshipMax = 200export const tasksCreateBodyBranchMax = 255@@ -872,6 +876,11 @@ export const TasksCreateBody = /* @__PURE__ */ zod.max(tasksCreateBodyRepositoryMax).nullish().describe('Target GitHub repository in `organization\/repo` format (e.g. `posthog\/posthog-js`).'),+ repositories: zod+ .array(zod.string().max(tasksCreateBodyRepositoriesItemMax))+ .max(tasksCreateBodyRepositoriesMax)+ .optional()+ .describe('GitHub repositories available to this task, each in `organization\/repo` format.'),github_integration: zod.number().nullish().describe('GitHub integration for this task.'),github_user_integration: zod.string()diff --git a/services/mcp/src/tools/generated/tasks.ts b/services/mcp/src/tools/generated/tasks.tsindex 7c2c11176c26..8c68f48f8b45 100644--- a/services/mcp/src/tools/generated/tasks.ts+++ b/services/mcp/src/tools/generated/tasks.ts@@ -332,6 +332,7 @@ const loopsRunsRetrieve = (): ToolBase<typeof LoopsRunsRetrieveSchema, WithPostHconst TasksCreateSchema = TasksCreateBody.omit({title_manually_set: true,origin_product: true,+ repositories: true,github_integration: true,github_user_integration: true,signal_report: true,