Skip to content

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

feat: Posthog code home tab backend (#61412)

Peter Kirkhamb21e4104f546
diff --git a/.semgrep/rules/idor-team-scoped-models.yaml b/.semgrep/rules/idor-team-scoped-models.yaml
index 5b039af47e21..929028a6cb8c 100644
--- a/.semgrep/rules/idor-team-scoped-models.yaml
+++ b/.semgrep/rules/idor-team-scoped-models.yaml
@@ -71,6 +71,9 @@ rules:
|ChangeRequest
|ClusteringConfig
|ClusteringJob
+ |CodePrSnapshot
+ |CodeWorkflowConfig
+ |CodeWorkstream
|Cohort
|Comment
|Conversation
@@ -310,6 +313,9 @@ rules:
|ChangeRequest
|ClusteringConfig
|ClusteringJob
+ |CodePrSnapshot
+ |CodeWorkflowConfig
+ |CodeWorkstream
|Cohort
|Comment
|Conversation
diff --git a/posthog/models/github_integration_base.py b/posthog/models/github_integration_base.py
index 637d29221b94..4ca1356f30bc 100644
--- a/posthog/models/github_integration_base.py
+++ b/posthog/models/github_integration_base.py
@@ -598,6 +598,168 @@ class GitHubIntegrationBase:
owner, repo, pr_number = parsed
return self.get_pull_request(f"{owner}/{repo}", pr_number)
+ _PR_SNAPSHOT_QUERY = """
+ query($owner: String!, $repo: String!, $number: Int!) {
+ repository(owner: $owner, name: $repo) {
+ pullRequest(number: $number) {
+ number title url state isDraft mergeable updatedAt
+ author { login }
+ reviewDecision
+ reviewRequests(first: 50) {
+ nodes { requestedReviewer { __typename ... on User { login } ... on Team { slug } } }
+ }
+ reviewThreads(first: 100) { nodes { isResolved } }
+ commits(last: 1) { nodes { commit { statusCheckRollup { state } } } }
+ }
+ }
+ }
+ """
+
+ def _gh_graphql(self, query: str, variables: dict[str, Any], *, endpoint: str, timeout: int = 10) -> dict:
+ """Authenticated POST to the GitHub GraphQL API. Returns the ``data`` object.
+
+ Mirrors ``_gh_api_get``'s auth lifecycle: proactive token refresh, one
+ retry on 401 (refresh) or transient network error, and secondary
+ rate-limit detection bubbled up as a retryable ``GitHubIntegrationError``.
+ """
+ url = "https://api.github.com/graphql"
+ try:
+ if self.access_token_expired():
+ self.refresh_access_token()
+ except Exception:
+ logger.warning("GitHubIntegration: token refresh pre-check failed", exc_info=True)
+
+ def post() -> requests.Response:
+ return self._github_api_post(
+ url,
+ endpoint=endpoint,
+ headers={
+ "Accept": "application/vnd.github+json",
+ "Authorization": f"Bearer {self.get_access_token()}",
+ "X-GitHub-Api-Version": "2022-11-28",
+ },
+ json_body={"query": query, "variables": variables},
+ )
+
+ for attempt in range(2):
+ try:
+ response = post()
+ except requests.RequestException as exc:
+ if attempt == 0:
+ logger.info("GitHubIntegration: _gh_graphql retrying network error", exc_info=True)
+ continue
+ raise GitHubIntegrationError(f"GitHubIntegration: _gh_graphql network error on {endpoint}") from exc
+
+ if response.status_code == 401 and attempt == 0:
+ self.refresh_access_token()
+ continue
+ if self._is_secondary_rate_limit(response):
+ retry_after = self._parse_retry_after_seconds(response) or 60.0
+ raise GitHubIntegrationError(
+ f"GitHubIntegration: secondary rate limit on {endpoint}",
+ status_code=response.status_code,
+ is_rate_limit=True,
+ retry_after_seconds=retry_after,
+ )
+ if response.status_code != 200:
+ raise GitHubIntegrationError(
+ f"GitHubIntegration: _gh_graphql {response.status_code} on {endpoint}: {response.text[:300]}",
+ status_code=response.status_code,
+ )
+ body = response.json()
+ data = body.get("data")
+ errors = body.get("errors")
+ if errors:
+ # GitHub can return useful partial data with field-level permission errors.
+ logger.warning("GitHubIntegration: GraphQL partial errors", endpoint=endpoint, errors=errors)
+ if not data:
+ raise GitHubIntegrationError(f"GitHubIntegration: GraphQL errors on {endpoint}: {errors}")
+ return data or {}
+
+ raise GitHubIntegrationError(f"GitHubIntegration: _gh_graphql exhausted retries on {endpoint}")
+
+ @staticmethod
+ def _map_pr_state(gql_state: str | None, is_draft: bool) -> str:
+ if gql_state == "MERGED":
+ return "merged"
+ if gql_state == "CLOSED":
+ return "closed"
+ if is_draft:
+ return "draft"
+ return "open"
+
+ @staticmethod
+ def _map_ci_status(rollup_state: str | None) -> str:
+ if rollup_state == "SUCCESS":
+ return "passing"
+ if rollup_state in ("FAILURE", "ERROR"):
+ return "failing"
+ if rollup_state in ("PENDING", "EXPECTED"):
+ return "pending"
+ return "none"
+
+ @staticmethod
+ def _map_mergeable(gql_mergeable: str | None) -> bool | None:
+ if gql_mergeable == "MERGEABLE":
+ return True
+ if gql_mergeable == "CONFLICTING":
+ return False
+ return None
+
+ def get_pull_request_snapshot(self, pr_url: str) -> dict[str, Any]:
+ """Fetch the classification-relevant PR signals in one GraphQL call.
+
+ On any handled failure returns ``{"success": False, "error": ...}``;
+ rate-limit and unexpected errors raise ``GitHubIntegrationError`` so the
+ caller can back off.
+ """
+ parsed = self.parse_pull_request_url(pr_url)
+ if parsed is None:
+ return {"success": False, "error": f"Invalid GitHub pull request URL: {pr_url}"}
+ owner, repo, pr_number = parsed
+
+ data = self._gh_graphql(
+ self._PR_SNAPSHOT_QUERY,
+ {"owner": owner, "repo": repo, "number": pr_number},
+ endpoint="/graphql:pullRequestSnapshot",
+ )
+ pr = ((data or {}).get("repository") or {}).get("pullRequest")
+ if not pr:
+ return {"success": False, "error": f"Pull request not found: {pr_url}"}
+
+ rollup_nodes = ((pr.get("commits") or {}).get("nodes")) or []
+ rollup_state = None
+ if rollup_nodes:
+ rollup_state = ((rollup_nodes[0].get("commit") or {}).get("statusCheckRollup") or {}).get("state")
+
+ thread_nodes = ((pr.get("reviewThreads") or {}).get("nodes")) or []
+ unresolved_threads = sum(1 for t in thread_nodes if t and t.get("isResolved") is False)
+
+ reviewer_logins: list[str] = []
+ for node in ((pr.get("reviewRequests") or {}).get("nodes")) or []:
+ reviewer = (node or {}).get("requestedReviewer") or {}
+ login = reviewer.get("login") or reviewer.get("slug")
+ if login:
+ reviewer_logins.append(login)
+
+ review_decision = pr.get("reviewDecision")
+ author = (pr.get("author") or {}).get("login")
+
+ return {
+ "success": True,
+ "number": pr.get("number"),
+ "title": pr.get("title") or "",
+ "url": pr.get("url") or pr_url,
+ "state": self._map_pr_state(pr.get("state"), bool(pr.get("isDraft"))),
+ "ci_status": self._map_ci_status(rollup_state),
+ "review_decision": review_decision.lower() if isinstance(review_decision, str) else None,
+ "unresolved_threads": unresolved_threads,
+ "mergeable": self._map_mergeable(pr.get("mergeable")),
+ "author_login": author,
+ "requested_reviewer_logins": reviewer_logins,
+ "updated_at": pr.get("updatedAt"),
+ }
+
def list_repositories(self, *, page: int = 1, per_page: int = 100) -> tuple[list[dict], bool]:
"""List one page of installation repositories from the GitHub API.
diff --git a/posthog/temporal/schedule.py b/posthog/temporal/schedule.py
index 1b2664e877a1..a253e4ebc314 100644
--- a/posthog/temporal/schedule.py
+++ b/posthog/temporal/schedule.py
@@ -88,6 +88,7 @@ from products.error_tracking.backend.temporal.symbol_set_cleanup.schedule import
from products.exports.backend.temporal.subscriptions.types import ScheduleAllSubscriptionsWorkflowInputs
from products.replay_vision.backend.temporal.reconciler import create_replay_vision_reconciler_schedule
from products.signals.backend.temporal.agentic.schedule import create_signals_scout_coordinator_schedule
+from products.tasks.backend.temporal.code_workstreams.schedule import create_evaluate_code_workstreams_schedule
from products.web_analytics.backend.temporal.weekly_digest.types import WAWeeklyDigestInput
from ee.billing.salesforce_enrichment.constants import DEFAULT_CHUNK_SIZE
@@ -661,6 +662,7 @@ schedules = [
create_cleanup_alert_checks_schedule,
create_signals_scout_coordinator_schedule,
create_replay_vision_reconciler_schedule,
+ create_evaluate_code_workstreams_schedule,
]
if settings.CLOUD_DEPLOYMENT:
diff --git a/products/tasks/backend/code_home_api.py b/products/tasks/backend/code_home_api.py
new file mode 100644
index 000000000000..586f75025dc7
--- /dev/null
+++ b/products/tasks/backend/code_home_api.py
@@ -0,0 +1,208 @@
+from datetime import datetime, timedelta
+from typing import cast
+
+from django.db import transaction
+from django.utils import timezone
+
+from rest_framework import status, viewsets
+from rest_framework.authentication import SessionAuthentication
+from rest_framework.decorators import action
+from rest_framework.permissions import IsAuthenticated
+from rest_framework.response import Response
+
+from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.auth import OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication
+from posthog.models.user import User
+from posthog.permissions import APIScopePermission
+
+from .code_workstreams.default_workflow import build_default_bindings
+from .code_workstreams.validation import ValidationDiagnostic, validate_bindings
+from .models import CodeWorkflowConfig, CodeWorkstream, TaskRun
+
+ACTIVE_AGENT_WINDOW = timedelta(minutes=30)
+RUNNING_STATUSES = (TaskRun.Status.QUEUED, TaskRun.Status.IN_PROGRESS)
+
+_AUTH_CLASSES = [SessionAuthentication, PersonalAPIKeyAuthentication, OAuthAccessTokenAuthentication]
+
+
+def _epoch_ms(dt: datetime) -> int:
+ return int(dt.timestamp() * 1000)
+
+
+def _serialize_diagnostic(d: ValidationDiagnostic) -> dict:
+ out = {"severity": d.severity, "code": d.code, "message": d.message}
+ if d.situation_id is not None:
+ out["situationId"] = d.situation_id
+ if d.action_id is not None:
+ out["actionId"] = d.action_id
+ return out
+
+
+def _serialize_config(config: CodeWorkflowConfig) -> dict:
+ return {
+ "id": str(config.id),
+ "version": config.version,
+ "updatedAt": config.updated_at.isoformat(),
+ "bindings": config.bindings,
+ }
+
+
+class CodeWorkflowViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
+ scope_object = "task"
+ authentication_classes = _AUTH_CLASSES
+ permission_classes = [IsAuthenticated, APIScopePermission]
+ hide_api_docs = True
+
+ def _get_or_seed(self) -> CodeWorkflowConfig:
+ config, _ = CodeWorkflowConfig.objects.get_or_create(
+ team=self.team,
+ user=self.request.user,
+ defaults={"bindings": build_default_bindings(), "version": 1},
+ )
+ return config
+
+ def list(self, request, *args, **kwargs):
+ return Response(_serialize_config(self._get_or_seed()))
+
+ @action(detail=False, methods=["post"], url_path="save", required_scopes=["task:write"])
+ def save(self, request, **kwargs):
+ config_in = request.data.get("config") or {}
+ expected_version = request.data.get("expectedVersion")
+ bindings = config_in.get("bindings") or {}
+
+ with transaction.atomic():
+ current, _ = CodeWorkflowConfig.objects.select_for_update().get_or_create(
+ team=self.team,
+ user=self.request.user,
+ defaults={"bindings": build_default_bindings(), "version": 1},
+ )
+ if not isinstance(expected_version, int) or current.version != expected_version:
+ return Response(
+ {"status": "conflict", "config": _serialize_config(current)},
+ status=status.HTTP_409_CONFLICT,
+ )
+
+ result = validate_bindings(bindings)
+ if not result.can_save:
+ return Response(
+ {
+ "status": "invalid",
+ "config": _serialize_config(current),
+ "diagnostics": [_serialize_diagnostic(d) for d in result.diagnostics],
+ },
+ status=status.HTTP_422_UNPROCESSABLE_ENTITY,
+ )
+
+ current.bindings = bindings
+ current.version = current.version + 1
+ current.save(update_fields=["bindings", "version", "updated_at"])
+ return Response({"status": "saved", "config": _serialize_config(current)})
+
+ @action(detail=False, methods=["post"], url_path="reset", required_scopes=["task:write"])
+ def reset(self, request, **kwargs):
+ with transaction.atomic():
+ config, _ = CodeWorkflowConfig.objects.select_for_update().get_or_create(
+ team=self.team,
+ user=self.request.user,
+ defaults={"bindings": build_default_bindings(), "version": 1},
+ )
+ config.bindings = build_default_bindings()
+ config.version = config.version + 1
+ config.save(update_fields=["bindings", "version", "updated_at"])
+ return Response(_serialize_config(config))
+
+
+class CodeHomeViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
+ scope_object = "task"
+ authentication_classes = _AUTH_CLASSES
+ permission_classes = [IsAuthenticated, APIScopePermission]
+ hide_api_docs = True
+
+ def _serialize_workstream(self, ws: CodeWorkstream) -> dict:
+ return {
+ "id": ws.key,
+ "repoName": ws.repo_name,
+ "repoFullPath": ws.repo_full_path,
+ "branch": ws.branch,
+ "prUrl": ws.pr_url,
+ "pr": ws.pr,
+ "tasks": [
+ {
+ "id": t.get("id"),
+ "title": t.get("title"),
+ "status": t.get("status"),
+ "isGenerating": False,
+ "needsPermission": False,
+ }
+ for t in (ws.tasks or [])
+ ],
+ "situations": ws.situations or [],
+ "primarySituation": ws.primary_situation,
+ "lastActivityAt": _epoch_ms(ws.last_activity_at),
+ }
+
+ def _active_agents(self) -> list[dict]:
+ # Active agents are computed live; workstreams are persisted by the worker.
+ cutoff = timezone.now() - ACTIVE_AGENT_WINDOW
+ runs = (
+ TaskRun.objects.filter(
+ team=self.team,
+ task__created_by=cast(User, self.request.user),
+ task__archived=False,
+ task__deleted=False,
+ status__in=RUNNING_STATUSES,
+ updated_at__gte=cutoff,
+ )
+ .select_related("task")
+ .order_by("-updated_at")
+ )
+
+ seen_tasks: set[str] = set()
+ agents: list[dict] = []
+ for run in runs.iterator():
+ task = run.task
+ if str(task.id) in seen_tasks:
+ continue
+ if (run.output or {}).get("pr_url"):
+ continue
+ seen_tasks.add(str(task.id))
+ agents.append(
+ {
+ "taskId": str(task.id),
+ "title": task.title,
+ "repoName": task.repository.split("/")[-1] if task.repository else None,
+ "branch": run.branch,
+ "status": run.status,
+ "lastActivityAt": _epoch_ms(run.updated_at),
+ "needsPermission": False,
+ "cloudPrUrl": None,
+ }
+ )
+ return agents
+
+ def list(self, request, *args, **kwargs):
+ workstreams = CodeWorkstream.objects.filter(team=self.team, user=cast(User, self.request.user))
+ needs_attention = []
+ in_progress = []
+ for ws in workstreams.iterator():
+ serialized = self._serialize_workstream(ws)
+ if ws.state == CodeWorkstream.WorkstreamState.ATTENTION:
+ needs_attention.append(serialized)
+ else:
+ in_progress.append(serialized)
+
+ return Response(
+ {
+ "activeAgents": self._active_agents(),
+ "needsAttention": needs_attention,
+ "inProgress": in_progress,
+ }
+ )
+
+ @action(detail=False, methods=["post"], url_path="refresh", required_scopes=["task:write"])
+ def refresh(self, request, **kwargs):
+ # Deferred import keeps the heavy temporalio dependency off the module import path.
+ from .temporal.code_workstreams.client import trigger_team_code_workstreams_evaluation
+
+ started = trigger_team_code_workstreams_evaluation(self.team.id)
+ return Response({"started": started}, status=status.HTTP_202_ACCEPTED)
diff --git a/products/tasks/backend/code_workstreams/__init__.py b/products/tasks/backend/code_workstreams/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/tasks/backend/code_workstreams/classify.py b/products/tasks/backend/code_workstreams/classify.py
new file mode 100644
index 000000000000..cc35f8a5b23b
--- /dev/null
+++ b/products/tasks/backend/code_workstreams/classify.py
@@ -0,0 +1,76 @@
+from collections.abc import Iterable
+from dataclasses import dataclass
+from typing import Literal, Optional
+
+from .situations import SITUATION_PRIORITY, SituationId
+
+STALE_THRESHOLD_MS = 7 * 24 * 60 * 60 * 1000
+
+PrState = Literal["open", "draft", "merged", "closed"]
+CiStatus = Literal["passing", "failing", "pending", "none"]
+ReviewDecision = Literal["approved", "changes_requested", "review_required"]
+
+
+@dataclass
+class ClassifyPr:
+ state: PrState
+ ci_status: CiStatus
+ review_decision: Optional[ReviewDecision]
+ unresolved_threads: int
+ is_current_user_author: bool
+ mergeable: Optional[bool] = None
+
+
+@dataclass
+class ClassifyInput:
+ has_pr_url: bool
+ pr: Optional[ClassifyPr]
+ branch: Optional[str]
+ last_activity_at: int
+ now: int
+ commits_ahead: Optional[int] = None
+
+
+def classify(input: ClassifyInput) -> set[SituationId]:
+ out: set[SituationId] = set()
+ pr = input.pr
+
+ if pr is not None:
+ if pr.state in ("merged", "closed"):
+ out.add("done")
+ return out
+
+ if pr.ci_status == "failing":
+ out.add("ci_failing")
+ if pr.review_decision == "changes_requested":
+ out.add("changes_requested")
+ if pr.unresolved_threads > 0 and pr.is_current_user_author:
+ out.add("comments_waiting")
+ if (
+ pr.state == "open"
+ and pr.ci_status == "passing"
+ and pr.review_decision == "approved"
+ and pr.mergeable is not False
+ ):
+ out.add("ready_to_merge")
+ if pr.state in ("open", "draft"):
+ out.add("in_review")
+ elif input.has_pr_url:
+ out.add("in_review")
+ elif input.branch:
+ ahead = input.commits_ahead
+ if ahead is None or ahead > 0:
+ out.add("working")
+
+ if input.now - input.last_activity_at > STALE_THRESHOLD_MS:
+ out.add("stale")
+
+ return out
+
+
+def pick_primary_situation(situations: Iterable[SituationId]) -> Optional[SituationId]:
+ present = set(situations)
+ for sid in SITUATION_PRIORITY:
+ if sid in present:
+ return sid
+ return None
diff --git a/products/tasks/backend/code_workstreams/default_workflow.py b/products/tasks/backend/code_workstreams/default_workflow.py
new file mode 100644
index 000000000000..677d8c507b56
--- /dev/null
+++ b/products/tasks/backend/code_workstreams/default_workflow.py
@@ -0,0 +1,51 @@
+from .situations import SITUATION_IDS
+
+_DEFAULT_BINDINGS: dict[str, list[dict]] = {
+ "working": [
+ {
+ "id": "create_pr",
+ "label": "Create PR",
+ "skillId": "",
+ "prompt": "Open a PR for the current branch. Use the task history to write a concise description.",
+ },
+ ],
+ "in_review": [],
+ "ci_failing": [
+ {
+ "id": "fix_ci",
+ "label": "Fix CI",
+ "skillId": "",
+ "prompt": "CI is failing on this PR. Investigate the failing checks and push a fix.",
+ },
+ ],
+ "changes_requested": [
+ {
+ "id": "address_comments",
+ "label": "Address review",
+ "skillId": "",
+ "prompt": "Address the change requests on this PR — read the latest review and respond with code.",
+ },
+ ],
+ "comments_waiting": [
+ {
+ "id": "address_threads",
+ "label": "Address comments",
+ "skillId": "",
+ "prompt": "Address the unresolved review comments on this PR.",
+ },
+ ],
+ "ready_to_merge": [
+ {
+ "id": "final_check",
+ "label": "Final check",
+ "skillId": "",
+ "prompt": "Do a last-pass review of this PR. Call out anything risky before I merge.",
+ },
+ ],
+ "stale": [],
+ "done": [],
+}
+
+
+def build_default_bindings() -> dict[str, list[dict]]:
+ return {sid: [dict(action) for action in _DEFAULT_BINDINGS.get(sid, [])] for sid in SITUATION_IDS}
diff --git a/products/tasks/backend/code_workstreams/grouping.py b/products/tasks/backend/code_workstreams/grouping.py
new file mode 100644
index 000000000000..a1ce8e3d1bf4
--- /dev/null
+++ b/products/tasks/backend/code_workstreams/grouping.py
@@ -0,0 +1,182 @@
+from collections.abc import Mapping
+from dataclasses import dataclass, field
+from typing import Optional
+
+from .classify import ClassifyInput, ClassifyPr, classify
+from .situations import ATTENTION_SITUATIONS, SituationId
+
+RUNNING_STATUSES = frozenset({"queued", "in_progress"})
+
+RUNNING_STALE_THRESHOLD_MS = 30 * 60 * 1000
+
+
+@dataclass
+class TaskInput:
+ id: str
+ title: str
+ status: Optional[str]
+ last_activity_at: int
+ repo_name: Optional[str] = None
+ repo_full_path: Optional[str] = None
+ branch: Optional[str] = None
+ cloud_pr_url: Optional[str] = None
+ folder_path: Optional[str] = None
+
+
+@dataclass
+class PrInput:
+ url: str
+ number: int
+ title: str
+ state: str
+ ci_status: str
+ review_decision: Optional[str]
+ unresolved_threads: int
+ mergeable: Optional[bool]
+ is_current_user_requested_reviewer: bool
+ is_current_user_author: bool
+ author: Optional[str]
+ last_updated_at: int
+
+
+@dataclass
+class WorkstreamTask:
+ id: str
+ title: str
+ status: Optional[str]
+
+
+@dataclass
+class Workstream:
+ id: str
+ repo_name: Optional[str]
+ repo_full_path: Optional[str]
+ branch: Optional[str]
+ pr_url: Optional[str]
+ pr: Optional[PrInput]
+ tasks: list[WorkstreamTask]
+ situations: list[SituationId]
+ last_activity_at: int
+
+
+@dataclass
+class WorkstreamsResult:
+ needs_attention: list[Workstream] = field(default_factory=list)
+ in_progress: list[Workstream] = field(default_factory=list)
+
+
+def _is_running(status: Optional[str]) -> bool:
+ return bool(status) and status in RUNNING_STATUSES
+
+
+def _is_actively_running(task: TaskInput, now: int, has_pr: bool) -> bool:
+ if not _is_running(task.status):
+ return False
+ if has_pr:
+ return False
+ return now - task.last_activity_at <= RUNNING_STALE_THRESHOLD_MS
+
+
+def workstream_key(task: TaskInput, pr_url: Optional[str]) -> Optional[str]:
+ if pr_url:
+ return f"pr:{pr_url}"
+ repo = task.repo_full_path or task.repo_name
+ branch = task.branch
+ if repo and branch:
+ return f"branch:{repo}#{branch}"
+ if task.folder_path:
+ return f"path:{task.folder_path}"
+ return None
+
+
+def build_workstreams(
+ tasks: list[TaskInput],
+ pr_by_task: Mapping[str, PrInput],
+ now: int,
+) -> WorkstreamsResult:
+ def pr_of(task: TaskInput) -> Optional[PrInput]:
+ return pr_by_task.get(task.id)
+
+ def pr_url_of(task: TaskInput) -> Optional[str]:
+ snap = pr_of(task)
+ if snap is not None:
+ return snap.url
+ return task.cloud_pr_url
+
+ groups: dict[str, list[TaskInput]] = {}
+
+ for task in tasks:
+ pr_url = pr_url_of(task)
+ if _is_actively_running(task, now, bool(pr_url)):
+ continue
+ key = workstream_key(task, pr_url)
+ if not key:
+ continue
+ groups.setdefault(key, []).append(task)
+
+ needs_attention: list[Workstream] = []
+ in_progress: list[Workstream] = []
+
+ for key, group_tasks in groups.items():
+ group_tasks.sort(key=lambda t: t.last_activity_at, reverse=True)
+ head = group_tasks[0]
+
+ pr: Optional[PrInput] = None
+ pr_url = None
+ for t in group_tasks:
+ snap = pr_of(t)
+ url = snap.url if snap is not None else t.cloud_pr_url
+ if url:
+ pr = snap
+ pr_url = url
+ break
+
+ branch = head.branch
+ last_activity_at = head.last_activity_at
+
+ situations = sorted(
+ classify(
+ ClassifyInput(
+ has_pr_url=bool(pr_url),
+ pr=_to_classify_pr(pr),
+ branch=branch,
+ last_activity_at=last_activity_at,
+ now=now,
+ )
+ )
+ )
+
+ workstream = Workstream(
+ id=key,
+ repo_name=head.repo_name,
+ repo_full_path=head.repo_full_path,
+ branch=branch,
+ pr_url=pr_url,
+ pr=pr,
+ tasks=[WorkstreamTask(id=t.id, title=t.title, status=t.status) for t in group_tasks],
+ situations=situations,
+ last_activity_at=last_activity_at,
+ )
+
+ if any(s in ATTENTION_SITUATIONS for s in situations):
+ needs_attention.append(workstream)
+ else:
+ in_progress.append(workstream)
+
+ needs_attention.sort(key=lambda w: w.last_activity_at, reverse=True)
+ in_progress.sort(key=lambda w: w.last_activity_at, reverse=True)
+
+ return WorkstreamsResult(needs_attention=needs_attention, in_progress=in_progress)
+
+
+def _to_classify_pr(pr: Optional[PrInput]) -> Optional[ClassifyPr]:
+ if pr is None:
+ return None
+ return ClassifyPr(
+ state=pr.state, # type: ignore[arg-type]
+ ci_status=pr.ci_status, # type: ignore[arg-type]
+ review_decision=pr.review_decision, # type: ignore[arg-type]
+ unresolved_threads=pr.unresolved_threads,
+ is_current_user_author=pr.is_current_user_author,
+ mergeable=pr.mergeable,
+ )
diff --git a/products/tasks/backend/code_workstreams/situations.py b/products/tasks/backend/code_workstreams/situations.py
new file mode 100644
index 000000000000..fc97048c522b
--- /dev/null
+++ b/products/tasks/backend/code_workstreams/situations.py
@@ -0,0 +1,29 @@
+from typing import Literal, get_args
+
+SituationId = Literal[
+ "working",
+ "in_review",
+ "ci_failing",
+ "changes_requested",
+ "comments_waiting",
+ "ready_to_merge",
+ "stale",
+ "done",
+]
+
+SITUATION_IDS: tuple[SituationId, ...] = get_args(SituationId)
+
+SITUATION_PRIORITY: tuple[SituationId, ...] = (
+ "done",
+ "ready_to_merge",
+ "ci_failing",
+ "changes_requested",
+ "comments_waiting",
+ "in_review",
+ "working",
+ "stale",
+)
+
+ATTENTION_SITUATIONS: frozenset[SituationId] = frozenset(
+ {"ci_failing", "changes_requested", "comments_waiting", "stale"}
+)
diff --git a/products/tasks/backend/code_workstreams/test_classify.py b/products/tasks/backend/code_workstreams/test_classify.py
new file mode 100644
index 000000000000..2d2d52d4d558
--- /dev/null
+++ b/products/tasks/backend/code_workstreams/test_classify.py
@@ -0,0 +1,100 @@
+from dataclasses import replace
+
+import pytest
+
+from products.tasks.backend.code_workstreams.classify import (
+ STALE_THRESHOLD_MS,
+ ClassifyInput,
+ ClassifyPr,
+ classify,
+ pick_primary_situation,
+)
+
+NOW = 1_700_000_000_000
+
+
+def _pr(**overrides) -> ClassifyPr:
+ return replace(
+ ClassifyPr(
+ state="open",
+ ci_status="passing",
+ review_decision=None,
+ unresolved_threads=0,
+ is_current_user_author=True,
+ mergeable=True,
+ ),
+ **overrides,
+ )
+
+
+def _input(**overrides) -> ClassifyInput:
+ return replace(
+ ClassifyInput(
+ has_pr_url=False,
+ pr=None,
+ branch=None,
+ last_activity_at=NOW,
+ now=NOW,
+ ),
+ **overrides,
+ )
+
+
[email protected]("state", ["merged", "closed"])
+def test_terminal_pr_state_is_done_and_exclusive(state):
+ assert classify(_input(pr=_pr(state=state, ci_status="failing"))) == {"done"}
+
+
+def test_failing_ci_open_pr():
+ assert classify(_input(pr=_pr(ci_status="failing"))) == {"ci_failing", "in_review"}
+
+
+def test_changes_requested():
+ result = classify(_input(pr=_pr(review_decision="changes_requested")))
+ assert result == {"changes_requested", "in_review"}
+
+
[email protected]("is_current_user_author,expected", [(True, True), (False, False)])
+def test_comments_waiting_only_for_author(is_current_user_author, expected):
+ result = classify(_input(pr=_pr(unresolved_threads=2, is_current_user_author=is_current_user_author)))
+ assert ("comments_waiting" in result) is expected
+
+
[email protected]("mergeable,expected", [(True, True), (False, False)])
+def test_ready_to_merge_requires_mergeable(mergeable, expected):
+ result = classify(_input(pr=_pr(review_decision="approved", ci_status="passing", mergeable=mergeable)))
+ assert ("ready_to_merge" in result) is expected
+
+
+def test_pr_url_without_data_is_in_review():
+ assert classify(_input(has_pr_url=True, pr=None)) == {"in_review"}
+
+
[email protected]("commits_ahead,expected", [(3, {"working"}), (None, {"working"}), (0, set())])
+def test_branch_with_commits_is_working(commits_ahead, expected):
+ assert classify(_input(branch="feat/x", commits_ahead=commits_ahead)) == expected
+
+
+def test_stale_stacks_on_top():
+ old = NOW - STALE_THRESHOLD_MS - 1
+ result = classify(_input(pr=_pr(ci_status="failing"), last_activity_at=old))
+ assert "stale" in result
+ assert "ci_failing" in result
+
+
+def test_stale_never_stacks_on_done():
+ old = NOW - STALE_THRESHOLD_MS - 1
+ result = classify(_input(pr=_pr(state="merged"), last_activity_at=old))
+ assert result == {"done"}
+
+
+ "situations,expected",
+ [
+ ({"working", "ci_failing", "stale"}, "ci_failing"),
+ ({"stale", "working"}, "working"),
+ (set(), None),
+ ],
+)
+def test_pick_primary_situation_priority(situations, expected):
+ assert pick_primary_situation(situations) == expected
diff --git a/products/tasks/backend/code_workstreams/test_grouping.py b/products/tasks/backend/code_workstreams/test_grouping.py
new file mode 100644
index 000000000000..ac83f2ca3c16
--- /dev/null
+++ b/products/tasks/backend/code_workstreams/test_grouping.py
@@ -0,0 +1,130 @@
+from dataclasses import replace
+
+import pytest
+
+from products.tasks.backend.code_workstreams.classify import STALE_THRESHOLD_MS
+from products.tasks.backend.code_workstreams.grouping import (
+ RUNNING_STALE_THRESHOLD_MS,
+ PrInput,
+ TaskInput,
+ build_workstreams,
+ workstream_key,
+)
+
+NOW = 1_700_000_000_000
+
+
+def _task(**overrides) -> TaskInput:
+ return replace(
+ TaskInput(
+ id="t1",
+ title="Task",
+ status="completed",
+ last_activity_at=NOW,
+ repo_name="posthog",
+ repo_full_path="posthog/posthog",
+ branch="feat/x",
+ cloud_pr_url=None,
+ folder_path=None,
+ ),
+ **overrides,
+ )
+
+
+def _pr(**overrides) -> PrInput:
+ return replace(
+ PrInput(
+ url="https://github.com/posthog/posthog/pull/1",
+ number=1,
+ title="PR",
+ state="open",
+ ci_status="passing",
+ review_decision=None,
+ unresolved_threads=0,
+ mergeable=True,
+ is_current_user_requested_reviewer=False,
+ is_current_user_author=True,
+ author="me",
+ last_updated_at=NOW,
+ ),
+ **overrides,
+ )
+
+
+ "task,pr_url,expected",
+ [
+ (
+ _task(branch="b", repo_name="r", repo_full_path="org/r", folder_path="/p"),
+ "https://x/pull/9",
+ "pr:https://x/pull/9",
+ ),
+ (_task(branch="b", repo_name="r", repo_full_path="org/r", folder_path="/p"), None, "branch:org/r#b"),
+ (_task(branch="b", repo_name="r", repo_full_path=None, folder_path="/p"), None, "branch:r#b"),
+ (_task(branch=None, repo_name=None, repo_full_path=None, folder_path="/p"), None, "path:/p"),
+ (_task(branch=None, repo_name=None, repo_full_path=None, folder_path=None), None, None),
+ ],
+)
+def test_workstream_key_precedence(task, pr_url, expected):
+ assert workstream_key(task, pr_url) == expected
+
+
+def test_running_task_no_pr_is_excluded_from_workstreams():
+ result = build_workstreams([_task(status="in_progress", branch=None, folder_path=None)], {}, NOW)
+ assert not result.needs_attention
+ assert not result.in_progress
+
+
+def test_running_task_with_pr_is_grouped():
+ task = _task(status="in_progress")
+ result = build_workstreams([task], {task.id: _pr(ci_status="failing")}, NOW)
+ assert len(result.needs_attention) == 1
+
+
+def test_idle_running_task_falls_through_to_grouping():
+ old = NOW - RUNNING_STALE_THRESHOLD_MS - 1
+ task = _task(status="in_progress", last_activity_at=old)
+ result = build_workstreams([task], {}, NOW)
+ assert len(result.in_progress) == 1
+
+
+def test_failing_ci_lands_in_needs_attention():
+ task = _task()
+ result = build_workstreams([task], {task.id: _pr(ci_status="failing")}, NOW)
+ assert len(result.needs_attention) == 1
+ ws = result.needs_attention[0]
+ assert ws.pr_url == _pr().url
+ assert "ci_failing" in ws.situations
+
+
+def test_healthy_open_pr_lands_in_in_progress():
+ task = _task()
+ result = build_workstreams([task], {task.id: _pr()}, NOW)
+ assert len(result.in_progress) == 1
+ assert result.in_progress[0].situations == ["in_review"]
+
+
+def test_tasks_group_by_shared_pr_url():
+ url = "https://github.com/posthog/posthog/pull/42"
+ t1 = _task(id="a", branch="x", last_activity_at=NOW)
+ t2 = _task(id="b", branch="y", last_activity_at=NOW - 1000)
+ pr_by_task = {"a": _pr(url=url), "b": _pr(url=url)}
+ result = build_workstreams([t1, t2], pr_by_task, NOW)
+ assert len(result.needs_attention) + len(result.in_progress) == 1
+ ws = (result.needs_attention + result.in_progress)[0]
+ assert {t.id for t in ws.tasks} == {"a", "b"}
+
+
+def test_stale_branch_no_pr_is_attention():
+ old = NOW - STALE_THRESHOLD_MS - 1
+ task = _task(status="completed", last_activity_at=old, cloud_pr_url=None)
+ result = build_workstreams([task], {}, NOW)
+ assert len(result.needs_attention) == 1
+ assert "stale" in result.needs_attention[0].situations
+
+
+def test_task_without_grouping_key_is_skipped():
+ task = _task(status="completed", branch=None, repo_name=None, folder_path=None, cloud_pr_url=None)
+ result = build_workstreams([task], {}, NOW)
+ assert not result.needs_attention
+ assert not result.in_progress
diff --git a/products/tasks/backend/code_workstreams/test_validation.py b/products/tasks/backend/code_workstreams/test_validation.py
new file mode 100644
index 000000000000..0ff881e71370
--- /dev/null
+++ b/products/tasks/backend/code_workstreams/test_validation.py
@@ -0,0 +1,63 @@
+from products.tasks.backend.code_workstreams.default_workflow import build_default_bindings
+from products.tasks.backend.code_workstreams.situations import SITUATION_IDS
+from products.tasks.backend.code_workstreams.validation import validate_bindings
+
+
+def test_default_bindings_cover_every_situation():
+ bindings = build_default_bindings()
+ assert set(bindings.keys()) == set(SITUATION_IDS)
+
+
+def test_default_bindings_are_valid():
+ result = validate_bindings(build_default_bindings())
+ assert result.can_save
+ assert result.diagnostics == []
+
+
+def test_duplicate_action_id_is_error():
+ bindings = {
+ "working": [
+ {"id": "a", "label": "A", "skillId": "s", "prompt": "p"},
+ {"id": "a", "label": "B", "skillId": "s", "prompt": "p"},
+ ]
+ }
+ result = validate_bindings(bindings)
+ assert not result.can_save
+ assert any(d.code == "duplicate_action_id" for d in result.diagnostics)
+
+
+def test_empty_fields_are_errors():
+ bindings = {"working": [{"id": "a", "label": " ", "skillId": "", "prompt": ""}]}
+ result = validate_bindings(bindings)
+ codes = {d.code for d in result.diagnostics}
+ assert codes == {"action_empty_label", "action_empty_prompt"}
+ assert not result.can_save
+
+
+def test_missing_skill_is_allowed():
+ bindings = {"working": [{"id": "a", "label": "A", "skillId": "", "prompt": "p"}]}
+ result = validate_bindings(bindings)
+ assert result.can_save
+ assert result.diagnostics == []
+
+
+def test_empty_bindings_are_valid():
+ assert validate_bindings({}).can_save
+
+
+def test_non_dict_bindings_is_rejected():
+ result = validate_bindings([{"id": "a"}]) # type: ignore[arg-type]
+ assert not result.can_save
+ assert {d.code for d in result.diagnostics} == {"bindings_not_object"}
+
+
+def test_non_list_situation_value_is_rejected():
+ result = validate_bindings({"working": "not a list"})
+ assert not result.can_save
+ assert any(d.code == "situation_not_list" for d in result.diagnostics)
+
+
+def test_non_dict_action_is_rejected():
+ result = validate_bindings({"working": ["not an object"]})
+ assert not result.can_save
+ assert any(d.code == "action_not_object" for d in result.diagnostics)
diff --git a/products/tasks/backend/code_workstreams/validation.py b/products/tasks/backend/code_workstreams/validation.py
new file mode 100644
index 000000000000..9c8ea5b21be7
--- /dev/null
+++ b/products/tasks/backend/code_workstreams/validation.py
@@ -0,0 +1,101 @@
+from collections.abc import Mapping
+from dataclasses import dataclass
+from typing import Any
+
+from .situations import SITUATION_IDS
+
+
+@dataclass
+class ValidationDiagnostic:
+ severity: str
+ code: str
+ message: str
+ situation_id: str | None = None
+ action_id: str | None = None
+
+
+@dataclass
+class ValidationResult:
+ diagnostics: list[ValidationDiagnostic]
+ can_save: bool
+
+
+def validate_bindings(bindings: Mapping[str, Any]) -> ValidationResult:
+ diagnostics: list[ValidationDiagnostic] = []
+
+ if not isinstance(bindings, dict):
+ return ValidationResult(
+ diagnostics=[
+ ValidationDiagnostic(
+ severity="error",
+ code="bindings_not_object",
+ message="bindings must be an object",
+ )
+ ],
+ can_save=False,
+ )
+
+ for sid in SITUATION_IDS:
+ actions = bindings.get(sid) or []
+ if not isinstance(actions, list):
+ diagnostics.append(
+ ValidationDiagnostic(
+ severity="error",
+ code="situation_not_list",
+ message=f"{sid} must be a list of actions",
+ situation_id=sid,
+ )
+ )
+ continue
+ seen_ids: set[str] = set()
+ for action in actions:
+ if not isinstance(action, dict):
+ diagnostics.append(
+ ValidationDiagnostic(
+ severity="error",
+ code="action_not_object",
+ message=f"An action in {sid} must be an object",
+ situation_id=sid,
+ )
+ )
+ continue
+ action_id = str(action.get("id", ""))
+ if action_id in seen_ids:
+ diagnostics.append(
+ ValidationDiagnostic(
+ severity="error",
+ code="duplicate_action_id",
+ message=f'Duplicate action id "{action_id}" in {sid}',
+ situation_id=sid,
+ action_id=action_id,
+ )
+ )
+ continue
+ seen_ids.add(action_id)
+
+ label = str(action.get("label", ""))
+ prompt = str(action.get("prompt", ""))
+
+ if label.strip() == "":
+ diagnostics.append(
+ ValidationDiagnostic(
+ severity="error",
+ code="action_empty_label",
+ message=f"An action in {sid} has no label",
+ situation_id=sid,
+ action_id=action_id,
+ )
+ )
+ if prompt.strip() == "":
+ diagnostics.append(
+ ValidationDiagnostic(
+ severity="error",
+ code="action_empty_prompt",
+ message=f'Action "{label}" in {sid} has an empty prompt',
+ situation_id=sid,
+ action_id=action_id,
+ )
+ )
+
+ can_save = not any(d.severity == "error" for d in diagnostics)
+ return ValidationResult(diagnostics=diagnostics, can_save=can_save)
diff --git a/products/tasks/backend/management/commands/evaluate_code_workstreams.py b/products/tasks/backend/management/commands/evaluate_code_workstreams.py
new file mode 100644
index 000000000000..87de13ff81ce
--- /dev/null
+++ b/products/tasks/backend/management/commands/evaluate_code_workstreams.py
@@ -0,0 +1,125 @@
+import json
+
+from django.core.management.base import BaseCommand, CommandError
+
+from posthog.models.scoping import team_scope
+
+from products.tasks.backend.models import CodePrSnapshot, CodeWorkstream
+from products.tasks.backend.temporal.code_workstreams.activities.list_active_teams import list_active_code_teams
+from products.tasks.backend.temporal.code_workstreams.activities.load_pr_urls import (
+ LoadTeamPrUrlsInput,
+ load_team_pr_urls,
+)
+from products.tasks.backend.temporal.code_workstreams.activities.poll_pull_requests import (
+ _resolve_integration,
+ poll_pull_requests_for_team,
+)
+from products.tasks.backend.temporal.code_workstreams.activities.rebuild_workstreams import (
+ RebuildTeamWorkstreamsInput,
+ rebuild_team_workstreams,
+)
+
+
+class Command(BaseCommand):
+ help = "Run one code-workstreams evaluation cycle synchronously (no Temporal worker/schedule). Diagnostic + local testing."
+
+ def add_arguments(self, parser):
+ parser.add_argument("--team-id", type=int, help="Team to evaluate. Omit to list active teams and exit.")
+ parser.add_argument(
+ "--skip-poll", action="store_true", help="Skip the GitHub PR poll (grouping/classify only)."
+ )
+ parser.add_argument(
+ "--pr-url",
+ type=str,
+ help="Probe a single PR: print exactly what get_pull_request_snapshot returns (needs --team-id).",
+ )
+
+ def handle(self, *args, **options):
+ team_id = options.get("team_id")
+
+ if team_id is None:
+ active = list_active_code_teams()
+ self.stdout.write(f"Active code teams (recent task activity): {active.team_ids}")
+ self.stdout.write("Re-run with --team-id <id> to evaluate one.")
+ return
+
+ if options.get("pr_url"):
+ self._probe_pr(team_id, options["pr_url"])
+ return
+
+ self.stdout.write(f"== Evaluating team {team_id} ==")
+
+ prs = load_team_pr_urls(LoadTeamPrUrlsInput(team_id=team_id))
+ self.stdout.write(f"PR URLs found on recent task runs: {len(prs.prs)}")
+ for ref in prs.prs[:10]:
+ self.stdout.write(f" - {ref.pr_url} (integration={ref.github_integration_id})")
+
+ if options["skip_poll"]:
+ self.stdout.write("Skipping GitHub poll (--skip-poll).")
+ elif prs.prs:
+ try:
+ result = poll_pull_requests_for_team(team_id, prs.prs)
+ self.stdout.write(
+ f"Polled {result.polled}, updated {result.updated}, rate_limited={result.rate_limited}"
+ )
+ except Exception as e:
+ raise CommandError(f"PR poll failed: {type(e).__name__}: {e}") from e
+
+ out = rebuild_team_workstreams(RebuildTeamWorkstreamsInput(team_id=team_id))
+ self.stdout.write(f"Rebuilt: users={out.users}, workstreams={out.workstreams}, pruned={out.pruned}")
+
+ with team_scope(team_id):
+ snapshots = list(CodePrSnapshot.objects.filter(team_id=team_id))
+ workstreams = list(CodeWorkstream.objects.filter(team_id=team_id))
+
+ self.stdout.write(f"\nCodePrSnapshot rows: {len(snapshots)}")
+ for s in snapshots[:25]:
+ self.stdout.write(
+ f" {s.pr_url} state={s.state} ci={s.ci_status} review={s.review_decision} "
+ f"threads={s.unresolved_threads} author={s.author_login}"
+ )
+
+ self.stdout.write(f"\nCodeWorkstream rows: {len(workstreams)}")
+ for ws in workstreams[:25]:
+ self.stdout.write(
+ f" [{ws.state}] {ws.key} → situations={ws.situations} (user={ws.user_id}, tasks={len(ws.tasks)})"
+ )
+
+ if not workstreams:
+ self.stdout.write(
+ "\nNo workstreams written. Likely causes: tasks have no PR URL and no (repository + run branch) "
+ "grouping key, all of the team's recent tasks are still actively-running agents, or there are no "
+ "task runs in the last 30 days for this team."
+ )
+ elif snapshots and all(
+ s.ci_status == "none" and s.review_decision is None and s.unresolved_threads == 0 for s in snapshots
+ ):
+ self.stdout.write(
+ "\nAll PR snapshots are empty (ci=none, no review, 0 threads). The GitHub poll reached GitHub but "
+ "the data came back blank — likely the GitHub App installation lacks 'Checks: read' / 'Pull "
+ "requests: read'. Run with --pr-url <one of the URLs above> to see the raw result + any GraphQL errors."
+ )
+
+ def _probe_pr(self, team_id: int, pr_url: str) -> None:
+ prs = load_team_pr_urls(LoadTeamPrUrlsInput(team_id=team_id))
+ ref = next((r for r in prs.prs if r.pr_url == pr_url), None)
+ if ref is None:
+ raise CommandError(
+ f"{pr_url} is not among the team's recent task-run PR URLs ({len(prs.prs)} found). "
+ "Is there a task run with output.pr_url == this URL in the last 30 days?"
+ )
+ self.stdout.write(
+ f"Resolved PrRef: team_integration={ref.github_integration_id}, user_integration={ref.github_user_integration_id}"
+ )
+ integration = _resolve_integration(ref)
+ if integration is None:
+ raise CommandError(
+ "No GitHub integration resolved for this PR: the task isn't linked to one, the team has no GitHub "
+ "integration, and the task creator has no user GitHub integration. Connect GitHub (team or user)."
+ )
+ self.stdout.write(f"Resolved integration: {type(integration).__name__}")
+ try:
+ snapshot = integration.get_pull_request_snapshot(pr_url)
+ except Exception as e:
+ raise CommandError(f"get_pull_request_snapshot raised: {type(e).__name__}: {e}") from e
+ self.stdout.write(json.dumps(snapshot, indent=2, default=str))
diff --git a/products/tasks/backend/migrations/0037_codeworkflowconfig_codeprsnapshot_codeworkstream.py b/products/tasks/backend/migrations/0037_codeworkflowconfig_codeprsnapshot_codeworkstream.py
new file mode 100644
index 000000000000..ed6eea769e20
--- /dev/null
+++ b/products/tasks/backend/migrations/0037_codeworkflowconfig_codeprsnapshot_codeworkstream.py
@@ -0,0 +1,216 @@
+import uuid
+
+import django.utils.timezone
+import django.db.models.deletion
+from django.conf import settings
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("posthog", "1166_oauth_impersonated_by"),
+ ("tasks", "0036_taskrun_output_pr_url_idx"),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="CodeWorkflowConfig",
+ fields=[
+ (
+ "id",
+ models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False),
+ ),
+ ("version", models.PositiveIntegerField(default=1)),
+ ("bindings", models.JSONField(default=dict, help_text="Situation id → ordered WorkflowAction list")),
+ ("created_at", models.DateTimeField(default=django.utils.timezone.now)),
+ ("updated_at", models.DateTimeField(auto_now=True)),
+ (
+ "team",
+ models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name="+", to="posthog.team"),
+ ),
+ (
+ "user",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE, related_name="+", to=settings.AUTH_USER_MODEL
+ ),
+ ),
+ ],
+ options={
+ "db_table": "posthog_code_workflow_config",
+ },
+ ),
+ migrations.CreateModel(
+ name="CodePrSnapshot",
+ fields=[
+ (
+ "id",
+ models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False),
+ ),
+ ("pr_url", models.CharField(max_length=500)),
+ ("number", models.PositiveIntegerField()),
+ ("title", models.TextField(blank=True, default="")),
+ (
+ "state",
+ models.CharField(
+ choices=[
+ ("open", "Open"),
+ ("draft", "Draft"),
+ ("merged", "Merged"),
+ ("closed", "Closed"),
+ ],
+ max_length=10,
+ ),
+ ),
+ (
+ "ci_status",
+ models.CharField(
+ choices=[
+ ("passing", "Passing"),
+ ("failing", "Failing"),
+ ("pending", "Pending"),
+ ("none", "None"),
+ ],
+ default="none",
+ max_length=10,
+ ),
+ ),
+ (
+ "review_decision",
+ models.CharField(
+ blank=True,
+ choices=[
+ ("approved", "Approved"),
+ ("changes_requested", "Changes requested"),
+ ("review_required", "Review required"),
+ ],
+ max_length=20,
+ null=True,
+ ),
+ ),
+ ("unresolved_threads", models.PositiveIntegerField(default=0)),
+ ("mergeable", models.BooleanField(blank=True, null=True)),
+ ("author_login", models.CharField(blank=True, max_length=255, null=True)),
+ (
+ "requested_reviewer_logins",
+ models.JSONField(default=list, help_text="GitHub logins requested as reviewers"),
+ ),
+ (
+ "pr_updated_at",
+ models.DateTimeField(blank=True, help_text="PR's last-updated time on GitHub", null=True),
+ ),
+ (
+ "fingerprint",
+ models.CharField(blank=True, default="", help_text="Change-detection hash", max_length=64),
+ ),
+ (
+ "fetched_at",
+ models.DateTimeField(
+ default=django.utils.timezone.now, help_text="When this snapshot was last polled"
+ ),
+ ),
+ ("created_at", models.DateTimeField(default=django.utils.timezone.now)),
+ ("updated_at", models.DateTimeField(auto_now=True)),
+ (
+ "team",
+ models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name="+", to="posthog.team"),
+ ),
+ (
+ "github_integration",
+ models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="+",
+ to="posthog.integration",
+ ),
+ ),
+ ],
+ options={
+ "db_table": "posthog_code_pr_snapshot",
+ },
+ ),
+ migrations.CreateModel(
+ name="CodeWorkstream",
+ fields=[
+ (
+ "id",
+ models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False),
+ ),
+ (
+ "key",
+ models.CharField(
+ help_text="Grouping key: pr:<url> | branch:<repo>#<branch> | path:<path>", max_length=600
+ ),
+ ),
+ ("repo_name", models.CharField(blank=True, max_length=255, null=True)),
+ ("repo_full_path", models.CharField(blank=True, max_length=512, null=True)),
+ ("branch", models.CharField(blank=True, max_length=255, null=True)),
+ ("pr_url", models.CharField(blank=True, max_length=500, null=True)),
+ ("pr", models.JSONField(blank=True, help_text="Per-user-resolved PrSnapshot wire shape", null=True)),
+ (
+ "situations",
+ models.JSONField(default=list, help_text="List of situation ids this workstream is in"),
+ ),
+ (
+ "primary_situation",
+ models.CharField(blank=True, help_text="Board column placement", max_length=20, null=True),
+ ),
+ (
+ "state",
+ models.CharField(
+ choices=[("attention", "Needs attention"), ("in_progress", "In progress")], max_length=20
+ ),
+ ),
+ ("tasks", models.JSONField(default=list, help_text="List of {id, title, status} for grouped tasks")),
+ ("last_activity_at", models.DateTimeField()),
+ (
+ "generated_at",
+ models.DateTimeField(default=django.utils.timezone.now, help_text="When this row was last rebuilt"),
+ ),
+ ("created_at", models.DateTimeField(default=django.utils.timezone.now)),
+ ("updated_at", models.DateTimeField(auto_now=True)),
+ (
+ "team",
+ models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name="+", to="posthog.team"),
+ ),
+ (
+ "user",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE, related_name="+", to=settings.AUTH_USER_MODEL
+ ),
+ ),
+ (
+ "pr_snapshot",
+ models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="+",
+ to="tasks.codeprsnapshot",
+ ),
+ ),
+ ],
+ options={
+ "db_table": "posthog_code_workstream",
+ "ordering": ["-last_activity_at"],
+ },
+ ),
+ migrations.AddConstraint(
+ model_name="codeworkflowconfig",
+ constraint=models.UniqueConstraint(fields=("team", "user"), name="code_workflow_config_team_user_unique"),
+ ),
+ migrations.AddConstraint(
+ model_name="codeprsnapshot",
+ constraint=models.UniqueConstraint(fields=("team", "pr_url"), name="code_pr_snapshot_team_url_unique"),
+ ),
+ migrations.AddConstraint(
+ model_name="codeworkstream",
+ constraint=models.UniqueConstraint(
+ fields=("team", "user", "key"), name="code_workstream_team_user_key_unique"
+ ),
+ ),
+ migrations.AddIndex(
+ model_name="codeworkstream",
+ index=models.Index(fields=["team", "user", "state"], name="code_workstream_state_idx"),
+ ),
+ ]
diff --git a/products/tasks/backend/migrations/max_migration.txt b/products/tasks/backend/migrations/max_migration.txt
index 969c9d1a58c4..6f8b9e4bc09c 100644
--- a/products/tasks/backend/migrations/max_migration.txt
+++ b/products/tasks/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0036_taskrun_output_pr_url_idx
+0037_codeworkflowconfig_codeprsnapshot_codeworkstream
diff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.py
index 4b940f0d465e..f03a387b8750 100644
--- a/products/tasks/backend/models.py
+++ b/products/tasks/backend/models.py
@@ -1408,6 +1408,115 @@ class TaskPresence(TeamScopedRootMixin):
return f"Presence: user {self.user_id} on task {self.task_id} via device {self.push_token_id}"
+class CodeWorkflowConfig(TeamScopedRootMixin):
+ # nosemgrep: prefer-uuid7-django-pk -- mirrors sibling task models in this app
+ id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, related_name="+")
+ user = models.ForeignKey("posthog.User", on_delete=models.CASCADE, related_name="+")
+ version = models.PositiveIntegerField(default=1)
+ bindings = models.JSONField(default=dict, help_text="Situation id → ordered WorkflowAction list")
+ created_at = models.DateTimeField(default=django_timezone.now)
+ updated_at = models.DateTimeField(auto_now=True)
+
+ class Meta:
+ db_table = "posthog_code_workflow_config"
+ constraints = [
+ models.UniqueConstraint(fields=["team", "user"], name="code_workflow_config_team_user_unique"),
+ ]
+
+ def __str__(self):
+ return f"CodeWorkflowConfig(team={self.team_id}, user={self.user_id}, v{self.version})"
+
+
+class CodePrSnapshot(TeamScopedRootMixin):
+ class State(models.TextChoices):
+ OPEN = "open", "Open"
+ DRAFT = "draft", "Draft"
+ MERGED = "merged", "Merged"
+ CLOSED = "closed", "Closed"
+
+ class CiStatus(models.TextChoices):
+ PASSING = "passing", "Passing"
+ FAILING = "failing", "Failing"
+ PENDING = "pending", "Pending"
+ NONE = "none", "None"
+
+ class ReviewDecision(models.TextChoices):
+ APPROVED = "approved", "Approved"
+ CHANGES_REQUESTED = "changes_requested", "Changes requested"
+ REVIEW_REQUIRED = "review_required", "Review required"
+
+ # nosemgrep: prefer-uuid7-django-pk -- mirrors sibling task models in this app
+ id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, related_name="+")
+ github_integration = models.ForeignKey(
+ "posthog.Integration", on_delete=models.SET_NULL, null=True, blank=True, related_name="+"
+ )
+ pr_url = models.CharField(max_length=500)
+ number = models.PositiveIntegerField()
+ title = models.TextField(blank=True, default="")
+ state = models.CharField(max_length=10, choices=State.choices)
+ ci_status = models.CharField(max_length=10, choices=CiStatus.choices, default=CiStatus.NONE)
+ review_decision = models.CharField(max_length=20, choices=ReviewDecision.choices, null=True, blank=True)
+ unresolved_threads = models.PositiveIntegerField(default=0)
+ mergeable = models.BooleanField(null=True, blank=True)
+ author_login = models.CharField(max_length=255, null=True, blank=True)
+ requested_reviewer_logins = models.JSONField(default=list, help_text="GitHub logins requested as reviewers")
+ pr_updated_at = models.DateTimeField(null=True, blank=True, help_text="PR's last-updated time on GitHub")
+ fingerprint = models.CharField(max_length=64, blank=True, default="", help_text="Change-detection hash")
+ fetched_at = models.DateTimeField(default=django_timezone.now, help_text="When this snapshot was last polled")
+ created_at = models.DateTimeField(default=django_timezone.now)
+ updated_at = models.DateTimeField(auto_now=True)
+
+ class Meta:
+ db_table = "posthog_code_pr_snapshot"
+ constraints = [
+ models.UniqueConstraint(fields=["team", "pr_url"], name="code_pr_snapshot_team_url_unique"),
+ ]
+
+ def __str__(self):
+ return f"CodePrSnapshot({self.pr_url} {self.state})"
+
+
+class CodeWorkstream(TeamScopedRootMixin):
+ class WorkstreamState(models.TextChoices):
+ ATTENTION = "attention", "Needs attention"
+ IN_PROGRESS = "in_progress", "In progress"
+
+ # nosemgrep: prefer-uuid7-django-pk -- mirrors sibling task models in this app
+ id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, related_name="+")
+ user = models.ForeignKey("posthog.User", on_delete=models.CASCADE, related_name="+")
+ key = models.CharField(max_length=600, help_text="Grouping key: pr:<url> | branch:<repo>#<branch> | path:<path>")
+ repo_name = models.CharField(max_length=255, null=True, blank=True)
+ repo_full_path = models.CharField(max_length=512, null=True, blank=True)
+ branch = models.CharField(max_length=255, null=True, blank=True)
+ pr_url = models.CharField(max_length=500, null=True, blank=True)
+ pr_snapshot = models.ForeignKey(CodePrSnapshot, on_delete=models.SET_NULL, null=True, blank=True, related_name="+")
+ pr = models.JSONField(null=True, blank=True, help_text="Per-user-resolved PrSnapshot wire shape")
+ situations = models.JSONField(default=list, help_text="List of situation ids this workstream is in")
+ primary_situation = models.CharField(max_length=20, null=True, blank=True, help_text="Board column placement")
+ state = models.CharField(max_length=20, choices=WorkstreamState.choices)
+ tasks = models.JSONField(default=list, help_text="List of {id, title, status} for grouped tasks")
+ last_activity_at = models.DateTimeField()
+ generated_at = models.DateTimeField(default=django_timezone.now, help_text="When this row was last rebuilt")
+ created_at = models.DateTimeField(default=django_timezone.now)
+ updated_at = models.DateTimeField(auto_now=True)
+
+ class Meta:
+ db_table = "posthog_code_workstream"
+ ordering = ["-last_activity_at"]
+ constraints = [
+ models.UniqueConstraint(fields=["team", "user", "key"], name="code_workstream_team_user_key_unique"),
+ ]
+ indexes = [
+ models.Index(fields=["team", "user", "state"], name="code_workstream_state_idx"),
+ ]
+
+ def __str__(self):
+ return f"CodeWorkstream({self.key} {self.state})"
+
+
@receiver(post_save, sender=TaskRun)
def track_task_run_completion(sender, instance: TaskRun, created: bool, **kwargs):
try:
diff --git a/products/tasks/backend/routes.py b/products/tasks/backend/routes.py
index c29486d4a2d4..5f50b1ad10de 100644
--- a/products/tasks/backend/routes.py
+++ b/products/tasks/backend/routes.py
@@ -2,6 +2,7 @@ from posthog.api.routing import RouterRegistry
import products.tasks.backend.api as tasks
import products.tasks.backend.seat_api as seats
+import products.tasks.backend.code_home_api as code_home
def register_routes(routers: RouterRegistry) -> None:
@@ -11,5 +12,7 @@ def register_routes(routers: RouterRegistry) -> None:
routers.projects.register(
r"sandbox_environments", tasks.SandboxEnvironmentViewSet, "project_sandbox_environments", ["team_id"]
)
+ routers.projects.register(r"code_workflow", code_home.CodeWorkflowViewSet, "project_code_workflow", ["team_id"])
+ routers.projects.register(r"code_home", code_home.CodeHomeViewSet, "project_code_home", ["team_id"])
routers.root.register(r"code/invites", tasks.CodeInviteViewSet, "code_invites")
routers.root.register(r"seats", seats.SeatViewSet, "seats")
diff --git a/products/tasks/backend/temporal/__init__.py b/products/tasks/backend/temporal/__init__.py
index 861f766a4987..c83d6a9ffa6b 100644
--- a/products/tasks/backend/temporal/__init__.py
+++ b/products/tasks/backend/temporal/__init__.py
@@ -1,4 +1,9 @@
from .automation import RunTaskAutomationWorkflow, run_task_automation_activity
+from .code_workstreams.activities.list_active_teams import list_active_code_teams
+from .code_workstreams.activities.load_pr_urls import load_team_pr_urls
+from .code_workstreams.activities.poll_pull_requests import poll_team_pull_requests
+from .code_workstreams.activities.rebuild_workstreams import rebuild_team_workstreams
+from .code_workstreams.workflow import EvaluateCodeWorkstreamsWorkflow, EvaluateTeamCodeWorkstreamsWorkflow
from .create_snapshot.activities import (
cleanup_sandbox as snapshot_cleanup_sandbox,
clone_repository as snapshot_clone_repository,
@@ -39,6 +44,8 @@ WORKFLOWS = [
CreateSnapshotForRepositoryWorkflow,
PostHogCodeAgentRelayWorkflow,
RunTaskAutomationWorkflow,
+ EvaluateCodeWorkstreamsWorkflow,
+ EvaluateTeamCodeWorkstreamsWorkflow,
]
ACTIVITIES = [
@@ -73,4 +80,8 @@ ACTIVITIES = [
snapshot_setup_repository,
snapshot_create_snapshot,
snapshot_cleanup_sandbox,
+ list_active_code_teams,
+ load_team_pr_urls,
+ poll_team_pull_requests,
+ rebuild_team_workstreams,
]
diff --git a/products/tasks/backend/temporal/code_workstreams/__init__.py b/products/tasks/backend/temporal/code_workstreams/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/tasks/backend/temporal/code_workstreams/activities/__init__.py b/products/tasks/backend/temporal/code_workstreams/activities/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/tasks/backend/temporal/code_workstreams/activities/list_active_teams.py b/products/tasks/backend/temporal/code_workstreams/activities/list_active_teams.py
new file mode 100644
index 000000000000..8682d35444e6
--- /dev/null
+++ b/products/tasks/backend/temporal/code_workstreams/activities/list_active_teams.py
@@ -0,0 +1,80 @@
+from dataclasses import dataclass
+
+from django.utils import timezone
+
+import posthoganalytics
+from temporalio import activity
+
+from posthog.models import Team
+from posthog.temporal.common.utils import close_db_connections
+
+from products.tasks.backend.models import Task, TaskRun
+from products.tasks.backend.temporal.code_workstreams.constants import (
+ ACTIVITY_WINDOW,
+ HOME_TAB_FLAG,
+ MAX_TEAMS_PER_CYCLE,
+)
+
+CODE_ORIGIN_PRODUCTS = (
+ Task.OriginProduct.USER_CREATED,
+ Task.OriginProduct.SLACK,
+ Task.OriginProduct.AUTOMATION,
+)
+
+
+@dataclass
+class ListActiveCodeTeamsOutput:
+ team_ids: list[int]
+ truncated: bool
+
+
+def _org_home_tab_enabled(organization_id: str) -> bool:
+ # Evaluate locally and fail closed so a flag-service blip doesn't fan out work.
+ try:
+ return bool(
+ posthoganalytics.feature_enabled(
+ HOME_TAB_FLAG,
+ distinct_id=organization_id,
+ groups={"organization": organization_id},
+ group_properties={"organization": {"id": organization_id}},
+ only_evaluate_locally=True,
+ send_feature_flag_events=False,
+ )
+ )
+ except Exception as e:
+ activity.logger.warning(
+ "code_workstreams_home_tab_flag_check_failed", organization_id=organization_id, error=str(e)
+ )
+ return False
+
+
+@close_db_connections
+def list_active_code_teams(_: None = None) -> ListActiveCodeTeamsOutput:
+ cutoff = timezone.now() - ACTIVITY_WINDOW
+ team_ids = list(
+ TaskRun.objects.filter(updated_at__gte=cutoff, task__origin_product__in=CODE_ORIGIN_PRODUCTS)
+ .order_by("team_id")
+ .values_list("team_id", flat=True)
+ .distinct()
+ )
+
+ org_enabled: dict[str, bool] = {}
+ enabled_team_ids: list[int] = []
+ for team_id, organization_id in Team.objects.filter(id__in=team_ids).values_list("id", "organization_id"):
+ org_id = str(organization_id)
+ if org_id not in org_enabled:
+ org_enabled[org_id] = _org_home_tab_enabled(org_id)
+ if org_enabled[org_id]:
+ enabled_team_ids.append(team_id)
+ enabled_team_ids.sort()
+
+ truncated = len(enabled_team_ids) > MAX_TEAMS_PER_CYCLE
+ if truncated:
+ activity.logger.warning(
+ "code_workstreams_active_teams_truncated",
+ total=len(enabled_team_ids),
+ cap=MAX_TEAMS_PER_CYCLE,
+ )
+ enabled_team_ids = enabled_team_ids[:MAX_TEAMS_PER_CYCLE]
+ return ListActiveCodeTeamsOutput(team_ids=enabled_team_ids, truncated=truncated)
diff --git a/products/tasks/backend/temporal/code_workstreams/activities/load_pr_urls.py b/products/tasks/backend/temporal/code_workstreams/activities/load_pr_urls.py
new file mode 100644
index 000000000000..d924268a509e
--- /dev/null
+++ b/products/tasks/backend/temporal/code_workstreams/activities/load_pr_urls.py
@@ -0,0 +1,94 @@
+from dataclasses import dataclass
+from typing import Optional
+
+from django.utils import timezone
+
+from temporalio import activity
+
+from posthog.models import Integration
+from posthog.models.github_integration_base import GitHubIntegrationBase
+from posthog.models.user_integration import UserIntegration
+from posthog.temporal.common.utils import close_db_connections
+
+from products.tasks.backend.models import TaskRun
+from products.tasks.backend.temporal.code_workstreams.constants import ACTIVITY_WINDOW, MAX_PRS_PER_TEAM_PER_CYCLE
+
+
+@dataclass
+class PrRef:
+ pr_url: str
+ github_integration_id: Optional[int]
+ github_user_integration_id: Optional[str]
+
+
+def _pr_url_belongs_to_task_repo(pr_url: str, repository: Optional[str]) -> bool:
+ """Whether ``pr_url`` points at the task's own ``repository`` (``owner/repo``).
+
+ ``output.pr_url`` is user-writable, and a team's GitHub App installation can
+ usually reach far more repos than any one task targeted. Without this check a
+ user could point ``pr_url`` at an arbitrary PR the installation can see and
+ have Code Home surface its metadata. The agent always opens the PR against
+ ``task.repository``, so legitimate runs match; runs without a configured
+ repository fail closed.
+ """
+ if not repository:
+ return False
+ parsed = GitHubIntegrationBase.parse_pull_request_url(pr_url)
+ if parsed is None:
+ return False
+ owner, repo, _ = parsed
+ return f"{owner}/{repo}".casefold() == repository.casefold()
+
+
+@dataclass
+class LoadTeamPrUrlsInput:
+ team_id: int
+
+
+@dataclass
+class LoadTeamPrUrlsOutput:
+ prs: list[PrRef]
+
+
+@close_db_connections
+def load_team_pr_urls(input: LoadTeamPrUrlsInput) -> LoadTeamPrUrlsOutput:
+ cutoff = timezone.now() - ACTIVITY_WINDOW
+ runs = (
+ TaskRun.objects.filter(team_id=input.team_id, updated_at__gte=cutoff, output__pr_url__isnull=False)
+ .select_related("task")
+ .order_by("-updated_at")
+ )
+
+ team_github_id: Optional[int] = (
+ Integration.objects.filter(team_id=input.team_id, kind="github").values_list("id", flat=True).first()
+ )
+ user_github_by_creator: dict[int, Optional[str]] = {}
+
+ def creator_user_github(creator_id: Optional[int]) -> Optional[str]:
+ if creator_id is None:
+ return None
+ if creator_id not in user_github_by_creator:
+ uid = UserIntegration.objects.filter(user_id=creator_id, kind="github").values_list("id", flat=True).first()
+ user_github_by_creator[creator_id] = str(uid) if uid else None
+ return user_github_by_creator[creator_id]
+
+ seen: dict[str, PrRef] = {}
+ for run in runs.iterator():
+ url = (run.output or {}).get("pr_url")
+ if not url or url in seen:
+ continue
+ task = run.task
+ if not _pr_url_belongs_to_task_repo(url, task.repository):
+ continue
+ team_int = task.github_integration_id
+ user_int = str(task.github_user_integration_id) if task.github_user_integration_id else None
+ if team_int is None and user_int is None:
+ team_int = team_github_id
+ if team_int is None:
+ user_int = creator_user_github(task.created_by_id)
+ seen[url] = PrRef(pr_url=url, github_integration_id=team_int, github_user_integration_id=user_int)
+ if len(seen) >= MAX_PRS_PER_TEAM_PER_CYCLE:
+ break
+
+ return LoadTeamPrUrlsOutput(prs=list(seen.values()))
diff --git a/products/tasks/backend/temporal/code_workstreams/activities/poll_pull_requests.py b/products/tasks/backend/temporal/code_workstreams/activities/poll_pull_requests.py
new file mode 100644
index 000000000000..63a1e86575af
--- /dev/null
+++ b/products/tasks/backend/temporal/code_workstreams/activities/poll_pull_requests.py
@@ -0,0 +1,140 @@
+from __future__ import annotations
+
+import hashlib
+from collections.abc import Callable
+from dataclasses import dataclass
+
+from django.core.exceptions import ObjectDoesNotExist
+from django.utils import timezone
+from django.utils.dateparse import parse_datetime
+
+import requests
+from temporalio import activity
+
+from posthog.models import Integration
+from posthog.models.github_integration_base import GitHubIntegrationBase, GitHubIntegrationError
+from posthog.models.integration import GitHubIntegration
+from posthog.models.scoping import team_scope
+from posthog.models.user_integration import UserGitHubIntegration, UserIntegration
+from posthog.temporal.common.utils import close_db_connections
+
+from products.tasks.backend.models import CodePrSnapshot
+from products.tasks.backend.temporal.code_workstreams.activities.load_pr_urls import PrRef
+
+
+@dataclass
+class PollTeamPullRequestsInput:
+ team_id: int
+ prs: list[PrRef]
+
+
+@dataclass
+class PollTeamPullRequestsOutput:
+ polled: int
+ updated: int
+ rate_limited: bool
+
+
+def _fingerprint(url: str, updated_at: str | None) -> str:
+ return hashlib.sha256(f"{url}|{updated_at or ''}".encode()).hexdigest()
+
+
+def _resolve_integration(ref: PrRef) -> GitHubIntegrationBase | None:
+ if ref.github_integration_id is not None:
+ integration = GitHubIntegration(Integration.objects.get(id=ref.github_integration_id))
+ if integration.access_token_expired():
+ integration.refresh_access_token()
+ return integration
+ if ref.github_user_integration_id is not None:
+ user_integration = UserGitHubIntegration(UserIntegration.objects.get(id=ref.github_user_integration_id))
+ if user_integration.access_token_expired():
+ user_integration.refresh_access_token()
+ return user_integration
+ return None
+
+
+@close_db_connections
+def poll_team_pull_requests(input: PollTeamPullRequestsInput) -> PollTeamPullRequestsOutput:
+ return poll_pull_requests_for_team(input.team_id, input.prs, heartbeat=activity.heartbeat)
+
+
+def poll_pull_requests_for_team(
+ team_id: int,
+ prs: list[PrRef],
+ *,
+ heartbeat: Callable[[int], None] | None = None,
+) -> PollTeamPullRequestsOutput:
+ integrations: dict[str, GitHubIntegrationBase | None] = {}
+ polled = 0
+ updated = 0
+ rate_limited = False
+
+ for index, ref in enumerate(prs):
+ if heartbeat is not None:
+ heartbeat(index)
+
+ cache_key = (
+ f"i:{ref.github_integration_id}"
+ if ref.github_integration_id is not None
+ else f"u:{ref.github_user_integration_id}"
+ )
+ try:
+ if cache_key not in integrations:
+ integrations[cache_key] = _resolve_integration(ref)
+ integration = integrations[cache_key]
+ except ObjectDoesNotExist:
+ activity.logger.warning("code_workstreams_pr_integration_missing", pr_url=ref.pr_url)
+ continue
+ except (GitHubIntegrationError, requests.RequestException) as e:
+ # A token-refresh failure for one PR must not abort the whole activity (which would
+ # block the team's rebuild this cycle); skip this PR and move on.
+ activity.logger.warning("code_workstreams_pr_integration_unavailable", pr_url=ref.pr_url, error=str(e))
+ continue
+ if integration is None:
+ continue
+
+ try:
+ snap = integration.get_pull_request_snapshot(ref.pr_url)
+ except GitHubIntegrationError as e:
+ if getattr(e, "is_rate_limit", False):
+ activity.logger.warning("code_workstreams_pr_rate_limited", team_id=team_id, polled=polled)
+ rate_limited = True
+ break
+ activity.logger.warning("code_workstreams_pr_fetch_failed", pr_url=ref.pr_url, error=str(e))
+ continue
+ except Exception as e:
+ activity.logger.warning("code_workstreams_pr_fetch_error", pr_url=ref.pr_url, error=str(e))
+ continue
+
+ polled += 1
+ if not snap.get("success"):
+ continue
+
+ fingerprint = _fingerprint(ref.pr_url, snap.get("updated_at"))
+ with team_scope(team_id):
+ existing = CodePrSnapshot.objects.filter(team_id=team_id, pr_url=ref.pr_url).first()
+ if existing is not None and existing.fingerprint == fingerprint:
+ continue
+ CodePrSnapshot.objects.update_or_create(
+ team_id=team_id,
+ pr_url=ref.pr_url,
+ defaults={
+ "github_integration_id": ref.github_integration_id,
+ "number": snap.get("number") or 0,
+ "title": snap.get("title") or "",
+ "state": snap["state"],
+ "ci_status": snap["ci_status"],
+ "review_decision": snap.get("review_decision"),
+ "unresolved_threads": snap.get("unresolved_threads") or 0,
+ "mergeable": snap.get("mergeable"),
+ "author_login": snap.get("author_login"),
+ "requested_reviewer_logins": snap.get("requested_reviewer_logins") or [],
+ "pr_updated_at": parse_datetime(snap["updated_at"]) if snap.get("updated_at") else None,
+ "fingerprint": fingerprint,
+ "fetched_at": timezone.now(),
+ },
+ )
+ updated += 1
+
+ return PollTeamPullRequestsOutput(polled=polled, updated=updated, rate_limited=rate_limited)
diff --git a/products/tasks/backend/temporal/code_workstreams/activities/rebuild_workstreams.py b/products/tasks/backend/temporal/code_workstreams/activities/rebuild_workstreams.py
new file mode 100644
index 000000000000..1cf82f2dc144
--- /dev/null
+++ b/products/tasks/backend/temporal/code_workstreams/activities/rebuild_workstreams.py
@@ -0,0 +1,226 @@
+from collections import defaultdict
+from dataclasses import dataclass
+from datetime import UTC, datetime
+from typing import Optional
+
+from django.db.models import Max
+from django.utils import timezone
+
+from temporalio import activity
+
+from posthog.models.scoping import team_scope
+from posthog.models.user_integration import UserIntegration
+from posthog.temporal.common.utils import close_db_connections
+
+from products.tasks.backend.code_workstreams.classify import pick_primary_situation
+from products.tasks.backend.code_workstreams.grouping import PrInput, TaskInput, Workstream, build_workstreams
+from products.tasks.backend.models import CodePrSnapshot, CodeWorkstream, Task, TaskRun
+from products.tasks.backend.temporal.code_workstreams.constants import ACTIVITY_WINDOW, MAX_TASKS_PER_TEAM
+
+
+@dataclass
+class RebuildTeamWorkstreamsInput:
+ team_id: int
+
+
+@dataclass
+class RebuildTeamWorkstreamsOutput:
+ users: int
+ workstreams: int
+ pruned: int
+
+
+def _epoch_ms(dt: datetime) -> int:
+ return int(dt.timestamp() * 1000)
+
+
+def _from_epoch_ms(ms: int) -> datetime:
+ return datetime.fromtimestamp(ms / 1000, tz=UTC)
+
+
+def _repo_name(full_path: Optional[str]) -> Optional[str]:
+ if not full_path:
+ return None
+ return full_path.split("/")[-1]
+
+
+def _pr_url_from_run(run: Optional[TaskRun]) -> Optional[str]:
+ return (run.output or {}).get("pr_url") if run and run.output else None
+
+
+def _task_to_input(task: Task) -> tuple[TaskInput, Optional[str]]:
+ run: Optional[TaskRun] = task.latest_run
+ last_activity = run.updated_at if run else task.updated_at
+ cloud_pr_url = _pr_url_from_run(run)
+ return (
+ TaskInput(
+ id=str(task.id),
+ title=task.title,
+ status=run.status if run else None,
+ last_activity_at=_epoch_ms(last_activity),
+ repo_name=_repo_name(task.repository),
+ repo_full_path=task.repository,
+ branch=run.branch if run else None,
+ cloud_pr_url=cloud_pr_url,
+ folder_path=None,
+ ),
+ cloud_pr_url,
+ )
+
+
+def _pr_wire(pr: PrInput) -> dict:
+ return {
+ "url": pr.url,
+ "number": pr.number,
+ "title": pr.title,
+ "state": pr.state,
+ "ciStatus": pr.ci_status,
+ "reviewDecision": pr.review_decision,
+ "unresolvedThreads": pr.unresolved_threads,
+ "mergeable": pr.mergeable,
+ "isCurrentUserRequestedReviewer": pr.is_current_user_requested_reviewer,
+ "isCurrentUserAuthor": pr.is_current_user_author,
+ "author": pr.author,
+ "lastUpdatedAt": pr.last_updated_at,
+ }
+
+
+def _build_pr_input(snapshot: CodePrSnapshot, user_github_logins: set[str]) -> PrInput:
+ author = snapshot.author_login
+ reviewer_logins = snapshot.requested_reviewer_logins or []
+ return PrInput(
+ url=snapshot.pr_url,
+ number=snapshot.number,
+ title=snapshot.title,
+ state=snapshot.state,
+ ci_status=snapshot.ci_status,
+ review_decision=snapshot.review_decision,
+ unresolved_threads=snapshot.unresolved_threads,
+ mergeable=snapshot.mergeable,
+ is_current_user_requested_reviewer=bool(user_github_logins.intersection(reviewer_logins)),
+ is_current_user_author=bool(author and author in user_github_logins),
+ author=author,
+ last_updated_at=_epoch_ms(snapshot.pr_updated_at) if snapshot.pr_updated_at else 0,
+ )
+
+
+def _github_logins_by_user(user_ids: list[int]) -> dict[int, set[str]]:
+ logins: dict[int, set[str]] = defaultdict(set)
+ for user_id, config in UserIntegration.objects.filter(user_id__in=user_ids, kind="github").values_list(
+ "user_id", "config"
+ ):
+ login = (config or {}).get("github_user", {}).get("login")
+ if login:
+ logins[user_id].add(login)
+ return logins
+
+
+@close_db_connections
+def rebuild_team_workstreams(input: RebuildTeamWorkstreamsInput) -> RebuildTeamWorkstreamsOutput:
+ now = timezone.now()
+ cutoff = now - ACTIVITY_WINDOW
+ now_ms = _epoch_ms(now)
+
+ # Group by task and order by most-recent activity so the MAX_TASKS_PER_TEAM cap deterministically
+ # keeps the freshest tasks instead of an arbitrary slice that flickers between cycles.
+ recent_task_ids = [
+ row["task_id"]
+ for row in TaskRun.objects.filter(team_id=input.team_id, updated_at__gte=cutoff)
+ .values("task_id")
+ .annotate(last_activity=Max("updated_at"))
+ .order_by("-last_activity")[:MAX_TASKS_PER_TEAM]
+ ]
+ tasks = list(
+ Task.objects.filter(id__in=recent_task_ids, team_id=input.team_id, archived=False, deleted=False)
+ .select_related("created_by")
+ .prefetch_related("runs")
+ )
+
+ by_user: dict[int, list[Task]] = defaultdict(list)
+ needed_pr_urls: set[str] = set()
+ for task in tasks:
+ if task.created_by_id is None:
+ continue
+ by_user[task.created_by_id].append(task)
+ pr_url = _pr_url_from_run(task.latest_run)
+ if pr_url:
+ needed_pr_urls.add(pr_url)
+
+ github_logins_by_user = _github_logins_by_user(list(by_user.keys()))
+
+ total_workstreams = 0
+ total_pruned = 0
+
+ with team_scope(input.team_id):
+ # Only load snapshots we will actually look up, so memory stays bounded by recent tasks
+ # rather than the team's all-time snapshot count.
+ snapshots_by_url = {
+ s.pr_url: s for s in CodePrSnapshot.objects.filter(team_id=input.team_id, pr_url__in=needed_pr_urls)
+ }
+
+ for user_id, user_tasks in by_user.items():
+ user_github_logins = github_logins_by_user.get(user_id, set())
+ task_inputs: list[TaskInput] = []
+ pr_by_task: dict[str, PrInput] = {}
+ snapshot_id_by_url: dict[str, str] = {}
+ for task in user_tasks:
+ task_input, pr_url = _task_to_input(task)
+ task_inputs.append(task_input)
+ if pr_url and pr_url in snapshots_by_url:
+ snapshot = snapshots_by_url[pr_url]
+ pr_by_task[task_input.id] = _build_pr_input(snapshot, user_github_logins)
+ snapshot_id_by_url[pr_url] = str(snapshot.id)
+
+ result = build_workstreams(task_inputs, pr_by_task, now_ms)
+ live_keys: set[str] = set()
+ for state, workstreams in (
+ (CodeWorkstream.WorkstreamState.ATTENTION, result.needs_attention),
+ (CodeWorkstream.WorkstreamState.IN_PROGRESS, result.in_progress),
+ ):
+ for ws in workstreams:
+ live_keys.add(ws.id)
+ _persist_workstream(input.team_id, user_id, state, ws, snapshot_id_by_url, now)
+ total_workstreams += 1
+
+ pruned, _ = (
+ CodeWorkstream.objects.filter(team_id=input.team_id, user_id=user_id)
+ .exclude(key__in=live_keys)
+ .delete()
+ )
+ total_pruned += pruned
+
+ return RebuildTeamWorkstreamsOutput(
+ users=len(by_user),
+ workstreams=total_workstreams,
+ pruned=total_pruned,
+ )
+
+
+def _persist_workstream(
+ team_id: int,
+ user_id: int,
+ state: str,
+ ws: Workstream,
+ snapshot_id_by_url: dict[str, str],
+ generated_at: datetime,
+) -> None:
+ CodeWorkstream.objects.update_or_create(
+ team_id=team_id,
+ user_id=user_id,
+ key=ws.id,
+ defaults={
+ "repo_name": ws.repo_name,
+ "repo_full_path": ws.repo_full_path,
+ "branch": ws.branch,
+ "pr_url": ws.pr_url,
+ "pr_snapshot_id": snapshot_id_by_url.get(ws.pr_url) if ws.pr_url else None,
+ "pr": _pr_wire(ws.pr) if ws.pr else None,
+ "situations": list(ws.situations),
+ "primary_situation": pick_primary_situation(ws.situations),
+ "state": state,
+ "tasks": [{"id": t.id, "title": t.title, "status": t.status} for t in ws.tasks],
+ "last_activity_at": _from_epoch_ms(ws.last_activity_at),
+ "generated_at": generated_at,
+ },
+ )
diff --git a/products/tasks/backend/temporal/code_workstreams/client.py b/products/tasks/backend/temporal/code_workstreams/client.py
new file mode 100644
index 000000000000..a22ca90bc69b
--- /dev/null
+++ b/products/tasks/backend/temporal/code_workstreams/client.py
@@ -0,0 +1,30 @@
+import logging
+
+from django.conf import settings
+
+from asgiref.sync import async_to_sync
+from temporalio.common import WorkflowIDReusePolicy
+from temporalio.exceptions import WorkflowAlreadyStartedError
+
+from posthog.temporal.common.client import sync_connect
+
+from products.tasks.backend.temporal.code_workstreams.workflow import EvaluateTeamCodeWorkstreamsInput
+
+logger = logging.getLogger(__name__)
+
+
+def trigger_team_code_workstreams_evaluation(team_id: int) -> bool:
+ client = sync_connect()
+ workflow_id = f"evaluate-team-code-workstreams-ondemand-{team_id}"
+ try:
+ async_to_sync(client.start_workflow)( # type: ignore[misc]
+ "evaluate-team-code-workstreams", # type: ignore[arg-type]
+ EvaluateTeamCodeWorkstreamsInput(team_id=team_id), # type: ignore[arg-type]
+ id=workflow_id,
+ id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE,
+ task_queue=settings.TASKS_TASK_QUEUE,
+ )
+ return True
+ except WorkflowAlreadyStartedError:
+ logger.info("code_workstreams_refresh_already_running", extra={"team_id": team_id})
+ return False
diff --git a/products/tasks/backend/temporal/code_workstreams/constants.py b/products/tasks/backend/temporal/code_workstreams/constants.py
new file mode 100644
index 000000000000..8a203864878d
--- /dev/null
+++ b/products/tasks/backend/temporal/code_workstreams/constants.py
@@ -0,0 +1,11 @@
+from datetime import timedelta
+
+HOME_TAB_FLAG = "posthog-code-home-tab"
+
+ACTIVITY_WINDOW = timedelta(days=30)
+
+MAX_PRS_PER_TEAM_PER_CYCLE = 50
+MAX_TASKS_PER_TEAM = 500
+MAX_TEAMS_PER_CYCLE = 2000
+
+TEAM_FANOUT_CONCURRENCY = 20
diff --git a/products/tasks/backend/temporal/code_workstreams/schedule.py b/products/tasks/backend/temporal/code_workstreams/schedule.py
new file mode 100644
index 000000000000..d7a6f4c5f183
--- /dev/null
+++ b/products/tasks/backend/temporal/code_workstreams/schedule.py
@@ -0,0 +1,37 @@
+from dataclasses import asdict
+from datetime import timedelta
+
+from django.conf import settings
+
+from temporalio.client import (
+ Client,
+ Schedule,
+ ScheduleActionStartWorkflow,
+ ScheduleIntervalSpec,
+ ScheduleOverlapPolicy,
+ SchedulePolicy,
+ ScheduleSpec,
+)
+
+from posthog.temporal.common.schedule import a_create_schedule, a_schedule_exists, a_update_schedule
+
+from products.tasks.backend.temporal.code_workstreams.workflow import EvaluateCodeWorkstreamsInput
+
+SCHEDULE_ID = "evaluate-code-workstreams-schedule"
+
+
+async def create_evaluate_code_workstreams_schedule(client: Client):
+ schedule = Schedule(
+ action=ScheduleActionStartWorkflow(
+ "evaluate-code-workstreams",
+ asdict(EvaluateCodeWorkstreamsInput()),
+ id="evaluate-code-workstreams",
+ task_queue=settings.TASKS_TASK_QUEUE,
+ ),
+ spec=ScheduleSpec(intervals=[ScheduleIntervalSpec(every=timedelta(minutes=3))]),
+ policy=SchedulePolicy(overlap=ScheduleOverlapPolicy.SKIP),
+ )
+ if await a_schedule_exists(client, SCHEDULE_ID):
+ await a_update_schedule(client, SCHEDULE_ID, schedule)
+ else:
+ await a_create_schedule(client, SCHEDULE_ID, schedule, trigger_immediately=False)
diff --git a/products/tasks/backend/temporal/code_workstreams/test_list_active_teams.py b/products/tasks/backend/temporal/code_workstreams/test_list_active_teams.py
new file mode 100644
index 000000000000..8984dc689ad4
--- /dev/null
+++ b/products/tasks/backend/temporal/code_workstreams/test_list_active_teams.py
@@ -0,0 +1,152 @@
+import random
+
+import pytest
+from unittest.mock import patch
+
+from posthog.models import Organization, Team
+
+from products.tasks.backend.models import Task, TaskRun
+from products.tasks.backend.temporal.code_workstreams.activities.list_active_teams import list_active_code_teams
+
+FLAG_PATH = (
+ "products.tasks.backend.temporal.code_workstreams.activities.list_active_teams.posthoganalytics.feature_enabled"
+)
+
+
+def _org() -> Organization:
+ return Organization.objects.create(name=f"WorkstreamsOrg-{random.randint(1, 99999)}")
+
+
+def _team(org: Organization) -> Team:
+ return Team.objects.create(organization=org, name=f"WorkstreamsTeam-{random.randint(1, 99999)}")
+
+
+def _active_team(
+ org: Organization,
+ origin_product: Task.OriginProduct = Task.OriginProduct.USER_CREATED,
+) -> Team:
+ team = _team(org)
+ task = Task.objects.create(
+ team=team,
+ title="t",
+ description="d",
+ origin_product=origin_product,
+ )
+ TaskRun.objects.create(task=task, team=team, status=TaskRun.Status.COMPLETED)
+ return team
+
+
[email protected]_db(transaction=True)
+def test_only_returns_teams_whose_org_has_flag(activity_environment):
+ enabled_org = _org()
+ disabled_org = _org()
+ enabled_team = _active_team(enabled_org)
+ _active_team(disabled_org)
+
+ def _flag(key, distinct_id=None, **kwargs):
+ return distinct_id == str(enabled_org.id)
+
+ with patch(FLAG_PATH, side_effect=_flag):
+ result = activity_environment.run(list_active_code_teams, None)
+
+ assert result.team_ids == [enabled_team.id]
+ assert result.truncated is False
+
+
[email protected]_db(transaction=True)
+def test_flag_checked_once_per_org_not_per_team(activity_environment):
+ org = _org()
+ team_a = _active_team(org)
+ team_b = _active_team(org)
+
+ with patch(FLAG_PATH, return_value=True) as flag:
+ result = activity_environment.run(list_active_code_teams, None)
+
+ assert sorted(result.team_ids) == sorted([team_a.id, team_b.id])
+ assert flag.call_count == 1
+
+
[email protected]_db(transaction=True)
+def test_excludes_org_when_flag_check_raises(activity_environment):
+ org = _org()
+ _active_team(org)
+
+ with patch(FLAG_PATH, side_effect=RuntimeError("flag service down")):
+ result = activity_environment.run(list_active_code_teams, None)
+
+ assert result.team_ids == []
+
+
[email protected]_db(transaction=True)
+def test_returns_empty_when_no_orgs_enabled(activity_environment):
+ org = _org()
+ _active_team(org)
+
+ with patch(FLAG_PATH, return_value=False):
+ result = activity_environment.run(list_active_code_teams, None)
+
+ assert result.team_ids == []
+ assert result.truncated is False
+
+
[email protected]_db(transaction=True)
+ "origin_product",
+ [
+ Task.OriginProduct.USER_CREATED,
+ Task.OriginProduct.SLACK,
+ Task.OriginProduct.AUTOMATION,
+ ],
+)
+def test_includes_teams_with_posthog_code_origin(activity_environment, origin_product):
+ org = _org()
+ team = _active_team(org, origin_product)
+
+ with patch(FLAG_PATH, return_value=True):
+ result = activity_environment.run(list_active_code_teams, None)
+
+ assert result.team_ids == [team.id]
+
+
[email protected]_db(transaction=True)
+ "origin_product",
+ [
+ Task.OriginProduct.ERROR_TRACKING,
+ Task.OriginProduct.EVAL_CLUSTERS,
+ Task.OriginProduct.SUPPORT_QUEUE,
+ Task.OriginProduct.SESSION_SUMMARIES,
+ Task.OriginProduct.SIGNAL_REPORT,
+ Task.OriginProduct.SIGNALS_SCOUT,
+ ],
+)
+def test_excludes_teams_with_only_non_code_origin(activity_environment, origin_product):
+ org = _org()
+ _active_team(org, origin_product)
+
+ # Org has the flag on, but its only recent run came from another product on
+ # the shared tasks infra — it must not be pulled into workstream evaluation.
+ with patch(FLAG_PATH, return_value=True):
+ result = activity_environment.run(list_active_code_teams, None)
+
+ assert result.team_ids == []
+
+
[email protected]_db(transaction=True)
+def test_includes_team_with_mix_of_code_and_non_code_runs(activity_environment):
+ org = _org()
+ team = _team(org)
+ code_task = Task.objects.create(
+ team=team, title="t", description="d", origin_product=Task.OriginProduct.USER_CREATED
+ )
+ other_task = Task.objects.create(
+ team=team, title="t", description="d", origin_product=Task.OriginProduct.ERROR_TRACKING
+ )
+ TaskRun.objects.create(task=code_task, team=team, status=TaskRun.Status.COMPLETED)
+ TaskRun.objects.create(task=other_task, team=team, status=TaskRun.Status.COMPLETED)
+
+ # A single PostHog Code run qualifies the team even amid other-product runs.
+ with patch(FLAG_PATH, return_value=True):
+ result = activity_environment.run(list_active_code_teams, None)
+
+ assert result.team_ids == [team.id]
diff --git a/products/tasks/backend/temporal/code_workstreams/test_load_pr_urls.py b/products/tasks/backend/temporal/code_workstreams/test_load_pr_urls.py
new file mode 100644
index 000000000000..19f6c24e817e
--- /dev/null
+++ b/products/tasks/backend/temporal/code_workstreams/test_load_pr_urls.py
@@ -0,0 +1,66 @@
+import random
+
+import pytest
+
+from posthog.models import Organization, Team
+
+from products.tasks.backend.models import Task, TaskRun
+from products.tasks.backend.temporal.code_workstreams.activities.load_pr_urls import (
+ LoadTeamPrUrlsInput,
+ _pr_url_belongs_to_task_repo,
+ load_team_pr_urls,
+)
+
+
+ "pr_url,repository,expected",
+ [
+ ("https://github.com/acme/widgets/pull/12", "acme/widgets", True),
+ # Repo names are case-insensitive on GitHub; the stored value is lowercased.
+ ("https://github.com/AcMe/Widgets/pull/12", "acme/widgets", True),
+ # Same repo name under a different owner must not match.
+ ("https://github.com/evil/widgets/pull/12", "acme/widgets", False),
+ # Same owner, different repo.
+ ("https://github.com/acme/secrets/pull/12", "acme/widgets", False),
+ # No configured repository ⇒ fail closed.
+ ("https://github.com/acme/widgets/pull/12", None, False),
+ ("https://github.com/acme/widgets/pull/12", "", False),
+ # Not a parseable GitHub PR URL.
+ ("https://github.com/acme/widgets", "acme/widgets", False),
+ ("https://example.com/acme/widgets/pull/12", "acme/widgets", False),
+ ("not-a-url", "acme/widgets", False),
+ ],
+)
+def test_pr_url_belongs_to_task_repo(pr_url, repository, expected):
+ assert _pr_url_belongs_to_task_repo(pr_url, repository) is expected
+
+
[email protected]_db(transaction=True)
+def test_load_team_pr_urls_drops_cross_repo_pr_urls(activity_environment):
+ org = Organization.objects.create(name=f"PrUrlsOrg-{random.randint(1, 99999)}")
+ team = Team.objects.create(organization=org, name=f"PrUrlsTeam-{random.randint(1, 99999)}")
+
+ def _run_with_pr(repository, pr_url):
+ task = Task.objects.create(
+ team=team,
+ title="t",
+ description="d",
+ origin_product=Task.OriginProduct.USER_CREATED,
+ repository=repository,
+ )
+ TaskRun.objects.create(
+ task=task,
+ team=team,
+ status=TaskRun.Status.COMPLETED,
+ output={"pr_url": pr_url},
+ )
+
+ _run_with_pr("acme/widgets", "https://github.com/acme/widgets/pull/1")
+ # User-writable output.pr_url pointed at a repo the task never targeted.
+ _run_with_pr("acme/widgets", "https://github.com/acme/secrets/pull/9")
+ # Run without a configured repository must not leak its PR either.
+ _run_with_pr(None, "https://github.com/acme/widgets/pull/2")
+
+ result = activity_environment.run(load_team_pr_urls, LoadTeamPrUrlsInput(team_id=team.id))
+
+ assert [ref.pr_url for ref in result.prs] == ["https://github.com/acme/widgets/pull/1"]
diff --git a/products/tasks/backend/temporal/code_workstreams/test_rebuild_workstreams.py b/products/tasks/backend/temporal/code_workstreams/test_rebuild_workstreams.py
new file mode 100644
index 000000000000..7408ce7276df
--- /dev/null
+++ b/products/tasks/backend/temporal/code_workstreams/test_rebuild_workstreams.py
@@ -0,0 +1,53 @@
+import pytest
+
+from products.tasks.backend.models import CodePrSnapshot
+from products.tasks.backend.temporal.code_workstreams.activities.rebuild_workstreams import _build_pr_input
+
+
+def _snapshot(**overrides) -> CodePrSnapshot:
+ defaults = {
+ "pr_url": "https://github.com/org/repo/pull/1",
+ "number": 1,
+ "title": "PR",
+ "state": "open",
+ "ci_status": "passing",
+ "review_decision": None,
+ "unresolved_threads": 2,
+ "mergeable": True,
+ "author_login": "octocat",
+ "requested_reviewer_logins": ["reviewer1"],
+ "pr_updated_at": None,
+ }
+ defaults.update(overrides)
+ return CodePrSnapshot(**defaults)
+
+
+ "author_login,user_github_logins,expected",
+ [
+ ("octocat", {"octocat"}, True),
+ ("octocat", {"octocat", "alt"}, True),
+ ("octocat", {"someone-else"}, False),
+ ("octocat", set(), False),
+ (None, {"octocat"}, False),
+ ],
+)
+def test_build_pr_input_is_author_requires_identity_match(author_login, user_github_logins, expected):
+ pr = _build_pr_input(_snapshot(author_login=author_login), user_github_logins)
+ assert pr.is_current_user_author is expected
+
+
+ "requested_reviewer_logins,user_github_logins,expected",
+ [
+ (["alice", "bob"], {"bob"}, True),
+ (["alice", "bob"], {"carol"}, False),
+ ([], {"bob"}, False),
+ (["alice"], set(), False),
+ ],
+)
+def test_build_pr_input_is_requested_reviewer_requires_identity_match(
+ requested_reviewer_logins, user_github_logins, expected
+):
+ pr = _build_pr_input(_snapshot(requested_reviewer_logins=requested_reviewer_logins), user_github_logins)
+ assert pr.is_current_user_requested_reviewer is expected
diff --git a/products/tasks/backend/temporal/code_workstreams/test_workflow.py b/products/tasks/backend/temporal/code_workstreams/test_workflow.py
new file mode 100644
index 000000000000..9163f4d3f7bd
--- /dev/null
+++ b/products/tasks/backend/temporal/code_workstreams/test_workflow.py
@@ -0,0 +1,143 @@
+import uuid
+
+import pytest
+
+import temporalio.worker
+from temporalio import activity
+from temporalio.testing import WorkflowEnvironment
+from temporalio.worker import Worker
+
+from products.tasks.backend.temporal.code_workstreams.activities.list_active_teams import ListActiveCodeTeamsOutput
+from products.tasks.backend.temporal.code_workstreams.activities.load_pr_urls import (
+ LoadTeamPrUrlsInput,
+ LoadTeamPrUrlsOutput,
+ PrRef,
+)
+from products.tasks.backend.temporal.code_workstreams.activities.poll_pull_requests import PollTeamPullRequestsOutput
+from products.tasks.backend.temporal.code_workstreams.activities.rebuild_workstreams import RebuildTeamWorkstreamsOutput
+from products.tasks.backend.temporal.code_workstreams.workflow import (
+ EvaluateCodeWorkstreamsInput,
+ EvaluateCodeWorkstreamsWorkflow,
+ EvaluateTeamCodeWorkstreamsInput,
+ EvaluateTeamCodeWorkstreamsWorkflow,
+)
+
+
+def _team_pipeline_activities(calls: list[str]):
+ @activity.defn(name="load_team_pr_urls")
+ async def load(input) -> LoadTeamPrUrlsOutput:
+ calls.append("load")
+ return LoadTeamPrUrlsOutput(
+ prs=[
+ PrRef(pr_url="https://github.com/o/r/pull/1", github_integration_id=1, github_user_integration_id=None)
+ ]
+ )
+
+ @activity.defn(name="poll_team_pull_requests")
+ async def poll(input) -> PollTeamPullRequestsOutput:
+ calls.append("poll")
+ return PollTeamPullRequestsOutput(polled=1, updated=1, rate_limited=False)
+
+ @activity.defn(name="rebuild_team_workstreams")
+ async def rebuild(input) -> RebuildTeamWorkstreamsOutput:
+ calls.append("rebuild")
+ return RebuildTeamWorkstreamsOutput(users=1, workstreams=2, pruned=0)
+
+ return [load, poll, rebuild]
+
+
+async def test_team_workflow_runs_pipeline_in_order():
+ calls: list[str] = []
+ task_queue = str(uuid.uuid4())
+ async with await WorkflowEnvironment.start_time_skipping() as env:
+ async with Worker(
+ env.client,
+ task_queue=task_queue,
+ workflows=[EvaluateTeamCodeWorkstreamsWorkflow],
+ activities=_team_pipeline_activities(calls),
+ workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),
+ ):
+ await env.client.execute_workflow(
+ EvaluateTeamCodeWorkstreamsWorkflow.run,
+ EvaluateTeamCodeWorkstreamsInput(team_id=1),
+ id=str(uuid.uuid4()),
+ task_queue=task_queue,
+ )
+ assert calls == ["load", "poll", "rebuild"]
+
+
+async def test_team_workflow_skips_poll_when_no_prs():
+ calls: list[str] = []
+
+ @activity.defn(name="load_team_pr_urls")
+ async def load(input) -> LoadTeamPrUrlsOutput:
+ calls.append("load")
+ return LoadTeamPrUrlsOutput(prs=[])
+
+ @activity.defn(name="poll_team_pull_requests")
+ async def poll(input) -> PollTeamPullRequestsOutput:
+ calls.append("poll")
+ return PollTeamPullRequestsOutput(polled=0, updated=0, rate_limited=False)
+
+ @activity.defn(name="rebuild_team_workstreams")
+ async def rebuild(input) -> RebuildTeamWorkstreamsOutput:
+ calls.append("rebuild")
+ return RebuildTeamWorkstreamsOutput(users=0, workstreams=0, pruned=0)
+
+ task_queue = str(uuid.uuid4())
+ async with await WorkflowEnvironment.start_time_skipping() as env:
+ async with Worker(
+ env.client,
+ task_queue=task_queue,
+ workflows=[EvaluateTeamCodeWorkstreamsWorkflow],
+ activities=[load, poll, rebuild],
+ workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),
+ ):
+ await env.client.execute_workflow(
+ EvaluateTeamCodeWorkstreamsWorkflow.run,
+ EvaluateTeamCodeWorkstreamsInput(team_id=1),
+ id=str(uuid.uuid4()),
+ task_queue=task_queue,
+ )
+ assert calls == ["load", "rebuild"]
+
+
+async def test_dispatcher_fans_out_per_team():
+ started_teams: list[int] = []
+
+ @activity.defn(name="list_active_code_teams")
+ async def list_teams(input=None) -> ListActiveCodeTeamsOutput:
+ return ListActiveCodeTeamsOutput(team_ids=[1, 2, 3], truncated=False)
+
+ @activity.defn(name="load_team_pr_urls")
+ async def load(input: LoadTeamPrUrlsInput) -> LoadTeamPrUrlsOutput:
+ started_teams.append(input.team_id)
+ return LoadTeamPrUrlsOutput(prs=[])
+
+ @activity.defn(name="poll_team_pull_requests")
+ async def poll(input) -> PollTeamPullRequestsOutput:
+ return PollTeamPullRequestsOutput(polled=0, updated=0, rate_limited=False)
+
+ @activity.defn(name="rebuild_team_workstreams")
+ async def rebuild(input) -> RebuildTeamWorkstreamsOutput:
+ return RebuildTeamWorkstreamsOutput(users=0, workstreams=0, pruned=0)
+
+ task_queue = str(uuid.uuid4())
+ async with await WorkflowEnvironment.start_time_skipping() as env:
+ async with Worker(
+ env.client,
+ task_queue=task_queue,
+ workflows=[EvaluateCodeWorkstreamsWorkflow, EvaluateTeamCodeWorkstreamsWorkflow],
+ activities=[list_teams, load, poll, rebuild],
+ workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),
+ ):
+ await env.client.execute_workflow(
+ EvaluateCodeWorkstreamsWorkflow.run,
+ EvaluateCodeWorkstreamsInput(),
+ id=str(uuid.uuid4()),
+ task_queue=task_queue,
+ )
+ assert sorted(started_teams) == [1, 2, 3]
diff --git a/products/tasks/backend/temporal/code_workstreams/workflow.py b/products/tasks/backend/temporal/code_workstreams/workflow.py
new file mode 100644
index 000000000000..de683136e26f
--- /dev/null
+++ b/products/tasks/backend/temporal/code_workstreams/workflow.py
@@ -0,0 +1,113 @@
+import json
+import asyncio
+from dataclasses import dataclass
+from datetime import timedelta
+
+from temporalio import workflow
+from temporalio.common import RetryPolicy, WorkflowIDReusePolicy
+
+from posthog.temporal.common.base import PostHogWorkflow
+
+from products.tasks.backend.temporal.code_workstreams.activities.list_active_teams import (
+ ListActiveCodeTeamsOutput,
+ list_active_code_teams,
+)
+from products.tasks.backend.temporal.code_workstreams.activities.load_pr_urls import (
+ LoadTeamPrUrlsInput,
+ LoadTeamPrUrlsOutput,
+ load_team_pr_urls,
+)
+from products.tasks.backend.temporal.code_workstreams.activities.poll_pull_requests import (
+ PollTeamPullRequestsInput,
+ poll_team_pull_requests,
+)
+from products.tasks.backend.temporal.code_workstreams.activities.rebuild_workstreams import (
+ RebuildTeamWorkstreamsInput,
+ rebuild_team_workstreams,
+)
+from products.tasks.backend.temporal.code_workstreams.constants import TEAM_FANOUT_CONCURRENCY
+
+
+@dataclass
+class EvaluateTeamCodeWorkstreamsInput:
+ team_id: int
+
+
+@dataclass
+class EvaluateCodeWorkstreamsInput:
+ pass
+
+
[email protected](name="evaluate-team-code-workstreams")
+class EvaluateTeamCodeWorkstreamsWorkflow(PostHogWorkflow):
+ @staticmethod
+ def parse_inputs(inputs: list[str]) -> EvaluateTeamCodeWorkstreamsInput:
+ loaded = json.loads(inputs[0])
+ return EvaluateTeamCodeWorkstreamsInput(team_id=loaded["team_id"])
+
+ @workflow.run
+ async def run(self, input: EvaluateTeamCodeWorkstreamsInput) -> None:
+ pr_urls: LoadTeamPrUrlsOutput = await workflow.execute_activity(
+ load_team_pr_urls,
+ LoadTeamPrUrlsInput(team_id=input.team_id),
+ start_to_close_timeout=timedelta(minutes=1),
+ retry_policy=RetryPolicy(maximum_attempts=3),
+ )
+
+ if pr_urls.prs:
+ await workflow.execute_activity(
+ poll_team_pull_requests,
+ PollTeamPullRequestsInput(team_id=input.team_id, prs=pr_urls.prs),
+ start_to_close_timeout=timedelta(minutes=10),
+ heartbeat_timeout=timedelta(minutes=2),
+ retry_policy=RetryPolicy(maximum_attempts=3),
+ )
+
+ await workflow.execute_activity(
+ rebuild_team_workstreams,
+ RebuildTeamWorkstreamsInput(team_id=input.team_id),
+ start_to_close_timeout=timedelta(minutes=5),
+ retry_policy=RetryPolicy(maximum_attempts=3),
+ )
+
+
[email protected](name="evaluate-code-workstreams")
+class EvaluateCodeWorkstreamsWorkflow(PostHogWorkflow):
+ @staticmethod
+ def parse_inputs(inputs: list[str]) -> EvaluateCodeWorkstreamsInput:
+ return EvaluateCodeWorkstreamsInput()
+
+ @workflow.run
+ async def run(self, input: EvaluateCodeWorkstreamsInput) -> None:
+ active: ListActiveCodeTeamsOutput = await workflow.execute_activity(
+ list_active_code_teams,
+ start_to_close_timeout=timedelta(minutes=2),
+ retry_policy=RetryPolicy(maximum_attempts=3),
+ )
+ if not active.team_ids:
+ return
+
+ parent_id = workflow.info().workflow_id
+ semaphore = asyncio.Semaphore(TEAM_FANOUT_CONCURRENCY)
+
+ async def evaluate_team(team_id: int) -> None:
+ async with semaphore:
+ await workflow.execute_child_workflow(
+ EvaluateTeamCodeWorkstreamsWorkflow.run,
+ EvaluateTeamCodeWorkstreamsInput(team_id=team_id),
+ id=f"{parent_id}-team-{team_id}",
+ id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE,
+ retry_policy=RetryPolicy(maximum_attempts=1),
+ )
+
+ results = await asyncio.gather(
+ *(evaluate_team(team_id) for team_id in active.team_ids),
+ return_exceptions=True,
+ )
+ failures = [r for r in results if isinstance(r, Exception)]
+ if failures:
+ workflow.logger.warning(
+ "code_workstreams_dispatch_partial_failures",
+ total=len(active.team_ids),
+ failures=len(failures),
+ )
diff --git a/products/tasks/package.json b/products/tasks/package.json
index ec3578f0c1ab..021abb472f38 100644
--- a/products/tasks/package.json
+++ b/products/tasks/package.json
@@ -1,7 +1,7 @@
{
"name": "@posthog/products-tasks",
"scripts": {
- "backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/tests backend/services backend/stream/tests -v --tb=short"
+ "backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/tests backend/services backend/stream/tests backend/code_workstreams -v --tb=short"
},
"dependencies": {
"fast-deep-equal": "catalog:",